text
stringlengths
54
60.6k
<commit_before>#include <libport/lexical-cast.hh> #include <ast/exps-type.hh> #include <ast/parametric-ast.hh> #include <parser/ast-factory.hh> #include <rewrite/pattern-binder.hh> namespace rewrite { using parser::ast_string; ast::rExp PatternBinder::to_binding(ast::rConstExp original) { PARAMETRIC_AST(rewrite, "Pattern.Binding.new(%exp:1)"); rewrite % ast_string(original->location_get(), next_name()); ast::rExp res = exp(rewrite); res->original_set(original); return res; } void PatternBinder::bind(ast::rConstLValue what, bool decl) { PARAMETRIC_AST(bind, "%lvalue:1 = %exp:2"); PARAMETRIC_AST(bind_decl, "var %lvalue:1 = %exp:2"); bindings_->children_get().push_back (exp((decl ? bind_decl : bind) % const_cast<ast::LValue*>(what.get()) % value_get())); } ast::rExp PatternBinder::value_get() { PARAMETRIC_AST(get, "%lvalue:1 . bindings[%exp:2]"); return exp(get % pattern_ % ast_string(ast::loc(), next_name())); } PatternBinder::PatternBinder(ast::rLValue pattern, const ast::loc& loc, bool assign) : bindings_(new ast::Pipe(loc, ast::exps_type())) , pattern_(pattern) , i_(0) , assign_(assign) {} libport::Symbol PatternBinder::next_name() { return libport::Symbol(boost::lexical_cast<std::string>(i_)); } void PatternBinder::visit(const ast::Binding* binding) { i_++; result_ = to_binding(binding); bind(binding->what_get(), true); } void PatternBinder::visit(const ast::Call* call) { if (call->arguments_get() || !assign_) { super_type::visit(call); return; } i_++; result_ = to_binding(call); bind(call, false); } void PatternBinder::visit(const ast::Property* prop) { ast::loc loc = prop->location_get(); i_++; result_ = to_binding(prop); bind(prop, false); } void PatternBinder::visit(const ast::Subscript* sub) { i_++; result_ = to_binding(sub); bind(sub, false); } ast::rPipe PatternBinder::bindings_get() const { return bindings_; } } <commit_msg>Likewise, assign list elements and properties only in assignments.<commit_after>#include <libport/lexical-cast.hh> #include <ast/exps-type.hh> #include <ast/parametric-ast.hh> #include <parser/ast-factory.hh> #include <rewrite/pattern-binder.hh> namespace rewrite { using parser::ast_string; ast::rExp PatternBinder::to_binding(ast::rConstExp original) { PARAMETRIC_AST(rewrite, "Pattern.Binding.new(%exp:1)"); rewrite % ast_string(original->location_get(), next_name()); ast::rExp res = exp(rewrite); res->original_set(original); return res; } void PatternBinder::bind(ast::rConstLValue what, bool decl) { PARAMETRIC_AST(bind, "%lvalue:1 = %exp:2"); PARAMETRIC_AST(bind_decl, "var %lvalue:1 = %exp:2"); bindings_->children_get().push_back (exp((decl ? bind_decl : bind) % const_cast<ast::LValue*>(what.get()) % value_get())); } ast::rExp PatternBinder::value_get() { PARAMETRIC_AST(get, "%lvalue:1 . bindings[%exp:2]"); return exp(get % pattern_ % ast_string(ast::loc(), next_name())); } PatternBinder::PatternBinder(ast::rLValue pattern, const ast::loc& loc, bool assign) : bindings_(new ast::Pipe(loc, ast::exps_type())) , pattern_(pattern) , i_(0) , assign_(assign) {} libport::Symbol PatternBinder::next_name() { return libport::Symbol(boost::lexical_cast<std::string>(i_)); } void PatternBinder::visit(const ast::Binding* binding) { i_++; result_ = to_binding(binding); bind(binding->what_get(), true); } void PatternBinder::visit(const ast::Call* call) { if (call->arguments_get() || !assign_) { super_type::visit(call); return; } i_++; result_ = to_binding(call); bind(call, false); } void PatternBinder::visit(const ast::Property* prop) { if (!assign_) { super_type::visit(call); return; } i_++; result_ = to_binding(prop); bind(prop, false); } void PatternBinder::visit(const ast::Subscript* sub) { if (!assign_) { super_type::visit(call); return; } i_++; result_ = to_binding(sub); bind(sub, false); } ast::rPipe PatternBinder::bindings_get() const { return bindings_; } } <|endoftext|>
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include <windows.h> #include <vector> #include "base/file_util.h" namespace file_util { bool EvictFileFromSystemCache(const wchar_t* file) { // Request exclusive access to the file and overwrite it with no buffering. win_util::ScopedHandle hfile( CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!hfile) return false; // Execute in chunks. It could be optimized. We want to do few of these since // these opterations will be slow without the cache. char buffer[4096]; int total_bytes = 0; DWORD bytes_read; for (;;) { bytes_read = 0; ReadFile(hfile, buffer, sizeof(buffer), &bytes_read, NULL); if (bytes_read == 0) break; SetFilePointer(hfile, total_bytes, 0, FILE_BEGIN); if (!WriteFile(hfile, buffer, bytes_read, &bytes_read, NULL)) return false; total_bytes += bytes_read; } return true; } // Like CopyFileNoCache but recursively copies all files and subdirectories // in the given input directory to the output directory. bool CopyRecursiveDirNoCache(const std::wstring& source_dir, const std::wstring& dest_dir) { // Try to create the directory if it doesn't already exist. if (!CreateDirectory(dest_dir)) { if (GetLastError() != ERROR_ALREADY_EXISTS) return false; } std::vector<std::wstring> files_copied; std::wstring src(source_dir); file_util::AppendToPath(&src, L"*"); WIN32_FIND_DATA fd; HANDLE fh = FindFirstFile(src.c_str(), &fd); if (fh == INVALID_HANDLE_VALUE) return false; do { std::wstring cur_file(fd.cFileName); if (cur_file == L"." || cur_file == L"..") continue; // Skip these special entries. std::wstring cur_source_path(source_dir); file_util::AppendToPath(&cur_source_path, cur_file); std::wstring cur_dest_path(dest_dir); file_util::AppendToPath(&cur_dest_path, cur_file); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Recursively copy a subdirectory. We stripped "." and ".." already. if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) { FindClose(fh); return false; } } else { // Copy the file. if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) { FindClose(fh); return false; } // We don't check for errors from this function, often, we are copying // files that are in the repository, and they will have read-only set. // This will prevent us from evicting from the cache, but these don't // matter anyway. EvictFileFromSystemCache(cur_dest_path.c_str()); } } while (FindNextFile(fh, &fd)); FindClose(fh); return true; } } // namespace file_util <commit_msg>ScopedHandle is not in a namespace.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include <windows.h> #include <vector> #include "base/file_util.h" #include "base/scoped_handle.h" namespace file_util { bool EvictFileFromSystemCache(const wchar_t* file) { // Request exclusive access to the file and overwrite it with no buffering. ScopedHandle hfile( CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!hfile) return false; // Execute in chunks. It could be optimized. We want to do few of these since // these opterations will be slow without the cache. char buffer[4096]; int total_bytes = 0; DWORD bytes_read; for (;;) { bytes_read = 0; ReadFile(hfile, buffer, sizeof(buffer), &bytes_read, NULL); if (bytes_read == 0) break; SetFilePointer(hfile, total_bytes, 0, FILE_BEGIN); if (!WriteFile(hfile, buffer, bytes_read, &bytes_read, NULL)) return false; total_bytes += bytes_read; } return true; } // Like CopyFileNoCache but recursively copies all files and subdirectories // in the given input directory to the output directory. bool CopyRecursiveDirNoCache(const std::wstring& source_dir, const std::wstring& dest_dir) { // Try to create the directory if it doesn't already exist. if (!CreateDirectory(dest_dir)) { if (GetLastError() != ERROR_ALREADY_EXISTS) return false; } std::vector<std::wstring> files_copied; std::wstring src(source_dir); file_util::AppendToPath(&src, L"*"); WIN32_FIND_DATA fd; HANDLE fh = FindFirstFile(src.c_str(), &fd); if (fh == INVALID_HANDLE_VALUE) return false; do { std::wstring cur_file(fd.cFileName); if (cur_file == L"." || cur_file == L"..") continue; // Skip these special entries. std::wstring cur_source_path(source_dir); file_util::AppendToPath(&cur_source_path, cur_file); std::wstring cur_dest_path(dest_dir); file_util::AppendToPath(&cur_dest_path, cur_file); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Recursively copy a subdirectory. We stripped "." and ".." already. if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) { FindClose(fh); return false; } } else { // Copy the file. if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) { FindClose(fh); return false; } // We don't check for errors from this function, often, we are copying // files that are in the repository, and they will have read-only set. // This will prevent us from evicting from the cache, but these don't // matter anyway. EvictFileFromSystemCache(cur_dest_path.c_str()); } } while (FindNextFile(fh, &fd)); FindClose(fh); return true; } } // namespace file_util <|endoftext|>
<commit_before>/*************************************************************************** * rubyinterpreter.cpp * This file is part of the KDE project * copyright (C)2005 by Cyrille Berger (cberger@cberger.net) * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "rubyextension.h" #include <st.h> #include <qmap.h> #include <qstring.h> #include "api/list.h" #include "rubyconfig.h" #include <version.h> #if(RUBY_VERSION_MAJOR==1 && RUBY_VERSION_MINOR == 8 && RUBY_VERSION_TEENY <= 1) void rb_hash_foreach _((VALUE, int (*)(ANYARGS), VALUE)); #endif namespace Kross { namespace Ruby { class RubyExtensionPrivate { friend class RubyExtension; /// The \a Kross::Api::Object this RubyExtension wraps. Kross::Api::Object::Ptr m_object; /// static VALUE s_krossObject; }; VALUE RubyExtensionPrivate::s_krossObject = 0; VALUE RubyExtension::method_missing(int argc, VALUE *argv, VALUE self) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "method_missing(argc, argv, self)" << endl; #endif if(argc < 1) { return 0; } #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Converting self to Kross::Api::Object" << endl; #endif Kross::Api::Object::Ptr object = toObject( self ); return RubyExtension::call_method(object, argc, argv); } VALUE RubyExtension::call_method( Kross::Api::Object::Ptr object, int argc, VALUE *argv) { QString funcname = rb_id2name(SYM2ID(argv[0])); QValueList<Api::Object::Ptr> argsList; #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Building arguments list for function : " << funcname << " there are " << (argc-1) << " arguments." << endl; #endif for(int i = 1; i < argc; i++) { Kross::Api::Object::Ptr obj = toObject(argv[i]); if(obj) argsList.append(obj); } Kross::Api::Object::Ptr result; if(object->hasChild(funcname)) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << QString("Kross::Ruby::RubyExtension::method_missing name='%1' is a child object of '%2'.").arg(funcname).arg(object->getName()) << endl; #endif result = object->getChild(funcname)->call(QString::null, new Api::List(argsList)); } else { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << QString("Kross::Ruby::RubyExtension::method_missing try to call function with name '%1' in object '%2'.").arg(funcname).arg(object->getName()) << endl; #endif result = object->call(funcname, new Api::List(argsList)); } return toVALUE(result); } RubyExtension::RubyExtension(Kross::Api::Object::Ptr object) : d(new RubyExtensionPrivate()) { d->m_object = object; } RubyExtension::~RubyExtension() { } typedef QMap<QString, Kross::Api::Object::Ptr> mStrObj; int RubyExtension::convertHash_i(VALUE key, VALUE value, VALUE vmap) { QMap<QString, Kross::Api::Object::Ptr>* map; Data_Get_Struct(vmap, mStrObj, map); if (key != Qundef) { Kross::Api::Object::Ptr o = RubyExtension::toObject( value ); if(o) map->replace(STR2CSTR(key), o); } return ST_CONTINUE; } Kross::Api::Object::Ptr RubyExtension::toObject(VALUE value) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "RubyExtension::toObject of type " << TYPE(value) << endl; #endif switch( TYPE( value ) ) { case T_DATA: { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Object is a Kross Object" << endl; #endif VALUE result = rb_funcall(value, rb_intern("kind_of?"), 1, RubyExtensionPrivate::s_krossObject ); if(TYPE(result) == T_TRUE) { RubyExtension* objectExtension; Data_Get_Struct(value, RubyExtension, objectExtension); Kross::Api::Object::Ptr object = objectExtension->d->m_object; return object; } else { kdWarning() << "Cannot yet convert standard ruby type to kross object" << endl; return 0; } } case T_FLOAT: return new Kross::Api::Variant(NUM2DBL(value)); case T_STRING: return new Kross::Api::Variant(QString(STR2CSTR(value))); case T_ARRAY: { QValueList<Kross::Api::Object::Ptr> l; for(int i = 0; i < RARRAY(value)->len; i++) { Kross::Api::Object::Ptr o = toObject( rb_ary_entry( value , i ) ); if(o) l.append(o); } return new Kross::Api::List(l); } case T_FIXNUM: return new Kross::Api::Variant((Q_LLONG)FIX2INT(value)); case T_HASH: { QMap<QString, Kross::Api::Object::Ptr> map; VALUE vmap = Data_Wrap_Struct(rb_cObject, 0,0, &map); rb_hash_foreach(value, (int (*)(...))convertHash_i, vmap); return new Kross::Api::Dict(map); } case T_BIGNUM: { return new Kross::Api::Variant((Q_LLONG)NUM2LONG(value)); } case T_TRUE: { return new Kross::Api::Variant(true); } case T_FALSE: { return new Kross::Api::Variant(false); } case T_SYMBOL: { return new Kross::Api::Variant(QString(rb_id2name(SYM2ID(value)))); } case T_MATCH: case T_OBJECT: case T_FILE: case T_STRUCT: case T_REGEXP: case T_MODULE: case T_ICLASS: case T_CLASS: kdWarning() << QString("This ruby type '%1' cannot be converted to a Kross::Api::Object").arg(TYPE(value)) << endl; default: case T_NIL: return 0; } } VALUE RubyExtension::toVALUE(const QString& s) { return s.isNull() ? rb_str_new2("") : rb_str_new2(s.latin1()); } VALUE RubyExtension::toVALUE(QStringList list) { VALUE l = rb_ary_new(); for(QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it) rb_ary_push(l, toVALUE(*it)); return l; } VALUE RubyExtension::toVALUE(QMap<QString, QVariant> map) { VALUE h = rb_hash_new(); for(QMap<QString, QVariant>::Iterator it = map.begin(); it != map.end(); ++it) rb_hash_aset(h, toVALUE(it.key()), toVALUE(it.data()) ); return h; } VALUE RubyExtension::toVALUE(QValueList<QVariant> list) { VALUE l = rb_ary_new(); for(QValueList<QVariant>::Iterator it = list.begin(); it != list.end(); ++it) rb_ary_push(l, toVALUE(*it)); return l; } VALUE RubyExtension::toVALUE(const QVariant& variant) { switch(variant.type()) { case QVariant::Invalid: return Qnil; case QVariant::Bool: return (variant.toBool()) ? Qtrue : Qfalse; case QVariant::Int: return INT2FIX(variant.toInt()); case QVariant::UInt: return UINT2NUM(variant.toUInt()); case QVariant::Double: return rb_float_new(variant.toDouble()); case QVariant::Date: case QVariant::Time: case QVariant::DateTime: case QVariant::ByteArray: case QVariant::BitArray: case QVariant::CString: case QVariant::String: return toVALUE(variant.toString()); case QVariant::StringList: return toVALUE(variant.toStringList()); case QVariant::Map: return toVALUE(variant.toMap()); case QVariant::List: return toVALUE(variant.toList()); // To handle following both cases is a bit difficult // cause Python doesn't spend an easy possibility // for such large numbers (TODO maybe BigInt?). So, // we risk overflows here, but well... case QVariant::LongLong: { return INT2NUM((long)variant.toLongLong()); } case QVariant::ULongLong: return UINT2NUM((unsigned long)variant.toULongLong()); default: { kdWarning() << QString("Kross::Ruby::RubyExtension::toVALUE(QVariant) Not possible to convert the QVariant type '%1' to a VALUE.").arg(variant.typeName()) << endl; return Qundef; } } } VALUE RubyExtension::toVALUE(Kross::Api::Object::Ptr object) { if(! object) { return 0; } if(object->getClassName() == "Kross::Api::Variant") { QVariant v = static_cast<Kross::Api::Variant*>( object.data() )->getValue(); return toVALUE(v); } if(object->getClassName() == "Kross::Api::List") { Kross::Api::List* list = static_cast<Kross::Api::List*>( object.data() ); return toVALUE((Kross::Api::List::Ptr)list); } if(object->getClassName() == "Kross::Api::Dict") { Kross::Api::Dict* dict = static_cast<Kross::Api::Dict*>( object.data() ); return toVALUE((Kross::Api::Dict::Ptr)dict); } if(RubyExtensionPrivate::s_krossObject == 0) { RubyExtensionPrivate::s_krossObject = rb_define_class("KrossObject", rb_cObject); rb_define_method(RubyExtensionPrivate::s_krossObject, "method_missing", (VALUE (*)(...))RubyExtension::method_missing, -1); } return Data_Wrap_Struct(RubyExtensionPrivate::s_krossObject, 0, free, new RubyExtension(object) ); } VALUE RubyExtension::toVALUE(Kross::Api::List::Ptr list) { VALUE l = rb_ary_new(); uint count = list ? list->count() : 0; for(uint i = 0; i < count; i++) rb_ary_push(l, toVALUE(list->item(i))); return l; } } } <commit_msg>- drop support for ruby <= 1.8.1<commit_after>/*************************************************************************** * rubyinterpreter.cpp * This file is part of the KDE project * copyright (C)2005 by Cyrille Berger (cberger@cberger.net) * * This program 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #include "rubyextension.h" #include <st.h> #include <qmap.h> #include <qstring.h> #include "api/list.h" #include "rubyconfig.h" namespace Kross { namespace Ruby { class RubyExtensionPrivate { friend class RubyExtension; /// The \a Kross::Api::Object this RubyExtension wraps. Kross::Api::Object::Ptr m_object; /// static VALUE s_krossObject; }; VALUE RubyExtensionPrivate::s_krossObject = 0; VALUE RubyExtension::method_missing(int argc, VALUE *argv, VALUE self) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "method_missing(argc, argv, self)" << endl; #endif if(argc < 1) { return 0; } #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Converting self to Kross::Api::Object" << endl; #endif Kross::Api::Object::Ptr object = toObject( self ); return RubyExtension::call_method(object, argc, argv); } VALUE RubyExtension::call_method( Kross::Api::Object::Ptr object, int argc, VALUE *argv) { QString funcname = rb_id2name(SYM2ID(argv[0])); QValueList<Api::Object::Ptr> argsList; #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Building arguments list for function : " << funcname << " there are " << (argc-1) << " arguments." << endl; #endif for(int i = 1; i < argc; i++) { Kross::Api::Object::Ptr obj = toObject(argv[i]); if(obj) argsList.append(obj); } Kross::Api::Object::Ptr result; if(object->hasChild(funcname)) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << QString("Kross::Ruby::RubyExtension::method_missing name='%1' is a child object of '%2'.").arg(funcname).arg(object->getName()) << endl; #endif result = object->getChild(funcname)->call(QString::null, new Api::List(argsList)); } else { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << QString("Kross::Ruby::RubyExtension::method_missing try to call function with name '%1' in object '%2'.").arg(funcname).arg(object->getName()) << endl; #endif result = object->call(funcname, new Api::List(argsList)); } return toVALUE(result); } RubyExtension::RubyExtension(Kross::Api::Object::Ptr object) : d(new RubyExtensionPrivate()) { d->m_object = object; } RubyExtension::~RubyExtension() { } typedef QMap<QString, Kross::Api::Object::Ptr> mStrObj; int RubyExtension::convertHash_i(VALUE key, VALUE value, VALUE vmap) { QMap<QString, Kross::Api::Object::Ptr>* map; Data_Get_Struct(vmap, mStrObj, map); if (key != Qundef) { Kross::Api::Object::Ptr o = RubyExtension::toObject( value ); if(o) map->replace(STR2CSTR(key), o); } return ST_CONTINUE; } Kross::Api::Object::Ptr RubyExtension::toObject(VALUE value) { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "RubyExtension::toObject of type " << TYPE(value) << endl; #endif switch( TYPE( value ) ) { case T_DATA: { #ifdef KROSS_RUBY_EXTENSION_DEBUG kdDebug() << "Object is a Kross Object" << endl; #endif VALUE result = rb_funcall(value, rb_intern("kind_of?"), 1, RubyExtensionPrivate::s_krossObject ); if(TYPE(result) == T_TRUE) { RubyExtension* objectExtension; Data_Get_Struct(value, RubyExtension, objectExtension); Kross::Api::Object::Ptr object = objectExtension->d->m_object; return object; } else { kdWarning() << "Cannot yet convert standard ruby type to kross object" << endl; return 0; } } case T_FLOAT: return new Kross::Api::Variant(NUM2DBL(value)); case T_STRING: return new Kross::Api::Variant(QString(STR2CSTR(value))); case T_ARRAY: { QValueList<Kross::Api::Object::Ptr> l; for(int i = 0; i < RARRAY(value)->len; i++) { Kross::Api::Object::Ptr o = toObject( rb_ary_entry( value , i ) ); if(o) l.append(o); } return new Kross::Api::List(l); } case T_FIXNUM: return new Kross::Api::Variant((Q_LLONG)FIX2INT(value)); case T_HASH: { QMap<QString, Kross::Api::Object::Ptr> map; VALUE vmap = Data_Wrap_Struct(rb_cObject, 0,0, &map); rb_hash_foreach(value, (int (*)(...))convertHash_i, vmap); return new Kross::Api::Dict(map); } case T_BIGNUM: { return new Kross::Api::Variant((Q_LLONG)NUM2LONG(value)); } case T_TRUE: { return new Kross::Api::Variant(true); } case T_FALSE: { return new Kross::Api::Variant(false); } case T_SYMBOL: { return new Kross::Api::Variant(QString(rb_id2name(SYM2ID(value)))); } case T_MATCH: case T_OBJECT: case T_FILE: case T_STRUCT: case T_REGEXP: case T_MODULE: case T_ICLASS: case T_CLASS: kdWarning() << QString("This ruby type '%1' cannot be converted to a Kross::Api::Object").arg(TYPE(value)) << endl; default: case T_NIL: return 0; } } VALUE RubyExtension::toVALUE(const QString& s) { return s.isNull() ? rb_str_new2("") : rb_str_new2(s.latin1()); } VALUE RubyExtension::toVALUE(QStringList list) { VALUE l = rb_ary_new(); for(QStringList::ConstIterator it = list.constBegin(); it != list.constEnd(); ++it) rb_ary_push(l, toVALUE(*it)); return l; } VALUE RubyExtension::toVALUE(QMap<QString, QVariant> map) { VALUE h = rb_hash_new(); for(QMap<QString, QVariant>::Iterator it = map.begin(); it != map.end(); ++it) rb_hash_aset(h, toVALUE(it.key()), toVALUE(it.data()) ); return h; } VALUE RubyExtension::toVALUE(QValueList<QVariant> list) { VALUE l = rb_ary_new(); for(QValueList<QVariant>::Iterator it = list.begin(); it != list.end(); ++it) rb_ary_push(l, toVALUE(*it)); return l; } VALUE RubyExtension::toVALUE(const QVariant& variant) { switch(variant.type()) { case QVariant::Invalid: return Qnil; case QVariant::Bool: return (variant.toBool()) ? Qtrue : Qfalse; case QVariant::Int: return INT2FIX(variant.toInt()); case QVariant::UInt: return UINT2NUM(variant.toUInt()); case QVariant::Double: return rb_float_new(variant.toDouble()); case QVariant::Date: case QVariant::Time: case QVariant::DateTime: case QVariant::ByteArray: case QVariant::BitArray: case QVariant::CString: case QVariant::String: return toVALUE(variant.toString()); case QVariant::StringList: return toVALUE(variant.toStringList()); case QVariant::Map: return toVALUE(variant.toMap()); case QVariant::List: return toVALUE(variant.toList()); // To handle following both cases is a bit difficult // cause Python doesn't spend an easy possibility // for such large numbers (TODO maybe BigInt?). So, // we risk overflows here, but well... case QVariant::LongLong: { return INT2NUM((long)variant.toLongLong()); } case QVariant::ULongLong: return UINT2NUM((unsigned long)variant.toULongLong()); default: { kdWarning() << QString("Kross::Ruby::RubyExtension::toVALUE(QVariant) Not possible to convert the QVariant type '%1' to a VALUE.").arg(variant.typeName()) << endl; return Qundef; } } } VALUE RubyExtension::toVALUE(Kross::Api::Object::Ptr object) { if(! object) { return 0; } if(object->getClassName() == "Kross::Api::Variant") { QVariant v = static_cast<Kross::Api::Variant*>( object.data() )->getValue(); return toVALUE(v); } if(object->getClassName() == "Kross::Api::List") { Kross::Api::List* list = static_cast<Kross::Api::List*>( object.data() ); return toVALUE((Kross::Api::List::Ptr)list); } if(object->getClassName() == "Kross::Api::Dict") { Kross::Api::Dict* dict = static_cast<Kross::Api::Dict*>( object.data() ); return toVALUE((Kross::Api::Dict::Ptr)dict); } if(RubyExtensionPrivate::s_krossObject == 0) { RubyExtensionPrivate::s_krossObject = rb_define_class("KrossObject", rb_cObject); rb_define_method(RubyExtensionPrivate::s_krossObject, "method_missing", (VALUE (*)(...))RubyExtension::method_missing, -1); } return Data_Wrap_Struct(RubyExtensionPrivate::s_krossObject, 0, free, new RubyExtension(object) ); } VALUE RubyExtension::toVALUE(Kross::Api::List::Ptr list) { VALUE l = rb_ary_new(); uint count = list ? list->count() : 0; for(uint i = 0; i < count; i++) rb_ary_push(l, toVALUE(list->item(i))); return l; } } } <|endoftext|>
<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include <windows.h> #include <vector> #include "base/file_util.h" #include "base/scoped_handle.h" namespace file_util { bool EvictFileFromSystemCache(const wchar_t* file) { // Request exclusive access to the file and overwrite it with no buffering. ScopedHandle hfile( CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!hfile) return false; // Execute in chunks. It could be optimized. We want to do few of these since // these opterations will be slow without the cache. char buffer[4096]; int total_bytes = 0; DWORD bytes_read; for (;;) { bytes_read = 0; ReadFile(hfile, buffer, sizeof(buffer), &bytes_read, NULL); if (bytes_read == 0) break; SetFilePointer(hfile, total_bytes, 0, FILE_BEGIN); if (!WriteFile(hfile, buffer, bytes_read, &bytes_read, NULL)) return false; total_bytes += bytes_read; } return true; } // Like CopyFileNoCache but recursively copies all files and subdirectories // in the given input directory to the output directory. bool CopyRecursiveDirNoCache(const std::wstring& source_dir, const std::wstring& dest_dir) { // Try to create the directory if it doesn't already exist. if (!CreateDirectory(dest_dir)) { if (GetLastError() != ERROR_ALREADY_EXISTS) return false; } std::vector<std::wstring> files_copied; std::wstring src(source_dir); file_util::AppendToPath(&src, L"*"); WIN32_FIND_DATA fd; HANDLE fh = FindFirstFile(src.c_str(), &fd); if (fh == INVALID_HANDLE_VALUE) return false; do { std::wstring cur_file(fd.cFileName); if (cur_file == L"." || cur_file == L"..") continue; // Skip these special entries. std::wstring cur_source_path(source_dir); file_util::AppendToPath(&cur_source_path, cur_file); std::wstring cur_dest_path(dest_dir); file_util::AppendToPath(&cur_dest_path, cur_file); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Recursively copy a subdirectory. We stripped "." and ".." already. if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) { FindClose(fh); return false; } } else { // Copy the file. if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) { FindClose(fh); return false; } // We don't check for errors from this function, often, we are copying // files that are in the repository, and they will have read-only set. // This will prevent us from evicting from the cache, but these don't // matter anyway. EvictFileFromSystemCache(cur_dest_path.c_str()); } } while (FindNextFile(fh, &fd)); FindClose(fh); return true; } } // namespace file_util <commit_msg>Making sure that the buffer we use with ReadFile/WriteFile is page aligned. Also restoring file attributes after evicting it from the cache (since the function writes to the file).<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/test_file_util.h" #include <windows.h> #include <vector> #include "base/file_util.h" #include "base/scoped_handle.h" namespace file_util { // We could use GetSystemInfo to get the page size, but this serves // our purpose fine since 4K is the page size on x86 as well as x64. static const ptrdiff_t kPageSize = 4096; bool EvictFileFromSystemCache(const wchar_t* file) { // Request exclusive access to the file and overwrite it with no buffering. ScopedHandle file_handle( CreateFile(file, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL)); if (!file_handle) return false; // Get some attributes to restore later. BY_HANDLE_FILE_INFORMATION bhi = {0}; CHECK(::GetFileInformationByHandle(file_handle, &bhi)); // Execute in chunks. It could be optimized. We want to do few of these since // these operations will be slow without the cache. // Non-buffered reads and writes need to be sector aligned and since sector // sizes typically range from 512-4096 bytes, we just use the page size. // The buffer size is twice the size of a page (minus one) since we need to // get an aligned pointer into the buffer that we can use. char buffer[2 * kPageSize - 1]; // Get an aligned pointer into buffer. char* read_write = reinterpret_cast<char*>( reinterpret_cast<ptrdiff_t>(buffer + kPageSize - 1) & ~(kPageSize - 1)); DCHECK((reinterpret_cast<int>(read_write) % kPageSize) == 0); // If the file size isn't a multiple of kPageSize, we'll need special // processing. bool file_is_page_aligned = true; int total_bytes = 0; DWORD bytes_read, bytes_written; for (;;) { bytes_read = 0; ReadFile(file_handle, read_write, kPageSize, &bytes_read, NULL); if (bytes_read == 0) break; if (bytes_read < kPageSize) { // Zero out the remaining part of the buffer. // WriteFile will fail if we provide a buffer size that isn't a // sector multiple, so we'll have to write the entire buffer with // padded zeros and then use SetEndOfFile to truncate the file. ZeroMemory(read_write + bytes_read, kPageSize - bytes_read); file_is_page_aligned = false; } // Move back to the position we just read from. // Note that SetFilePointer will also fail if total_bytes isn't sector // aligned, but that shouldn't happen here. DCHECK((total_bytes % kPageSize) == 0); SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN); if (!WriteFile(file_handle, read_write, kPageSize, &bytes_written, NULL) || bytes_written != kPageSize) { DCHECK(false); return false; } total_bytes += bytes_read; // If this is false, then we just processed the last portion of the file. if (!file_is_page_aligned) break; } if (!file_is_page_aligned) { // The size of the file isn't a multiple of the page size, so we'll have // to open the file again, this time without the FILE_FLAG_NO_BUFFERING // flag and use SetEndOfFile to mark EOF. file_handle.Set(CreateFile(file, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL)); CHECK(SetFilePointer(file_handle, total_bytes, NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER); CHECK(::SetEndOfFile(file_handle)); } // Restore the file attributes. CHECK(::SetFileTime(file_handle, &bhi.ftCreationTime, &bhi.ftLastAccessTime, &bhi.ftLastWriteTime)); return true; } // Like CopyFileNoCache but recursively copies all files and subdirectories // in the given input directory to the output directory. bool CopyRecursiveDirNoCache(const std::wstring& source_dir, const std::wstring& dest_dir) { // Try to create the directory if it doesn't already exist. if (!CreateDirectory(dest_dir)) { if (GetLastError() != ERROR_ALREADY_EXISTS) return false; } std::vector<std::wstring> files_copied; std::wstring src(source_dir); file_util::AppendToPath(&src, L"*"); WIN32_FIND_DATA fd; HANDLE fh = FindFirstFile(src.c_str(), &fd); if (fh == INVALID_HANDLE_VALUE) return false; do { std::wstring cur_file(fd.cFileName); if (cur_file == L"." || cur_file == L"..") continue; // Skip these special entries. std::wstring cur_source_path(source_dir); file_util::AppendToPath(&cur_source_path, cur_file); std::wstring cur_dest_path(dest_dir); file_util::AppendToPath(&cur_dest_path, cur_file); if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // Recursively copy a subdirectory. We stripped "." and ".." already. if (!CopyRecursiveDirNoCache(cur_source_path, cur_dest_path)) { FindClose(fh); return false; } } else { // Copy the file. if (!::CopyFile(cur_source_path.c_str(), cur_dest_path.c_str(), false)) { FindClose(fh); return false; } // We don't check for errors from this function, often, we are copying // files that are in the repository, and they will have read-only set. // This will prevent us from evicting from the cache, but these don't // matter anyway. EvictFileFromSystemCache(cur_dest_path.c_str()); } } while (FindNextFile(fh, &fd)); FindClose(fh); return true; } } // namespace file_util <|endoftext|>
<commit_before>#include <QRegExp> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QSettings> #include <QSqlField> #include "identity.h" #include "kernel.h" #include "oshelper.h" #include "connectorinterface.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogexplorer.h" #include "catalogconnector.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwiscontext.h" #include "catalog.h" #include "symboltable.h" #include "operationExpression.h" Ilwis::MasterCatalog *Ilwis::MasterCatalog::_masterCatalog = 0; using namespace Ilwis; MasterCatalog* Ilwis::mastercatalog() { if (Ilwis::MasterCatalog::_masterCatalog == 0) { Ilwis::MasterCatalog::_masterCatalog = new Ilwis::MasterCatalog(); Ilwis::MasterCatalog::_masterCatalog->prepare(); } return Ilwis::MasterCatalog::_masterCatalog; } MasterCatalog::MasterCatalog() { } MasterCatalog::~MasterCatalog() { _lookup.clear(); _knownHashes.clear(); _catalogs.clear(); } bool MasterCatalog::prepare() { QSettings settings("52n","ilwis4"); //TODO: this piece code must move to a more appropriate place; at this moment it // is not guaranteed that the catalogconnectors are already known due to the order of the plugins // as they are loaded. // QString local = settings.value("localfilesystem",QVariant(sUNDEF)).toString(); return true; } bool MasterCatalog::addContainer(const QUrl &inlocation) { if ( !inlocation.isValid()) // it is valid to try this with an empty url; just wont do anything return true; QString original = inlocation.toString().trimmed(); if ( Resource::isRoot(original)) return true; QString loc = original; if ( loc[loc.size() - 1] == '/' ){ loc = loc.left(loc.size() - 1); int count = loc.count("/"); if ( loc.indexOf(":///") != -1){ if ( count == 3) loc = original; }else if ( loc.indexOf("://") != -1){ if ( count == 2){ loc= original; } } } if ( loc.indexOf("ilwis://tables") == 0|| loc.indexOf("ilwis://factory") == 0 || loc.indexOf("ilwis://system") == 0 || loc.indexOf("ilwis://operations") == 0 || loc == "file://" || loc == "file:/" || loc == "ilwis:/" || loc.isEmpty()) return true; QUrl location(loc); if ( _catalogs.find(location) != _catalogs.end()) return true; ICatalog catalog(loc); if ( !catalog.isValid()){ return false; } addItems({catalog->source()}); _catalogs.insert(location); return true; } ESPIlwisObject MasterCatalog::get(const QUrl &resource, IlwisTypes type) const { quint64 id = url2id(resource, type); return get(id); } ESPIlwisObject MasterCatalog::get(quint64 id) const { if ( id != i64UNDEF) { auto iter = _lookup.find(id); if ( iter != _lookup.end()) return iter.value(); } return ESPIlwisObject(); } bool MasterCatalog::contains(const QUrl& url, IlwisTypes type) const{ auto hash = Ilwis::qHash2(url, type); auto iter = _knownHashes.find(hash); if ( iter != _knownHashes.end()) { auto id = url2id(url, type); if ( id != i64UNDEF) return true; } return false; } bool MasterCatalog::usesContainers(const QUrl &url) const { return _containerExceptions.find(url.scheme()) == _containerExceptions.end(); } void MasterCatalog::addContainerException(const QString &scheme) { _containerExceptions.insert(scheme); } bool MasterCatalog::removeItems(const QList<Resource> &items){ for(const Resource &resource : items) { auto iter = _knownHashes.find(Ilwis::qHash(resource)); if ( iter != _knownHashes.end()) { _knownHashes.erase(iter); } QString stmt = QString("DELETE FROM mastercatalog WHERE resource = %1" ).arg(resource.id()); QSqlQuery db(kernel()->database()); if(!db.exec(stmt)) { kernel()->issues()->logSql(db.lastError()); return false; } stmt = QString("DELETE FROM catalogitemproperties WHERE resource = %1").arg(resource.id()); if(!db.exec(stmt)) { kernel()->issues()->logSql(db.lastError()); return false; } } return true; } bool MasterCatalog::addItems(const std::vector<Resource>& items) { if( items.size() == 0) // nothing to do; not wrong perse return true; QSqlQuery queryItem(kernel()->database()), queryProperties(kernel()->database()); bool ok = queryItem.prepare("INSERT INTO mastercatalog VALUES(\ :itemid,:name,:code,:container,:resource,:rawresource,:urlquery,:type,:extendedtype, :size,:dimensions \ )" ); if (!ok) { kernel()->issues()->logSql(queryItem.lastError()); return false; } ok = queryProperties.prepare("INSERT INTO catalogitemproperties VALUES(\ :propertyvalue,:propertyname,:itemid\ )" ); if (!ok) { kernel()->issues()->logSql(queryItem.lastError()); return false; } for(const Resource &resource : items) { if (!resource.isValid()) continue; if ( mastercatalog()->contains(resource.url(), resource.ilwisType())) continue; _knownHashes.insert(Ilwis::qHash(resource)); resource.store(queryItem, queryProperties); } return true; } quint64 MasterCatalog::url2id(const QUrl &url, IlwisTypes tp, bool casesensitive) const { QString query = QString("select itemid,type from mastercatalog where resource = '%1'").arg(url.toString()); if (!casesensitive) query = QString("select itemid,type from mastercatalog where lower(resource) = '%1'").arg(url.toString().toLower()) ; auto results = kernel()->database().exec(query); while ( results.next()) { auto rec = results.record(); auto iid = rec.value(0).toLongLong(); auto itype = rec.value(1).toLongLong(); if ( (itype & tp) || tp == itUNKNOWN) return iid; } return i64UNDEF; } Resource MasterCatalog::id2Resource(quint64 iid) const { auto query = QString("select * from mastercatalog where itemid = %1").arg(iid); auto results = kernel()->database().exec(query); if ( results.next()) { auto rec = results.record(); return Resource(rec); } return Resource(); } quint64 MasterCatalog::name2id(const QString &name, IlwisTypes tp) const { quint64 id = IlwisObject::internalname2id(name); if ( id == i64UNDEF){ Resource resource = name2Resource(name,tp); id = resource.id(); } return id; } IlwisTypes MasterCatalog::id2type(quint64 iid) const { QString query = QString("select type from mastercatalog where itemid = %1").arg(iid); QSqlQuery results = kernel()->database().exec(query); if ( results.next()) { return results.value(0).toLongLong(); } return itUNKNOWN; } Resource MasterCatalog::name2Resource(const QString &name, IlwisTypes tp) const { if ( tp == itUNKNOWN) { // no definitive type given we, try to find based on name/type combination. will work mostely but not guaranteed. this is anyway a last resort method std::vector<IlwisTypes> types { itRASTER, itFEATURE, itTABLE, itGEOREF, itCOORDSYSTEM, itDOMAIN}; for(IlwisTypes type: types) { Resource resource = name2Resource(name, type); if (resource.isValid()) return resource; } return Resource(); } auto resolvedName = name2url(name, tp); if (!resolvedName.isValid()) return Resource(); resolvedName = OSHelper::neutralizeFileName(resolvedName.toString()); auto query = QString("select * from mastercatalog where resource = '%1' and (type & %2) != 0").arg(resolvedName.toString()).arg(tp); auto results = kernel()->database().exec(query); if ( results.next()) { auto rec = results.record(); return Resource(rec); } else { query = QString("select propertyvalue from catalogitemproperties,mastercatalog \ where mastercatalog.resource='%1' and mastercatalog.itemid=catalogitemproperties.itemid\ and (mastercatalog.extendedtype & %2) != 0").arg(resolvedName.toString()).arg(tp); auto viaExtType = kernel()->database().exec(query); bool isExternalRef = true; while ( viaExtType.next()){ // external reference finding isExternalRef = false; bool ok; auto propertyid = viaExtType.value(0).toLongLong(&ok); if (!ok) { kernel()->issues()->log(TR("Invalid catalog property, mastercatalog corrupted?"),IssueObject::itWarning); } auto type = id2type(propertyid); if ( type & tp) return id2Resource(propertyid); } if ( !isExternalRef) { // it was not an external reference but an internal one; if it was external it will never come here // this is a new resource which only existed as reference but now gets real, so add it to the catalog Resource resource(QUrl(resolvedName), tp); const_cast<MasterCatalog *>(this)->addItems({resource}); return resource; } } return Resource(); } QUrl MasterCatalog::name2url(const QString &name, IlwisTypes tp) const{ if ( name.contains(QRegExp("\\\\|/"))) { // is there already path info; then assume it is already a unique resource bool ok = OSHelper::isAbsolute(name); // name might be a partial path if ( ok && !OSHelper::isFileName(name)) // translate name to url; we have the following cases // * already is a path, no big deal; just make an url of it // * is a code; construct a path leading to the internal connector as all codes are handled there // * no, path, no code. So it must be in the current working catalog. // * backup case. we try it by name. may fail as names are not necessarily unique. system is robust enough to handle fail cases return name; if ( ok){ return QUrl::fromLocalFile(name).toString(); }else { QString resolvedName = context()->workingCatalog()->source().url().toString() + "/" + name; return resolvedName; } } if ( name.indexOf("code=wkt:")==0) { // second case -- handle most codes cases auto code = name.right(name.size() - 5); auto wkt = code.mid(4); auto table = "projection"; if ( tp & itELLIPSOID ) table = "ellipsoid"; else if ( tp & itGEODETICDATUM) table = "datum"; //auto query = QString("select code from %1 where wkt='%2'").arg(table, wkt); auto query = QString("select code from %1 where wkt like '%%2%'").arg(table, wkt); auto codes = kernel()->database().exec(query); if ( codes.next()) { QString res = QString("ilwis://tables/%1?code=%2").arg(table,codes.value(0).toString()); return res; }else { kernel()->issues()->log(TR(ERR_FIND_SYSTEM_OBJECT_1).arg(wkt)); return QUrl(); } } else if ( name.indexOf("code=epsg:")== 0 ) { auto code = name.right(name.size() - 5); return QString("ilwis://tables/projectedcsy?code=%1").arg(code); } else if ( name.left(6) == "code=proj4:") { auto code = name.right(name.size() - 5); return QString("ilwis://projection/code=%1").arg(code); } else if ( name.left(12) == "code=domain:") { return QString("ilwis://internalcatalog/%1").arg(name); }else if ( name.left(12) == "code=georef:") { QString shortname = name.mid(name.indexOf(":") + 1); return QString("ilwis://internalcatalog/%1").arg(shortname); }else if ( name.left(9) == "code=csy:") { QString shortname = name.mid(name.indexOf(":") + 1); return QString("ilwis://internalcatalog/%1").arg(shortname); } if ( context()->workingCatalog().isValid()) { // thirde case -- use the working catalog to extend the path auto resolvedName = context()->workingCatalog()->resolve(name, tp); if ( resolvedName != sUNDEF) return resolvedName; } auto code = name; if ( code.indexOf("code=") == 0) code = code.mid(5); // fourth case -- try name auto query = QString("select resource,type from mastercatalog where name = '%1' or code='%1'").arg(code); auto results = kernel()->database().exec(query); while ( results.next()) { auto rec = results.record(); auto type = rec.value(1).toLongLong(); if ( type & tp) return rec.value(0).toString(); } return QUrl(); } bool MasterCatalog::isRegistered(quint64 id) const { return _lookup.contains(id); } bool MasterCatalog::unregister(quint64 id) { QHash<quint64,ESPIlwisObject>::const_iterator iter = _lookup.find(id); if ( iter != _lookup.end()) { _lookup.remove(id); } return true; } std::vector<Resource> MasterCatalog::select(const QUrl &resource, const QString &selection) const { QString rest = selection == "" ? "" : QString("and (%1)").arg(selection); QString query = QString("select * from mastercatalog where container = '%1' %2").arg(resource.toString(), rest); QSqlQuery results = kernel()->database().exec(query); std::vector<Resource> items; while( results.next()) { QSqlRecord rec = results.record(); items.push_back(Resource(rec)); } return items; } void MasterCatalog::registerObject(ESPIlwisObject &data) { if ( data.get() == 0) { QHash<quint64,ESPIlwisObject>::iterator iter = _lookup.find(data->id()); data = iter.value(); } else { if ( !data->isAnonymous()) addItems({data->source()}); _lookup[data->id()] = data; } } #ifdef QT_DEBUG void MasterCatalog::dumpLookup() const { for(auto pr : _lookup) { qDebug() << pr->name(); } } quint32 MasterCatalog::usecount(quint64 id) { auto iter = _lookup.find(id); if ( iter != _lookup.end()) { return iter.value().use_count(); } return 0; } #endif <commit_msg>added guard<commit_after>#include <QRegExp> #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QSettings> #include <QSqlField> #include "identity.h" #include "kernel.h" #include "oshelper.h" #include "connectorinterface.h" #include "mastercatalog.h" #include "ilwisobjectconnector.h" #include "catalogexplorer.h" #include "catalogconnector.h" #include "abstractfactory.h" #include "connectorfactory.h" #include "ilwiscontext.h" #include "catalog.h" #include "symboltable.h" #include "operationExpression.h" Ilwis::MasterCatalog *Ilwis::MasterCatalog::_masterCatalog = 0; using namespace Ilwis; MasterCatalog* Ilwis::mastercatalog() { if (Ilwis::MasterCatalog::_masterCatalog == 0) { Ilwis::MasterCatalog::_masterCatalog = new Ilwis::MasterCatalog(); Ilwis::MasterCatalog::_masterCatalog->prepare(); } return Ilwis::MasterCatalog::_masterCatalog; } MasterCatalog::MasterCatalog() { } MasterCatalog::~MasterCatalog() { _lookup.clear(); _knownHashes.clear(); _catalogs.clear(); } bool MasterCatalog::prepare() { QSettings settings("52n","ilwis4"); //TODO: this piece code must move to a more appropriate place; at this moment it // is not guaranteed that the catalogconnectors are already known due to the order of the plugins // as they are loaded. // QString local = settings.value("localfilesystem",QVariant(sUNDEF)).toString(); return true; } bool MasterCatalog::addContainer(const QUrl &inlocation) { if ( !inlocation.isValid()) // it is valid to try this with an empty url; just wont do anything return true; QString original = inlocation.toString().trimmed(); if ( Resource::isRoot(original)) return true; QString loc = original; if ( loc[loc.size() - 1] == '/' ){ loc = loc.left(loc.size() - 1); int count = loc.count("/"); if ( loc.indexOf(":///") != -1){ if ( count == 3) loc = original; }else if ( loc.indexOf("://") != -1){ if ( count == 2){ loc= original; } } } if ( loc.indexOf("ilwis://tables") == 0|| loc.indexOf("ilwis://factory") == 0 || loc.indexOf("ilwis://system") == 0 || loc.indexOf("ilwis://operations") == 0 || loc == "file://" || loc == "file:/" || loc == "ilwis:/" || loc.isEmpty()) return true; QUrl location(loc); if ( _catalogs.find(location) != _catalogs.end()) return true; ICatalog catalog(loc); if ( !catalog.isValid()){ return false; } addItems({catalog->source()}); _catalogs.insert(location); return true; } ESPIlwisObject MasterCatalog::get(const QUrl &resource, IlwisTypes type) const { quint64 id = url2id(resource, type); return get(id); } ESPIlwisObject MasterCatalog::get(quint64 id) const { if ( id != i64UNDEF) { auto iter = _lookup.find(id); if ( iter != _lookup.end()) return iter.value(); } return ESPIlwisObject(); } bool MasterCatalog::contains(const QUrl& url, IlwisTypes type) const{ auto hash = Ilwis::qHash2(url, type); auto iter = _knownHashes.find(hash); if ( iter != _knownHashes.end()) { auto id = url2id(url, type); if ( id != i64UNDEF) return true; } return false; } bool MasterCatalog::usesContainers(const QUrl &url) const { return _containerExceptions.find(url.scheme()) == _containerExceptions.end(); } void MasterCatalog::addContainerException(const QString &scheme) { _containerExceptions.insert(scheme); } bool MasterCatalog::removeItems(const QList<Resource> &items){ for(const Resource &resource : items) { auto iter = _knownHashes.find(Ilwis::qHash(resource)); if ( iter != _knownHashes.end()) { _knownHashes.erase(iter); } QString stmt = QString("DELETE FROM mastercatalog WHERE resource = %1" ).arg(resource.id()); QSqlQuery db(kernel()->database()); if(!db.exec(stmt)) { kernel()->issues()->logSql(db.lastError()); return false; } stmt = QString("DELETE FROM catalogitemproperties WHERE resource = %1").arg(resource.id()); if(!db.exec(stmt)) { kernel()->issues()->logSql(db.lastError()); return false; } } return true; } bool MasterCatalog::addItems(const std::vector<Resource>& items) { if( items.size() == 0) // nothing to do; not wrong perse return true; QSqlQuery queryItem(kernel()->database()), queryProperties(kernel()->database()); bool ok = queryItem.prepare("INSERT INTO mastercatalog VALUES(\ :itemid,:name,:code,:container,:resource,:rawresource,:urlquery,:type,:extendedtype, :size,:dimensions \ )" ); if (!ok) { kernel()->issues()->logSql(queryItem.lastError()); return false; } ok = queryProperties.prepare("INSERT INTO catalogitemproperties VALUES(\ :propertyvalue,:propertyname,:itemid\ )" ); if (!ok) { kernel()->issues()->logSql(queryItem.lastError()); return false; } for(const Resource &resource : items) { if (!resource.isValid()) continue; if ( mastercatalog()->contains(resource.url(), resource.ilwisType())) continue; _knownHashes.insert(Ilwis::qHash(resource)); resource.store(queryItem, queryProperties); } return true; } quint64 MasterCatalog::url2id(const QUrl &url, IlwisTypes tp, bool casesensitive) const { QString query = QString("select itemid,type from mastercatalog where resource = '%1'").arg(url.toString()); if (!casesensitive) query = QString("select itemid,type from mastercatalog where lower(resource) = '%1'").arg(url.toString().toLower()) ; auto results = kernel()->database().exec(query); while ( results.next()) { auto rec = results.record(); auto iid = rec.value(0).toLongLong(); auto itype = rec.value(1).toLongLong(); if ( (itype & tp) || tp == itUNKNOWN) return iid; } return i64UNDEF; } Resource MasterCatalog::id2Resource(quint64 iid) const { auto query = QString("select * from mastercatalog where itemid = %1").arg(iid); auto results = kernel()->database().exec(query); if ( results.next()) { auto rec = results.record(); return Resource(rec); } return Resource(); } quint64 MasterCatalog::name2id(const QString &name, IlwisTypes tp) const { quint64 id = IlwisObject::internalname2id(name); if ( id == i64UNDEF){ Resource resource = name2Resource(name,tp); id = resource.id(); } return id; } IlwisTypes MasterCatalog::id2type(quint64 iid) const { QString query = QString("select type from mastercatalog where itemid = %1").arg(iid); QSqlQuery results = kernel()->database().exec(query); if ( results.next()) { return results.value(0).toLongLong(); } return itUNKNOWN; } Resource MasterCatalog::name2Resource(const QString &name, IlwisTypes tp) const { if ( name == sUNDEF) return Resource(); if ( tp == itUNKNOWN) { // no definitive type given we, try to find based on name/type combination. will work mostely but not guaranteed. this is anyway a last resort method std::vector<IlwisTypes> types { itRASTER, itFEATURE, itTABLE, itGEOREF, itCOORDSYSTEM, itDOMAIN}; for(IlwisTypes type: types) { Resource resource = name2Resource(name, type); if (resource.isValid()) return resource; } return Resource(); } auto resolvedName = name2url(name, tp); if (!resolvedName.isValid()) return Resource(); resolvedName = OSHelper::neutralizeFileName(resolvedName.toString()); auto query = QString("select * from mastercatalog where resource = '%1' and (type & %2) != 0").arg(resolvedName.toString()).arg(tp); auto results = kernel()->database().exec(query); if ( results.next()) { auto rec = results.record(); return Resource(rec); } else { query = QString("select propertyvalue from catalogitemproperties,mastercatalog \ where mastercatalog.resource='%1' and mastercatalog.itemid=catalogitemproperties.itemid\ and (mastercatalog.extendedtype & %2) != 0").arg(resolvedName.toString()).arg(tp); auto viaExtType = kernel()->database().exec(query); bool isExternalRef = true; while ( viaExtType.next()){ // external reference finding isExternalRef = false; bool ok; auto propertyid = viaExtType.value(0).toLongLong(&ok); if (!ok) { kernel()->issues()->log(TR("Invalid catalog property, mastercatalog corrupted?"),IssueObject::itWarning); } auto type = id2type(propertyid); if ( type & tp) return id2Resource(propertyid); } if ( !isExternalRef) { // it was not an external reference but an internal one; if it was external it will never come here // this is a new resource which only existed as reference but now gets real, so add it to the catalog Resource resource(QUrl(resolvedName), tp); const_cast<MasterCatalog *>(this)->addItems({resource}); return resource; } } return Resource(); } QUrl MasterCatalog::name2url(const QString &name, IlwisTypes tp) const{ if ( name.contains(QRegExp("\\\\|/"))) { // is there already path info; then assume it is already a unique resource bool ok = OSHelper::isAbsolute(name); // name might be a partial path if ( ok && !OSHelper::isFileName(name)) // translate name to url; we have the following cases // * already is a path, no big deal; just make an url of it // * is a code; construct a path leading to the internal connector as all codes are handled there // * no, path, no code. So it must be in the current working catalog. // * backup case. we try it by name. may fail as names are not necessarily unique. system is robust enough to handle fail cases return name; if ( ok){ return QUrl::fromLocalFile(name).toString(); }else { QString resolvedName = context()->workingCatalog()->source().url().toString() + "/" + name; return resolvedName; } } if ( name.indexOf("code=wkt:")==0) { // second case -- handle most codes cases auto code = name.right(name.size() - 5); auto wkt = code.mid(4); auto table = "projection"; if ( tp & itELLIPSOID ) table = "ellipsoid"; else if ( tp & itGEODETICDATUM) table = "datum"; //auto query = QString("select code from %1 where wkt='%2'").arg(table, wkt); auto query = QString("select code from %1 where wkt like '%%2%'").arg(table, wkt); auto codes = kernel()->database().exec(query); if ( codes.next()) { QString res = QString("ilwis://tables/%1?code=%2").arg(table,codes.value(0).toString()); return res; }else { kernel()->issues()->log(TR(ERR_FIND_SYSTEM_OBJECT_1).arg(wkt)); return QUrl(); } } else if ( name.indexOf("code=epsg:")== 0 ) { auto code = name.right(name.size() - 5); return QString("ilwis://tables/projectedcsy?code=%1").arg(code); } else if ( name.left(6) == "code=proj4:") { auto code = name.right(name.size() - 5); return QString("ilwis://projection/code=%1").arg(code); } else if ( name.left(12) == "code=domain:") { return QString("ilwis://internalcatalog/%1").arg(name); }else if ( name.left(12) == "code=georef:") { QString shortname = name.mid(name.indexOf(":") + 1); return QString("ilwis://internalcatalog/%1").arg(shortname); }else if ( name.left(9) == "code=csy:") { QString shortname = name.mid(name.indexOf(":") + 1); return QString("ilwis://internalcatalog/%1").arg(shortname); } if ( context()->workingCatalog().isValid()) { // thirde case -- use the working catalog to extend the path auto resolvedName = context()->workingCatalog()->resolve(name, tp); if ( resolvedName != sUNDEF) return resolvedName; } auto code = name; if ( code.indexOf("code=") == 0) code = code.mid(5); // fourth case -- try name auto query = QString("select resource,type from mastercatalog where name = '%1' or code='%1'").arg(code); auto results = kernel()->database().exec(query); while ( results.next()) { auto rec = results.record(); auto type = rec.value(1).toLongLong(); if ( type & tp) return rec.value(0).toString(); } return QUrl(); } bool MasterCatalog::isRegistered(quint64 id) const { return _lookup.contains(id); } bool MasterCatalog::unregister(quint64 id) { QHash<quint64,ESPIlwisObject>::const_iterator iter = _lookup.find(id); if ( iter != _lookup.end()) { _lookup.remove(id); } return true; } std::vector<Resource> MasterCatalog::select(const QUrl &resource, const QString &selection) const { QString rest = selection == "" ? "" : QString("and (%1)").arg(selection); QString query = QString("select * from mastercatalog where container = '%1' %2").arg(resource.toString(), rest); QSqlQuery results = kernel()->database().exec(query); std::vector<Resource> items; while( results.next()) { QSqlRecord rec = results.record(); items.push_back(Resource(rec)); } return items; } void MasterCatalog::registerObject(ESPIlwisObject &data) { if ( data.get() == 0) { QHash<quint64,ESPIlwisObject>::iterator iter = _lookup.find(data->id()); data = iter.value(); } else { if ( !data->isAnonymous()) addItems({data->source()}); _lookup[data->id()] = data; } } #ifdef QT_DEBUG void MasterCatalog::dumpLookup() const { for(auto pr : _lookup) { qDebug() << pr->name(); } } quint32 MasterCatalog::usecount(quint64 id) { auto iter = _lookup.find(id); if ( iter != _lookup.end()) { return iter.value().use_count(); } return 0; } #endif <|endoftext|>
<commit_before>#include <nek/utility/addressof.hpp> #include <gtest/gtest.h> TEST(addressof_test, enable_apply_address_operator_type) { int val = 0; int* val_ptr = nek::addressof(val); EXPECT_EQ(&val, val_ptr); } struct address_operator_overrided_class { public: void* operator&() const { return nullptr; } bool is_same_address(address_operator_overrided_class* right) const { return this == right; } }; TEST(addressof_test, disable_apply_address_operator_type) { address_operator_overrided_class ad; ASSERT_EQ(nullptr, &ad); address_operator_overrided_class* ad_ptr = nek::addressof(ad); EXPECT_NE(nullptr, ad_ptr); EXPECT_TRUE(ad.is_same_address(ad_ptr)); }<commit_msg>fix test class's namespace<commit_after>#include <nek/utility/addressof.hpp> #include <gtest/gtest.h> TEST(addressof_test, enable_apply_address_operator_type) { int val = 0; int* val_ptr = nek::addressof(val); EXPECT_EQ(&val, val_ptr); } namespace { struct address_operator_overrided_class { public: void* operator&() const { return nullptr; } bool is_same_address(address_operator_overrided_class* right) const { return this == right; } }; } TEST(addressof_test, disable_apply_address_operator_type) { address_operator_overrided_class ad; ASSERT_EQ(nullptr, &ad); address_operator_overrided_class* ad_ptr = nek::addressof(ad); EXPECT_NE(nullptr, ad_ptr); EXPECT_TRUE(ad.is_same_address(ad_ptr)); }<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xrmmerge.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 15:52:07 $ * * 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 * ************************************************************************/ // global includes #include <tools/string.hxx> // // XRMResParser // class XRMResParser { private: ByteString sGID; ByteString sLID; BOOL bError; BOOL bText; bool sLocalized; ByteString sCurrentOpenTag; ByteString sCurrentCloseTag; ByteString sCurrentText; std::vector<ByteString> aLanguages; protected: ByteString GetAttribute( const ByteString &rToken, const ByteString &rAttribute ); void Error( const ByteString &rError ); virtual void Output( const ByteString& rOutput )=0; virtual void WorkOnText( const ByteString &rOpenTag, ByteString &rText )=0; virtual void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag )=0; ByteString GetGID() { return sGID; } ByteString GetLID() { return sLID; } void ConvertStringToDBFormat( ByteString &rString ); void ConvertStringToXMLFormat( ByteString &rString ); public: XRMResParser(); virtual ~XRMResParser(); int Execute( int nToken, char * pToken ); void SetError( BOOL bErr = TRUE ) { bError = bErr; } BOOL GetError() { return bError; } }; // // class XRMResOutputParser // class XRMResOutputParser : public XRMResParser { private: std::vector<ByteString> aLanguages; protected: SvFileStream *pOutputStream; public: XRMResOutputParser ( const ByteString &rOutputFile ); virtual ~XRMResOutputParser(); }; // // XRMResExport // class XRMResExport : public XRMResOutputParser { private: ResData *pResData; ByteString sPrj; ByteString sPath; std::vector<ByteString> aLanguages; protected: void WorkOnText( const ByteString &rOpenTag, ByteString &rText ); void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag ); void Output( const ByteString& rOutput ); public: XRMResExport( const ByteString &rOutputFile, const ByteString &rProject, const ByteString &rFilePath ); virtual ~XRMResExport(); }; // // class XRMResMerge // class XRMResMerge : public XRMResOutputParser { private: MergeDataFile *pMergeDataFile; ByteString sFilename; ResData *pResData; std::vector<ByteString> aLanguages; protected: void WorkOnText( const ByteString &rOpenTag, ByteString &rText ); void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag ); void Output( const ByteString& rOutput ); public: XRMResMerge( const ByteString &rMergeSource, const ByteString &rOutputFile, ByteString &rFilename ); virtual ~XRMResMerge(); }; <commit_msg>INTEGRATION: CWS changefileheader (1.6.72); FILE MERGED 2008/03/28 15:41:59 rt 1.6.72.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: xrmmerge.hxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ // global includes #include <tools/string.hxx> // // XRMResParser // class XRMResParser { private: ByteString sGID; ByteString sLID; BOOL bError; BOOL bText; bool sLocalized; ByteString sCurrentOpenTag; ByteString sCurrentCloseTag; ByteString sCurrentText; std::vector<ByteString> aLanguages; protected: ByteString GetAttribute( const ByteString &rToken, const ByteString &rAttribute ); void Error( const ByteString &rError ); virtual void Output( const ByteString& rOutput )=0; virtual void WorkOnText( const ByteString &rOpenTag, ByteString &rText )=0; virtual void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag )=0; ByteString GetGID() { return sGID; } ByteString GetLID() { return sLID; } void ConvertStringToDBFormat( ByteString &rString ); void ConvertStringToXMLFormat( ByteString &rString ); public: XRMResParser(); virtual ~XRMResParser(); int Execute( int nToken, char * pToken ); void SetError( BOOL bErr = TRUE ) { bError = bErr; } BOOL GetError() { return bError; } }; // // class XRMResOutputParser // class XRMResOutputParser : public XRMResParser { private: std::vector<ByteString> aLanguages; protected: SvFileStream *pOutputStream; public: XRMResOutputParser ( const ByteString &rOutputFile ); virtual ~XRMResOutputParser(); }; // // XRMResExport // class XRMResExport : public XRMResOutputParser { private: ResData *pResData; ByteString sPrj; ByteString sPath; std::vector<ByteString> aLanguages; protected: void WorkOnText( const ByteString &rOpenTag, ByteString &rText ); void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag ); void Output( const ByteString& rOutput ); public: XRMResExport( const ByteString &rOutputFile, const ByteString &rProject, const ByteString &rFilePath ); virtual ~XRMResExport(); }; // // class XRMResMerge // class XRMResMerge : public XRMResOutputParser { private: MergeDataFile *pMergeDataFile; ByteString sFilename; ResData *pResData; std::vector<ByteString> aLanguages; protected: void WorkOnText( const ByteString &rOpenTag, ByteString &rText ); void EndOfText( const ByteString &rOpenTag, const ByteString &rCloseTag ); void Output( const ByteString& rOutput ); public: XRMResMerge( const ByteString &rMergeSource, const ByteString &rOutputFile, ByteString &rFilename ); virtual ~XRMResMerge(); }; <|endoftext|>
<commit_before>#ifndef UTILS_MAPCSSUTILS_HPP_DEFINED #define UTILS_MAPCSSUTILS_HPP_DEFINED #include "Exceptions.hpp" #include "entities/Element.hpp" #include "index/StringTable.hpp" #include "mapcss/Style.hpp" #include "utils/GeoUtils.hpp" #include <string> namespace utymap { namespace utils { // Checks whether key exists. inline bool hasKey(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style) { return style.has(stringTable.getId(key)); } // Gets raw declaration value as string. inline std::shared_ptr<std::string> getString(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, const std::string& defaultValue = "") { uint32_t keyId = stringTable.getId(key); return style.has(keyId) ? style.get(keyId)->value() : std::shared_ptr<std::string>(new std::string(defaultValue)); } // Gets declaration value as double. Evaluates if necessary. inline double getDouble(const std::string& key, const std::vector<utymap::entities::Tag>& tags, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style) { uint32_t keyId = stringTable.getId(key); return style.get(keyId)->evaluate(tags, stringTable); } // Gets declaration value as double without evaluation. inline double getDouble(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double defaultValue = 0) { uint32_t keyId = stringTable.getId(key); return style.has(keyId) ? std::stod(*style.get(keyId)->value()) : defaultValue; } // Gets dimension value. Evaluation is not supported. inline double getDimension(uint32_t keyId, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double size, const utymap::GeoCoordinate& coordinate) { auto declaration = style.get(keyId); auto rawValue = declaration->value(); char dimen = (*rawValue)[rawValue->size() - 1]; double value = std::stod(rawValue->substr(0, rawValue->size() - 1)); // defined in meters: use raw value if (dimen == 'm' && coordinate.latitude != 90) return coordinate.isValid() ? GeoUtils::getOffset(coordinate, value) : value; // relative to size if (dimen == '%') return size * value * 0.01; throw utymap::MapCssException("Unknown width dimension."); } // Gets dimension value. Evaluation is not supported. inline double getDimension(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double size, double defaultValue, const utymap::GeoCoordinate& coordinate = GeoCoordinate()) { uint32_t keyId = stringTable.getId(key); if (!style.has(keyId)) return defaultValue; return getDimension(keyId, stringTable, style, size, coordinate); } // Gets dimension value. Evaluation is not supported. inline double getDimension(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double size, const utymap::GeoCoordinate& coordinate = GeoCoordinate()) { return getDimension(stringTable.getId(key), stringTable, style, size, coordinate); } }} #endif // UTILS_MAPCSSUTILS_HPP_DEFINED <commit_msg>core: refactor MapCssUtils.getDimension<commit_after>#ifndef UTILS_MAPCSSUTILS_HPP_DEFINED #define UTILS_MAPCSSUTILS_HPP_DEFINED #include "Exceptions.hpp" #include "entities/Element.hpp" #include "index/StringTable.hpp" #include "mapcss/Style.hpp" #include "utils/GeoUtils.hpp" #include <string> namespace utymap { namespace utils { // Checks whether key exists. inline bool hasKey(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style) { return style.has(stringTable.getId(key)); } // Gets raw declaration value as string. inline std::shared_ptr<std::string> getString(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, const std::string& defaultValue = "") { uint32_t keyId = stringTable.getId(key); return style.has(keyId) ? style.get(keyId)->value() : std::shared_ptr<std::string>(new std::string(defaultValue)); } // Gets declaration value as double. Evaluates if necessary. inline double getDouble(const std::string& key, const std::vector<utymap::entities::Tag>& tags, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style) { uint32_t keyId = stringTable.getId(key); return style.get(keyId)->evaluate(tags, stringTable); } // Gets declaration value as double without evaluation. inline double getDouble(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double defaultValue = 0) { uint32_t keyId = stringTable.getId(key); return style.has(keyId) ? std::stod(*style.get(keyId)->value()) : defaultValue; } // Gets dimension value. Evaluation is not supported. inline double getDimension(uint32_t keyId, const utymap::mapcss::Style& style, double size, const utymap::GeoCoordinate& coordinate) { auto declaration = style.get(keyId); auto rawValue = declaration->value(); char dimen = (*rawValue)[rawValue->size() - 1]; double value = std::stod(rawValue->substr(0, rawValue->size() - 1)); // defined in meters: use raw value if (dimen == 'm' && coordinate.latitude != 90) return coordinate.isValid() ? GeoUtils::getOffset(coordinate, value) : value; // relative to size if (dimen == '%') return size * value * 0.01; throw utymap::MapCssException("Unknown width dimension."); } // Gets dimension value. Evaluation is not supported. inline double getDimension(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double size, double defaultValue, const utymap::GeoCoordinate& coordinate = GeoCoordinate()) { uint32_t keyId = stringTable.getId(key); if (!style.has(keyId)) return defaultValue; return getDimension(keyId, style, size, coordinate); } // Gets dimension value. Evaluation is not supported. inline double getDimension(const std::string& key, utymap::index::StringTable& stringTable, const utymap::mapcss::Style& style, double size, const utymap::GeoCoordinate& coordinate = GeoCoordinate()) { return getDimension(stringTable.getId(key), style, size, coordinate); } }} #endif // UTILS_MAPCSSUTILS_HPP_DEFINED <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fragmenthandler.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2008-01-17 08:05:44 $ * * 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 OOX_CORE_FRAGMENTHANDLER_HXX #define OOX_CORE_FRAGMENTHANDLER_HXX #include <com/sun/star/xml/sax/XFastDocumentHandler.hpp> #include <cppuhelper/implbase1.hxx> #include "oox/core/recordcontext.hxx" #include "oox/core/relations.hxx" #include "oox/core/xmlfilterbase.hxx" namespace oox { namespace core { class RecordParser; // ============================================================================ class FragmentHandler : public ::cppu::WeakImplHelper1< ::com::sun::star::xml::sax::XFastDocumentHandler >, public RecordContext { public: explicit FragmentHandler( const XmlFilterRef& rxFilter, const ::rtl::OUString& rFragmentPath ); explicit FragmentHandler( const XmlFilterRef& rxFilter, const ::rtl::OUString& rFragmentPath, RelationsRef xRelations ); /** Returns the filter instance. */ inline const XmlFilterRef& getFilter() const { return mxFilter; } /** Returns the full fragment path containing these relations. */ inline const Relations& getRelations() const { return *mxRelations; } /** Returns the full fragment path containing these relations. */ inline const ::rtl::OUString& getFragmentPath() const { return maFragmentPath; } /** Returns the full fragment path for the passed relative target. */ ::rtl::OUString getFragmentPathFromTarget( const ::rtl::OUString& rTarget ) const; /** Returns the full fragment path for the passed relation identifier. */ ::rtl::OUString getFragmentPathFromRelId( const ::rtl::OUString& rRelId ) const; /** Returns the full fragment path for the passed type. */ ::rtl::OUString getFragmentPathFromType( const ::rtl::OUString& rType ) const; /** Sets the record parser used to import binary streams. */ void setRecordParser( RecordParser& rParser ); /** Returns access to the record parser used to import binary streams. Needed for direct manipulation of the parser context stack via RecordParser::pushContext() and RecordParser::popContext(). Must not be called while loading XML fragments. */ RecordParser& getRecordParser(); // resolve ambiguity from base classes virtual void SAL_CALL acquire() throw() { ::cppu::OWeakObject::acquire(); } virtual void SAL_CALL release() throw() { ::cppu::OWeakObject::release(); } // com.sun.star.xml.sax.XFastDocumentHandler interface -------------------- virtual void SAL_CALL startDocument( ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endDocument( ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& xLocator ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); // com.sun.star.xml.sax.XFastContextHandler interface --------------------- virtual void SAL_CALL startFastElement( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL startUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); private: XmlFilterRef mxFilter; RelationsRef mxRelations; ::rtl::OUString maFragmentPath; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > mxLocator; RecordParser* mpParser; /// Pointer to record parser for binary import. }; typedef ::rtl::Reference< FragmentHandler > FragmentHandlerRef; // ============================================================================ } // namespace core } // namespace oox #endif // OOX_CORE_FRAGMENTHANDLER_HXX <commit_msg>INTEGRATION: CWS xmlfilter03_DEV300 (1.2.4); FILE MERGED 2008/02/07 13:40:49 dr 1.2.4.5: add fragment base path to relations 2008/02/05 14:05:05 dr 1.2.4.4: oox::core::ContextHandler2 and oox::core::FragmentHandler2 for convenience 2008/02/04 13:31:15 dr 1.2.4.3: rework of fragment handler/context handler base classes 2008/02/01 09:53:54 dr 1.2.4.2: addShape() code cleanup, started xlsx drawing import 2008/01/24 14:56:40 dr 1.2.4.1: OOBIN additions, BIFF string handling<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fragmenthandler.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-03-05 17:34:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef OOX_CORE_FRAGMENTHANDLER_HXX #define OOX_CORE_FRAGMENTHANDLER_HXX #include <com/sun/star/xml/sax/XFastDocumentHandler.hpp> #include <cppuhelper/implbase1.hxx> #include "oox/core/contexthandler.hxx" #include "oox/core/relations.hxx" namespace oox { namespace core { // ============================================================================ /** Base data of a fragment. This data is stored in a separate struct to make it accessible in every child context handler of the fragment. */ struct FragmentBaseData { XmlFilterBase& mrFilter; const ::rtl::OUString maFragmentPath; ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > mxLocator; RelationsRef mxRelations; explicit FragmentBaseData( XmlFilterBase& rFilter, const ::rtl::OUString& rFragmentPath, RelationsRef xRelations ); }; // ============================================================================ /** Describes record identifiers used to create contexts in a binary stream. If a record is used to start a new context, usually the record identifier increased by 1 is used to mark the end of this context, e.g. the Excel record SHEETDATA == 0x0091 starts the <sheetData> context, and the record SHEETDATA_END == 0x0092 ends this context. But some records are used to start a new context, though there is no identifier to end this context, e.g. the ROW or EXTROW records. These record identifiers can be marked by setting the mnEndRecId member of this struct to -1. */ struct RecordInfo { sal_Int32 mnStartRecId; /// Record identifier for context start. sal_Int32 mnEndRecId; /// Record identifier for context end, -1 = no record. }; // ============================================================================ typedef ::cppu::ImplInheritanceHelper1< ContextHandler, ::com::sun::star::xml::sax::XFastDocumentHandler > FragmentHandlerImplBase; class FragmentHandler : public FragmentHandlerImplBase { public: explicit FragmentHandler( XmlFilterBase& rFilter, const ::rtl::OUString& rFragmentPath ); virtual ~FragmentHandler(); /** Returns the com.sun.star.xml.sax.XFastContextHandler interface of this context. */ inline ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > getFastContextHandler() { return static_cast< ContextHandler* >( this ); } // com.sun.star.xml.sax.XFastDocumentHandler interface -------------------- virtual void SAL_CALL startDocument() throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endDocument() throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL setDocumentLocator( const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >& rxLocator ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); // com.sun.star.xml.sax.XFastContextHandler interface --------------------- virtual void SAL_CALL startFastElement( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL startUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endFastElement( ::sal_Int32 Element ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL endUnknownElement( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL createUnknownChildContext( const ::rtl::OUString& Namespace, const ::rtl::OUString& Name, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL characters( const ::rtl::OUString& aChars ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL ignorableWhitespace( const ::rtl::OUString& aWhitespaces ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL processingInstruction( const ::rtl::OUString& aTarget, const ::rtl::OUString& aData ) throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException); // binary records --------------------------------------------------------- virtual const RecordInfo* getRecordInfos() const; protected: explicit FragmentHandler( XmlFilterBase& rFilter, const ::rtl::OUString& rFragmentPath, RelationsRef xRelations ); }; typedef ::rtl::Reference< FragmentHandler > FragmentHandlerRef; // ============================================================================ } // namespace core } // namespace oox #endif <|endoftext|>
<commit_before>// @(#)root/textinput:$Id$ // Author: Axel Naumann <axel@cern.ch>, 2011-05-21 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Getline.h" #include <algorithm> #include <string> #include <sstream> #include "textinput/TextInput.h" #include "textinput/TextInputContext.h" #include "textinput/History.h" #include "textinput/TerminalDisplay.h" #include "textinput/StreamReader.h" #include "textinput/Callbacks.h" #include "Getline_color.h" #include "TApplication.h" extern "C" { int (* Gl_in_key)(int ch) = 0; int (* Gl_beep_hook)() = 0; } using namespace textinput; namespace { // TTabCom adapter. class ROOTTabCompletion: public TabCompletion { public: ROOTTabCompletion(): fLineBuf(new char[fgLineBufSize]) {} virtual ~ROOTTabCompletion() { delete []fLineBuf; } ROOTTabCompletion(const ROOTTabCompletion&) = delete; ROOTTabCompletion& operator=(const ROOTTabCompletion&) = delete; // Returns false on error bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/, EditorRange& r /*out*/, std::vector<std::string>& displayCompletions /*out*/) { strlcpy(fLineBuf, line.GetText().c_str(), fgLineBufSize); int cursorInt = (int) cursor; std::stringstream sstr; size_t posFirstChange = gApplication->TabCompletionHook(fLineBuf, &cursorInt, sstr); if (posFirstChange == (size_t) -1) { // no change return true; } line = std::string(fLineBuf); std::string compLine; while (std::getline(sstr, compLine)) { displayCompletions.push_back(compLine); } std::sort(displayCompletions.begin(), displayCompletions.end()); size_t lenLineBuf = strlen(fLineBuf); if (posFirstChange == (size_t) -2) { // redraw whole line, incl prompt r.fEdit.Extend(Range::AllWithPrompt()); r.fDisplay.Extend(Range::AllWithPrompt()); } else { if (!lenLineBuf) { r.fEdit.Extend(Range::AllText()); r.fDisplay.Extend(Range::AllText()); } else { r.fEdit.Extend(Range(posFirstChange, Range::End())); r.fDisplay.Extend(Range(posFirstChange, Range::End())); } } cursor = (size_t)cursorInt; line.GetColors().resize(lenLineBuf); return true; } private: static const size_t fgLineBufSize; char* fLineBuf; }; const size_t ROOTTabCompletion::fgLineBufSize = 16*1024; class TClingTabCompletion: public TabCompletion { public: TClingTabCompletion() {} virtual ~TClingTabCompletion() {} TClingTabCompletion(const TClingTabCompletion&) = delete; TClingTabCompletion& operator=(const TClingTabCompletion&) = delete; // Returns false on error bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/, EditorRange& r /*out*/, std::vector<std::string>& completions /*out*/) { gInterpreter->CodeComplete(line.GetText(), cursor, completions); return true; } }; // Helper to define the lifetime of the TextInput singleton. class TextInputHolder { public: TextInputHolder(): fTextInput(*(fReader = StreamReader::Create()), *(fDisplay = TerminalDisplay::Create()), fgHistoryFile.c_str()) { fTextInput.SetColorizer(&fCol); fTextInput.SetCompletion(&fTabComp); fTextInput.EnableAutoHistAdd(false); History* Hist = fTextInput.GetContext()->GetHistory(); Hist->SetMaxDepth(fgSizeLines); Hist->SetPruneLength(fgSaveLines); } ~TextInputHolder() { // Delete allocated objects. delete fReader; delete fDisplay; } const char* TakeInput(bool force = false) { fTextInput.TakeInput(fInputLine, force); fInputLine += "\n"; // ROOT wants a trailing newline. return fInputLine.c_str(); } void SetColors(const char* colorTab, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { fCol.SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket, colorPrompt); } static void SetHistoryFile(const char* hist) { fgHistoryFile = hist; } static void SetHistSize(int size, int save) { fgSizeLines = size; fgSaveLines = save; } static TextInputHolder& getHolder() { // Controls initialization of static TextInput. static TextInputHolder sTIHolder; return sTIHolder; } static TextInput& get() { return getHolder().fTextInput; } private: TextInput fTextInput; // The singleton TextInput object. Display* fDisplay; // Default TerminalDisplay Reader* fReader; // Default StreamReader std::string fInputLine; // Taken from TextInput ROOT::TextInputColorizer fCol; // Colorizer ROOTTabCompletion fTabComp; // Tab completion handler / TTabCom adapter // Config values: static std::string fgHistoryFile; // # History file size, once HistSize is reached remove all but HistSave entries, // # set to 0 to turn off command recording. // # Can be overridden by environment variable ROOT_HIST=size[:save], // # the ":save" part is optional. // # Rint.HistSize: 500 // # Set to -1 for sensible default (80% of HistSize), set to 0 to disable history. // # Rint.HistSave: 400 static int fgSizeLines; static int fgSaveLines; }; int TextInputHolder::fgSizeLines = 500; int TextInputHolder::fgSaveLines = -1; std::string TextInputHolder::fgHistoryFile; } /************************ extern "C" part *********************************/ extern "C" { void Gl_config(const char* which, int value) { if (strcmp(which, "noecho") == 0) { TextInputHolder::get().MaskInput(value); } else { // unsupported directive printf("Gl_config unsupported: %s ?\n", which); } } void Gl_histadd(const char* buf) { TextInputHolder::get().AddHistoryLine(buf); } /* Wrapper around textinput. * Modes: -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup, 3 = clear input line */ const char* Getlinem(EGetLineMode mode, const char* prompt) { if (mode == kClear) { TextInputHolder::getHolder().TakeInput(true); return 0; } if (mode == kCleanUp) { TextInputHolder::get().ReleaseInputOutput(); return 0; } if (mode == kOneChar) { // Check first display: if !TTY, read full line. const textinput::Display* disp = TextInputHolder::get().GetContext()->GetDisplays()[0]; const textinput::TerminalDisplay* tdisp = 0; if (disp) tdisp = dynamic_cast<const textinput::TerminalDisplay*>(disp); if (tdisp && !tdisp->IsTTY()) { mode = kLine1; } } if (mode == kInit || mode == kLine1) { if (prompt) { TextInputHolder::get().SetPrompt(prompt); } // Trigger attach: TextInputHolder::get().Redraw(); if (mode == kInit) { return 0; } TextInputHolder::get().SetBlockingUntilEOL(); } else { // mode == kOneChar if (Gl_in_key) { // We really need to go key by key: TextInputHolder::get().SetMaxPendingCharsToRead(1); } else { // Can consume all pending characters TextInputHolder::get().SetReadingAllPendingChars(); } } TextInput::EReadResult res = TextInputHolder::get().ReadInput(); if (Gl_in_key) { (*Gl_in_key)(TextInputHolder::get().GetLastKey()); } if (res == TextInput::kRRReadEOLDelimiter) { return TextInputHolder::getHolder().TakeInput(); } else if (res == TextInput::kRREOF) { // ROOT expects "" and then Gl_eol() returning true return ""; } return NULL; } const char* Getline(const char* prompt) { // Get a line of user input, showing prompt. // Does not return after every character entered, but // only returns once the user has hit return. // For ROOT Getline.c backward compatibility reasons, // the returned value is volatile and will be overwritten // by the subsequent call to Getline() or Getlinem(), // so copy the string if it needs to stay around. // The returned value must not be deleted. // The returned string contains a trailing newline '\n'. return Getlinem(kLine1, prompt); } /******************* Simple C -> C++ forwards *********************************/ void Gl_histsize(int size, int save) { TextInputHolder::SetHistSize(size, save); } void Gl_histinit(const char* file) { // Has to be called before constructing TextInputHolder singleton. TextInputHolder::SetHistoryFile(file); } int Gl_eof() { return TextInputHolder::get().GetReadState() == TextInput::kRREOF; } void Gl_setColors(const char* colorTab, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // call to enhance.cxx to set colours TextInputHolder::getHolder().SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket, colorPrompt); } /******************** Superseded interface *********************************/ void Gl_setwidth(int /*w*/) { // ignored, handled by displays themselves. } void Gl_windowchanged() { // ignored, handled by displays themselves. } } // extern "C" <commit_msg>Comment out unused parameter<commit_after>// @(#)root/textinput:$Id$ // Author: Axel Naumann <axel@cern.ch>, 2011-05-21 /************************************************************************* * Copyright (C) 1995-2011, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Getline.h" #include <algorithm> #include <string> #include <sstream> #include "textinput/TextInput.h" #include "textinput/TextInputContext.h" #include "textinput/History.h" #include "textinput/TerminalDisplay.h" #include "textinput/StreamReader.h" #include "textinput/Callbacks.h" #include "Getline_color.h" #include "TApplication.h" extern "C" { int (* Gl_in_key)(int ch) = 0; int (* Gl_beep_hook)() = 0; } using namespace textinput; namespace { // TTabCom adapter. class ROOTTabCompletion: public TabCompletion { public: ROOTTabCompletion(): fLineBuf(new char[fgLineBufSize]) {} virtual ~ROOTTabCompletion() { delete []fLineBuf; } ROOTTabCompletion(const ROOTTabCompletion&) = delete; ROOTTabCompletion& operator=(const ROOTTabCompletion&) = delete; // Returns false on error bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/, EditorRange& r /*out*/, std::vector<std::string>& displayCompletions /*out*/) { strlcpy(fLineBuf, line.GetText().c_str(), fgLineBufSize); int cursorInt = (int) cursor; std::stringstream sstr; size_t posFirstChange = gApplication->TabCompletionHook(fLineBuf, &cursorInt, sstr); if (posFirstChange == (size_t) -1) { // no change return true; } line = std::string(fLineBuf); std::string compLine; while (std::getline(sstr, compLine)) { displayCompletions.push_back(compLine); } std::sort(displayCompletions.begin(), displayCompletions.end()); size_t lenLineBuf = strlen(fLineBuf); if (posFirstChange == (size_t) -2) { // redraw whole line, incl prompt r.fEdit.Extend(Range::AllWithPrompt()); r.fDisplay.Extend(Range::AllWithPrompt()); } else { if (!lenLineBuf) { r.fEdit.Extend(Range::AllText()); r.fDisplay.Extend(Range::AllText()); } else { r.fEdit.Extend(Range(posFirstChange, Range::End())); r.fDisplay.Extend(Range(posFirstChange, Range::End())); } } cursor = (size_t)cursorInt; line.GetColors().resize(lenLineBuf); return true; } private: static const size_t fgLineBufSize; char* fLineBuf; }; const size_t ROOTTabCompletion::fgLineBufSize = 16*1024; class TClingTabCompletion: public TabCompletion { public: TClingTabCompletion() {} virtual ~TClingTabCompletion() {} TClingTabCompletion(const TClingTabCompletion&) = delete; TClingTabCompletion& operator=(const TClingTabCompletion&) = delete; // Returns false on error bool Complete(Text& line /*in+out*/, size_t& cursor /*in+out*/, EditorRange& /* r */ /*out*/, std::vector<std::string>& completions /*out*/) { gInterpreter->CodeComplete(line.GetText(), cursor, completions); return true; } }; // Helper to define the lifetime of the TextInput singleton. class TextInputHolder { public: TextInputHolder(): fTextInput(*(fReader = StreamReader::Create()), *(fDisplay = TerminalDisplay::Create()), fgHistoryFile.c_str()) { fTextInput.SetColorizer(&fCol); fTextInput.SetCompletion(&fTabComp); fTextInput.EnableAutoHistAdd(false); History* Hist = fTextInput.GetContext()->GetHistory(); Hist->SetMaxDepth(fgSizeLines); Hist->SetPruneLength(fgSaveLines); } ~TextInputHolder() { // Delete allocated objects. delete fReader; delete fDisplay; } const char* TakeInput(bool force = false) { fTextInput.TakeInput(fInputLine, force); fInputLine += "\n"; // ROOT wants a trailing newline. return fInputLine.c_str(); } void SetColors(const char* colorTab, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { fCol.SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket, colorPrompt); } static void SetHistoryFile(const char* hist) { fgHistoryFile = hist; } static void SetHistSize(int size, int save) { fgSizeLines = size; fgSaveLines = save; } static TextInputHolder& getHolder() { // Controls initialization of static TextInput. static TextInputHolder sTIHolder; return sTIHolder; } static TextInput& get() { return getHolder().fTextInput; } private: TextInput fTextInput; // The singleton TextInput object. Display* fDisplay; // Default TerminalDisplay Reader* fReader; // Default StreamReader std::string fInputLine; // Taken from TextInput ROOT::TextInputColorizer fCol; // Colorizer ROOTTabCompletion fTabComp; // Tab completion handler / TTabCom adapter // Config values: static std::string fgHistoryFile; // # History file size, once HistSize is reached remove all but HistSave entries, // # set to 0 to turn off command recording. // # Can be overridden by environment variable ROOT_HIST=size[:save], // # the ":save" part is optional. // # Rint.HistSize: 500 // # Set to -1 for sensible default (80% of HistSize), set to 0 to disable history. // # Rint.HistSave: 400 static int fgSizeLines; static int fgSaveLines; }; int TextInputHolder::fgSizeLines = 500; int TextInputHolder::fgSaveLines = -1; std::string TextInputHolder::fgHistoryFile; } /************************ extern "C" part *********************************/ extern "C" { void Gl_config(const char* which, int value) { if (strcmp(which, "noecho") == 0) { TextInputHolder::get().MaskInput(value); } else { // unsupported directive printf("Gl_config unsupported: %s ?\n", which); } } void Gl_histadd(const char* buf) { TextInputHolder::get().AddHistoryLine(buf); } /* Wrapper around textinput. * Modes: -1 = init, 0 = line mode, 1 = one char at a time mode, 2 = cleanup, 3 = clear input line */ const char* Getlinem(EGetLineMode mode, const char* prompt) { if (mode == kClear) { TextInputHolder::getHolder().TakeInput(true); return 0; } if (mode == kCleanUp) { TextInputHolder::get().ReleaseInputOutput(); return 0; } if (mode == kOneChar) { // Check first display: if !TTY, read full line. const textinput::Display* disp = TextInputHolder::get().GetContext()->GetDisplays()[0]; const textinput::TerminalDisplay* tdisp = 0; if (disp) tdisp = dynamic_cast<const textinput::TerminalDisplay*>(disp); if (tdisp && !tdisp->IsTTY()) { mode = kLine1; } } if (mode == kInit || mode == kLine1) { if (prompt) { TextInputHolder::get().SetPrompt(prompt); } // Trigger attach: TextInputHolder::get().Redraw(); if (mode == kInit) { return 0; } TextInputHolder::get().SetBlockingUntilEOL(); } else { // mode == kOneChar if (Gl_in_key) { // We really need to go key by key: TextInputHolder::get().SetMaxPendingCharsToRead(1); } else { // Can consume all pending characters TextInputHolder::get().SetReadingAllPendingChars(); } } TextInput::EReadResult res = TextInputHolder::get().ReadInput(); if (Gl_in_key) { (*Gl_in_key)(TextInputHolder::get().GetLastKey()); } if (res == TextInput::kRRReadEOLDelimiter) { return TextInputHolder::getHolder().TakeInput(); } else if (res == TextInput::kRREOF) { // ROOT expects "" and then Gl_eol() returning true return ""; } return NULL; } const char* Getline(const char* prompt) { // Get a line of user input, showing prompt. // Does not return after every character entered, but // only returns once the user has hit return. // For ROOT Getline.c backward compatibility reasons, // the returned value is volatile and will be overwritten // by the subsequent call to Getline() or Getlinem(), // so copy the string if it needs to stay around. // The returned value must not be deleted. // The returned string contains a trailing newline '\n'. return Getlinem(kLine1, prompt); } /******************* Simple C -> C++ forwards *********************************/ void Gl_histsize(int size, int save) { TextInputHolder::SetHistSize(size, save); } void Gl_histinit(const char* file) { // Has to be called before constructing TextInputHolder singleton. TextInputHolder::SetHistoryFile(file); } int Gl_eof() { return TextInputHolder::get().GetReadState() == TextInput::kRREOF; } void Gl_setColors(const char* colorTab, const char* colorTabComp, const char* colorBracket, const char* colorBadBracket, const char* colorPrompt) { // call to enhance.cxx to set colours TextInputHolder::getHolder().SetColors(colorTab, colorTabComp, colorBracket, colorBadBracket, colorPrompt); } /******************** Superseded interface *********************************/ void Gl_setwidth(int /*w*/) { // ignored, handled by displays themselves. } void Gl_windowchanged() { // ignored, handled by displays themselves. } } // extern "C" <|endoftext|>
<commit_before>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include <cstdint> #include <cstdlib> #include <iostream> #include <string> #ifdef SPARROW_DEBUG # define CHECK(cond, msg) do {\ if (!(cond)) {\ std::cerr\ << "[" << __FILE__ << ":" << __LINE__ << "] "\ << "CHECKING FAILED: " << __func__ << "() - " << (msg) << std::endl;\ std::abort();\ }\ } while (false) #else # define CHECK(cond, msg) ((void)0) #endif #define UNREACHED() do {\ std::cerr\ << "[" << __FILE__ << ":" << __LINE__ << "] "\ << "UNREACHED: " << __func__ << "()" << std::endl;\ while (true) {}\ } while (false) namespace sparrow { using nil_t = std::nullptr_t; using byte_t = std::uint8_t; using ssz_t = std::int32_t; using sz_t = std::size_t; using i8_t = std::int8_t; using u8_t = std::uint8_t; using i16_t = std::int16_t; using u16_t = std::uint16_t; using i32_t = std::int32_t; using u32_t = std::uint32_t; using i64_t = std::int64_t; using u64_t = std::uint64_t; using str_t = std::string; class Copyable { protected: Copyable(void) noexcept = default; ~Copyable(void) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) = delete; UnCopyable& operator=(const UnCopyable&) = delete; }; namespace Xt { // Xtra utilities template <typename I, typename E> inline I as_int(E x) { return static_cast<I>(x); } template <typename E, typename I> inline E as_enum(I x) { return static_cast<E>(x); } template <typename T> inline u8_t as_u8(T x) { return static_cast<u8_t>(x); } template <typename T> inline void* as_address(T* x) { return reinterpret_cast<void*>(x); } template <typename T> inline const void* as_address(const T* x) { return reinterpret_cast<const void*>(x); } template <typename T> inline byte_t* as_bytes(T* x) { return reinterpret_cast<byte_t*>(x); } template <typename T> inline const byte_t* as_bytes(const T* x) { return reinterpret_cast<const byte_t*>(x); } template <typename Target, typename Source> inline Target* cast(Source* x) { return static_cast<Target*>(x); } template <typename Target, typename Source> inline Target* down(Source* x) { return dynamic_cast<Target*>(x); } } enum class ErrType { IO, MEMORY, LEXICAL, COMPILE, RUNTIME, }; void error_report(ErrType type, const char* fname, int line, const char* func, const char* format, ...); } #define IO_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::IO, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define MEM_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::MEMORY, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define LEX_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::LEXICAL, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define COMPILE_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::COMPILE, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define RUNTIME_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::RUNTIME, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) <commit_msg>:bug: fix(uncopyable): fixed uncopyable constructor<commit_after>// Copyright (c) 2019 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include <cstdint> #include <cstdlib> #include <iostream> #include <string> #ifdef SPARROW_DEBUG # define CHECK(cond, msg) do {\ if (!(cond)) {\ std::cerr\ << "[" << __FILE__ << ":" << __LINE__ << "] "\ << "CHECKING FAILED: " << __func__ << "() - " << (msg) << std::endl;\ std::abort();\ }\ } while (false) #else # define CHECK(cond, msg) ((void)0) #endif #define UNREACHED() do {\ std::cerr\ << "[" << __FILE__ << ":" << __LINE__ << "] "\ << "UNREACHED: " << __func__ << "()" << std::endl;\ while (true) {}\ } while (false) namespace sparrow { using nil_t = std::nullptr_t; using byte_t = std::uint8_t; using ssz_t = std::int32_t; using sz_t = std::size_t; using i8_t = std::int8_t; using u8_t = std::uint8_t; using i16_t = std::int16_t; using u16_t = std::uint16_t; using i32_t = std::int32_t; using u32_t = std::uint32_t; using i64_t = std::int64_t; using u64_t = std::uint64_t; using str_t = std::string; class Copyable { protected: Copyable(void) noexcept = default; ~Copyable(void) noexcept = default; }; class UnCopyable { UnCopyable(const UnCopyable&) = delete; UnCopyable& operator=(const UnCopyable&) = delete; protected: UnCopyable(void) noexcept = default; ~UnCopyable(void) noexcept = default; }; namespace Xt { // Xtra utilities template <typename I, typename E> inline I as_int(E x) { return static_cast<I>(x); } template <typename E, typename I> inline E as_enum(I x) { return static_cast<E>(x); } template <typename T> inline u8_t as_u8(T x) { return static_cast<u8_t>(x); } template <typename T> inline void* as_address(T* x) { return reinterpret_cast<void*>(x); } template <typename T> inline const void* as_address(const T* x) { return reinterpret_cast<const void*>(x); } template <typename T> inline byte_t* as_bytes(T* x) { return reinterpret_cast<byte_t*>(x); } template <typename T> inline const byte_t* as_bytes(const T* x) { return reinterpret_cast<const byte_t*>(x); } template <typename Target, typename Source> inline Target* cast(Source* x) { return static_cast<Target*>(x); } template <typename Target, typename Source> inline Target* down(Source* x) { return dynamic_cast<Target*>(x); } } enum class ErrType { IO, MEMORY, LEXICAL, COMPILE, RUNTIME, }; void error_report(ErrType type, const char* fname, int line, const char* func, const char* format, ...); } #define IO_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::IO, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define MEM_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::MEMORY, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define LEX_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::LEXICAL, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define COMPILE_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::COMPILE, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) #define RUNTIME_ERR(fmt, ...) sparrow::error_report(\ sparrow::ErrType::RUNTIME, __FILE__, __LINE__, __func__, (fmt), ##__VA_ARGS__) <|endoftext|>
<commit_before>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "core/Setup.h" #if OUZEL_COMPILE_OPENAL #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <objc/message.h> extern "C" id const AVAudioSessionCategoryAmbient; #endif #include "AudioDeviceAL.hpp" #include "core/Engine.hpp" #include "utils/Errors.hpp" #include "utils/Log.hpp" namespace ouzel { namespace audio { AudioDeviceAL::AudioDeviceAL(): AudioDevice(Audio::Driver::OPENAL) { #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil); #endif #if OUZEL_MULTITHREADED running = false; #endif std::fill(std::begin(bufferIds), std::end(bufferIds), 0); } AudioDeviceAL::~AudioDeviceAL() { #if OUZEL_MULTITHREADED running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (sourceId) { alSourceStop(sourceId); alSourcei(sourceId, AL_BUFFER, 0); alDeleteSources(1, &sourceId); if (checkOpenALError()) Log(Log::Level::ERR) << "Failed to delete OpenAL source"; } for (ALuint bufferId : bufferIds) { if (bufferId) { alDeleteBuffers(1, &bufferId); if (checkOpenALError()) Log(Log::Level::ERR) << "Failed to delete OpenAL buffer"; } } if (context) { alcMakeContextCurrent(nullptr); alcDestroyContext(context); } if (device) alcCloseDevice(device); } void AudioDeviceAL::init(bool debugAudio) { AudioDevice::init(debugAudio); const ALCchar* deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); if (deviceName) Log(Log::Level::INFO) << "Using " << deviceName << " for audio"; device = alcOpenDevice(deviceName); if (!device || checkALCError()) throw SystemError("Failed to create OpenAL device"); int capabilities[] = { ALC_FREQUENCY, 44100, ALC_STEREO_SOURCES, 4, 0, 0 }; context = alcCreateContext(device, capabilities); if (checkALCError()) throw SystemError("Failed to create OpenAL context"); alcMakeContextCurrent(context); if (checkALCError()) throw SystemError("Failed to make OpenAL context current"); #if !OUZEL_PLATFORM_EMSCRIPTEN format40 = alGetEnumValue("AL_FORMAT_QUAD16"); format51 = alGetEnumValue("AL_FORMAT_51CHN16"); format61 = alGetEnumValue("AL_FORMAT_61CHN16"); format71 = alGetEnumValue("AL_FORMAT_71CHN16"); #endif if (checkOpenALError()) Log(Log::Level::WARN) << "Failed to get OpenAL enum values"; alGenSources(1, &sourceId); if (checkOpenALError()) throw SystemError("Failed to create OpenAL source"); alGenBuffers(2, bufferIds); if (checkOpenALError()) throw SystemError("Failed to create OpenAL buffers"); switch (channels) { case 1: format = AL_FORMAT_MONO16; break; case 2: format = AL_FORMAT_STEREO16; break; case 4: format = format40; break; case 6: format = format51; break; case 7: format = format61; break; case 8: format = format71; break; default: throw SystemError("Invalid channel count"); } sampleFormat = Audio::SampleFormat::SINT16; getData(bufferSize / (channels * sizeof(int16_t)), data); alBufferData(bufferIds[0], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); getData(bufferSize / (channels * sizeof(int16_t)), data); alBufferData(bufferIds[1], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); nextBuffer = 0; alSourceQueueBuffers(sourceId, 2, bufferIds); if (checkOpenALError()) throw SystemError("Failed to queue OpenAL buffers"); alSourcePlay(sourceId); if (checkOpenALError()) throw SystemError("Failed to play OpenAL source"); #if OUZEL_MULTITHREADED running = true; audioThread = Thread(std::bind(&AudioDeviceAL::run, this), "Audio"); #endif } void AudioDeviceAL::process() { AudioDevice::process(); alcMakeContextCurrent(context); if (checkALCError()) throw SystemError("Failed to make OpenAL context current"); ALint buffersProcessed; alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed); if (checkOpenALError()) throw SystemError("Failed to get processed buffer count"); // requeue all processed buffers for (; buffersProcessed > 0; --buffersProcessed) { alSourceUnqueueBuffers(sourceId, 1, &bufferIds[nextBuffer]); if (checkOpenALError()) throw SystemError("Failed to unqueue OpenAL buffer"); if (!getData(bufferSize / (channels * sizeof(int16_t)), data)) throw SystemError("Failed to get data"); alBufferData(bufferIds[nextBuffer], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, 1, &bufferIds[nextBuffer]); if (checkOpenALError()) throw SystemError("Failed to queue OpenAL buffer"); ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { alSourcePlay(sourceId); if (checkOpenALError()) throw SystemError("Failed to play OpenAL source"); } // swap the buffer nextBuffer = (nextBuffer + 1) % 2; } } void AudioDeviceAL::run() { #if OUZEL_MULTITHREADED while (running) process(); #endif } } // namespace audio } // namespace ouzel #endif <commit_msg>Don't log errors in the destructor<commit_after>// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "core/Setup.h" #if OUZEL_COMPILE_OPENAL #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS #include <objc/message.h> extern "C" id const AVAudioSessionCategoryAmbient; #endif #include "AudioDeviceAL.hpp" #include "core/Engine.hpp" #include "utils/Errors.hpp" namespace ouzel { namespace audio { AudioDeviceAL::AudioDeviceAL(): AudioDevice(Audio::Driver::OPENAL) { #if OUZEL_PLATFORM_IOS || OUZEL_PLATFORM_TVOS id audioSession = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("AVAudioSession"), sel_getUid("sharedInstance")); reinterpret_cast<BOOL (*)(id, SEL, id, id)>(&objc_msgSend)(audioSession, sel_getUid("setCategory:error:"), AVAudioSessionCategoryAmbient, nil); #endif #if OUZEL_MULTITHREADED running = false; #endif std::fill(std::begin(bufferIds), std::end(bufferIds), 0); } AudioDeviceAL::~AudioDeviceAL() { #if OUZEL_MULTITHREADED running = false; if (audioThread.isJoinable()) audioThread.join(); #endif if (sourceId) { alSourceStop(sourceId); alSourcei(sourceId, AL_BUFFER, 0); alDeleteSources(1, &sourceId); checkOpenALError(); } for (ALuint bufferId : bufferIds) { if (bufferId) { alDeleteBuffers(1, &bufferId); checkOpenALError(); } } if (context) { alcMakeContextCurrent(nullptr); alcDestroyContext(context); } if (device) alcCloseDevice(device); } void AudioDeviceAL::init(bool debugAudio) { AudioDevice::init(debugAudio); const ALCchar* deviceName = alcGetString(nullptr, ALC_DEFAULT_DEVICE_SPECIFIER); if (deviceName) Log(Log::Level::INFO) << "Using " << deviceName << " for audio"; device = alcOpenDevice(deviceName); if (!device || checkALCError()) throw SystemError("Failed to create OpenAL device"); int capabilities[] = { ALC_FREQUENCY, 44100, ALC_STEREO_SOURCES, 4, 0, 0 }; context = alcCreateContext(device, capabilities); if (checkALCError()) throw SystemError("Failed to create OpenAL context"); alcMakeContextCurrent(context); if (checkALCError()) throw SystemError("Failed to make OpenAL context current"); #if !OUZEL_PLATFORM_EMSCRIPTEN format40 = alGetEnumValue("AL_FORMAT_QUAD16"); format51 = alGetEnumValue("AL_FORMAT_51CHN16"); format61 = alGetEnumValue("AL_FORMAT_61CHN16"); format71 = alGetEnumValue("AL_FORMAT_71CHN16"); #endif if (checkOpenALError()) Log(Log::Level::WARN) << "Failed to get OpenAL enum values"; alGenSources(1, &sourceId); if (checkOpenALError()) throw SystemError("Failed to create OpenAL source"); alGenBuffers(2, bufferIds); if (checkOpenALError()) throw SystemError("Failed to create OpenAL buffers"); switch (channels) { case 1: format = AL_FORMAT_MONO16; break; case 2: format = AL_FORMAT_STEREO16; break; case 4: format = format40; break; case 6: format = format51; break; case 7: format = format61; break; case 8: format = format71; break; default: throw SystemError("Invalid channel count"); } sampleFormat = Audio::SampleFormat::SINT16; getData(bufferSize / (channels * sizeof(int16_t)), data); alBufferData(bufferIds[0], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); getData(bufferSize / (channels * sizeof(int16_t)), data); alBufferData(bufferIds[1], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); nextBuffer = 0; alSourceQueueBuffers(sourceId, 2, bufferIds); if (checkOpenALError()) throw SystemError("Failed to queue OpenAL buffers"); alSourcePlay(sourceId); if (checkOpenALError()) throw SystemError("Failed to play OpenAL source"); #if OUZEL_MULTITHREADED running = true; audioThread = Thread(std::bind(&AudioDeviceAL::run, this), "Audio"); #endif } void AudioDeviceAL::process() { AudioDevice::process(); alcMakeContextCurrent(context); if (checkALCError()) throw SystemError("Failed to make OpenAL context current"); ALint buffersProcessed; alGetSourcei(sourceId, AL_BUFFERS_PROCESSED, &buffersProcessed); if (checkOpenALError()) throw SystemError("Failed to get processed buffer count"); // requeue all processed buffers for (; buffersProcessed > 0; --buffersProcessed) { alSourceUnqueueBuffers(sourceId, 1, &bufferIds[nextBuffer]); if (checkOpenALError()) throw SystemError("Failed to unqueue OpenAL buffer"); if (!getData(bufferSize / (channels * sizeof(int16_t)), data)) throw SystemError("Failed to get data"); alBufferData(bufferIds[nextBuffer], format, data.data(), static_cast<ALsizei>(data.size()), static_cast<ALsizei>(sampleRate)); alSourceQueueBuffers(sourceId, 1, &bufferIds[nextBuffer]); if (checkOpenALError()) throw SystemError("Failed to queue OpenAL buffer"); ALint state; alGetSourcei(sourceId, AL_SOURCE_STATE, &state); if (state != AL_PLAYING) { alSourcePlay(sourceId); if (checkOpenALError()) throw SystemError("Failed to play OpenAL source"); } // swap the buffer nextBuffer = (nextBuffer + 1) % 2; } } void AudioDeviceAL::run() { #if OUZEL_MULTITHREADED while (running) process(); #endif } } // namespace audio } // namespace ouzel #endif <|endoftext|>
<commit_before>#include "controller/rocket_angular_acceleration_controller.hpp" #include <algorithm> #include "unit_config.hpp" RocketAngularAccelerationController::RocketAngularAccelerationController() : rollAccPid(unit_config::ANGACC_X_KP, unit_config::ANGACC_X_KI, unit_config::ANGACC_X_KD), pitchAccPid(unit_config::ANGACC_Y_KP, unit_config::ANGACC_Y_KI, unit_config::ANGACC_Y_KD), yawAccPid(unit_config::ANGACC_Z_KP, unit_config::ANGACC_Z_KI, unit_config::ANGACC_Z_KD) { } actuator_setpoint_t RocketAngularAccelerationController::run(const attitude_estimate_t& estimate, const angular_acceleration_setpoint_t& input) { // Limit to maximum angular accelerations float rollAccSp = std::max(-unit_config::MAX_PITCH_ROLL_ACC, std::min(unit_config::MAX_PITCH_ROLL_ACC, input.roll_acc_sp)); float pitchAccSp = std::max(-unit_config::MAX_PITCH_ROLL_ACC, std::min(unit_config::MAX_PITCH_ROLL_ACC, input.pitch_acc_sp)); // Constants const float M_PI = 3.1415926535; const float F_LE = M_PI * 7/18; // Fin leading edge angle (rad) const float F_TR = 0; // Fin trailing edge distance past fin base (m) const float F_LEN = 0.123; // Fin length (m) const float F_AREA = 0.0027552; // Fin area (m^2) const float F_CP = 0.33 * F_LEN; // Fin Cp (m) const float F_NUM = 2; // Number of fins const float F_D = 0.06477; // Distance from roll axis to fin Cp (m) const float I = 1; // TODO: Rocket rotational inertia // Sensor inputs float alt = 4900; // Altitude (m) float v_rocket = 0; // TODO: Magically figure this out from sensors (m/s) // TODO: Expand estimate to full 12-space // Calculate atmospheric pressure. We should eventually get this from MS5611. // Eq. 9 from "A Quick Derivation relating altitude to air pressure", PSAS, // 2004. float pressure = 100*pow((44331.514-alt)/11880.516, 5.255877); // Pressure (Pa) float temp = 273.15; // Absolute temperature (K) TODO: add external thermistor // Calculate air density, speed of sound float p_air = pressure/(287.058*temp); // Air density from ideal gas law (kg/m^3) float v_air = 20.05*sqrt(temp+273.15); // Speed of sound (m/s) // Mach number float M = v_rocket / v_air; // Mach number // Mach angle float u = asin(1/M); // Unicorn float beta = sqrt(pow(M,2) - 1); // Bollocks float m = beta * tan(M_PI/2 - F_LE); // Magic cot(x) = tan(pi/2 - x) // Elliptic Integral const float a[] = {0.44325141463, 0.06260601220, 0.04757383546, 0.01736506451}; const float b[] = {0.24998368310, 0.09200180037, 0.04069697526, 0.00526449639}; float E = 1; for (int i=0; i<4; i++) { E += a[i]*pow(m,2*(i+1)) + log(1/pow(m,2))*b[i]*pow(m,2*(i+1)); // 0 <= m < 1 } // Lift coefficient float C_L = (2 * M_PI * m) / (E * beta); // Roll controller float torque = I * rollAccSp; float F_L = torque / (F_NUM * F_D); // Force required per fin (N) // Fin controller float rollActuatorSp = (2*F_L) / (C_L * p_air * pow(v_air,2) * F_AREA); // Output fin angle // Output actuator_setpoint_t setpoint { .roll_sp = rollActuatorSp, .pitch_sp = 0.0f, .yaw_sp = 0.0f, .throttle_sp = input.throttle_sp }; return setpoint; } <commit_msg>Fix rocket equations for subsonic flight.<commit_after>#include "controller/rocket_angular_acceleration_controller.hpp" #include <algorithm> #include "unit_config.hpp" RocketAngularAccelerationController::RocketAngularAccelerationController() : rollAccPid(unit_config::ANGACC_X_KP, unit_config::ANGACC_X_KI, unit_config::ANGACC_X_KD), pitchAccPid(unit_config::ANGACC_Y_KP, unit_config::ANGACC_Y_KI, unit_config::ANGACC_Y_KD), yawAccPid(unit_config::ANGACC_Z_KP, unit_config::ANGACC_Z_KI, unit_config::ANGACC_Z_KD) { } actuator_setpoint_t RocketAngularAccelerationController::run(const attitude_estimate_t& estimate, const angular_acceleration_setpoint_t& input) { // Limit to maximum angular accelerations float rollAccSp = std::max(-unit_config::MAX_PITCH_ROLL_ACC, std::min(unit_config::MAX_PITCH_ROLL_ACC, input.roll_acc_sp)); float pitchAccSp = std::max(-unit_config::MAX_PITCH_ROLL_ACC, std::min(unit_config::MAX_PITCH_ROLL_ACC, input.pitch_acc_sp)); // Constants const float M_PI = 3.1415926535; const float F_LE = M_PI * 7/18; // Fin leading edge angle (rad) const float F_TR = 0; // Fin trailing edge distance past fin base (m) const float F_LEN = 0.123; // Fin length (m) const float F_AREA = 0.0027552; // Fin area (m^2) const float F_CP = 0.33 * F_LEN; // Fin Cp (m) const float F_NUM = 2; // Number of fins const float F_D = 0.06477; // Distance from roll axis to fin Cp (m) const float I = 1; // TODO: Rocket rotational inertia // Sensor inputs float alt = 1414; // Altitude (m) float v_rocket = 50; // TODO: Magically figure this out from sensors (m/s) // TODO: Expand estimate to full 12-space // Calculate atmospheric pressure. We should eventually get this from MS5611. // Eq. 9 from "A Quick Derivation relating altitude to air pressure", PSAS, // 2004. float pressure = 100*pow((44331.514-alt)/11880.516, 5.255877); // Pressure (Pa) float temp = 273.15; // Absolute temperature (K) TODO: add external thermistor // Calculate air density, speed of sound float p_air = pressure/(287.058*temp); // Air density from ideal gas law (kg/m^3) float v_air = 20.05*sqrt(temp); // Speed of sound (m/s) // Mach number float M = v_rocket / v_air; // Mach number // Mach angle //float u = asin(1/M); // Unicorn //float beta = sqrt(pow(M,2) - 1); // Bollocks //float m = beta * tan(M_PI/2 - F_LE); // Magic cot(x) = tan(pi/2 - x) // Elliptic Integral //const float a[] = {0.44325141463, // 0.06260601220, // 0.04757383546, // 0.01736506451}; //const float b[] = {0.24998368310, // 0.09200180037, // 0.04069697526, // 0.00526449639}; //float E = 1; //for (int i=0; i<4; i++) { // E += a[i]*pow(m,2*(i+1)) + log(1/pow(m,2))*b[i]*pow(m,2*(i+1)); // 0 <= m < 1 //} // Roll controller float torque = I * rollAccSp; float F_L = torque / (F_NUM * F_D); // Force required per fin (N) // Lift coefficient float C_L = 2*F_L/(p_air * pow(v_rocket,2) * F_AREA); // Subsonic //float C_L = (2 * M_PI * m) / (E * beta); // Supersonic // Fin controller float rollActuatorSp = 0.5 + C_L/(2*M_PI); // Fin angle // Output actuator_setpoint_t setpoint { .roll_sp = rollActuatorSp, .pitch_sp = 0.0f, .yaw_sp = 0.0f, .throttle_sp = input.throttle_sp }; return setpoint; } <|endoftext|>
<commit_before>/** \brief Utility for creating ngram language models. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <stdexcept> #include <cstdlib> #include "BinaryIO.h" #include "FileUtil.h" #include "NGram.h" #include "util.h" int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("language_blob language_model\n" "The \"language_blob\" should be a file containing example text w/o markup in whatever language.\n" "\"language_model\" should be named after the language followed by \".lm\".\n"); std::ifstream input(argv[1]); if (not input) LOG_ERROR("failed to open \"" + std::string(argv[1]) + "\" for reading!"); NGram::NGramCounts ngram_counts; NGram::SortedNGramCounts sorted_ngram_counts; NGram::CreateLanguageModel(input, &ngram_counts, &sorted_ngram_counts); const auto output(FileUtil::OpenOutputFileOrDie(argv[2])); BinaryIO::WriteOrDie(*output, ngram_counts.size()); for (const auto &ngram_and_rank : sorted_ngram_counts) { BinaryIO::WriteOrDie(*output, ngram_and_rank.first); BinaryIO::WriteOrDie(*output, ngram_and_rank.second); } return EXIT_SUCCESS; } <commit_msg>Fixed a bug.<commit_after>/** \brief Utility for creating ngram language models. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <stdexcept> #include <cstdlib> #include "BinaryIO.h" #include "FileUtil.h" #include "NGram.h" #include "util.h" int Main(int argc, char *argv[]) { if (argc != 3) ::Usage("language_blob language_model\n" "The \"language_blob\" should be a file containing example text w/o markup in whatever language.\n" "\"language_model\" should be named after the language followed by \".lm\".\n"); std::ifstream input(argv[1]); if (not input) LOG_ERROR("failed to open \"" + std::string(argv[1]) + "\" for reading!"); NGram::NGramCounts ngram_counts; NGram::SortedNGramCounts sorted_ngram_counts; NGram::CreateLanguageModel(input, &ngram_counts, &sorted_ngram_counts); const auto output(FileUtil::OpenOutputFileOrDie(argv[2])); BinaryIO::WriteOrDie(*output, sorted_ngram_counts.size()); for (const auto &ngram_and_rank : sorted_ngram_counts) { BinaryIO::WriteOrDie(*output, ngram_and_rank.first); BinaryIO::WriteOrDie(*output, ngram_and_rank.second); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/** \brief MARC grep the Next Generation. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "Compiler.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("--query=query [--output-format=output_format] marc_file1 [marc_file2 .. marc_fileN]\n" "Queries have the following syntax:\n" "expression → term {OR term}\n" "term → factor {AND factor}\n" "factor → field_or_subfield_reference (== | !=) string_constant_or_regex\n" "factor → NOT factor\n" "factor → '(' expression ')'\n" ); std::exit(EXIT_FAILURE); } enum TokenType { AND, OR, NOT, STRING_CONST, FUNC_CALL, OPEN_PAREN, CLOSE_PAREN, REGEX, EQUALS, NOT_EQUALS, COMMA, ERROR, END_OF_QUERY }; class Tokenizer { struct FunctionDesc { std::string name_; unsigned argument_count_; }; std::string::const_iterator next_ch_; const std::string::const_iterator end_; bool pushed_back_; TokenType last_token_; std::string last_error_message_; std::string last_string_; std::string last_function_name_; const static std::vector<FunctionDesc> function_descriptions_; public: explicit Tokenizer(const std:: string &query): next_ch_(query.cbegin()), end_(query.cend()), pushed_back_(false) { } TokenType getNextToken(); void ungetLastToken(); inline const std::string &getLastErrorMessage() const { return last_error_message_; } inline const std::string &getLastString() const { return last_string_; } inline const std::string &getLastFunctionName() const { return last_function_name_; } static std::string TokenTypeToString(const TokenType token); private: TokenType parseStringConstantOrRegex(); bool isKnownFunctionName(const std::string &name_candidate) const; }; const std::vector<Tokenizer::FunctionDesc> Tokenizer::function_descriptions_{ { "HasField", 1 }, { "HasSubfield", 2} }; TokenType Tokenizer::getNextToken() { if (pushed_back_) { pushed_back_ = false; return last_token_; } // Skip over spaces: while (next_ch_ != end_ and *next_ch_ == ' ') ++next_ch_; if (next_ch_ == end_) return last_token_ = END_OF_QUERY; if (*next_ch_ == '"' or *next_ch_ == '/') return last_token_ = parseStringConstantOrRegex(); if (*next_ch_ == ',') { ++next_ch_; return last_token_ = COMMA; } if (*next_ch_ == '(') { ++next_ch_; return last_token_ = OPEN_PAREN; } if (*next_ch_ == ')') { ++next_ch_; return last_token_ = CLOSE_PAREN; } if (*next_ch_ == '=') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single equal sign found!"; return ERROR; } return last_token_ = EQUALS; } if (*next_ch_ == '!') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single exclamation point found!"; return ERROR; } return last_token_ = NOT_EQUALS; } if (unlikely(not StringUtil::IsAsciiLetter(*next_ch_))) { last_error_message_ = "expected ASCII letter!"; return ERROR; } std::string id; while (next_ch_ != end_ and StringUtil::IsAsciiLetter(*next_ch_)) id += *next_ch_; if (id == "AND") return last_token_ = AND; if (id == "OR") return last_token_ = OR; if (id == "NOT") return last_token_ = NOT; if (isKnownFunctionName(id)) { last_function_name_ = id; return last_token_ = FUNC_CALL; } last_error_message_ = "unknown function name \"" + id + "\"!"; return ERROR; } void Tokenizer::ungetLastToken() { if (unlikely(pushed_back_)) LOG_ERROR("can't push back two tokens in a row!"); pushed_back_ = true; } TokenType Tokenizer::parseStringConstantOrRegex() { const char terminator(*next_ch_++); last_string_.clear(); bool escaped(false); for (/* Intentionally empty! */; next_ch_ != end_; ++next_ch_) { if (escaped) { escaped = false; last_string_ += *next_ch_; } else if (*next_ch_ == terminator) { ++next_ch_; return (terminator == '"') ? STRING_CONST : REGEX; } else if (*next_ch_ == '\\') escaped = true; else last_string_ += *next_ch_; } last_error_message_ = "unterminated string constant or regex!"; return ERROR; } bool Tokenizer::isKnownFunctionName(const std::string &name_candidate) const { for (const auto &function_description : function_descriptions_) { if (function_description.name_ == name_candidate) return true; } return false; } std::string Tokenizer::TokenTypeToString(const TokenType token) { switch (token) { case AND: return "AND"; case OR: return "OR"; case NOT: return "NOT"; case STRING_CONST: return "string constant"; case FUNC_CALL: return "function call"; case OPEN_PAREN: return "("; case CLOSE_PAREN: return ")"; case REGEX: return "regular expression"; case EQUALS: return "=="; case NOT_EQUALS: return "!="; case COMMA: return ","; case ERROR: return "unexpected input"; case END_OF_QUERY: return "end-of-query"; } } class Query { enum NodeType { AND_NODE, OR_NODE, STRING_COMPARISON_NODE, REGEX_COMPARISON_NODE }; class Node { protected: Node() {} public: virtual ~Node() = 0; virtual NodeType getNodeType() const = 0; virtual bool eval(const MARC::Record &record) const = 0; }; class AndNode final : public Node { std::vector<Node *> children_; public: AndNode() { } ~AndNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return AND_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class OrNode final : public Node { std::vector<Node *> children_; public: OrNode() { } ~OrNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return OR_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class StringComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; std::string string_const_; bool invert_; public: StringComparisonNode(const std::string &field_or_subfield_reference, const std::string &string_const, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), string_const_(string_const), invert_(invert) { } ~StringComparisonNode() = default; virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; Tokenizer tokenizer_; public: explicit Query(const std:: string &query); bool matched(const MARC::Record &record) const; private: void ParseExpression(); void ParseTerm(); void ParseFactor(); }; Query::Node::~Node() { /* Intentionally empty! */ } bool Query::AndNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (not child_node->eval(record)) return false; } return true; } bool Query::OrNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (child_node->eval(record)) return true; } return false; } bool Query::StringComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (field .getContents() == string_const_) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (value_and_code.value_ == string_const_) { if (not invert_) return true; } else if (invert_) return true; } } } } return invert_; } Query::Query(const std:: string &query): tokenizer_(query) { ParseExpression(); } bool Query::matched(const MARC::Record &/*record*/) const { return false; } void Query::ParseExpression() { ParseTerm(); TokenType token(tokenizer_.getNextToken()); while (token == OR) { ParseTerm(); token = tokenizer_.getNextToken(); } tokenizer_.ungetLastToken(); } void Query::ParseTerm() { ParseFactor(); TokenType token(tokenizer_.getNextToken()); while (token == AND) { ParseFactor(); token = tokenizer_.getNextToken(); } tokenizer_.ungetLastToken(); } void Query::ParseFactor() { TokenType token(tokenizer_.getNextToken()); if (token == STRING_CONST) { if (tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH and tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH + 1) throw std::runtime_error("invalid field or subfield reference \"" + tokenizer_.getLastString() + "\"!"); token = tokenizer_.getNextToken(); if (token != EQUALS and token != NOT_EQUALS) throw std::runtime_error("expected == or != after field or subfield reference, found " + Tokenizer::TokenTypeToString(token) + " instead!"); const TokenType last_token(token); token = tokenizer_.getNextToken(); if (token != STRING_CONST and token != REGEX) throw std::runtime_error("expected a string constant or a regex after " + Tokenizer::TokenTypeToString(last_token) + ", found " + Tokenizer::TokenTypeToString(token) + " instead!"); return; } if (token == NOT) { ParseFactor(); return; } if (token != OPEN_PAREN) throw std::runtime_error("opening parenthesis, NOT or string constant expected found " + Tokenizer::TokenTypeToString(token) + "instead!"); ParseExpression(); token = tokenizer_.getNextToken(); if (token != CLOSE_PAREN) throw std::runtime_error("closing parenthesis after expression expected, found " + Tokenizer::TokenTypeToString(token) + "instead!"); } void ProcessRecords(const Query &query, MARC::Reader * const marc_reader) { unsigned record_count(0), matched_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; if (not query.matched(record)) continue; ++matched_count; } std::cerr << "Matched " << matched_count << " of " << record_count << " records.\n"; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) Usage(); if (not StringUtil::StartsWith(argv[1], "--query=")) LOG_ERROR("missing --query=...!"); const std::string query_str(argv[1] + __builtin_strlen("--query=")); Query query(query_str); if (argc < 3) Usage(); for (int arg_no(1); arg_no < argc; ++arg_no) { auto marc_reader(MARC::Reader::Factory(argv[1])); ProcessRecords(query, marc_reader.get()); } return EXIT_SUCCESS; } <commit_msg>Fixed a return value.<commit_after>/** \brief MARC grep the Next Generation. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <cstdlib> #include "Compiler.h" #include "MARC.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage("--query=query [--output-format=output_format] marc_file1 [marc_file2 .. marc_fileN]\n" "Queries have the following syntax:\n" "expression → term {OR term}\n" "term → factor {AND factor}\n" "factor → field_or_subfield_reference (== | !=) string_constant_or_regex\n" "factor → NOT factor\n" "factor → '(' expression ')'\n" ); std::exit(EXIT_FAILURE); } enum TokenType { AND, OR, NOT, STRING_CONST, FUNC_CALL, OPEN_PAREN, CLOSE_PAREN, REGEX, EQUALS, NOT_EQUALS, COMMA, ERROR, END_OF_QUERY }; class Tokenizer { struct FunctionDesc { std::string name_; unsigned argument_count_; }; std::string::const_iterator next_ch_; const std::string::const_iterator end_; bool pushed_back_; TokenType last_token_; std::string last_error_message_; std::string last_string_; std::string last_function_name_; const static std::vector<FunctionDesc> function_descriptions_; public: explicit Tokenizer(const std:: string &query): next_ch_(query.cbegin()), end_(query.cend()), pushed_back_(false) { } TokenType getNextToken(); void ungetLastToken(); inline const std::string &getLastErrorMessage() const { return last_error_message_; } inline const std::string &getLastString() const { return last_string_; } inline const std::string &getLastFunctionName() const { return last_function_name_; } static std::string TokenTypeToString(const TokenType token); private: TokenType parseStringConstantOrRegex(); bool isKnownFunctionName(const std::string &name_candidate) const; }; const std::vector<Tokenizer::FunctionDesc> Tokenizer::function_descriptions_{ { "HasField", 1 }, { "HasSubfield", 2} }; TokenType Tokenizer::getNextToken() { if (pushed_back_) { pushed_back_ = false; return last_token_; } // Skip over spaces: while (next_ch_ != end_ and *next_ch_ == ' ') ++next_ch_; if (next_ch_ == end_) return last_token_ = END_OF_QUERY; if (*next_ch_ == '"' or *next_ch_ == '/') return last_token_ = parseStringConstantOrRegex(); if (*next_ch_ == ',') { ++next_ch_; return last_token_ = COMMA; } if (*next_ch_ == '(') { ++next_ch_; return last_token_ = OPEN_PAREN; } if (*next_ch_ == ')') { ++next_ch_; return last_token_ = CLOSE_PAREN; } if (*next_ch_ == '=') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single equal sign found!"; return ERROR; } return last_token_ = EQUALS; } if (*next_ch_ == '!') { ++next_ch_; if (next_ch_ == end_ or *next_ch_ != '=') { last_error_message_ = "unexpected single exclamation point found!"; return ERROR; } return last_token_ = NOT_EQUALS; } if (unlikely(not StringUtil::IsAsciiLetter(*next_ch_))) { last_error_message_ = "expected ASCII letter!"; return ERROR; } std::string id; while (next_ch_ != end_ and StringUtil::IsAsciiLetter(*next_ch_)) id += *next_ch_; if (id == "AND") return last_token_ = AND; if (id == "OR") return last_token_ = OR; if (id == "NOT") return last_token_ = NOT; if (isKnownFunctionName(id)) { last_function_name_ = id; return last_token_ = FUNC_CALL; } last_error_message_ = "unknown function name \"" + id + "\"!"; return ERROR; } void Tokenizer::ungetLastToken() { if (unlikely(pushed_back_)) LOG_ERROR("can't push back two tokens in a row!"); pushed_back_ = true; } TokenType Tokenizer::parseStringConstantOrRegex() { const char terminator(*next_ch_++); last_string_.clear(); bool escaped(false); for (/* Intentionally empty! */; next_ch_ != end_; ++next_ch_) { if (escaped) { escaped = false; last_string_ += *next_ch_; } else if (*next_ch_ == terminator) { ++next_ch_; return (terminator == '"') ? STRING_CONST : REGEX; } else if (*next_ch_ == '\\') escaped = true; else last_string_ += *next_ch_; } last_error_message_ = "unterminated string constant or regex!"; return ERROR; } bool Tokenizer::isKnownFunctionName(const std::string &name_candidate) const { for (const auto &function_description : function_descriptions_) { if (function_description.name_ == name_candidate) return true; } return false; } std::string Tokenizer::TokenTypeToString(const TokenType token) { switch (token) { case AND: return "AND"; case OR: return "OR"; case NOT: return "NOT"; case STRING_CONST: return "string constant"; case FUNC_CALL: return "function call"; case OPEN_PAREN: return "("; case CLOSE_PAREN: return ")"; case REGEX: return "regular expression"; case EQUALS: return "=="; case NOT_EQUALS: return "!="; case COMMA: return ","; case ERROR: return "unexpected input"; case END_OF_QUERY: return "end-of-query"; } } class Query { enum NodeType { AND_NODE, OR_NODE, STRING_COMPARISON_NODE, REGEX_COMPARISON_NODE }; class Node { protected: Node() {} public: virtual ~Node() = 0; virtual NodeType getNodeType() const = 0; virtual bool eval(const MARC::Record &record) const = 0; }; class AndNode final : public Node { std::vector<Node *> children_; public: AndNode() { } ~AndNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return AND_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class OrNode final : public Node { std::vector<Node *> children_; public: OrNode() { } ~OrNode() { for (const auto child_node : children_) delete child_node; } virtual NodeType getNodeType() const override { return OR_NODE; } virtual bool eval(const MARC::Record &record) const override; }; class StringComparisonNode final : public Node { MARC::Tag field_tag_; char subfield_code_; std::string string_const_; bool invert_; public: StringComparisonNode(const std::string &field_or_subfield_reference, const std::string &string_const, const bool invert) : field_tag_(field_or_subfield_reference.substr(0, MARC::Record::TAG_LENGTH)), subfield_code_(field_or_subfield_reference.length() > MARC::Record::TAG_LENGTH ? field_or_subfield_reference[MARC::Record::TAG_LENGTH] : '\0'), string_const_(string_const), invert_(invert) { } ~StringComparisonNode() = default; virtual NodeType getNodeType() const override { return STRING_COMPARISON_NODE; } virtual bool eval(const MARC::Record &record) const override; }; Tokenizer tokenizer_; public: explicit Query(const std:: string &query); bool matched(const MARC::Record &record) const; private: void ParseExpression(); void ParseTerm(); void ParseFactor(); }; Query::Node::~Node() { /* Intentionally empty! */ } bool Query::AndNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (not child_node->eval(record)) return false; } return true; } bool Query::OrNode::eval(const MARC::Record &record) const { for (const auto child_node : children_) { if (child_node->eval(record)) return true; } return false; } bool Query::StringComparisonNode::eval(const MARC::Record &record) const { for (const auto &field : record.getTagRange(field_tag_)) { if (subfield_code_ == '\0') { if (field .getContents() == string_const_) { if (not invert_) return true; } else if (invert_) return true; } else { const MARC::Subfields subfields(field.getSubfields()); for (const auto &value_and_code : subfields) { if (value_and_code.code_ == subfield_code_) { if (value_and_code.value_ == string_const_) { if (not invert_) return true; } else if (invert_) return true; } } } } return false; } Query::Query(const std:: string &query): tokenizer_(query) { ParseExpression(); } bool Query::matched(const MARC::Record &/*record*/) const { return false; } void Query::ParseExpression() { ParseTerm(); TokenType token(tokenizer_.getNextToken()); while (token == OR) { ParseTerm(); token = tokenizer_.getNextToken(); } tokenizer_.ungetLastToken(); } void Query::ParseTerm() { ParseFactor(); TokenType token(tokenizer_.getNextToken()); while (token == AND) { ParseFactor(); token = tokenizer_.getNextToken(); } tokenizer_.ungetLastToken(); } void Query::ParseFactor() { TokenType token(tokenizer_.getNextToken()); if (token == STRING_CONST) { if (tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH and tokenizer_.getLastString().length() != MARC::Record::TAG_LENGTH + 1) throw std::runtime_error("invalid field or subfield reference \"" + tokenizer_.getLastString() + "\"!"); token = tokenizer_.getNextToken(); if (token != EQUALS and token != NOT_EQUALS) throw std::runtime_error("expected == or != after field or subfield reference, found " + Tokenizer::TokenTypeToString(token) + " instead!"); const TokenType last_token(token); token = tokenizer_.getNextToken(); if (token != STRING_CONST and token != REGEX) throw std::runtime_error("expected a string constant or a regex after " + Tokenizer::TokenTypeToString(last_token) + ", found " + Tokenizer::TokenTypeToString(token) + " instead!"); return; } if (token == NOT) { ParseFactor(); return; } if (token != OPEN_PAREN) throw std::runtime_error("opening parenthesis, NOT or string constant expected found " + Tokenizer::TokenTypeToString(token) + "instead!"); ParseExpression(); token = tokenizer_.getNextToken(); if (token != CLOSE_PAREN) throw std::runtime_error("closing parenthesis after expression expected, found " + Tokenizer::TokenTypeToString(token) + "instead!"); } void ProcessRecords(const Query &query, MARC::Reader * const marc_reader) { unsigned record_count(0), matched_count(0); while (const MARC::Record record = marc_reader->read()) { ++record_count; if (not query.matched(record)) continue; ++matched_count; } std::cerr << "Matched " << matched_count << " of " << record_count << " records.\n"; } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc < 3) Usage(); if (not StringUtil::StartsWith(argv[1], "--query=")) LOG_ERROR("missing --query=...!"); const std::string query_str(argv[1] + __builtin_strlen("--query=")); Query query(query_str); if (argc < 3) Usage(); for (int arg_no(1); arg_no < argc; ++arg_no) { auto marc_reader(MARC::Reader::Factory(argv[1])); ProcessRecords(query, marc_reader.get()); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <iostream> class Hi { public: Hi() { std::cout << "Hi constructed" << std::endl; } ~Hi() { std::cout << "Hi destructed" << std::endl; } }; int main() { Hi *my = new Hi(); return 0; } <commit_msg>[trash] refs/new/constructor/destructor<commit_after>#include <iostream> class Hi { public: int value; Hi(int value) : value(value) { std::cout << "Hi(" << this->value << ") constructed" << std::endl; } Hi(const Hi &other) : value(other.value) { std::cout << "Hi(" << this->value << ") constructed from Hi(" << other.value << ")" << std::endl; } ~Hi() { std::cout << "Hi(" << value << ") destructed" << std::endl; } Hi &operator=(const Hi &rhs) { std::cout << "Hi(" << this->value << ") := Hi(" << rhs.value << ")" << std::endl; if (this != &rhs) { value = rhs.value; } return *this; } }; int main() { Hi &a0 = *new Hi(0); Hi *a1 = new Hi(1); return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 "include/cpu_operations.h" #include <unistd.h> #include <stdexcept> #include <iostream> #include "Eigen/Dense" #include "include/matrix.h" #include "include/vector.h" namespace Nice { // This function returns the transpose of a matrix template<typename T> Matrix<T> CpuOperations<T>::Transpose(const Matrix<T> &a) { return a.transpose(); // Return transpose } template<typename T> Vector<T> CpuOperations<T>::Transpose(const Vector<T> &a) { return a.transpose(); } // Returns the resulting matrix that is created by running a logical or // operation on the two input matrices template<typename T> Matrix<bool> CpuOperations<T>::LogicalOr(const Matrix<bool> &a, const Matrix<bool> &b) { if ((a.rows() != b.rows()) || (a.cols() != b.cols())) { std::cout << std::endl << "ERROR: MATRICES ARE NOT THE SAME SIZE!" << std::endl << std::endl; exit(-1); // Exits the program } else if (b.rows() == 0 || b.cols() == 0 || a.rows() == 0 || a.cols() == 0) { std::cout << std::endl << "ERROR: EMPTY MATRIX AS ARGUMENT!" << std::endl << std::endl; exit(-1); // Exits the program } return (a.array() || b.array()); } // Returns the resulting vector that is created by running a logical or // operation on the two input vectors template<typename T> Vector<bool> CpuOperations<T>::LogicalOr(const Vector<bool> &a, const Vector<bool> &b) { if ( a.size() != b.size() ) { std::cout << std::endl << "ERROR: VECTORS ARE NOT THE SAME SIZE!" << std::endl << std::endl; exit(-1); // Exits the program } else if (a.size() == 0 || b.size() == 0) { std::cout << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(-1); // Exits the program } return (a.array() || b.array()); } template<typename T> Matrix<bool> CpuOperations<T>::LogicalNot(const Matrix<bool> &a) { Matrix<bool> b = a.replicate(1, 1); int r; // Iterate through the copied matrix for (r = 0; r < b.rows(); ++r) { for (int c = 0; c < b.cols(); ++c) { b(r, c) = !b(r, c); } } if (b.rows() == 0 || b.cols() == 0) { std::cout << std::endl << "ERROR: EMPTY MATRIX AS ARGUMENT!" << std::endl << std::endl; exit(-1); // Exits the program } return b; } template<typename T> Vector<bool> CpuOperations<T>::LogicalNot(const Vector<bool> &a) { Vector<bool> b = a.replicate(1, 1); int i; // Iterate through vector for (i = 0; i < b.size(); ++i) { b(i) = !b(i); } if (a.size() == 0) { std::cout << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(-1); // Exits the program } return b; } // Scalar-matrix multiplication template<typename T> Matrix<T> CpuOperations<T>::Multiply(const Matrix<T> &a, const T &scalar) { return scalar * a; } // Matrix-matrix multiplication template<typename T> Matrix<T> CpuOperations<T>::Multiply(const Matrix<T> &a, const Matrix<T> &b) { return a * b; } // Trace of a matrix template<typename T> T CpuOperations<T>::Trace(const Matrix<T> &a) { return a.trace(); } /* // Rank of a matrix template<typename T> T CpuOperations<T>::Rank(const Matrix<T> &a) { return a.rank(); } */ // This function returns the logical AND of two boolean matrices template<typename T> Matrix<bool> CpuOperations<T>::LogicalAnd(const Matrix<bool> &a, const Matrix<bool> &b) { // Checks to see that the number of rows and columns are the same if ((a.rows() != b.rows()) || (a.cols() != b.cols())) { std::cout << "/nERROR: MATRICES ARE NOT THE SAME SIZE!/n/n"; exit(1); // Exits the program } return (a.array() && b.array()); // Will return a matrix due to implicit conversion } // This function returns the outer product of he two passed in vectors template<typename T> Matrix<T> CpuOperations<T>::OuterProduct(const Vector<T> &a, const Vector<T> &b) { if (a.size() == 0 || b.size() == 0) { std::cout << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(-1); } return a * b.transpose(); } template class CpuOperations<int>; template class CpuOperations<float>; template class CpuOperations<double>; template class CpuOperations<bool>; } // namespace Nice <commit_msg>Adjusted for cerr and exit(1) format<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Northeastern University // // 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 "include/cpu_operations.h" #include <unistd.h> #include <stdexcept> #include <iostream> #include "Eigen/Dense" #include "include/matrix.h" #include "include/vector.h" namespace Nice { // This function returns the transpose of a matrix template<typename T> Matrix<T> CpuOperations<T>::Transpose(const Matrix<T> &a) { return a.transpose(); // Return transpose } template<typename T> Vector<T> CpuOperations<T>::Transpose(const Vector<T> &a) { return a.transpose(); } // Returns the resulting matrix that is created by running a logical or // operation on the two input matrices template<typename T> Matrix<bool> CpuOperations<T>::LogicalOr(const Matrix<bool> &a, const Matrix<bool> &b) { if ((a.rows() != b.rows()) || (a.cols() != b.cols())) { std::cerr << std::endl << "ERROR: MATRICES ARE NOT THE SAME SIZE!" << std::endl << std::endl; exit(1); // Exits the program } else if (b.rows() == 0 || b.cols() == 0 || a.rows() == 0 || a.cols() == 0) { std::cerr << std::endl << "ERROR: EMPTY MATRIX AS ARGUMENT!" << std::endl << std::endl; exit(1); // Exits the program } return (a.array() || b.array()); } // Returns the resulting vector that is created by running a logical or // operation on the two input vectors template<typename T> Vector<bool> CpuOperations<T>::LogicalOr(const Vector<bool> &a, const Vector<bool> &b) { if ( a.size() != b.size() ) { std::cerr << std::endl << "ERROR: VECTORS ARE NOT THE SAME SIZE!" << std::endl << std::endl; exit(1); // Exits the program } else if (a.size() == 0 || b.size() == 0) { std::cerr << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(1); // Exits the program } return (a.array() || b.array()); } template<typename T> Matrix<bool> CpuOperations<T>::LogicalNot(const Matrix<bool> &a) { Matrix<bool> b = a.replicate(1, 1); int r; // Iterate through the copied matrix for (r = 0; r < b.rows(); ++r) { for (int c = 0; c < b.cols(); ++c) { b(r, c) = !b(r, c); } } if (b.rows() == 0 || b.cols() == 0) { std::cerr << std::endl << "ERROR: EMPTY MATRIX AS ARGUMENT!" << std::endl << std::endl; exit(1); // Exits the program } return b; } template<typename T> Vector<bool> CpuOperations<T>::LogicalNot(const Vector<bool> &a) { Vector<bool> b = a.replicate(1, 1); int i; // Iterate through vector for (i = 0; i < b.size(); ++i) { b(i) = !b(i); } if (a.size() == 0) { std::cerr << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(1); // Exits the program } return b; } // Scalar-matrix multiplication template<typename T> Matrix<T> CpuOperations<T>::Multiply(const Matrix<T> &a, const T &scalar) { return scalar * a; } // Matrix-matrix multiplication template<typename T> Matrix<T> CpuOperations<T>::Multiply(const Matrix<T> &a, const Matrix<T> &b) { return a * b; } // Trace of a matrix template<typename T> T CpuOperations<T>::Trace(const Matrix<T> &a) { return a.trace(); } /* // Rank of a matrix template<typename T> T CpuOperations<T>::Rank(const Matrix<T> &a) { return a.rank(); } */ // This function returns the logical AND of two boolean matrices template<typename T> Matrix<bool> CpuOperations<T>::LogicalAnd(const Matrix<bool> &a, const Matrix<bool> &b) { // Checks to see that the number of rows and columns are the same if ((a.rows() != b.rows()) || (a.cols() != b.cols())) { std::cerr << "/nERROR: MATRICES ARE NOT THE SAME SIZE!/n/n"; exit(1); // Exits the program } return (a.array() && b.array()); // Will return a matrix due to implicit conversion } // This function returns the outer product of he two passed in vectors template<typename T> Matrix<T> CpuOperations<T>::OuterProduct(const Vector<T> &a, const Vector<T> &b) { if (a.size() == 0 || b.size() == 0) { std::cerr << std::endl << "ERROR: EMPTY VECTOR AS ARGUMENT!" << std::endl << std::endl; exit(1); } return a * b.transpose(); } template class CpuOperations<int>; template class CpuOperations<float>; template class CpuOperations<double>; template class CpuOperations<bool>; } // namespace Nice <|endoftext|>
<commit_before>#include"MatasanoConverter.h" // styled according to the Google C++ Style guide // https://google.github.io/styleguide/cppguide.html uint8_t NumberFromHexChar(char hex_character) { if (48 <= hex_character && hex_character <= 57) { //0-9 return (uint8_t) hex_character - 48; } else if (65 <= hex_character && hex_character <= 70) { //A-F return (uint8_t) hex_character - 55; } else if (97 <= hex_character && hex_character <= 102) { //a-f return (uint8_t) hex_character - 87; } else { //other - error! throw std::invalid_argument("numberFromHexChar: hex_character not valid."); } } std::vector<uint8_t> Base64Splitter(std::vector<uint8_t> eight_bit_number_array) { uint8_t temp; std::vector<uint8_t> base_64_output; base_64_output.clear(); //may be redundant for (int i = 0; i < eight_bit_number_array.size(); i+=3) { //three 8 bit numbers are taken at once and converted into four 6 bit numbers temp = eight_bit_number_array[i] >> 2; base_64_output.push_back(temp); temp = (eight_bit_number_array[ i ] & 0x3) << 4 | eight_bit_number_array[i+1] >> 4; base_64_output.push_back(temp); temp = (eight_bit_number_array[i+1] & 0xF) << 2 | eight_bit_number_array[i+2] >> 6; base_64_output.push_back(temp); temp = eight_bit_number_array[i+2] & 0x3F; base_64_output.push_back(temp); } return base_64_output; } std::vector<uint8_t> HexSplitter(std::vector<uint8_t> eight_bit_number_array) { uint8_t temp; std::vector<uint8_t> hex_output; hex_output.clear(); //may be redundant for (int i = 0; i < eight_bit_number_array.size(); i++) { temp = eight_bit_number_array[i] >> 4; hex_output.push_back(temp); temp = eight_bit_number_array[i] & 0xF; hex_output.push_back(temp); } return hex_output; } char Base64Character(uint8_t base_64_number) { if (0 <= base_64_number && base_64_number <= 25) { //upper case characters return (char) base_64_number + 65; } else if (26 <= base_64_number && base_64_number <= 51) { //lower case characters return (char) base_64_number + 71; } else if (52 <= base_64_number && base_64_number <= 61) { //numbers return (char) base_64_number - 4; } else if (62 == base_64_number) { //+ return '+'; } else if (63 == base_64_number) { // / return '/'; } else { throw std::invalid_argument("Base64Character: invalid base64 number (not a number 0-63)"); } } char HexCharacter(uint8_t hex_number) { if (0 <= hex_number && hex_number <= 9) { return (char) hex_number + 48; } else if (10 <= hex_number && hex_number <= 15) { return (char) hex_number + 87; } else { throw std::invalid_argument("HexCharacter: invalid hex number (not a number 0-15)"); } } uint8_t CombineHex(uint8_t msb, uint8_t lsb) { return (msb << 4) | lsb; } std::string GetBase64String(std::vector<uint8_t> input_vector) { std::vector<uint8_t> data_copy = input_vector; //create copy that can be safely modified if needed char padding_bytes; //counter to record number of bytes added - value will be 0, 1 or 2 std::string base_64_string = ""; if (data_copy.size() % 3 == 1) { //add two pad bytes data_copy.push_back(0); data_copy.push_back(0); padding_bytes = 2; } else if (data_copy.size() % 3 == 2) { //add one pad byte data_copy.push_back(0); padding_bytes = 1; } else { //no padding required padding_bytes = 0; } data_copy = Base64Splitter(data_copy); for (int i = 0; i < data_copy.size(); i++) { base_64_string += Base64Character(data_copy[i]); } if (padding_bytes == 1) { base_64_string.replace(base_64_string.length() - 1, 1, "=", 0, 1); } else if (padding_bytes == 2) { base_64_string.replace(base_64_string.length() - 2, 2, "==", 0, 2); } data_copy.clear(); //destroy the vector as the copy is no longer needed - maybe redundant return base_64_string; } std::string GetHexString(std::vector<uint8_t> input_vector) { std::vector<uint8_t> data_copy = input_vector; //create copy that can be safely modified if needed std::string hex_string = ""; data_copy = HexSplitter(data_copy); for (int i = 0; i < data_copy.size(); i++) { hex_string += HexCharacter(data_copy[i]); } return hex_string; } std::vector<uint8_t> HexStringConvert(std::string input_string) { //need to loop over each character and add two characters at a time to the uint8_t array std::vector<uint8_t> output_vector; uint32_t max = input_string.length(); uint8_t a = 0, b = 0; output_vector.clear(); //may be redundant if (max % 2 != 0) { throw std::invalid_argument("HexStringInput: inputString not valid hex - uneven length."); } for(uint32_t i = 0; i < max; i+=2) { a = NumberFromHexChar(input_string[i]); b = NumberFromHexChar(input_string[i + 1]); output_vector.push_back( CombineHex( a , b ) ); } return output_vector; } std::string StringFromVectorASCII(std::vector<uint8_t> input_vector) { std::string out = ""; for (uint32_t i = 0; i < input_vector.size(); i++) { out += (char) input_vector[i]; } return out; } std::string StringFromByteVector(std::vector<uint8_t> input_vector, std::string output_type) { std::string temp; //needed for upper case hex output if (output_type.compare("base64") == 0 || output_type.compare("b64") == 0 || output_type.compare("Base64") == 0 || output_type.compare("B64") == 0) { return GetBase64String(input_vector); } else if (output_type.compare("hex") == 0 || output_type.compare("h") == 0) { //returns lower case hex output return GetHexString(input_vector); } else if (output_type.compare("H") == 0 || output_type.compare("Hex") == 0 || output_type.compare("HEX") == 0) { //returns upper case hex output temp = GetHexString(input_vector); transform(temp.begin(), temp.end(), temp.begin(), ::toupper); return temp; } else if (output_type.compare("ASCII") == 0 || output_type.compare("ascii") == 0) { return StringFromVectorASCII(input_vector); } else { throw std::invalid_argument("GetStringOutput: unknown output_type."); } } std::vector<uint8_t> ByteVectorFromString(std::string input_string, std::string input_type) { //this function uses an if statement and the hexStringInput function to allow for easy expansion of the MatasanoConverter class //e.g. for base64 input if (input_type.compare("hex") == 0 || input_type.compare("Hex") == 0 || input_type.compare("h") == 0) { return HexStringConvert(input_string); } else { throw std::invalid_argument("inputString: unknown inputType."); } } <commit_msg>Add ASCII to byte values convertion<commit_after>#include"MatasanoConverter.h" // styled according to the Google C++ Style guide // https://google.github.io/styleguide/cppguide.html uint8_t NumberFromHexChar(char hex_character) { if (48 <= hex_character && hex_character <= 57) { //0-9 return (uint8_t) hex_character - 48; } else if (65 <= hex_character && hex_character <= 70) { //A-F return (uint8_t) hex_character - 55; } else if (97 <= hex_character && hex_character <= 102) { //a-f return (uint8_t) hex_character - 87; } else { //other - error! throw std::invalid_argument("numberFromHexChar: hex_character not valid."); } } std::vector<uint8_t> Base64Splitter(std::vector<uint8_t> eight_bit_number_array) { uint8_t temp; std::vector<uint8_t> base_64_output; base_64_output.clear(); //may be redundant for (int i = 0; i < eight_bit_number_array.size(); i+=3) { //three 8 bit numbers are taken at once and converted into four 6 bit numbers temp = eight_bit_number_array[i] >> 2; base_64_output.push_back(temp); temp = (eight_bit_number_array[ i ] & 0x3) << 4 | eight_bit_number_array[i+1] >> 4; base_64_output.push_back(temp); temp = (eight_bit_number_array[i+1] & 0xF) << 2 | eight_bit_number_array[i+2] >> 6; base_64_output.push_back(temp); temp = eight_bit_number_array[i+2] & 0x3F; base_64_output.push_back(temp); } return base_64_output; } std::vector<uint8_t> HexSplitter(std::vector<uint8_t> eight_bit_number_array) { uint8_t temp; std::vector<uint8_t> hex_output; hex_output.clear(); //may be redundant for (int i = 0; i < eight_bit_number_array.size(); i++) { temp = eight_bit_number_array[i] >> 4; hex_output.push_back(temp); temp = eight_bit_number_array[i] & 0xF; hex_output.push_back(temp); } return hex_output; } char Base64Character(uint8_t base_64_number) { if (0 <= base_64_number && base_64_number <= 25) { //upper case characters return (char) base_64_number + 65; } else if (26 <= base_64_number && base_64_number <= 51) { //lower case characters return (char) base_64_number + 71; } else if (52 <= base_64_number && base_64_number <= 61) { //numbers return (char) base_64_number - 4; } else if (62 == base_64_number) { //+ return '+'; } else if (63 == base_64_number) { // / return '/'; } else { throw std::invalid_argument("Base64Character: invalid base64 number (not a number 0-63)"); } } char HexCharacter(uint8_t hex_number) { if (0 <= hex_number && hex_number <= 9) { return (char) hex_number + 48; } else if (10 <= hex_number && hex_number <= 15) { return (char) hex_number + 87; } else { throw std::invalid_argument("HexCharacter: invalid hex number (not a number 0-15)"); } } uint8_t CombineHex(uint8_t msb, uint8_t lsb) { return (msb << 4) | lsb; } std::string GetBase64String(std::vector<uint8_t> input_vector) { std::vector<uint8_t> data_copy = input_vector; //create copy that can be safely modified if needed char padding_bytes; //counter to record number of bytes added - value will be 0, 1 or 2 std::string base_64_string = ""; if (data_copy.size() % 3 == 1) { //add two pad bytes data_copy.push_back(0); data_copy.push_back(0); padding_bytes = 2; } else if (data_copy.size() % 3 == 2) { //add one pad byte data_copy.push_back(0); padding_bytes = 1; } else { //no padding required padding_bytes = 0; } data_copy = Base64Splitter(data_copy); for (int i = 0; i < data_copy.size(); i++) { base_64_string += Base64Character(data_copy[i]); } if (padding_bytes == 1) { base_64_string.replace(base_64_string.length() - 1, 1, "=", 0, 1); } else if (padding_bytes == 2) { base_64_string.replace(base_64_string.length() - 2, 2, "==", 0, 2); } data_copy.clear(); //destroy the vector as the copy is no longer needed - maybe redundant return base_64_string; } std::string GetHexString(std::vector<uint8_t> input_vector) { std::vector<uint8_t> data_copy = input_vector; //create copy that can be safely modified if needed std::string hex_string = ""; data_copy = HexSplitter(data_copy); for (int i = 0; i < data_copy.size(); i++) { hex_string += HexCharacter(data_copy[i]); } return hex_string; } std::vector<uint8_t> HexStringConvert(std::string input_string) { //need to loop over each character and add two characters at a time to the uint8_t array std::vector<uint8_t> output_vector; uint32_t max = input_string.length(); uint8_t a = 0, b = 0; output_vector.clear(); //may be redundant if (max % 2 != 0) { throw std::invalid_argument("HexStringInput: inputString not valid hex - uneven length."); } for(uint32_t i = 0; i < max; i+=2) { a = NumberFromHexChar(input_string[i]); b = NumberFromHexChar(input_string[i + 1]); output_vector.push_back( CombineHex( a , b ) ); } return output_vector; } std::vector<uint8_t> ASCIIStringConvert(std::string input_string) { std::vector<uint8_t> output_vector; for (int i = 0; i < input_string.size(); i++) { output_vector.push_back((uint8_t) input_string[i]); } return output_vector; } std::string StringFromVectorASCII(std::vector<uint8_t> input_vector) { std::string out = ""; for (uint32_t i = 0; i < input_vector.size(); i++) { out += (char) input_vector[i]; } return out; } std::string StringFromByteVector(std::vector<uint8_t> input_vector, std::string output_type) { std::string temp; //needed for upper case hex output if (output_type.compare("base64") == 0 || output_type.compare("b64") == 0 || output_type.compare("Base64") == 0 || output_type.compare("B64") == 0) { return GetBase64String(input_vector); } else if (output_type.compare("hex") == 0 || output_type.compare("h") == 0) { //returns lower case hex output return GetHexString(input_vector); } else if (output_type.compare("H") == 0 || output_type.compare("Hex") == 0 || output_type.compare("HEX") == 0) { //returns upper case hex output temp = GetHexString(input_vector); transform(temp.begin(), temp.end(), temp.begin(), ::toupper); return temp; } else if (output_type.compare("ASCII") == 0 || output_type.compare("ascii") == 0) { return StringFromVectorASCII(input_vector); } else { throw std::invalid_argument("GetStringOutput: unknown output_type."); } } std::vector<uint8_t> ByteVectorFromString(std::string input_string, std::string input_type) { //this function uses an if statement and the hexStringInput function to allow for easy expansion of the MatasanoConverter class //e.g. for base64 input if (input_type.compare("hex") == 0 || input_type.compare("Hex") == 0 || input_type.compare("h") == 0) { return HexStringConvert(input_string); } else if (input_type.compare("ASCII") == 0 || input_type.compare("ascii") == 0 || input_type.compare("Ascii")) { return ASCIIStringConvert(input_string); } else { throw std::invalid_argument("inputString: unknown inputType."); } } <|endoftext|>
<commit_before>/** * @file DartLoader.cpp */ #include "DartLoader.h" #include <map> #include <urdf_parser/urdf_parser.h> #include <urdf_world/world.h> #include "urdf_world_parser.h" #include <iostream> #include <fstream> #include "dart/dynamics/Skeleton.h" #include "dart/dynamics/BodyNode.h" #include "dart/dynamics/Joint.h" #include "dart/dynamics/RevoluteJoint.h" #include "dart/dynamics/PrismaticJoint.h" #include "dart/dynamics/WeldJoint.h" #include "dart/dynamics/FreeJoint.h" #include "dart/dynamics/GenCoord.h" #include "dart/dynamics/Shape.h" #include "dart/dynamics/BoxShape.h" #include "dart/dynamics/EllipsoidShape.h" #include "dart/dynamics/CylinderShape.h" #include "dart/dynamics/MeshShape.h" #include "dart/simulation/World.h" namespace dart { namespace utils { /** * @function parseSkeleton */ dynamics::Skeleton* DartLoader::parseSkeleton(std::string _urdfFileName) { urdf::ModelInterface* skeletonModel = urdf::parseURDF(readFileToString(_urdfFileName)).get(); if(!skeletonModel) return NULL; // Change path to a Unix-style path if given a Windows one // Windows can handle Unix-style paths (apparently) std::replace(_urdfFileName.begin(), _urdfFileName.end(), '\\' , '/' ); std::string skelDirectory = _urdfFileName.substr(0, _urdfFileName.rfind("/") + 1); return modelInterfaceToSkeleton(skeletonModel, skelDirectory); } /** * @function parseWorld */ simulation::World* DartLoader::parseWorld(std::string _urdfFileName) { std::string xmlString = readFileToString(_urdfFileName); // Change path to a Unix-style path if given a Windows one // Windows can handle Unix-style paths (apparently) std::replace(_urdfFileName.begin(), _urdfFileName.end(), '\\' , '/'); std::string worldDirectory = _urdfFileName.substr(0, _urdfFileName.rfind("/") + 1); urdf::World* worldInterface = urdf::parseWorldURDF(xmlString, worldDirectory); if(!worldInterface) return NULL; // Store paths from world to entities parseWorldToEntityPaths(xmlString); simulation::World* world = new simulation::World(); for(unsigned int i = 0; i < worldInterface->models.size(); ++i) { std::string skeletonDirectory = worldDirectory + mWorld_To_Entity_Paths.find(worldInterface->models[i].model->getName())->second; dynamics::Skeleton* skeleton = modelInterfaceToSkeleton(worldInterface->models[i].model.get(), skeletonDirectory); if(!skeleton) { std::cout << "[ERROR] Robot " << worldInterface->models[i].model->getName() << " was not correctly parsed. World is not loaded. Exiting!" << std::endl; return NULL; } // Initialize position and RPY dynamics::Joint* rootJoint = skeleton->getRootBodyNode()->getParentJoint(); Eigen::Isometry3d transform = toEigen(worldInterface->models[i].origin); if(dynamic_cast<dynamics::FreeJoint*>(rootJoint)) { Eigen::Vector6d coordinates; coordinates << math::logMap(transform.linear()), transform.translation(); rootJoint->set_q(coordinates); } else { rootJoint->setTransformFromParentBodyNode(transform); } world->addSkeleton(skeleton); } return world; } /** * @function parseWorldToEntityPaths */ void DartLoader::parseWorldToEntityPaths(const std::string &_xml_string) { TiXmlDocument xml_doc; xml_doc.Parse(_xml_string.c_str()); TiXmlElement *world_xml = xml_doc.FirstChildElement("world"); if( !world_xml ) { return; } // Get all include filenames std::map<std::string, std::string> includedFiles; for( TiXmlElement* include_xml = world_xml->FirstChildElement("include"); include_xml; include_xml = include_xml->NextSiblingElement("include") ) { const char *filename = include_xml->Attribute("filename"); const char *model_name = include_xml->Attribute("model_name"); std::string string_filename( filename ); std::string string_filepath = string_filename.substr( 0, string_filename.rfind("/") + 1 ); std::string string_model_name( model_name ); includedFiles[string_model_name] = string_filepath; } // Get all entities for( TiXmlElement* entity_xml = world_xml->FirstChildElement("entity"); entity_xml; entity_xml = entity_xml->NextSiblingElement("entity") ) { // Find model and name for entity, if not, error const char* entity_model = entity_xml->Attribute("model"); const char* entity_name = entity_xml->Attribute("name"); if( entity_name && entity_model ) { std::string string_entity_model( entity_model ); std::string string_entity_name( entity_name ); // Find the model if( includedFiles.find( string_entity_model ) == includedFiles.end() ) { std::cout<<"[!] Did not find entity model included. Weird things may happen"<<std::endl; return; } // Add it else { std::string string_entity_filepath = includedFiles.find( string_entity_model )->second; mWorld_To_Entity_Paths[string_entity_name] = string_entity_filepath; } } // If no name or model is defined else { std::cout<< "[!] Entity was not defined. Weird things will happen" <<std::endl; } } // for all entities } /** * @function modelInterfaceToSkeleton * @brief Read the ModelInterface and spits out a Skeleton object */ dynamics::Skeleton* DartLoader::modelInterfaceToSkeleton(const urdf::ModelInterface* _model, std::string _rootToSkelPath) { if( _rootToSkelPath.empty() ) { std::cout<< "[DartLoader] Absolute path to skeleton "<<_model->getName()<<" is not set. Probably I will crash!"<<std::endl; } dynamics::Skeleton* skeleton = new dynamics::Skeleton(_model->getName()); dynamics::BodyNode* rootNode; dynamics::Joint* rootJoint; const urdf::Link* root = _model->getRoot().get(); if(root->name == "world") { if(_model->getRoot()->child_links.size() != 1) { std::cout<< "[ERROR] Not unique link attached to world." << std::endl; } else { root = root->child_links[0].get(); rootNode = createDartNode(root, _rootToSkelPath); rootJoint = createDartJoint(root->parent_joint.get()); if(!rootJoint) return NULL; } } else { rootNode = createDartNode(root, _rootToSkelPath); rootJoint = new dynamics::FreeJoint(); rootJoint->setName("rootJoint"); rootJoint->setTransformFromParentBodyNode(Eigen::Isometry3d::Identity()); rootJoint->setTransformFromChildBodyNode(Eigen::Isometry3d::Identity()); } rootNode->setParentJoint(rootJoint); skeleton->addBodyNode(rootNode); for(unsigned int i = 0; i < root->child_links.size(); i++) { createSkeletonRecursive(skeleton, root->child_links[i].get(), rootNode, _rootToSkelPath); } return skeleton; } void DartLoader::createSkeletonRecursive(dynamics::Skeleton* _skel, const urdf::Link* _lk, dynamics::BodyNode* _parentNode, std::string _rootToSkelPath) { dynamics::BodyNode* node = createDartNode(_lk, _rootToSkelPath); dynamics::Joint* joint = createDartJoint(_lk->parent_joint.get()); node->setParentJoint(joint); _parentNode->addChildBodyNode(node); _skel->addBodyNode(node); for(unsigned int i = 0; i < _lk->child_links.size(); i++) { createSkeletonRecursive(_skel, _lk->child_links[i].get(), node, _rootToSkelPath); } } /** * @function readXml */ std::string DartLoader::readFileToString(std::string _xmlFile) { std::string xml_string; std::ifstream xml_file(_xmlFile.c_str()); // Read xml while(xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); return xml_string; } /** * @function createDartJoint */ dynamics::Joint* DartLoader::createDartJoint(const urdf::Joint* _jt) { dynamics::Joint* joint; switch(_jt->type) { case urdf::Joint::REVOLUTE: joint = new dynamics::RevoluteJoint(toEigen(_jt->axis)); joint->getGenCoord(0)->set_qMin(_jt->limits->lower); joint->getGenCoord(0)->set_qMax(_jt->limits->upper); break; case urdf::Joint::CONTINUOUS: joint = new dynamics::RevoluteJoint(toEigen(_jt->axis)); break; case urdf::Joint::PRISMATIC: joint = new dynamics::PrismaticJoint(toEigen(_jt->axis)); joint->getGenCoord(0)->set_qMin(_jt->limits->lower); joint->getGenCoord(0)->set_qMax(_jt->limits->upper); break; case urdf::Joint::FIXED: joint = new dynamics::WeldJoint(); break; case urdf::Joint::FLOATING: joint = new dynamics::FreeJoint(); break; case urdf::Joint::PLANAR: std::cout << "Planar joint not supported." << std::endl; assert(false); return NULL; default: std::cout << "Unsupported joint type." << std::endl; assert(false); return NULL; } joint->setName(_jt->name); joint->setTransformFromParentBodyNode(toEigen(_jt->parent_to_joint_origin_transform)); joint->setTransformFromChildBodyNode(Eigen::Isometry3d::Identity()); if(joint->getNumGenCoords() == 1 && _jt->limits) { joint->getGenCoord(0)->set_dqMin(-_jt->limits->velocity); joint->getGenCoord(0)->set_dqMax(_jt->limits->velocity); joint->getGenCoord(0)->set_tauMin(-_jt->limits->effort); joint->getGenCoord(0)->set_tauMax(_jt->limits->effort); } return joint; } /** * @function createDartNode */ dynamics::BodyNode* DartLoader::createDartNode(const urdf::Link* _lk, std::string _rootToSkelPath) { dynamics::BodyNode* node = new dynamics::BodyNode(_lk->name); // Mesh Loading //FIXME: Shouldn't mass and inertia default to 0? double mass = 0.1; Eigen::Matrix3d inertia = Eigen::MatrixXd::Identity(3,3); inertia *= 0.1; // Load Inertial information if(_lk->inertial) { node->setLocalCOM(toEigen(_lk->inertial->origin.position)); node->setMass(_lk->inertial->mass); node->setInertia(_lk->inertial->ixx, _lk->inertial->iyy, _lk->inertial->izz, _lk->inertial->ixy, _lk->inertial->ixz, _lk->inertial->iyz); } // Set visual information for(unsigned int i = 0; i < _lk->visual_array.size(); i++) { if(dynamics::Shape* shape = createShape(_lk->visual_array[i].get(), _rootToSkelPath)) { node->addVisualizationShape(shape); } } // Set collision information for(unsigned int i = 0; i < _lk->collision_array.size(); i++) { if(dynamics::Shape* shape = createShape(_lk->collision_array[i].get(), _rootToSkelPath)) { node->addCollisionShape(shape); } } return node; } void setMaterial(dynamics::Shape* _shape, const urdf::Visual* _viz) { if(_viz->material) { _shape->setColor(Eigen::Vector3d(_viz->material->color.r, _viz->material->color.g, _viz->material->color.b)); } } void setMaterial(dynamics::Shape* _shape, const urdf::Collision* _col) { } /** * @function createShape */ template <class VisualOrCollision> dynamics::Shape* DartLoader::createShape(const VisualOrCollision* _vizOrCol, std::string _rootToSkelPath) { dynamics::Shape* shape; // Sphere if(urdf::Sphere* sphere = dynamic_cast<urdf::Sphere*>(_vizOrCol->geometry.get())) { shape = new dynamics::EllipsoidShape(2.0 * sphere->radius * Eigen::Vector3d::Ones()); } // Box else if(urdf::Box* box = dynamic_cast<urdf::Box*>(_vizOrCol->geometry.get())) { shape = new dynamics::BoxShape(Eigen::Vector3d(box->dim.x, box->dim.y, box->dim.z)); } // Cylinder else if(urdf::Cylinder* cylinder = dynamic_cast<urdf::Cylinder*>(_vizOrCol->geometry.get())) { shape = new dynamics::CylinderShape(cylinder->radius, cylinder->length); } // Mesh else if(urdf::Mesh* mesh = dynamic_cast<urdf::Mesh*>(_vizOrCol->geometry.get())) { std::string fullPath = _rootToSkelPath + mesh->filename; const aiScene* model = dynamics::MeshShape::loadMesh( fullPath ); if(!model) { std::cout<< "[add_Shape] [ERROR] Not loading model " << fullPath << " (NULL) \n"; shape = NULL; } else { shape = new dynamics::MeshShape(Eigen::Vector3d(mesh->scale.x, mesh->scale.y, mesh->scale.z), model); } } // Unknown geometry type else { std::cout << "[add_Shape] No MESH, BOX, CYLINDER OR SPHERE! Not loading this shape." << std::endl; return NULL; } shape->setLocalTransform(toEigen(_vizOrCol->origin)); setMaterial(shape, _vizOrCol); return shape; } template dynamics::Shape* DartLoader::createShape<urdf::Visual>(const urdf::Visual* _vizOrCol, std::string _rootToSkelPath); template dynamics::Shape* DartLoader::createShape<urdf::Collision>(const urdf::Collision* _vizOrCol, std::string _rootToSkelPath); /** * @function pose2Affine3d */ Eigen::Isometry3d DartLoader::toEigen(const urdf::Pose& _pose) { Eigen::Quaterniond quat; _pose.rotation.getQuaternion(quat.x(), quat.y(), quat.z(), quat.w()); Eigen::Isometry3d transform(quat); transform.translation() = Eigen::Vector3d(_pose.position.x, _pose.position.y, _pose.position.z); return transform; } Eigen::Vector3d DartLoader::toEigen(const urdf::Vector3& _vector) { return Eigen::Vector3d(_vector.x, _vector.y, _vector.z); } } // namespace utils } // namespace dart <commit_msg>Fix use of boost::shared_ptr in DartLoader::parseSkeleton()<commit_after>/** * @file DartLoader.cpp */ #include "DartLoader.h" #include <map> #include <urdf_parser/urdf_parser.h> #include <urdf_world/world.h> #include "urdf_world_parser.h" #include <iostream> #include <fstream> #include "dart/dynamics/Skeleton.h" #include "dart/dynamics/BodyNode.h" #include "dart/dynamics/Joint.h" #include "dart/dynamics/RevoluteJoint.h" #include "dart/dynamics/PrismaticJoint.h" #include "dart/dynamics/WeldJoint.h" #include "dart/dynamics/FreeJoint.h" #include "dart/dynamics/GenCoord.h" #include "dart/dynamics/Shape.h" #include "dart/dynamics/BoxShape.h" #include "dart/dynamics/EllipsoidShape.h" #include "dart/dynamics/CylinderShape.h" #include "dart/dynamics/MeshShape.h" #include "dart/simulation/World.h" namespace dart { namespace utils { /** * @function parseSkeleton */ dynamics::Skeleton* DartLoader::parseSkeleton(std::string _urdfFileName) { boost::shared_ptr<urdf::ModelInterface> skeletonModelPtr = urdf::parseURDF(readFileToString(_urdfFileName)); if(!skeletonModelPtr) return NULL; // Change path to a Unix-style path if given a Windows one // Windows can handle Unix-style paths (apparently) std::replace(_urdfFileName.begin(), _urdfFileName.end(), '\\' , '/' ); std::string skelDirectory = _urdfFileName.substr(0, _urdfFileName.rfind("/") + 1); return modelInterfaceToSkeleton(skeletonModelPtr.get(), skelDirectory); } /** * @function parseWorld */ simulation::World* DartLoader::parseWorld(std::string _urdfFileName) { std::string xmlString = readFileToString(_urdfFileName); // Change path to a Unix-style path if given a Windows one // Windows can handle Unix-style paths (apparently) std::replace(_urdfFileName.begin(), _urdfFileName.end(), '\\' , '/'); std::string worldDirectory = _urdfFileName.substr(0, _urdfFileName.rfind("/") + 1); urdf::World* worldInterface = urdf::parseWorldURDF(xmlString, worldDirectory); if(!worldInterface) return NULL; // Store paths from world to entities parseWorldToEntityPaths(xmlString); simulation::World* world = new simulation::World(); for(unsigned int i = 0; i < worldInterface->models.size(); ++i) { std::string skeletonDirectory = worldDirectory + mWorld_To_Entity_Paths.find(worldInterface->models[i].model->getName())->second; dynamics::Skeleton* skeleton = modelInterfaceToSkeleton(worldInterface->models[i].model.get(), skeletonDirectory); if(!skeleton) { std::cout << "[ERROR] Robot " << worldInterface->models[i].model->getName() << " was not correctly parsed. World is not loaded. Exiting!" << std::endl; return NULL; } // Initialize position and RPY dynamics::Joint* rootJoint = skeleton->getRootBodyNode()->getParentJoint(); Eigen::Isometry3d transform = toEigen(worldInterface->models[i].origin); if(dynamic_cast<dynamics::FreeJoint*>(rootJoint)) { Eigen::Vector6d coordinates; coordinates << math::logMap(transform.linear()), transform.translation(); rootJoint->set_q(coordinates); } else { rootJoint->setTransformFromParentBodyNode(transform); } world->addSkeleton(skeleton); } return world; } /** * @function parseWorldToEntityPaths */ void DartLoader::parseWorldToEntityPaths(const std::string &_xml_string) { TiXmlDocument xml_doc; xml_doc.Parse(_xml_string.c_str()); TiXmlElement *world_xml = xml_doc.FirstChildElement("world"); if( !world_xml ) { return; } // Get all include filenames std::map<std::string, std::string> includedFiles; for( TiXmlElement* include_xml = world_xml->FirstChildElement("include"); include_xml; include_xml = include_xml->NextSiblingElement("include") ) { const char *filename = include_xml->Attribute("filename"); const char *model_name = include_xml->Attribute("model_name"); std::string string_filename( filename ); std::string string_filepath = string_filename.substr( 0, string_filename.rfind("/") + 1 ); std::string string_model_name( model_name ); includedFiles[string_model_name] = string_filepath; } // Get all entities for( TiXmlElement* entity_xml = world_xml->FirstChildElement("entity"); entity_xml; entity_xml = entity_xml->NextSiblingElement("entity") ) { // Find model and name for entity, if not, error const char* entity_model = entity_xml->Attribute("model"); const char* entity_name = entity_xml->Attribute("name"); if( entity_name && entity_model ) { std::string string_entity_model( entity_model ); std::string string_entity_name( entity_name ); // Find the model if( includedFiles.find( string_entity_model ) == includedFiles.end() ) { std::cout<<"[!] Did not find entity model included. Weird things may happen"<<std::endl; return; } // Add it else { std::string string_entity_filepath = includedFiles.find( string_entity_model )->second; mWorld_To_Entity_Paths[string_entity_name] = string_entity_filepath; } } // If no name or model is defined else { std::cout<< "[!] Entity was not defined. Weird things will happen" <<std::endl; } } // for all entities } /** * @function modelInterfaceToSkeleton * @brief Read the ModelInterface and spits out a Skeleton object */ dynamics::Skeleton* DartLoader::modelInterfaceToSkeleton(const urdf::ModelInterface* _model, std::string _rootToSkelPath) { if( _rootToSkelPath.empty() ) { std::cout<< "[DartLoader] Absolute path to skeleton "<<_model->getName()<<" is not set. Probably I will crash!"<<std::endl; } dynamics::Skeleton* skeleton = new dynamics::Skeleton(_model->getName()); dynamics::BodyNode* rootNode; dynamics::Joint* rootJoint; const urdf::Link* root = _model->getRoot().get(); if(root->name == "world") { if(_model->getRoot()->child_links.size() != 1) { std::cout<< "[ERROR] Not unique link attached to world." << std::endl; } else { root = root->child_links[0].get(); rootNode = createDartNode(root, _rootToSkelPath); rootJoint = createDartJoint(root->parent_joint.get()); if(!rootJoint) return NULL; } } else { rootNode = createDartNode(root, _rootToSkelPath); rootJoint = new dynamics::FreeJoint(); rootJoint->setName("rootJoint"); rootJoint->setTransformFromParentBodyNode(Eigen::Isometry3d::Identity()); rootJoint->setTransformFromChildBodyNode(Eigen::Isometry3d::Identity()); } rootNode->setParentJoint(rootJoint); skeleton->addBodyNode(rootNode); for(unsigned int i = 0; i < root->child_links.size(); i++) { createSkeletonRecursive(skeleton, root->child_links[i].get(), rootNode, _rootToSkelPath); } return skeleton; } void DartLoader::createSkeletonRecursive(dynamics::Skeleton* _skel, const urdf::Link* _lk, dynamics::BodyNode* _parentNode, std::string _rootToSkelPath) { dynamics::BodyNode* node = createDartNode(_lk, _rootToSkelPath); dynamics::Joint* joint = createDartJoint(_lk->parent_joint.get()); node->setParentJoint(joint); _parentNode->addChildBodyNode(node); _skel->addBodyNode(node); for(unsigned int i = 0; i < _lk->child_links.size(); i++) { createSkeletonRecursive(_skel, _lk->child_links[i].get(), node, _rootToSkelPath); } } /** * @function readXml */ std::string DartLoader::readFileToString(std::string _xmlFile) { std::string xml_string; std::ifstream xml_file(_xmlFile.c_str()); // Read xml while(xml_file.good()) { std::string line; std::getline(xml_file, line); xml_string += (line + "\n"); } xml_file.close(); return xml_string; } /** * @function createDartJoint */ dynamics::Joint* DartLoader::createDartJoint(const urdf::Joint* _jt) { dynamics::Joint* joint; switch(_jt->type) { case urdf::Joint::REVOLUTE: joint = new dynamics::RevoluteJoint(toEigen(_jt->axis)); joint->getGenCoord(0)->set_qMin(_jt->limits->lower); joint->getGenCoord(0)->set_qMax(_jt->limits->upper); break; case urdf::Joint::CONTINUOUS: joint = new dynamics::RevoluteJoint(toEigen(_jt->axis)); break; case urdf::Joint::PRISMATIC: joint = new dynamics::PrismaticJoint(toEigen(_jt->axis)); joint->getGenCoord(0)->set_qMin(_jt->limits->lower); joint->getGenCoord(0)->set_qMax(_jt->limits->upper); break; case urdf::Joint::FIXED: joint = new dynamics::WeldJoint(); break; case urdf::Joint::FLOATING: joint = new dynamics::FreeJoint(); break; case urdf::Joint::PLANAR: std::cout << "Planar joint not supported." << std::endl; assert(false); return NULL; default: std::cout << "Unsupported joint type." << std::endl; assert(false); return NULL; } joint->setName(_jt->name); joint->setTransformFromParentBodyNode(toEigen(_jt->parent_to_joint_origin_transform)); joint->setTransformFromChildBodyNode(Eigen::Isometry3d::Identity()); if(joint->getNumGenCoords() == 1 && _jt->limits) { joint->getGenCoord(0)->set_dqMin(-_jt->limits->velocity); joint->getGenCoord(0)->set_dqMax(_jt->limits->velocity); joint->getGenCoord(0)->set_tauMin(-_jt->limits->effort); joint->getGenCoord(0)->set_tauMax(_jt->limits->effort); } return joint; } /** * @function createDartNode */ dynamics::BodyNode* DartLoader::createDartNode(const urdf::Link* _lk, std::string _rootToSkelPath) { dynamics::BodyNode* node = new dynamics::BodyNode(_lk->name); // Mesh Loading //FIXME: Shouldn't mass and inertia default to 0? double mass = 0.1; Eigen::Matrix3d inertia = Eigen::MatrixXd::Identity(3,3); inertia *= 0.1; // Load Inertial information if(_lk->inertial) { node->setLocalCOM(toEigen(_lk->inertial->origin.position)); node->setMass(_lk->inertial->mass); node->setInertia(_lk->inertial->ixx, _lk->inertial->iyy, _lk->inertial->izz, _lk->inertial->ixy, _lk->inertial->ixz, _lk->inertial->iyz); } // Set visual information for(unsigned int i = 0; i < _lk->visual_array.size(); i++) { if(dynamics::Shape* shape = createShape(_lk->visual_array[i].get(), _rootToSkelPath)) { node->addVisualizationShape(shape); } } // Set collision information for(unsigned int i = 0; i < _lk->collision_array.size(); i++) { if(dynamics::Shape* shape = createShape(_lk->collision_array[i].get(), _rootToSkelPath)) { node->addCollisionShape(shape); } } return node; } void setMaterial(dynamics::Shape* _shape, const urdf::Visual* _viz) { if(_viz->material) { _shape->setColor(Eigen::Vector3d(_viz->material->color.r, _viz->material->color.g, _viz->material->color.b)); } } void setMaterial(dynamics::Shape* _shape, const urdf::Collision* _col) { } /** * @function createShape */ template <class VisualOrCollision> dynamics::Shape* DartLoader::createShape(const VisualOrCollision* _vizOrCol, std::string _rootToSkelPath) { dynamics::Shape* shape; // Sphere if(urdf::Sphere* sphere = dynamic_cast<urdf::Sphere*>(_vizOrCol->geometry.get())) { shape = new dynamics::EllipsoidShape(2.0 * sphere->radius * Eigen::Vector3d::Ones()); } // Box else if(urdf::Box* box = dynamic_cast<urdf::Box*>(_vizOrCol->geometry.get())) { shape = new dynamics::BoxShape(Eigen::Vector3d(box->dim.x, box->dim.y, box->dim.z)); } // Cylinder else if(urdf::Cylinder* cylinder = dynamic_cast<urdf::Cylinder*>(_vizOrCol->geometry.get())) { shape = new dynamics::CylinderShape(cylinder->radius, cylinder->length); } // Mesh else if(urdf::Mesh* mesh = dynamic_cast<urdf::Mesh*>(_vizOrCol->geometry.get())) { std::string fullPath = _rootToSkelPath + mesh->filename; const aiScene* model = dynamics::MeshShape::loadMesh( fullPath ); if(!model) { std::cout<< "[add_Shape] [ERROR] Not loading model " << fullPath << " (NULL) \n"; shape = NULL; } else { shape = new dynamics::MeshShape(Eigen::Vector3d(mesh->scale.x, mesh->scale.y, mesh->scale.z), model); } } // Unknown geometry type else { std::cout << "[add_Shape] No MESH, BOX, CYLINDER OR SPHERE! Not loading this shape." << std::endl; return NULL; } shape->setLocalTransform(toEigen(_vizOrCol->origin)); setMaterial(shape, _vizOrCol); return shape; } template dynamics::Shape* DartLoader::createShape<urdf::Visual>(const urdf::Visual* _vizOrCol, std::string _rootToSkelPath); template dynamics::Shape* DartLoader::createShape<urdf::Collision>(const urdf::Collision* _vizOrCol, std::string _rootToSkelPath); /** * @function pose2Affine3d */ Eigen::Isometry3d DartLoader::toEigen(const urdf::Pose& _pose) { Eigen::Quaterniond quat; _pose.rotation.getQuaternion(quat.x(), quat.y(), quat.z(), quat.w()); Eigen::Isometry3d transform(quat); transform.translation() = Eigen::Vector3d(_pose.position.x, _pose.position.y, _pose.position.z); return transform; } Eigen::Vector3d DartLoader::toEigen(const urdf::Vector3& _vector) { return Eigen::Vector3d(_vector.x, _vector.y, _vector.z); } } // namespace utils } // namespace dart <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_ppm_firinit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_ppm_firinit.C /// @brief Configures the PPM FIR errors /// // *HWP HW Owner: Amit Kumar <akumar3@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 1 // *HWP Consumed by: FSP:HS /// /// \verbatim /// /// Procedure Prereq: /// - completed istep procedure /// /// High-level procedure flow: /// /// get all functional child chiplets /// /// loop over all functional chiplets { /// calculate address /// set the error mask in order to mask all errors /// /// } /// /// \endverbatim // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_ppm_firinit.H> // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- fapi2::ReturnCode p9_pm_ppm_firinit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_IMP("p9_pm_ppm_firinit start"); FAPI_INF("p9_pm_ppm_firinit end"); return fapi2::current_err; } <commit_msg>p9_pm_ppm_firinit & p9_pm_cme_firinit L2 delivery<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_ppm_firinit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_ppm_firinit.C /// @brief Configures the CME FIRs, Mask & Actions /// // *HWP HW Owner: Amit Kumar <akumar3@us.ibm.com> // *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// High-level procedure flow: /// \verbatim /// if reset: /// loop over all functional chiplets (core and quad){ /// Mask all bits of error mask /// } /// else if init: /// loop over all functional chiplets (core and quad) { /// Mask the required bits /// } /// /// Procedure Prereq: /// o System clocks are running /// \endverbatim // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_pm_ppm_firinit.H> // ---------------------------------------------------------------------- // Constant Definitions // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // Function prototype // ---------------------------------------------------------------------- /// @brief Initialize the core and quad's error mask registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_ppm_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// @brief Reset the core and quad's error mask registers /// /// @param[in] i_target Chip target /// /// @return FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode pm_ppm_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- fapi2::ReturnCode p9_pm_ppm_firinit( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9pm::PM_FLOW_MODE i_mode) { FAPI_IMP("p9_pm_ppm_firinit start"); if(i_mode == p9pm::PM_RESET) { FAPI_TRY(pm_ppm_fir_reset(i_target), "ERROR: Failed to reset the Core and Quad error masks"); } else if(i_mode == p9pm::PM_INIT) { FAPI_TRY(pm_ppm_fir_init(i_target), "ERROR: Failed to initialize Core and Quad error masks"); } else { FAPI_ASSERT(false, fapi2::PM_PPM_FIRINIT_BAD_MODE().set_BADMODE(i_mode), "ERROR; Unknown mode passed to p9_pm_ppm_firinit. Mode %x", i_mode); } fapi_try_exit: FAPI_INF("p9_pm_ppm_firinit end"); return fapi2::current_err; } fapi2::ReturnCode pm_ppm_fir_init( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_ppm_fir_init start"); uint8_t l_firinit_done_flag; auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); auto l_coreChiplets = i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_eq_chplt : l_eqChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_PPM_LFIR> l_qppmFir(l_eq_chplt); // As of now I am just masking all the bits. // The exact details about which bits to be masked/unmasked // is yet to be known FAPI_TRY(l_qppmFir.setAllRegBits(p9pmFIR::REG_ERRMASK), "ERROR: Faled to set the Quad Error MASK"); if (l_firinit_done_flag) { /* Restore Quad PPM Error Mask */ FAPI_TRY(l_qppmFir.restoreSavedMask(), "ERROR: Failed to restore the Quad Error mask saved"); } FAPI_TRY(l_qppmFir.put(), "ERROR:Failed to write to the Quad Error mask FIR MASK"); } for (auto l_core_chplt : l_coreChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_PPM_LFIR> l_cppmFir(l_core_chplt); // As of now I am just masking all the bits. // The exact details about which bits to be masked/unmasked // is yet to be known FAPI_TRY(l_cppmFir.setAllRegBits(p9pmFIR::REG_ERRMASK), "ERROR: Failed to set the Core Error MASK"); if (l_firinit_done_flag) { /* Restore Core PPM Error Mask */ FAPI_TRY(l_cppmFir.restoreSavedMask(), "ERROR: Failed to restore the Core Error mask saved"); } FAPI_TRY(l_cppmFir.put(), "ERROR:Failed to write to the Core Error mask"); } fapi_try_exit: return fapi2::current_err; } fapi2::ReturnCode pm_ppm_fir_reset( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_IMP("pm_ppm_fir_reset start"); uint8_t l_firinit_done_flag; auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ> (fapi2::TARGET_STATE_FUNCTIONAL); auto l_coreChiplets = i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PM_FIRINIT_DONE_ONCE_FLAG, i_target, l_firinit_done_flag), "ERROR: Failed to fetch the entry status of FIRINIT"); for (auto l_eq_chplt : l_eqChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_PPM_LFIR> l_ppmFir(l_eq_chplt); if (l_firinit_done_flag == 1) { FAPI_TRY(l_ppmFir.get(p9pmFIR::REG_ERRMASK), "ERROR: Failed to get the QUAD ERROR MASK value"); /* Fetch the QUAD ERROR MASK; Save it to HWP attribute; clear it */ FAPI_TRY(l_ppmFir.saveMask(), "ERROR: Failed to save Quad ERROR Mask to the attribute"); } FAPI_TRY(l_ppmFir.setAllRegBits(p9pmFIR::REG_ERRMASK), "ERROR: Faled to set the Quad Error MASK"); FAPI_TRY(l_ppmFir.put(), "ERROR:Failed to write to the Quad Error MASK"); } for (auto l_c_chplt : l_coreChiplets) { p9pmFIR::PMFir <p9pmFIR::FIRTYPE_PPM_LFIR> l_cppmFir(l_c_chplt); if (l_firinit_done_flag == 1) { FAPI_TRY(l_cppmFir.get(p9pmFIR::REG_ERRMASK), "ERROR: Failed to get the Core ERROR MASK value"); /* Fetch the core ERROR MASK; Save it to HWP attribute; clear it */ FAPI_TRY(l_cppmFir.saveMask(), "ERROR: Failed to save Core ERROR Mask to the attribute"); } FAPI_TRY(l_cppmFir.setAllRegBits(p9pmFIR::REG_ERRMASK), "ERROR: Faled to set the Core Error MASK"); FAPI_TRY(l_cppmFir.put(), "ERROR:Failed to write to the Core Error MASK"); } fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_scan_ring_util.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_RING_UTIL_H #define __P9_SCAN_RING_UTIL_H #include <fapi2.H> #include "p9_ringId.H" #include "p9_stop_util.H" #include <map> //#define __CRONUS_VER /// /// @file p9_scan_ring_util.H /// @brief utility classes and functions for scan ring debug. /// /// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot:Phyp:Cro // namespace p9_hcodeImageBuild { /** * @brief enumerates all the platforms associated with hcode image build. */ enum PlatId { PLAT_SELF = 0, PLAT_SGPE = 1, PLAT_CME = 2, PLAT_PGPE = 3, }; /** * @brief constants associated with fake scan rings. */ enum FakeScanRing_t { SCAN_RNG_START = 0x5363616e20526e67, SCAN_RNG_END = 0x52696e6720456e64, MAX_SCAN_RING_SIZE = 120, MAX_FAKE_CMN_RING = 0x14, MAX_FAKE_RING = 0x1E, }; /** * @brief debug modes supported for scan rings. */ enum RingDebugMode_t { SCAN_RING_NO_DEBUG = 0x00, SCAN_RING_TRACE_DEBUG = 0x01, SCAN_RING_TRACE_DEEP_DEBUG = 0x02, }; /** * @brief models a fake ring for debug. */ struct FakeRing { uint64_t iv_ringHeader; uint64_t iv_ringNumber; uint8_t iv_ringPayload[MAX_SCAN_RING_SIZE]; uint64_t iv_ringEnd; #ifdef __CRONUS_VER FakeRing( uint8_t i_ringNumber ): iv_ringHeader( SWIZZLE_8_BYTE(SCAN_RNG_START) ), iv_ringEnd(SWIZZLE_8_BYTE(SCAN_RNG_END)) { memset( &iv_ringPayload, 0xAA, MAX_SCAN_RING_SIZE ); uint8_t temp1 = i_ringNumber / 100; temp1 = temp1 + 0x30; iv_ringNumber = temp1 << 16; temp1 = i_ringNumber % 100; iv_ringNumber |= (( temp1 / 10) + 0x30 ) << 8; iv_ringNumber |= ((temp1 % 10) + 0x30 ); iv_ringNumber = SWIZZLE_8_BYTE(iv_ringNumber); } #else FakeRing( uint8_t i_ringNumber ): iv_ringHeader( 0 ), iv_ringEnd( 0) { //dummy constructor to avoid compilation issue memset( &iv_ringPayload, 0xAA, MAX_SCAN_RING_SIZE ); } #endif }; class RingName { public: /** * @brief constructor * @param i_ringName name associated with the a scan ring. * @param i_debugMode debug mode. */ RingName( char* i_ringName ); /** * @brief constructor */ RingName() {}; /** * @brief destructor */ ~RingName() {}; /** * @brief returns string Name. */ char* c_str(); private: char iv_ringStr[40]; }; /** * @brief models the profile of a scan ring for debug. */ struct RingProfile { RingID iv_ringId; uint32_t iv_ringOffset; uint32_t iv_ringSize; uint32_t iv_chipletPos; RingProfile ( RingID i_ringId, uint16_t i_ringOffset, uint16_t i_ringSize ) : iv_ringId( i_ringId ), iv_ringOffset( i_ringOffset ), iv_ringSize( i_ringSize ), iv_chipletPos( 0 ) { } RingProfile ( RingID i_ringId, uint8_t i_chipletPos ) : iv_ringId( i_ringId ), iv_ringOffset( 0 ), iv_ringSize( 0 ), iv_chipletPos( i_chipletPos ) { } RingProfile(): iv_ringId(eq_fure), iv_ringOffset(0), iv_ringSize(0) {} }; /** * @brief populates an input buffer with a fake scan ring. * @param o_pRingBuffer rings in which scan rings are copied. * @param o_size size of scan ring. * @param i_ringId scan ring id. * @param i_plat platform associated with scan ring. */ void getScanRing( void* o_pRingBuffer, uint32_t& o_size, uint32_t i_ringId, PlatId i_plat ); /** * @brief class to suppport debug of scan ring layout in P9 HOMER * @note Intended platform is cronus. */ class RingBucket { public: /** * @brief constructor */ RingBucket( PlatId i_plat, uint8_t* i_pRingStart, RingDebugMode_t i_debugMode ); /** * @brief destructor */ ~RingBucket(); /** * @brief returns the id of common ring from storage index. * @param i_ringPos storage position of ring. * @return scan ring id. */ RingID getCommonRingId( uint16_t i_ringPos ); /** * @brief returns the id of chiplet instance specific ring from storage index. * @param i_ringPos storage position of ring. * @return scan ring id. */ RingID getInstRingId ( uint16_t i_ringPos ); /** * @brief returns the offset associated with scan ring of given id. * @param i_ringId Id associated with a scan ring. * @param SUCCESS for successful operation erro code otherwise. * @return offset associated with a given ring. */ uint16_t getRingOffset( RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief sets the offset associated with scan ring of given id. * @param i_pRingPtr points to start of scan ring. * @param i_ringId Id associated with a scan ring. * @param SUCCESS for successful operation, error code otherwise. */ void setRingOffset( uint8_t* i_pRingPtr, RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief sets base of a ring associated with a given platform. * @param i_ringPos points to start of ring index of CME/SGPE */ void initRingBase( uint8_t* i_pRingStart ); /** * @brief sets size of a given scan ring. * @param i_ringId Id associated with a given scan ring. * @param i_ringSize size of scan ring. */ void setRingSize( RingID i_ringId, uint16_t i_ringSize, uint8_t i_chipletPos = 0 ); /** * @brief returns size of a given scan ring. * @param i_ringId Id associated with a given scan ring. * @return size of a given scan ring. */ uint16_t getRingSize( RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief returns name of scan ring associated with given id. * @param i_ringId Id associated with a given scan ring. * @return size of a given scan ring. */ const char* getRingName( RingID i_ringId ); /** * @brief generates a report on layout of CME/SGPE scan rings in HOMER. */ void dumpRings( ); /** * @brief generates a report on layout of CME/SGPE scan ring overrides in HOMER. */ void dumpOverrideRings(); /** * @brief prints a given ring for content debug * @param i_ptr points to a work buffer containing ring. * @param i_ringSize size of a ring. * @param i_ringId ring id */ void extractRing( void* i_ptr, uint32_t i_ringSize, uint32_t i_ringId ); private: std::map<uint16_t, RingProfile> iv_cmnRingMap; std::map<uint16_t, RingProfile> iv_instRingMap; uint8_t* iv_pRingStart; uint16_t iv_ringSize; PlatId iv_plat; RingDebugMode_t iv_debugMode; std::map<RingID, RingName> iv_ringName; }; class P9FuncModel { public: /** * @brief constructor */ P9FuncModel( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procTgt ); /** * brief destructor */ ~P9FuncModel( ); /** * @brief returns functional state of a given core. */ bool isCoreFunctional( uint32_t i_corePos ) const; /** * @brief returns functional state of a given ex. */ bool isExFunctional( uint32_t i_exPos ) const; /** * @brief returns functional state of a given quad. */ bool isQuadFunctional( uint32_t i_quadPos ) const; /** * @brief returns dd level associated with a processor. */ uint8_t getChipLevel() const; /** * uint8_t returns an ID pertaining to chip name. */ uint8_t getChipName() const; /** * @brief constructor */ P9FuncModel( ); private: P9FuncModel( const P9FuncModel& ); //Disallow copy constructor P9FuncModel& operator = ( const P9FuncModel&); // Disallow assignment operator uint32_t iv_funcCores; uint16_t iv_funcExes; uint8_t iv_funcQuads; uint8_t iv_ddLevel; uint8_t iv_chipName; uint8_t iv_reserve[3]; }; }// namesapce p9_hcodeImageBuild ends #endif //__P9_SCAN_RING_UTIL_H <commit_msg>UV Support : Augmented STOP API and self restore for enabling ultravisor.<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_scan_ring_util.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __P9_SCAN_RING_UTIL_H #define __P9_SCAN_RING_UTIL_H #include <fapi2.H> #include "p9_ringId.H" #include "p9_stop_util.H" #include <map> //#define __CRONUS_VER /// /// @file p9_scan_ring_util.H /// @brief utility classes and functions for scan ring debug. /// /// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com> /// *HWP FW Owner: Prem S Jha <premjha2@in.ibm.com> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot:Phyp:Cro // namespace p9_hcodeImageBuild { /** * @brief enumerates all the platforms associated with hcode image build. */ enum PlatId { PLAT_SELF = 0, PLAT_SGPE = 1, PLAT_CME = 2, PLAT_PGPE = 3, }; /** * @brief constants associated with fake scan rings. */ enum FakeScanRing_t { SCAN_RNG_START = 0x5363616e20526e67, SCAN_RNG_END = 0x52696e6720456e64, MAX_SCAN_RING_SIZE = 120, MAX_FAKE_CMN_RING = 0x14, MAX_FAKE_RING = 0x1E, }; /** * @brief debug modes supported for scan rings. */ enum RingDebugMode_t { SCAN_RING_NO_DEBUG = 0x00, SCAN_RING_TRACE_DEBUG = 0x01, SCAN_RING_TRACE_DEEP_DEBUG = 0x02, }; /** * @brief models a fake ring for debug. */ struct FakeRing { uint64_t iv_ringHeader; uint64_t iv_ringNumber; uint8_t iv_ringPayload[MAX_SCAN_RING_SIZE]; uint64_t iv_ringEnd; #ifdef __CRONUS_VER FakeRing( uint8_t i_ringNumber ): iv_ringHeader( SWIZZLE_8_BYTE(SCAN_RNG_START) ), iv_ringEnd(SWIZZLE_8_BYTE(SCAN_RNG_END)) { memset( &iv_ringPayload, 0xAA, MAX_SCAN_RING_SIZE ); uint8_t temp1 = i_ringNumber / 100; temp1 = temp1 + 0x30; iv_ringNumber = temp1 << 16; temp1 = i_ringNumber % 100; iv_ringNumber |= (( temp1 / 10) + 0x30 ) << 8; iv_ringNumber |= ((temp1 % 10) + 0x30 ); iv_ringNumber = SWIZZLE_8_BYTE(iv_ringNumber); } #else FakeRing( uint8_t i_ringNumber ): iv_ringHeader( 0 ), iv_ringEnd( 0) { //dummy constructor to avoid compilation issue memset( &iv_ringPayload, 0xAA, MAX_SCAN_RING_SIZE ); } #endif }; class RingName { public: /** * @brief constructor * @param i_ringName name associated with the a scan ring. * @param i_debugMode debug mode. */ RingName( char* i_ringName ); /** * @brief constructor */ RingName() {}; /** * @brief destructor */ ~RingName() {}; /** * @brief returns string Name. */ char* c_str(); private: char iv_ringStr[40]; }; /** * @brief models the profile of a scan ring for debug. */ struct RingProfile { RingID iv_ringId; uint32_t iv_ringOffset; uint32_t iv_ringSize; uint32_t iv_chipletPos; RingProfile ( RingID i_ringId, uint16_t i_ringOffset, uint16_t i_ringSize ) : iv_ringId( i_ringId ), iv_ringOffset( i_ringOffset ), iv_ringSize( i_ringSize ), iv_chipletPos( 0 ) { } RingProfile ( RingID i_ringId, uint8_t i_chipletPos ) : iv_ringId( i_ringId ), iv_ringOffset( 0 ), iv_ringSize( 0 ), iv_chipletPos( i_chipletPos ) { } RingProfile(): iv_ringId(eq_fure), iv_ringOffset(0), iv_ringSize(0) {} }; /** * @brief populates an input buffer with a fake scan ring. * @param o_pRingBuffer rings in which scan rings are copied. * @param o_size size of scan ring. * @param i_ringId scan ring id. * @param i_plat platform associated with scan ring. */ void getScanRing( void* o_pRingBuffer, uint32_t& o_size, uint32_t i_ringId, PlatId i_plat ); /** * @brief class to suppport debug of scan ring layout in P9 HOMER * @note Intended platform is cronus. */ class RingBucket { public: /** * @brief constructor */ RingBucket( PlatId i_plat, uint8_t* i_pRingStart, RingDebugMode_t i_debugMode ); /** * @brief destructor */ ~RingBucket(); /** * @brief returns the id of common ring from storage index. * @param i_ringPos storage position of ring. * @return scan ring id. */ RingID getCommonRingId( uint16_t i_ringPos ); /** * @brief returns the id of chiplet instance specific ring from storage index. * @param i_ringPos storage position of ring. * @return scan ring id. */ RingID getInstRingId ( uint16_t i_ringPos ); /** * @brief returns the offset associated with scan ring of given id. * @param i_ringId Id associated with a scan ring. * @param SUCCESS for successful operation erro code otherwise. * @return offset associated with a given ring. */ uint16_t getRingOffset( RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief sets the offset associated with scan ring of given id. * @param i_pRingPtr points to start of scan ring. * @param i_ringId Id associated with a scan ring. * @param SUCCESS for successful operation, error code otherwise. */ void setRingOffset( uint8_t* i_pRingPtr, RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief sets base of a ring associated with a given platform. * @param i_ringPos points to start of ring index of CME/SGPE */ void initRingBase( uint8_t* i_pRingStart ); /** * @brief sets size of a given scan ring. * @param i_ringId Id associated with a given scan ring. * @param i_ringSize size of scan ring. */ void setRingSize( RingID i_ringId, uint16_t i_ringSize, uint8_t i_chipletPos = 0 ); /** * @brief returns size of a given scan ring. * @param i_ringId Id associated with a given scan ring. * @return size of a given scan ring. */ uint16_t getRingSize( RingID i_ringId, uint8_t i_chipletPos = 0 ); /** * @brief returns name of scan ring associated with given id. * @param i_ringId Id associated with a given scan ring. * @return size of a given scan ring. */ const char* getRingName( RingID i_ringId ); /** * @brief generates a report on layout of CME/SGPE scan rings in HOMER. */ void dumpRings( ); /** * @brief generates a report on layout of CME/SGPE scan ring overrides in HOMER. */ void dumpOverrideRings(); /** * @brief prints a given ring for content debug * @param i_ptr points to a work buffer containing ring. * @param i_ringSize size of a ring. * @param i_ringId ring id */ void extractRing( void* i_ptr, uint32_t i_ringSize, uint32_t i_ringId ); private: std::map<uint16_t, RingProfile> iv_cmnRingMap; std::map<uint16_t, RingProfile> iv_instRingMap; uint8_t* iv_pRingStart; uint16_t iv_ringSize; PlatId iv_plat; RingDebugMode_t iv_debugMode; std::map<RingID, RingName> iv_ringName; }; class P9FuncModel { public: /** * @brief constructor */ P9FuncModel( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procTgt ); /** * brief destructor */ ~P9FuncModel( ); /** * @brief returns functional state of a given core. */ bool isCoreFunctional( uint32_t i_corePos ) const; /** * @brief returns functional state of a given ex. */ bool isExFunctional( uint32_t i_exPos ) const; /** * @brief returns functional state of a given quad. */ bool isQuadFunctional( uint32_t i_quadPos ) const; /** * @brief returns dd level associated with a processor. */ uint8_t getChipLevel() const; /** * uint8_t returns an ID pertaining to chip name. */ uint8_t getChipName() const; /** * returns true if URMOR has a hw bug else false. */ uint8_t hasUrmorBug() const; /** * @brief constructor */ P9FuncModel( ); private: P9FuncModel( const P9FuncModel& ); //Disallow copy constructor P9FuncModel& operator = ( const P9FuncModel&); // Disallow assignment operator uint32_t iv_funcCores; uint16_t iv_funcExes; uint8_t iv_funcQuads; uint8_t iv_ddLevel; uint8_t iv_chipName; uint8_t iv_urmorBug; uint8_t iv_reserve[2]; }; }// namesapce p9_hcodeImageBuild ends #endif //__P9_SCAN_RING_UTIL_H <|endoftext|>
<commit_before>/* * Molch, an implementation of the axolotl ratchet based on libsodium * * ISC License * * Copyright (C) 2015-2016 Max Bruckner (FSMaxB) <max at maxbruckner dot de> * * 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. */ #ifndef LIB_KEY_HPP #define LIB_KEY_HPP #include <array> #include <memory> #include <ostream> #include <sodium.h> #include <iterator> #include <algorithm> #include "buffer.hpp" #include "constants.h" #include "molch-exception.hpp" #include "endianness.hpp" #include "gsl.hpp" #include "protobuf-pool.hpp" #include "protobuf.hpp" namespace Molch { //type of key, this is used to distinguish key types //and for example avoid copying a private key to a public key enum class KeyType : uint8_t { Key, MessageKey, ChainKey, HeaderKey, RootKey, BackupKey, PublicKey, PrivateKey, PublicSigningKey, PrivateSigningKey }; template <size_t length, KeyType keytype> class Key : public std::array<gsl::byte,length> { private: Key& copy(const Key& key) { this->empty = key.empty; std::copy(std::cbegin(key), std::cend(key), std::begin(*this)); return *this; } Key& move(Key&& key) { this->empty = key.empty; if (key.empty) { key.clear(); return *this; } for (size_t i{0}; i < length; ++i) { (*this)[i] = key[i]; } return *this; } public: bool empty{true}; Key() = default; Key(const Key& key) { this->copy(key); } Key(Key&& key) { this->move(std::move(key)); } Key(const ProtobufCKey& key) { this->set({uchar_to_byte(key.key.data), key.key.len}); } ~Key() { this->clear(); } Key& operator=(const Key& key) { return this->copy(key); } Key& operator=(Key&& key) { return this->move(std::move(key)); } /* * Constant time comparison of two keys. * * returns: * -1 if this is less than key * 0 if this is equal to key * +1 if this is greater than key * * throws an exception if either is empty. */ int compare(const Key& key) const { Expects(!this->empty && !key.empty); return sodium_compare(*this, key); } //comparison operators bool operator>(const Key& key) const { return (this->compare(key) == 1); } bool operator<(const Key& key) const { return (this->compare(key) == -1); } bool operator>=(const Key& key) const { return !(*this < key); } bool operator<=(const Key& key) const { return !(*this > key); } bool operator==(const Key& key) const { if (this->empty && key.empty) { return true; } else if (this->empty || key.empty) { return false; } return (this->compare(key) == 0); } bool operator!=(const Key& key) const { return !(*this == key); } KeyType type() { return type; } template <size_t derived_length,KeyType derived_type> void deriveTo(Key<derived_length,derived_type>& derived_key, const uint32_t subkey_counter) const { Expects(!this->empty); static_assert(derived_length <= crypto_generichash_blake2b_BYTES_MAX, "The derived length is greater than crypto_generichas_blake2b_BYTES_MAX"); static_assert(derived_length >= crypto_generichash_blake2b_BYTES_MIN, "The derived length is smaller than crypto_generichash_blake2b_BYTES_MAX"); static_assert(length <= crypto_generichash_blake2b_KEYBYTES_MAX, "The length to derive from is greater than crypto_generichash_blake2b_KEYBYTES_MAX"); static_assert(length >= crypto_generichash_blake2b_KEYBYTES_MIN, "The length to derive from is smaller than crypto_generichash_blake2b_KEYBYTES_MIN"); //create a salt that contains the number of the subkey Key<crypto_generichash_blake2b_SALTBYTES,KeyType::Key> salt; salt.clear(); //fill with zeroes salt.empty = false; //fill the salt with a big endian representation of the subkey counter to_big_endian(subkey_counter, {salt.data()+ salt.size() - sizeof(uint32_t), sizeof(uint32_t)}); const unsigned char personal[]{"molch_cryptolib"}; static_assert(sizeof(personal) == crypto_generichash_blake2b_PERSONALBYTES, "personal string is not crypto_generichash_blake2b_PERSONALBYTES long"); //set length of output crypto_generichash_blake2b_salt_personal( derived_key, {nullptr}, //input *this, salt, {uchar_to_byte(personal), sizeof(personal)}); derived_key.empty = false; } void fillRandom() { randombytes_buf(*this); this->empty = false; } //TODO get rid of this bool isNone() const { if (this->empty) { return true; } return sodium_is_zero(*this); } //copy from a raw byte array void set(const span<const gsl::byte> data) { Expects(data.size() == length); std::copy(std::cbegin(data), std::cend(data), this->data()); this->empty = false; } //copy to a raw byte array void copyTo(span<gsl::byte> data) const { Expects(data.size() == length); std::copy(std::cbegin(*this), std::cend(*this), std::begin(data)); } void clear() { sodium_memzero(*this); this->empty = true; } ProtobufCKey* exportProtobuf(ProtobufPool& pool) const { auto key{pool.allocate<ProtobufCKey>(1)}; key__init(key); key->key.data = pool.allocate<uint8_t>(length); key->key.len = length; this->copyTo({ uchar_to_byte(key->key.data), key->key.len }); return key; } std::ostream& printHex(std::ostream& stream) const { static constexpr size_t width{30}; if (this->empty) { return stream << "(empty)"; } const size_t hex_length{this->size() * 2 + sizeof("")}; auto hex{std::make_unique<char[]>(hex_length)}; sodium_bin2hex({hex.get(), hex_length}, *this); for (size_t i{0}; i < hex_length; i++) { if ((width != 0) && ((i % width) == 0) && (i != 0)) { stream << '\n'; } else if ((i % 2 == 0) && (i != 0)) { stream << ' '; } stream << hex[i]; } return stream; } }; class MessageKey : public Key<MESSAGE_KEY_SIZE,KeyType::MessageKey> { public: //inherit constructors using Key<MESSAGE_KEY_SIZE,KeyType::MessageKey>::Key; }; class ChainKey : public Key<CHAIN_KEY_SIZE,KeyType::ChainKey> { public: //inherit constructors using Key<CHAIN_KEY_SIZE,KeyType::ChainKey>::Key; MessageKey deriveMessageKey() const { MessageKey message_key; this->deriveTo(message_key, 0); return message_key; } ChainKey deriveChainKey() const { ChainKey chain_key; this->deriveTo(chain_key, 1); return chain_key; } }; class HeaderKey : public Key<HEADER_KEY_SIZE,KeyType::HeaderKey> { public: //inherit constructors using Key<HEADER_KEY_SIZE,KeyType::HeaderKey>::Key; }; class RootKey : public Key<ROOT_KEY_SIZE,KeyType::RootKey> { public: //inherit constructors using Key<ROOT_KEY_SIZE,KeyType::RootKey>::Key; }; class BackupKey : public Key<BACKUP_KEY_SIZE,KeyType::BackupKey> { public: //inherit constructors using Key<BACKUP_KEY_SIZE,KeyType::BackupKey>::Key; }; class PublicKey : public Key<PUBLIC_KEY_SIZE,KeyType::PublicKey> { public: //inherit constructors using Key<PUBLIC_KEY_SIZE,KeyType::PublicKey>::Key; }; class PrivateKey : public Key<PRIVATE_KEY_SIZE,KeyType::PrivateKey> { public: //inherit constructors using Key<PRIVATE_KEY_SIZE,KeyType::PrivateKey>::Key; }; class PublicSigningKey : public Key<PUBLIC_MASTER_KEY_SIZE,KeyType::PublicSigningKey> { public: //inherit constructors using Key<PUBLIC_MASTER_KEY_SIZE,KeyType::PublicSigningKey>::Key; }; class PrivateSigningKey : public Key<PRIVATE_MASTER_KEY_SIZE,KeyType::PrivateSigningKey> { public: //inherit constructors using Key<PRIVATE_MASTER_KEY_SIZE,KeyType::PrivateSigningKey>::Key; }; } #endif /* LIB_KEY_HPP */ <commit_msg>Coverity: Key: Catch exception in destructor<commit_after>/* * Molch, an implementation of the axolotl ratchet based on libsodium * * ISC License * * Copyright (C) 2015-2016 Max Bruckner (FSMaxB) <max at maxbruckner dot de> * * 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. */ #ifndef LIB_KEY_HPP #define LIB_KEY_HPP #include <array> #include <memory> #include <ostream> #include <sodium.h> #include <iterator> #include <algorithm> #include "buffer.hpp" #include "constants.h" #include "molch-exception.hpp" #include "endianness.hpp" #include "gsl.hpp" #include "protobuf-pool.hpp" #include "protobuf.hpp" namespace Molch { //type of key, this is used to distinguish key types //and for example avoid copying a private key to a public key enum class KeyType : uint8_t { Key, MessageKey, ChainKey, HeaderKey, RootKey, BackupKey, PublicKey, PrivateKey, PublicSigningKey, PrivateSigningKey }; template <size_t length, KeyType keytype> class Key : public std::array<gsl::byte,length> { private: Key& copy(const Key& key) { this->empty = key.empty; std::copy(std::cbegin(key), std::cend(key), std::begin(*this)); return *this; } Key& move(Key&& key) { this->empty = key.empty; if (key.empty) { key.clear(); return *this; } for (size_t i{0}; i < length; ++i) { (*this)[i] = key[i]; } return *this; } public: bool empty{true}; Key() = default; Key(const Key& key) { this->copy(key); } Key(Key&& key) { this->move(std::move(key)); } Key(const ProtobufCKey& key) { this->set({uchar_to_byte(key.key.data), key.key.len}); } ~Key() { try { this->clear(); } catch (...) { std::terminate(); } } Key& operator=(const Key& key) { return this->copy(key); } Key& operator=(Key&& key) { return this->move(std::move(key)); } /* * Constant time comparison of two keys. * * returns: * -1 if this is less than key * 0 if this is equal to key * +1 if this is greater than key * * throws an exception if either is empty. */ int compare(const Key& key) const { Expects(!this->empty && !key.empty); return sodium_compare(*this, key); } //comparison operators bool operator>(const Key& key) const { return (this->compare(key) == 1); } bool operator<(const Key& key) const { return (this->compare(key) == -1); } bool operator>=(const Key& key) const { return !(*this < key); } bool operator<=(const Key& key) const { return !(*this > key); } bool operator==(const Key& key) const { if (this->empty && key.empty) { return true; } else if (this->empty || key.empty) { return false; } return (this->compare(key) == 0); } bool operator!=(const Key& key) const { return !(*this == key); } KeyType type() { return type; } template <size_t derived_length,KeyType derived_type> void deriveTo(Key<derived_length,derived_type>& derived_key, const uint32_t subkey_counter) const { Expects(!this->empty); static_assert(derived_length <= crypto_generichash_blake2b_BYTES_MAX, "The derived length is greater than crypto_generichas_blake2b_BYTES_MAX"); static_assert(derived_length >= crypto_generichash_blake2b_BYTES_MIN, "The derived length is smaller than crypto_generichash_blake2b_BYTES_MAX"); static_assert(length <= crypto_generichash_blake2b_KEYBYTES_MAX, "The length to derive from is greater than crypto_generichash_blake2b_KEYBYTES_MAX"); static_assert(length >= crypto_generichash_blake2b_KEYBYTES_MIN, "The length to derive from is smaller than crypto_generichash_blake2b_KEYBYTES_MIN"); //create a salt that contains the number of the subkey Key<crypto_generichash_blake2b_SALTBYTES,KeyType::Key> salt; salt.clear(); //fill with zeroes salt.empty = false; //fill the salt with a big endian representation of the subkey counter to_big_endian(subkey_counter, {salt.data()+ salt.size() - sizeof(uint32_t), sizeof(uint32_t)}); const unsigned char personal[]{"molch_cryptolib"}; static_assert(sizeof(personal) == crypto_generichash_blake2b_PERSONALBYTES, "personal string is not crypto_generichash_blake2b_PERSONALBYTES long"); //set length of output crypto_generichash_blake2b_salt_personal( derived_key, {nullptr}, //input *this, salt, {uchar_to_byte(personal), sizeof(personal)}); derived_key.empty = false; } void fillRandom() { randombytes_buf(*this); this->empty = false; } //TODO get rid of this bool isNone() const { if (this->empty) { return true; } return sodium_is_zero(*this); } //copy from a raw byte array void set(const span<const gsl::byte> data) { Expects(data.size() == length); std::copy(std::cbegin(data), std::cend(data), this->data()); this->empty = false; } //copy to a raw byte array void copyTo(span<gsl::byte> data) const { Expects(data.size() == length); std::copy(std::cbegin(*this), std::cend(*this), std::begin(data)); } void clear() { sodium_memzero(*this); this->empty = true; } ProtobufCKey* exportProtobuf(ProtobufPool& pool) const { auto key{pool.allocate<ProtobufCKey>(1)}; key__init(key); key->key.data = pool.allocate<uint8_t>(length); key->key.len = length; this->copyTo({ uchar_to_byte(key->key.data), key->key.len }); return key; } std::ostream& printHex(std::ostream& stream) const { static constexpr size_t width{30}; if (this->empty) { return stream << "(empty)"; } const size_t hex_length{this->size() * 2 + sizeof("")}; auto hex{std::make_unique<char[]>(hex_length)}; sodium_bin2hex({hex.get(), hex_length}, *this); for (size_t i{0}; i < hex_length; i++) { if ((width != 0) && ((i % width) == 0) && (i != 0)) { stream << '\n'; } else if ((i % 2 == 0) && (i != 0)) { stream << ' '; } stream << hex[i]; } return stream; } }; class MessageKey : public Key<MESSAGE_KEY_SIZE,KeyType::MessageKey> { public: //inherit constructors using Key<MESSAGE_KEY_SIZE,KeyType::MessageKey>::Key; }; class ChainKey : public Key<CHAIN_KEY_SIZE,KeyType::ChainKey> { public: //inherit constructors using Key<CHAIN_KEY_SIZE,KeyType::ChainKey>::Key; MessageKey deriveMessageKey() const { MessageKey message_key; this->deriveTo(message_key, 0); return message_key; } ChainKey deriveChainKey() const { ChainKey chain_key; this->deriveTo(chain_key, 1); return chain_key; } }; class HeaderKey : public Key<HEADER_KEY_SIZE,KeyType::HeaderKey> { public: //inherit constructors using Key<HEADER_KEY_SIZE,KeyType::HeaderKey>::Key; }; class RootKey : public Key<ROOT_KEY_SIZE,KeyType::RootKey> { public: //inherit constructors using Key<ROOT_KEY_SIZE,KeyType::RootKey>::Key; }; class BackupKey : public Key<BACKUP_KEY_SIZE,KeyType::BackupKey> { public: //inherit constructors using Key<BACKUP_KEY_SIZE,KeyType::BackupKey>::Key; }; class PublicKey : public Key<PUBLIC_KEY_SIZE,KeyType::PublicKey> { public: //inherit constructors using Key<PUBLIC_KEY_SIZE,KeyType::PublicKey>::Key; }; class PrivateKey : public Key<PRIVATE_KEY_SIZE,KeyType::PrivateKey> { public: //inherit constructors using Key<PRIVATE_KEY_SIZE,KeyType::PrivateKey>::Key; }; class PublicSigningKey : public Key<PUBLIC_MASTER_KEY_SIZE,KeyType::PublicSigningKey> { public: //inherit constructors using Key<PUBLIC_MASTER_KEY_SIZE,KeyType::PublicSigningKey>::Key; }; class PrivateSigningKey : public Key<PRIVATE_MASTER_KEY_SIZE,KeyType::PrivateSigningKey> { public: //inherit constructors using Key<PRIVATE_MASTER_KEY_SIZE,KeyType::PrivateSigningKey>::Key; }; } #endif /* LIB_KEY_HPP */ <|endoftext|>
<commit_before>#include "stdafx.h" #include "d3d.h" #include <SADXModLoader.h> #include "Trampoline.h" #include "globals.h" #include "../include/lanternapi.h" #include "Obj_SkyDeck.h" DataPointer(int, SkyDeck_AltitudeMode, 0x03C80608); DataPointer(float, SkyDeck_SkyAltitude, 0x03C80610); static Trampoline* SkyDeck_SimulateAltitude_t = nullptr; static Trampoline* SkyBox_SkyDeck_t = nullptr; static Trampoline* Obj_SkyDeck_t = nullptr; static size_t handle = 0; static void __cdecl SkyDeck_SimulateAltitude_r(Uint16 act) { TARGET_DYNAMIC(SkyDeck_SimulateAltitude)(act); // 0 = high altitide (bright), 1 = low altitude (dark) if (SkyDeck_AltitudeMode > 1) { set_blend_factor(0.0f); } else { float f = (max(180.0f, min(250.0f, SkyDeck_SkyAltitude)) - 180.0f) / 70.0f; set_blend_factor(f); } } static void __cdecl SkyBox_SkyDeck_Delete(ObjectMaster*) { // Disable blending in the shader. set_shader_flags(ShaderFlags_Blend, false); // Reset blend indices. set_blend(-1, -1); } static void __cdecl SkyBox_SkyDeck_r(ObjectMaster* _this) { if (_this->DeleteSub != SkyBox_SkyDeck_Delete) { _this->DeleteSub = SkyBox_SkyDeck_Delete; } TARGET_DYNAMIC(SkyBox_SkyDeck)(_this); } static void __cdecl Obj_SkyDeck_Delete(ObjectMaster* _this) { globals::palettes.Remove(handle); set_shader_flags(ShaderFlags_Blend, false); globals::palettes.ForwardBlendAll(false); handle = 0; } static void __cdecl Obj_SkyDeck_r(ObjectMaster* _this) { TARGET_DYNAMIC(Obj_SkyDeck)(_this); if (handle || d3d::effect == nullptr) { return; } _this->DeleteSub = Obj_SkyDeck_Delete; globals::palettes.LoadPalette(LevelIDs_SkyDeck, 0); globals::palettes.LoadSource(LevelIDs_SkyDeck, 0); LanternInstance lantern(&param::PaletteB); lantern.LoadPalette(LevelIDs_SkyDeck, 1); handle = globals::palettes.Add(lantern); globals::palettes.SetLastLevel(-1, -1); globals::palettes.ForwardBlendAll(true); set_shader_flags(ShaderFlags_Blend, true); } void SkyDeck_Init() { Obj_SkyDeck_t = new Trampoline(0x005F02E0, 0x005F02E5, Obj_SkyDeck_r); SkyDeck_SimulateAltitude_t = new Trampoline(0x005ECA80, 0x005ECA87, SkyDeck_SimulateAltitude_r); SkyBox_SkyDeck_t = new Trampoline(0x005F0340, 0x005F0347, SkyBox_SkyDeck_r); } <commit_msg>More work on #45 (fixes perma-darkness after going to the past)<commit_after>#include "stdafx.h" #include "d3d.h" #include <SADXModLoader.h> #include "Trampoline.h" #include "globals.h" #include "../include/lanternapi.h" #include "Obj_SkyDeck.h" DataPointer(int, SkyDeck_AltitudeMode, 0x03C80608); DataPointer(float, SkyDeck_SkyAltitude, 0x03C80610); static Trampoline* SkyDeck_SimulateAltitude_t = nullptr; static Trampoline* SkyBox_SkyDeck_t = nullptr; static Trampoline* Obj_SkyDeck_t = nullptr; static size_t handle = 0; static void __cdecl SkyDeck_SimulateAltitude_r(Uint16 act) { TARGET_DYNAMIC(SkyDeck_SimulateAltitude)(act); // 0 = high altitide (bright), 1 = low altitude (dark) if (SkyDeck_AltitudeMode > 1) { set_blend_factor(0.0f); } else { float f = (max(180.0f, min(250.0f, SkyDeck_SkyAltitude)) - 180.0f) / 70.0f; set_blend_factor(f); } } static void __cdecl SkyBox_SkyDeck_Delete(ObjectMaster*) { // Disable blending in the shader. set_shader_flags(ShaderFlags_Blend, false); // Reset blend indices. set_blend(-1, -1); } static void __cdecl SkyBox_SkyDeck_r(ObjectMaster* _this) { if (_this->DeleteSub != SkyBox_SkyDeck_Delete) { _this->DeleteSub = SkyBox_SkyDeck_Delete; } TARGET_DYNAMIC(SkyBox_SkyDeck)(_this); } static void __cdecl Obj_SkyDeck_Delete(ObjectMaster* _this) { globals::palettes.Remove(handle); set_shader_flags(ShaderFlags_Blend, false); globals::palettes.ForwardBlendAll(false); handle = 0; } static void __cdecl Obj_SkyDeck_r(ObjectMaster* _this) { TARGET_DYNAMIC(Obj_SkyDeck)(_this); if (handle || d3d::effect == nullptr) { return; } _this->DeleteSub = Obj_SkyDeck_Delete; globals::palettes.LoadPalette(LevelIDs_SkyDeck, 0); globals::palettes.LoadSource(LevelIDs_SkyDeck, 0); param::PaletteB = nullptr; LanternInstance lantern(&param::PaletteB); lantern.LoadPalette(LevelIDs_SkyDeck, 1); handle = globals::palettes.Add(lantern); globals::palettes.SetLastLevel(-1, -1); globals::palettes.ForwardBlendAll(true); set_shader_flags(ShaderFlags_Blend, true); } void SkyDeck_Init() { Obj_SkyDeck_t = new Trampoline(0x005F02E0, 0x005F02E5, Obj_SkyDeck_r); SkyDeck_SimulateAltitude_t = new Trampoline(0x005ECA80, 0x005ECA87, SkyDeck_SimulateAltitude_r); SkyBox_SkyDeck_t = new Trampoline(0x005F0340, 0x005F0347, SkyBox_SkyDeck_r); } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/conv.h" namespace tflite { namespace reference_integer_ops { // Fixed-point per-channel-quantization convolution reference kernel. void OneByOneConvPerChannel( const ConvParams& params, const int32_t* output_multiplier, const int32_t* output_shift, const RuntimeShape& input_shape, const int8_t* input_data, const RuntimeShape& filter_shape, const int8_t* filter_data, const RuntimeShape& bias_shape, const int32_t* bias_data, const RuntimeShape& output_shape, int8_t* output_data) { // Get parameters. const int32_t input_offset = params.input_offset; // r = s(q - Z) const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int dilation_width_factor = params.dilation_width_factor; const int dilation_height_factor = params.dilation_height_factor; const int pad_width = params.padding_values.width; const int pad_height = params.padding_values.height; const int32_t output_offset = params.output_offset; // Set min and max value of the output. const int32_t output_activation_min = params.quantized_activation_min; const int32_t output_activation_max = params.quantized_activation_max; // Consistency check. TFLITE_DCHECK_LE(output_activation_min, output_activation_max); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_depth = input_shape.Dims(3); const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3); if (bias_data) { TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); } // Check dimensions of the tensors. const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int filter_input_depth = filter_shape.Dims(3); const int groups = input_depth / filter_input_depth; TFLITE_DCHECK_EQ(input_depth % filter_input_depth, 0); const int filters_per_group = output_depth / groups; const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); for (int batch = 0; batch < batches; ++batch) { for (int out_y = 0; out_y < output_height; ++out_y) { const int in_y_origin = (out_y * stride_height) - pad_height; for (int out_x = 0; out_x < output_width; ++out_x) { const int in_x_origin = (out_x * stride_width) - pad_width; for (int out_channel = 0; out_channel < output_depth; ++out_channel) { auto group = out_channel / filters_per_group; int32_t acc = 0; for (int filter_y = 0; filter_y < filter_height; ++filter_y) { const int in_y = in_y_origin + dilation_height_factor * filter_y; for (int filter_x = 0; filter_x < filter_width; ++filter_x) { const int in_x = in_x_origin + dilation_width_factor * filter_x; // Zero padding by omitting the areas outside the image. const bool is_point_inside_image = (in_x >= 0) && (in_x < input_width) && (in_y >= 0) && (in_y < input_height); if (!is_point_inside_image) { continue; } for (int in_channel = 0; in_channel < filter_input_depth; ++in_channel) { int32_t input_val = input_data[Offset(input_shape, batch, in_y, in_x, in_channel + group * filter_input_depth)]; int32_t filter_val = filter_data[Offset( filter_shape, out_channel, filter_y, filter_x, in_channel)]; // Accumulate with 32 bits accumulator. // In the nudging process during model quantization, we force // real value of 0.0 be represented by a quantized value. This // guarantees that the input_offset is a int8_t, even though // it is represented using int32_t. int32_t += int8_t * // (int8_t - int8_t) so the highest value we can get from each // accumulation is [-127, 127] * ([-128, 127] - // [-128, 127]), which is [-32512, 32512]. log2(32512) // = 14.98, which means we can accumulate at least 2^16 // multiplications without overflow. The accumulator is // applied to a filter so the accumulation logic will hold as // long as the filter size (filter_y * filter_x * in_channel) // does not exceed 2^16, which is the case in all the models // we have seen so far. // TODO(b/174275578): Add a check to make sure the // accumulator depth is smaller than 2^16. acc += filter_val * (input_val + input_offset); } } } if (bias_data) { acc += bias_data[out_channel]; } acc = MultiplyByQuantizedMultiplier( acc, output_multiplier[out_channel], output_shift[out_channel]); acc += output_offset; acc = std::max(acc, output_activation_min); acc = std::min(acc, output_activation_max); output_data[Offset(output_shape, batch, out_y, out_x, out_channel)] = static_cast<int8_t>(acc); } } } } } } // namespace reference_integer_ops } // namespace tflite <commit_msg>fccm_tutorial/conv: accelerate<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <cstdio> #include "fccm_cfu.h" #include "tensorflow/lite/kernels/internal/common.h" #include "tensorflow/lite/kernels/internal/reference/integer_ops/conv.h" namespace tflite { namespace reference_integer_ops { inline const uint32_t* as_word_ptr(const int8_t* byte_ptr) { return reinterpret_cast<const uint32_t*>(byte_ptr); } // Fixed-point per-channel-quantization convolution reference kernel. void OneByOneConvPerChannel( const ConvParams& params, const int32_t* output_multiplier, const int32_t* output_shift, const RuntimeShape& input_shape, const int8_t* input_data, const RuntimeShape& filter_shape, const int8_t* filter_data, const RuntimeShape& bias_shape, const int32_t* bias_data, const RuntimeShape& output_shape, int8_t* output_data) { // Get parameters. const int stride_width = params.stride_width; const int stride_height = params.stride_height; const int dilation_width_factor = params.dilation_width_factor; const int dilation_height_factor = params.dilation_height_factor; const int pad_width = params.padding_values.width; const int pad_height = params.padding_values.height; const int32_t output_offset = params.output_offset; // Set min and max value of the output. const int32_t output_activation_min = params.quantized_activation_min; const int32_t output_activation_max = params.quantized_activation_max; // Consistency check. TFLITE_DCHECK_LE(output_activation_min, output_activation_max); TFLITE_DCHECK_EQ(input_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(filter_shape.DimensionsCount(), 4); TFLITE_DCHECK_EQ(output_shape.DimensionsCount(), 4); const int batches = MatchingDim(input_shape, 0, output_shape, 0); const int input_depth = input_shape.Dims(3); const int output_depth = MatchingDim(filter_shape, 0, output_shape, 3); if (bias_data) { TFLITE_DCHECK_EQ(bias_shape.FlatSize(), output_depth); } // Check dimensions of the tensors. const int input_height = input_shape.Dims(1); const int input_width = input_shape.Dims(2); const int filter_height = filter_shape.Dims(1); const int filter_width = filter_shape.Dims(2); const int filter_input_depth = filter_shape.Dims(3); const int groups = input_depth / filter_input_depth; TFLITE_DCHECK_EQ(input_depth % filter_input_depth, 0); const int filters_per_group = output_depth / groups; const int output_height = output_shape.Dims(1); const int output_width = output_shape.Dims(2); for (int batch = 0; batch < batches; ++batch) { for (int out_y = 0; out_y < output_height; ++out_y) { const int in_y_origin = (out_y * stride_height) - pad_height; for (int out_x = 0; out_x < output_width; ++out_x) { const int in_x_origin = (out_x * stride_width) - pad_width; for (int out_channel = 0; out_channel < output_depth; ++out_channel) { auto group = out_channel / filters_per_group; cfu_reset(); for (int filter_y = 0; filter_y < filter_height; ++filter_y) { const int in_y = in_y_origin + dilation_height_factor * filter_y; for (int filter_x = 0; filter_x < filter_width; ++filter_x) { const int in_x = in_x_origin + dilation_width_factor * filter_x; // Zero padding by omitting the areas outside the image. const bool is_point_inside_image = (in_x >= 0) && (in_x < input_width) && (in_y >= 0) && (in_y < input_height); if (!is_point_inside_image) { continue; } // filter_input_depth is divisible by 4 for (int in_channel = 0; in_channel < filter_input_depth; in_channel += 4) { const uint32_t * input_ptr = as_word_ptr(input_data+Offset(input_shape, batch, in_y, in_x, in_channel + group * filter_input_depth)); const uint32_t * filter_ptr = as_word_ptr(filter_data + Offset( filter_shape, out_channel, filter_y, filter_x, in_channel)); cfu_accumulate(*input_ptr, *filter_ptr); } } } int32_t acc = cfu_read(); if (bias_data) { acc += bias_data[out_channel]; } acc = MultiplyByQuantizedMultiplier( acc, output_multiplier[out_channel], output_shift[out_channel]); acc += output_offset; acc = std::max(acc, output_activation_min); acc = std::min(acc, output_activation_max); output_data[Offset(output_shape, batch, out_y, out_x, out_channel)] = static_cast<int8_t>(acc); } } } } } } // namespace reference_integer_ops } // namespace tflite <|endoftext|>
<commit_before>#include "dict.h" #include <string> #include <vector> #include <boost/regex.hpp> #include <boost/algorithm/string/regex.hpp> void Dict::AsVector(const WordID& id, std::vector<std::string>* results) const { boost::algorithm::split_regex(*results, Convert(id), boost::regex(" \\|\\|\\| ")); } <commit_msg>Fixed major bug with spaces in regex.<commit_after>#include "dict.h" #include <string> #include <vector> #include <boost/regex.hpp> #include <boost/algorithm/string/regex.hpp> void Dict::AsVector(const WordID& id, std::vector<std::string>* results) const { boost::algorithm::split_regex(*results, Convert(id), boost::regex("\\s\\|\\|\\|\\s")); } <|endoftext|>
<commit_before>#include "plugin.h" #include "plugininterface.h" #include "pluginmanager.h" #include <QApplication> #include <QDir> #include <QPluginLoader> namespace OpenCOR { PluginManager::PluginManager(QSettings *pSettings, const PluginInfo::PluginType &pGuiOrConsoleType) : mSettings(pSettings), mGuiOrConsoleType(pGuiOrConsoleType) { mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath() +QDir::separator()+QString("..") #ifndef Q_WS_MAC +QDir::separator()+"plugins" #else +QDir::separator()+"PlugIns" #endif +QDir::separator()+qApp->applicationName(); #ifndef Q_WS_MAC // The plugins directory should be correct, but in case we try to run // OpenCOR on Windows or Linux AND from within Qt Creator, then the binary // will be running from [OpenCOR]/build/OpenCOR[.exe] rather than // [OpenCOR]/build/bin/OpenCOR[.exe] as it should if we were to mimic the // case where OpenCOR has been deployed. Then, because the plugins are in // [OpenCOR]/build/plugins/OpenCOR, we must skip the "../" bit. Yes, it's // not neat, but... is there another solution?... if (!QDir(mPluginsDir).exists()) mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath() +QDir::separator()+"plugins" +QDir::separator()+qApp->applicationName(); #endif // Retrieve the list of plugins available for loading QFileInfoList fileInfoList = QDir(mPluginsDir).entryInfoList(QStringList("*"+PluginExtension), QDir::Files); QStringList fileNames; foreach (const QFileInfo &file, fileInfoList) fileNames << QDir::toNativeSeparators(file.canonicalFilePath()); // Self-contained plugins (e.g. the Core plugin) don't, by default, get // loaded, but the situation is obviously different if such a plugin is // required by another plugin (e.g. the Help plugin requires the Core // plugin), in which case the self-contained plugin should be loaded. So, we // must here determine which of those plugins need to be loaded... QStringList plugins; foreach (const QString &fileName, fileNames) plugins << requiredPlugins(fileName); plugins.removeDuplicates(); // Knowing which plugins are required, we must now ensure that these are // loaded first. Note that this is not required on Windows (even though it // clearly doesn't harm having them loaded first!), but on Linux (and maybe // also on Mac OS X -- TO BE CHECKED!) it is otherwise the plugin's status // will be wrong (since on Linux and Mac OS X, we check that dependencies // are first loaded before loading the plugin itself), so... QStringList orderedFileNames; foreach (const QString &plugin, plugins) orderedFileNames << Plugin::fileName(mPluginsDir, plugin); orderedFileNames << fileNames; orderedFileNames.removeDuplicates(); // Deal with all the plugins we can find foreach (const QString &fileName, orderedFileNames) mPlugins.insert(Plugin::name(fileName), new Plugin(this, fileName, mGuiOrConsoleType, plugins.contains(Plugin::name(fileName)))); } PluginManager::~PluginManager() { // Delete all of the plugins while (!mPlugins.isEmpty()) { delete mPlugins.begin().value(); mPlugins.erase(mPlugins.begin()); } } QList<Plugin *> PluginManager::plugins(const bool &pOnlyLoadedPlugins) { // Return a list of all the plugins QList<Plugin *> res; QMap<QString, Plugin *>::const_iterator iter = mPlugins.begin(); while (iter != mPlugins.constEnd()) { if ( !pOnlyLoadedPlugins || ( pOnlyLoadedPlugins && (iter.value()->status() == Plugin::Loaded))) res << iter.value(); ++iter; } return res; } QList<Plugin *> PluginManager::loadedPlugins() { // Return a list of all the loaded plugins return plugins(true); } Plugin * PluginManager::plugin(const QString &pName) { // Return the plugin which name is that we have been passed return mPlugins.value(pName); } QSettings * PluginManager::settings() { // Return the settings object return mSettings; } QStringList PluginManager::requiredPlugins(const QString &pFileName, const int &pLevel) { // Return the list of plugins required by a given plugin QStringList res; // Recursively look for the plugins required by the current plugin foreach(const QString &plugin, Plugin::info(pFileName).dependencies()) res << requiredPlugins(Plugin::fileName(mPluginsDir, plugin), pLevel+1); // Add the current plugin to the list if it is not the original plugin for // which we want to know what its requirements are if (pLevel) res << Plugin::name(pFileName); return res; } } <commit_msg>Updated a comment about ordering the loading of the plugins, now that things have been tested on Mac OS X.<commit_after>#include "plugin.h" #include "plugininterface.h" #include "pluginmanager.h" #include <QApplication> #include <QDir> #include <QPluginLoader> namespace OpenCOR { PluginManager::PluginManager(QSettings *pSettings, const PluginInfo::PluginType &pGuiOrConsoleType) : mSettings(pSettings), mGuiOrConsoleType(pGuiOrConsoleType) { mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath() +QDir::separator()+QString("..") #ifndef Q_WS_MAC +QDir::separator()+"plugins" #else +QDir::separator()+"PlugIns" #endif +QDir::separator()+qApp->applicationName(); #ifndef Q_WS_MAC // The plugins directory should be correct, but in case we try to run // OpenCOR on Windows or Linux AND from within Qt Creator, then the binary // will be running from [OpenCOR]/build/OpenCOR[.exe] rather than // [OpenCOR]/build/bin/OpenCOR[.exe] as it should if we were to mimic the // case where OpenCOR has been deployed. Then, because the plugins are in // [OpenCOR]/build/plugins/OpenCOR, we must skip the "../" bit. Yes, it's // not neat, but... is there another solution?... if (!QDir(mPluginsDir).exists()) mPluginsDir = QDir(qApp->applicationDirPath()).canonicalPath() +QDir::separator()+"plugins" +QDir::separator()+qApp->applicationName(); #endif // Retrieve the list of plugins available for loading QFileInfoList fileInfoList = QDir(mPluginsDir).entryInfoList(QStringList("*"+PluginExtension), QDir::Files); QStringList fileNames; foreach (const QFileInfo &file, fileInfoList) fileNames << QDir::toNativeSeparators(file.canonicalFilePath()); // Self-contained plugins (e.g. the Core plugin) don't, by default, get // loaded, but the situation is obviously different if such a plugin is // required by another plugin (e.g. the Help plugin requires the Core // plugin), in which case the self-contained plugin should be loaded. So, we // must here determine which of those plugins need to be loaded... QStringList plugins; foreach (const QString &fileName, fileNames) plugins << requiredPlugins(fileName); plugins.removeDuplicates(); // Knowing which plugins are required, we must now ensure that these are // loaded first. Note that this is not required on Windows (even though it // clearly doesn't harm having them loaded first!), but on Linux and Mac OS // X it certainly is since otherwise the plugin's status will be wrong // (indeed, on those systems, we check that dependencies are first loaded // before loading the plugin itself), so... QStringList orderedFileNames; foreach (const QString &plugin, plugins) orderedFileNames << Plugin::fileName(mPluginsDir, plugin); orderedFileNames << fileNames; orderedFileNames.removeDuplicates(); // Deal with all the plugins we can find foreach (const QString &fileName, orderedFileNames) mPlugins.insert(Plugin::name(fileName), new Plugin(this, fileName, mGuiOrConsoleType, plugins.contains(Plugin::name(fileName)))); } PluginManager::~PluginManager() { // Delete all of the plugins while (!mPlugins.isEmpty()) { delete mPlugins.begin().value(); mPlugins.erase(mPlugins.begin()); } } QList<Plugin *> PluginManager::plugins(const bool &pOnlyLoadedPlugins) { // Return a list of all the plugins QList<Plugin *> res; QMap<QString, Plugin *>::const_iterator iter = mPlugins.begin(); while (iter != mPlugins.constEnd()) { if ( !pOnlyLoadedPlugins || ( pOnlyLoadedPlugins && (iter.value()->status() == Plugin::Loaded))) res << iter.value(); ++iter; } return res; } QList<Plugin *> PluginManager::loadedPlugins() { // Return a list of all the loaded plugins return plugins(true); } Plugin * PluginManager::plugin(const QString &pName) { // Return the plugin which name is that we have been passed return mPlugins.value(pName); } QSettings * PluginManager::settings() { // Return the settings object return mSettings; } QStringList PluginManager::requiredPlugins(const QString &pFileName, const int &pLevel) { // Return the list of plugins required by a given plugin QStringList res; // Recursively look for the plugins required by the current plugin foreach(const QString &plugin, Plugin::info(pFileName).dependencies()) res << requiredPlugins(Plugin::fileName(mPluginsDir, plugin), pLevel+1); // Add the current plugin to the list if it is not the original plugin for // which we want to know what its requirements are if (pLevel) res << Plugin::name(pFileName); return res; } } <|endoftext|>
<commit_before>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "yaml.h" #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <fstream> using namespace std; using namespace kdb; namespace { NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } void addKey (YAML::Node & data, NameIterator & keyIterator, Key const & key) { if (keyIterator == --key.end ()) { data[*keyIterator] = YAML::Node (key.getString ()); return; } YAML::Node dictionary = (data[*keyIterator] && data[*keyIterator].IsMap ()) ? data[*keyIterator] : YAML::Node (YAML::NodeType::Map); data[*keyIterator] = dictionary; addKey (dictionary, ++keyIterator, key); } void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent) { for (auto key : mappings) { NameIterator keyIterator = relativeKeyIterator (key, parent); addKey (data, keyIterator, key); } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { ofstream output (parent.getString ()); auto data = YAML::Node (YAML::NodeType::Map); addKeys (data, mappings, parent); output << data; } <commit_msg>YAML CPP: Add documentation for write functions<commit_after>/** * @file * * @brief Write key sets using yaml-cpp * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ #include "write.hpp" #include "yaml.h" #include <kdbease.h> #include <kdblogger.h> #include <kdbplugin.h> #include <fstream> using namespace std; using namespace kdb; namespace { /** * @brief This function returns a `NameIterator` starting at the first level that is not part of `parent`. * * @pre The parameter `key` must be a child of `parent`. * * @param key This is the key for which this function returns a relative iterator. * @param parent This key specifies the part of the name iterator that will not be part of the return value of this function. * * @returns A relative iterator that starts with the first part of the name of `key` not contained in `parent`. */ NameIterator relativeKeyIterator (Key const & key, Key const & parent) { auto parentIterator = parent.begin (); auto keyIterator = key.begin (); while (parentIterator != parent.end () && keyIterator != key.end ()) { parentIterator++; keyIterator++; } return keyIterator; } /** * @brief This function adds a key to a YAML node. * * @param data This node stores the data specified via `keyIterator`. * @param keyIterator This iterator specifies the current part of the key name this function adds to `data`. * @param key This parameter specifies the key that should be added to `data`. * **/ void addKey (YAML::Node & data, NameIterator & keyIterator, Key const & key) { if (keyIterator == --key.end ()) { data[*keyIterator] = YAML::Node (key.getString ()); return; } YAML::Node dictionary = (data[*keyIterator] && data[*keyIterator].IsMap ()) ? data[*keyIterator] : YAML::Node (YAML::NodeType::Map); data[*keyIterator] = dictionary; addKey (dictionary, ++keyIterator, key); } /** * @brief This function adds a key set to a YAML node. * * @param data This node stores the data specified via `mappings`. * @param mappings This keyset specifies all keys and values this function adds to `data`. * @param parent This key is the root of all keys stored in `mappings`. * **/ void addKeys (YAML::Node & data, KeySet const & mappings, Key const & parent) { for (auto key : mappings) { NameIterator keyIterator = relativeKeyIterator (key, parent); addKey (data, keyIterator, key); } } } // end namespace /** * @brief This function saves the key-value pairs stored in `mappings` as YAML data in the location specified via `parent`. * * @param mappings This key set stores the mappings that should be saved as YAML data. * @param parent This key specifies the path to the YAML data file that should be written. */ void yamlcpp::yamlWrite (KeySet const & mappings, Key const & parent) { ofstream output (parent.getString ()); auto data = YAML::Node (YAML::NodeType::Map); addKeys (data, mappings, parent); output << data; } <|endoftext|>
<commit_before>/* Copyright 2016 fixstars 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 <stdlib.h> #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stereo_sgm.h> #include "demo.h" #include "renderer.h" int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "usage: stereosgm left_img_fmt right_img_fmt [disp_size]" << std::endl; std::exit(EXIT_FAILURE); } std::string left_filename_fmt, right_filename_fmt; left_filename_fmt = argv[1]; right_filename_fmt = argv[2]; // dangerous char buf[1024]; sprintf(buf, left_filename_fmt.c_str(), 0); cv::Mat left = cv::imread(buf, -1); sprintf(buf, right_filename_fmt.c_str(), 0); cv::Mat right = cv::imread(buf, -1); int disp_size = 64; if (argc >= 4) { disp_size = atoi(argv[3]); } if (left.size() != right.size() || left.type() != right.type()) { std::cerr << "mismatch input image size" << std::endl; std::exit(EXIT_FAILURE); } int bits = 0; switch (left.type()) { // case CV_8UC1: bits = 8; break; // TODO case CV_16UC1: bits = 16; break; default: std::cerr << "invalid input image color format" << left.type() << std::endl; std::exit(EXIT_FAILURE); } int width = left.cols; int height = left.rows; cudaGLSetGLDevice(0); SGMDemo demo(width, height); if (demo.init()) { printf("fail to init SGM Demo\n"); std::exit(EXIT_FAILURE); } sgm::StereoSGM ssgm(width, height, bits, disp_size); Renderer renderer(width, height); uint16_t* d_output_buffer = NULL; int frame_no = 0; int max_frame = INT_MAX; while (!demo.should_close()) { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); if (frame_no == max_frame) { frame_no = 0; } sprintf(buf, left_filename_fmt.c_str(), frame_no); cv::Mat left = cv::imread(buf, -1); sprintf(buf, right_filename_fmt.c_str(), frame_no); cv::Mat right = cv::imread(buf, -1); if (left.size() == cv::Size(0, 0) || right.size() == cv::Size(0, 0)) { max_frame = frame_no; frame_no = 0; continue; } ssgm.execute(left.data, right.data, (void**)&d_output_buffer, sgm::DST_TYPE_CUDA_PTR, 16); switch (demo.get_flag()) { case 0: { renderer.render_input((uint16_t*)left.data); } break; case 1: renderer.render_disparity(d_output_buffer, disp_size); break; case 2: renderer.render_disparity_color(d_output_buffer, disp_size); break; } demo.swap_buffer(); frame_no++; } } <commit_msg>add frame_num arg<commit_after>/* Copyright 2016 fixstars 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 <stdlib.h> #include <iostream> #include <string> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stereo_sgm.h> #include "demo.h" #include "renderer.h" int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "usage: stereosgm left_img_fmt right_img_fmt [disp_size] [max_frame_num]" << std::endl; std::exit(EXIT_FAILURE); } std::string left_filename_fmt, right_filename_fmt; left_filename_fmt = argv[1]; right_filename_fmt = argv[2]; // dangerous char buf[1024]; sprintf(buf, left_filename_fmt.c_str(), 0); cv::Mat left = cv::imread(buf, -1); sprintf(buf, right_filename_fmt.c_str(), 0); cv::Mat right = cv::imread(buf, -1); int disp_size = 64; if (argc >= 4) { disp_size = atoi(argv[3]); } int max_frame = 100; if(argc >= 5) { max_frame = atoi(argv[4]); } if (left.size() != right.size() || left.type() != right.type()) { std::cerr << "mismatch input image size" << std::endl; std::exit(EXIT_FAILURE); } int bits = 0; switch (left.type()) { // case CV_8UC1: bits = 8; break; // TODO case CV_16UC1: bits = 16; break; default: std::cerr << "invalid input image color format" << left.type() << std::endl; std::exit(EXIT_FAILURE); } int width = left.cols; int height = left.rows; cudaGLSetGLDevice(0); SGMDemo demo(width, height); if (demo.init()) { printf("fail to init SGM Demo\n"); std::exit(EXIT_FAILURE); } sgm::StereoSGM ssgm(width, height, bits, disp_size); Renderer renderer(width, height); uint16_t* d_output_buffer = NULL; int frame_no = 0; while (!demo.should_close()) { glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); if (frame_no == max_frame) { frame_no = 0; } sprintf(buf, left_filename_fmt.c_str(), frame_no); cv::Mat left = cv::imread(buf, -1); sprintf(buf, right_filename_fmt.c_str(), frame_no); cv::Mat right = cv::imread(buf, -1); if (left.size() == cv::Size(0, 0) || right.size() == cv::Size(0, 0)) { max_frame = frame_no; frame_no = 0; continue; } ssgm.execute(left.data, right.data, (void**)&d_output_buffer, sgm::DST_TYPE_CUDA_PTR, 16); switch (demo.get_flag()) { case 0: { renderer.render_input((uint16_t*)left.data); } break; case 1: renderer.render_disparity(d_output_buffer, disp_size); break; case 2: renderer.render_disparity_color(d_output_buffer, disp_size); break; } demo.swap_buffer(); frame_no++; } } <|endoftext|>
<commit_before>/******************************************************************************* The MIT License (MIT) Copyright (c) 2014 Alexander Zolotarev <me@alex.bio> from Minsk, Belarus 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 "../http_client.h" #include "../file_manager.h" #include "../logger.h" #include <array> #include <vector> #include <fstream> #include <sstream> #include <iostream> // std::cerr #include <stdexcept> // std::runtime_error #include <assert.h> // assert #include <stdio.h> // popen #ifdef _MSC_VER #define popen _popen #define pclose _pclose #else #include <unistd.h> // close #endif // Used as a test stub for basic HTTP client implementation. // Make sure that you have curl installed in the PATH. // TODO(AlexZ): Not a production-ready implementation. namespace alohalytics { std::string RunCurl(const std::string & cmd) { FILE * pipe = ::popen(cmd.c_str(), "r"); assert(pipe); std::array<char, 8 * 1024> arr; std::string result; size_t read; do { read = ::fread(arr.data(), 1, arr.size(), pipe); if (read > 0) { result.append(arr.data(), read); } } while (read == arr.size()); const int err = ::pclose(pipe); if (err) { throw std::runtime_error("Error " + std::to_string(err) + " while calling " + cmd); } return result; } // TODO(AlexZ): Move this function to File Manager. std::string GetTmpFileName() { #ifdef _MSC_VER char tmp_file[L_tmpnam]; const errno_t err = ::tmpnam_s(tmp_file, L_tmpnam); if (err != 0) { throw std::runtime_error("Error " + std::to_string(err) + ", failed to create temporary file."); } #else char tmp_file[] = "/tmp/alohalyticstmp-XXXXXX"; if (nullptr == ::mktemp(tmp_file)) { // tmpnam is deprecated and insecure. throw std::runtime_error("Error: failed to create temporary file."); } #endif return tmp_file; } typedef std::vector<std::pair<std::string, std::string>> HeadersT; HeadersT ParseHeaders(const std::string & raw) { std::istringstream stream(raw); HeadersT headers; std::string line; while (std::getline(stream, line)) { const auto cr = line.rfind('\r'); if (cr != std::string::npos) { line.erase(cr); } const auto delims = line.find(": "); if (delims != std::string::npos) { headers.push_back(std::make_pair(line.substr(0, delims), line.substr(delims + 2))); } } return headers; } // Extract HTTP headers via temporary file with -D switch. // HTTP status code is extracted from curl output (-w switches). // Redirects are handled recursively. TODO(AlexZ): avoid infinite redirects loop. bool HTTPClientPlatformWrapper::RunHTTPRequest() { const alohalytics::ScopedRemoveFile headers_deleter(GetTmpFileName()); std::string cmd = "curl -s -w '%{http_code}' -X " + http_method_ + " -D '" + headers_deleter.file + "' "; if (!content_type_.empty()) { cmd += "-H 'Content-Type: " + content_type_ + "' "; } if (!content_encoding_.empty()) { cmd += "-H 'Content-Encoding: " + content_encoding_ + "' "; } if (!basic_auth_user_.empty()) { cmd += "-u '" + basic_auth_user_ + ":" + basic_auth_password_ + "' "; } if (!cookies_.empty()) { cmd += "-b '" + cookies_ + "' "; } alohalytics::ScopedRemoveFile body_deleter; if (!body_data_.empty()) { body_deleter.file = GetTmpFileName(); // POST body through tmp file to avoid breaking command line. if (!(std::ofstream(body_deleter.file) << body_data_).good()) { std::cerr << "Error: failed to write into a temporary file." << std::endl; return false; } // TODO(AlexZ): Correctly clean up this internal var to avoid client confusion. body_file_ = body_deleter.file; } if (!body_file_.empty()) { // Content-Length is added automatically by curl. cmd += "--data-binary '@" + body_file_ + "' "; } // Use temporary file to receive data from server. // If user has specified file name to save data, it is not temporary and is not deleted automatically. alohalytics::ScopedRemoveFile received_file_deleter; std::string rfile = received_file_; if (rfile.empty()) { rfile = GetTmpFileName(); received_file_deleter.file = rfile; } cmd += "-o " + rfile + " "; cmd += "'" + url_requested_ + "'"; try { if (debug_mode_) { ALOG("Executing", cmd); } error_code_ = std::stoi(RunCurl(cmd)); const HeadersT headers = ParseHeaders(alohalytics::FileManager::ReadFileAsString(headers_deleter.file)); for (const auto & header : headers) { if (header.first == "Set-Cookie") { server_cookies_ += header.second + ", "; } else if (header.first == "Content-Type") { content_type_received_ = header.second; } else if (header.first == "Content-Encoding") { content_encoding_received_ = header.second; } else if (header.first == "Location") { url_received_ = header.second; } } server_cookies_ = normalize_server_cookies(std::move(server_cookies_)); if (url_received_.empty()) { url_received_ = url_requested_; // Load body contents in final request only (skip redirects). if (received_file_.empty()) { // Sometimes server can reply with empty body, and it's ok. try { server_response_ = alohalytics::FileManager::ReadFileAsString(rfile); } catch (const std::exception &) { } } } else { // Handle HTTP redirect. // TODO(AlexZ): Should we check HTTP redirect code here? if (debug_mode_) { ALOG("HTTP redirect", error_code_, "to", url_received_); } HTTPClientPlatformWrapper redirect(url_received_); redirect.set_cookies(combined_cookies()); const bool success = redirect.RunHTTPRequest(); if (success) { error_code_ = redirect.error_code(); url_received_ = redirect.url_received(); server_cookies_ = move(redirect.server_cookies_); server_response_ = move(redirect.server_response_); content_type_received_ = move(redirect.content_type_received_); content_encoding_received_ = move(redirect.content_encoding_received_); } else { error_code_ = -1; } return success; } } catch (const std::exception & ex) { std::cerr << "Exception " << ex.what() << std::endl; return false; } return true; } } // namespace alohalytics <commit_msg>Fixed linux compilation warning about mktemp.<commit_after>/******************************************************************************* The MIT License (MIT) Copyright (c) 2014 Alexander Zolotarev <me@alex.bio> from Minsk, Belarus 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 "../http_client.h" #include "../file_manager.h" #include "../logger.h" #include <array> #include <vector> #include <fstream> #include <sstream> #include <iostream> // std::cerr #include <stdexcept> // std::runtime_error #include <assert.h> // assert #include <stdio.h> // popen #ifdef _MSC_VER #define popen _popen #define pclose _pclose #else #include <unistd.h> // close #endif // Used as a test stub for basic HTTP client implementation. // Make sure that you have curl installed in the PATH. // TODO(AlexZ): Not a production-ready implementation. namespace alohalytics { std::string RunCurl(const std::string & cmd) { FILE * pipe = ::popen(cmd.c_str(), "r"); assert(pipe); std::array<char, 8 * 1024> arr; std::string result; size_t read; do { read = ::fread(arr.data(), 1, arr.size(), pipe); if (read > 0) { result.append(arr.data(), read); } } while (read == arr.size()); const int err = ::pclose(pipe); if (err) { throw std::runtime_error("Error " + std::to_string(err) + " while calling " + cmd); } return result; } // TODO(AlexZ): Move this function to File Manager. // TODO(AlexZ): Rewrite code to use safe opened descriptors instead of file names. std::string GetTmpFileName() { #ifdef _MSC_VER char tmp_file[L_tmpnam]; const errno_t err = ::tmpnam_s(tmp_file, L_tmpnam); if (err != 0) { throw std::runtime_error("Error " + std::to_string(err) + ", failed to create temporary file."); } #else char tmp_file[] = "/tmp/alohalyticstmp-XXXXXX"; int fd = ::mkstemp(tmp_file); // tmpnam is deprecated and insecure. if (fd == -1) { throw std::runtime_error("Error: failed to create temporary file."); } ::close(fd); #endif return tmp_file; } typedef std::vector<std::pair<std::string, std::string>> HeadersT; HeadersT ParseHeaders(const std::string & raw) { std::istringstream stream(raw); HeadersT headers; std::string line; while (std::getline(stream, line)) { const auto cr = line.rfind('\r'); if (cr != std::string::npos) { line.erase(cr); } const auto delims = line.find(": "); if (delims != std::string::npos) { headers.push_back(std::make_pair(line.substr(0, delims), line.substr(delims + 2))); } } return headers; } // Extract HTTP headers via temporary file with -D switch. // HTTP status code is extracted from curl output (-w switches). // Redirects are handled recursively. TODO(AlexZ): avoid infinite redirects loop. bool HTTPClientPlatformWrapper::RunHTTPRequest() { const alohalytics::ScopedRemoveFile headers_deleter(GetTmpFileName()); std::string cmd = "curl -s -w '%{http_code}' -X " + http_method_ + " -D '" + headers_deleter.file + "' "; if (!content_type_.empty()) { cmd += "-H 'Content-Type: " + content_type_ + "' "; } if (!content_encoding_.empty()) { cmd += "-H 'Content-Encoding: " + content_encoding_ + "' "; } if (!basic_auth_user_.empty()) { cmd += "-u '" + basic_auth_user_ + ":" + basic_auth_password_ + "' "; } if (!cookies_.empty()) { cmd += "-b '" + cookies_ + "' "; } alohalytics::ScopedRemoveFile body_deleter; if (!body_data_.empty()) { body_deleter.file = GetTmpFileName(); // POST body through tmp file to avoid breaking command line. if (!(std::ofstream(body_deleter.file) << body_data_).good()) { std::cerr << "Error: failed to write into a temporary file." << std::endl; return false; } // TODO(AlexZ): Correctly clean up this internal var to avoid client confusion. body_file_ = body_deleter.file; } if (!body_file_.empty()) { // Content-Length is added automatically by curl. cmd += "--data-binary '@" + body_file_ + "' "; } // Use temporary file to receive data from server. // If user has specified file name to save data, it is not temporary and is not deleted automatically. alohalytics::ScopedRemoveFile received_file_deleter; std::string rfile = received_file_; if (rfile.empty()) { rfile = GetTmpFileName(); received_file_deleter.file = rfile; } cmd += "-o " + rfile + " "; cmd += "'" + url_requested_ + "'"; try { if (debug_mode_) { ALOG("Executing", cmd); } error_code_ = std::stoi(RunCurl(cmd)); const HeadersT headers = ParseHeaders(alohalytics::FileManager::ReadFileAsString(headers_deleter.file)); for (const auto & header : headers) { if (header.first == "Set-Cookie") { server_cookies_ += header.second + ", "; } else if (header.first == "Content-Type") { content_type_received_ = header.second; } else if (header.first == "Content-Encoding") { content_encoding_received_ = header.second; } else if (header.first == "Location") { url_received_ = header.second; } } server_cookies_ = normalize_server_cookies(std::move(server_cookies_)); if (url_received_.empty()) { url_received_ = url_requested_; // Load body contents in final request only (skip redirects). if (received_file_.empty()) { // Sometimes server can reply with empty body, and it's ok. try { server_response_ = alohalytics::FileManager::ReadFileAsString(rfile); } catch (const std::exception &) { } } } else { // Handle HTTP redirect. // TODO(AlexZ): Should we check HTTP redirect code here? if (debug_mode_) { ALOG("HTTP redirect", error_code_, "to", url_received_); } HTTPClientPlatformWrapper redirect(url_received_); redirect.set_cookies(combined_cookies()); const bool success = redirect.RunHTTPRequest(); if (success) { error_code_ = redirect.error_code(); url_received_ = redirect.url_received(); server_cookies_ = move(redirect.server_cookies_); server_response_ = move(redirect.server_response_); content_type_received_ = move(redirect.content_type_received_); content_encoding_received_ = move(redirect.content_encoding_received_); } else { error_code_ = -1; } return success; } } catch (const std::exception & ex) { std::cerr << "Exception " << ex.what() << std::endl; return false; } return true; } } // namespace alohalytics <|endoftext|>
<commit_before>/*************************************************************************** copyright : (C) 2002, 2003 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tbytevectorlist.h> #include <tdebug.h> #include "commentsframe.h" using namespace TagLib; using namespace ID3v2; class CommentsFrame::CommentsFramePrivate { public: CommentsFramePrivate() : textEncoding(String::Latin1) {} String::Type textEncoding; ByteVector language; String description; String text; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// CommentsFrame::CommentsFrame(String::Type encoding) : Frame("COMM") { d = new CommentsFramePrivate; d->textEncoding = encoding; } CommentsFrame::CommentsFrame(const ByteVector &data) : Frame(data) { d = new CommentsFramePrivate; parseFields(data.mid(Header::size(header()->version()), size())); } CommentsFrame::~CommentsFrame() { delete d; } String CommentsFrame::toString() const { return d->text; } ByteVector CommentsFrame::language() const { return d->language; } String CommentsFrame::description() const { return d->description; } String CommentsFrame::text() const { return d->text; } void CommentsFrame::setLanguage(const ByteVector &languageEncoding) { d->language = languageEncoding.mid(0, 3); } void CommentsFrame::setDescription(const String &s) { d->description = s; } void CommentsFrame::setText(const String &s) { d->text = s; } String::Type CommentsFrame::textEncoding() const { return d->textEncoding; } void CommentsFrame::setTextEncoding(String::Type encoding) { d->textEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void CommentsFrame::parseFields(const ByteVector &data) { if(data.size() < 5) { debug("A comment frame must contain at least 5 bytes."); return; } d->textEncoding = String::Type(data[0]); d->language = data.mid(1, 3); int byteAlign = d->textEncoding == String::Latin1 || d->textEncoding == String::UTF8 ? 1 : 2; ByteVectorList l = ByteVectorList::split(data.mid(4), textDelimiter(d->textEncoding), byteAlign); if(l.size() == 2) { d->description = String(l.front(), d->textEncoding); d->text = String(l.back(), d->textEncoding); } } ByteVector CommentsFrame::renderFields() const { ByteVector v; v.append(char(d->textEncoding)); v.append(d->language); v.append(d->description.data(d->textEncoding)); v.append(textDelimiter(d->textEncoding)); v.append(d->text.data(d->textEncoding)); return v; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// CommentsFrame::CommentsFrame(const ByteVector &data, Header *h) : Frame(h) { d = new CommentsFramePrivate(); parseFields(fieldData(data)); } <commit_msg>Use setData() rather than parseFields() here to make sure that the frame header is initialized.<commit_after>/*************************************************************************** copyright : (C) 2002, 2003 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ #include <tbytevectorlist.h> #include <tdebug.h> #include "commentsframe.h" using namespace TagLib; using namespace ID3v2; class CommentsFrame::CommentsFramePrivate { public: CommentsFramePrivate() : textEncoding(String::Latin1) {} String::Type textEncoding; ByteVector language; String description; String text; }; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// CommentsFrame::CommentsFrame(String::Type encoding) : Frame("COMM") { d = new CommentsFramePrivate; d->textEncoding = encoding; } CommentsFrame::CommentsFrame(const ByteVector &data) : Frame(data) { d = new CommentsFramePrivate; setData(data); } CommentsFrame::~CommentsFrame() { delete d; } String CommentsFrame::toString() const { return d->text; } ByteVector CommentsFrame::language() const { return d->language; } String CommentsFrame::description() const { return d->description; } String CommentsFrame::text() const { return d->text; } void CommentsFrame::setLanguage(const ByteVector &languageEncoding) { d->language = languageEncoding.mid(0, 3); } void CommentsFrame::setDescription(const String &s) { d->description = s; } void CommentsFrame::setText(const String &s) { d->text = s; } String::Type CommentsFrame::textEncoding() const { return d->textEncoding; } void CommentsFrame::setTextEncoding(String::Type encoding) { d->textEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// void CommentsFrame::parseFields(const ByteVector &data) { if(data.size() < 5) { debug("A comment frame must contain at least 5 bytes."); return; } d->textEncoding = String::Type(data[0]); d->language = data.mid(1, 3); int byteAlign = d->textEncoding == String::Latin1 || d->textEncoding == String::UTF8 ? 1 : 2; ByteVectorList l = ByteVectorList::split(data.mid(4), textDelimiter(d->textEncoding), byteAlign); if(l.size() == 2) { d->description = String(l.front(), d->textEncoding); d->text = String(l.back(), d->textEncoding); } } ByteVector CommentsFrame::renderFields() const { ByteVector v; v.append(char(d->textEncoding)); v.append(d->language); v.append(d->description.data(d->textEncoding)); v.append(textDelimiter(d->textEncoding)); v.append(d->text.data(d->textEncoding)); return v; } //////////////////////////////////////////////////////////////////////////////// // private members //////////////////////////////////////////////////////////////////////////////// CommentsFrame::CommentsFrame(const ByteVector &data, Header *h) : Frame(h) { d = new CommentsFramePrivate(); parseFields(fieldData(data)); } <|endoftext|>
<commit_before>#ifdef _DEBUG #include "testdatapath.h" #endif #include <opencv2/opencv.hpp> #include <iostream> #include <string> #include "ImageScrap.h" using namespace std; //画像表示用関数 int showImage(const cv::Mat& image, int wait = 0){ static const string wname("EBookChecker"); cv::imshow(wname, image); return cv::waitKey(wait); } int main(int argc, char** argv) { #ifndef _DEBUG //コマンドライン引数の解析。デバッグの時は使わない string commandArgs = "@input | | processing one image or image named serial number" ; cv::CommandLineParser parser(argc, argv, commandArgs); string src = parser.get<string>(0); #else string src = TEST_DATA_0; #endif cout << "input file:" << src << endl; //画像の読み込み。グレースケール画像として読み込む cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE); CV_Assert(image.channels() == 1 && image.type() == CV_8UC1); showImage(image); //二値化 cv::Mat binary; int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。 int binaryThreshold = 128; cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV); CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1); showImage(binary); cv::imwrite("binary.jpg", binary); //積分画像の生成 cv::Mat integral; cv::integral(binary, integral); CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1); showImage(integral); cv::imwrite("integral.jpg", integral); //積分画像を見やすくする処理 cv::Mat integralVisible; double max; double min; cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う CV_Assert(min == 0.0);//本当に最小値が0になっているか確認 integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。 showImage(integralVisible); cv::imwrite("integralVisible.jpg", integralVisible); //横方向 //文字のない範囲を受け取る変数 vector<Range> horizontalRanges; findSameValueHorizontal(integral, horizontalRanges); //1チャンネルの原画像から3チャンネルの画像を作る cv::Mat srcArray[] = {image, image, image}; cv::Mat srcColor; cv::merge(srcArray, 3, srcColor); const cv::Scalar colorVertical(0, 0, 255); const cv::Scalar colorHorizontal(240, 176, 0); //文字のない範囲を書き込む画像 cv::Mat horizontalRangeDst; drawRange(srcColor, horizontalRanges, ImageScrap::RANGE_COLS, horizontalRangeDst, colorHorizontal); /* //文字のない範囲を3チャンネルの原画像に書き込む for (size_t i = 0; i < horizontalRanges.size(); i++){ Range& r = horizontalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(r.start, 0, r.end - r.start, horizontalRangeDst.rows); cv::Mat roi(horizontalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(240, 176, 0); } */ showImage(horizontalRangeDst); cv::imwrite("horizontalDst.jpg", horizontalRangeDst); //縦方向 //文字のない範囲を受け取る変数 vector<Range> verticalRanges; findSameValueVertical(integral, verticalRanges); //文字のない範囲を書き込む画像 cv::Mat verticalRangeDst; drawRange(srcColor, verticalRanges, ImageScrap::RANGE_ROWS, verticalRangeDst, colorVertical); /** //文字のない範囲を3チャンネルの原画像に書き込む for (size_t i = 0; i < verticalRanges.size(); i++){ Range& r = verticalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(0, r.start, verticalRangeDst.cols, r.end - r.start); cv::Mat roi(verticalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(0, 0, 255); } */ showImage(verticalRangeDst); cv::imwrite("verticalDst.jpg", verticalRangeDst); drawRange(horizontalRangeDst, verticalRanges, ImageScrap::RANGE_ROWS, horizontalRangeDst, colorVertical); /** //横方向の結果と縦方向の結果を合わせる for (size_t i = 0; i < verticalRanges.size(); i++){ Range& r = verticalRanges[i]; //文字のない範囲を3チャンネルの原画像から切り出す cv::Rect rect(0, r.start, horizontalRangeDst.cols, r.end - r.start); cv::Mat roi(horizontalRangeDst, rect); //切り出した画像を1色で塗りつぶす roi = cv::Scalar(0, 0, 255); } */ showImage(horizontalRangeDst); cv::imwrite("horizontalVerticalDst.jpg", horizontalRangeDst); }<commit_msg>無駄なコメントやコードの削除<commit_after>#ifdef _DEBUG #include "testdatapath.h" #endif #include <opencv2/opencv.hpp> #include <iostream> #include <string> #include "ImageScrap.h" using namespace std; //画像表示用関数 int showImage(const cv::Mat& image, int wait = 0){ static const string wname("EBookChecker"); cv::imshow(wname, image); return cv::waitKey(wait); } int main(int argc, char** argv) { #ifndef _DEBUG //コマンドライン引数の解析。デバッグの時は使わない string commandArgs = "@input | | processing one image or image named serial number" ; cv::CommandLineParser parser(argc, argv, commandArgs); string src = parser.get<string>(0); #else string src = TEST_DATA_0; #endif cout << "input file:" << src << endl; //画像の読み込み。グレースケール画像として読み込む cv::Mat image = cv::imread(src, CV_LOAD_IMAGE_GRAYSCALE); CV_Assert(image.channels() == 1 && image.type() == CV_8UC1); showImage(image); //二値化 cv::Mat binary; int binaryMax = 1;//二値化時の最大値は1に。積分するときに白だったところか黒だったところかがわかればいい。 int binaryThreshold = 128; cv::threshold(image, binary, binaryThreshold, binaryMax, cv::THRESH_BINARY_INV); CV_Assert(binary.channels() == 1 && binary.type() == CV_8UC1); showImage(binary); cv::imwrite("binary.jpg", binary); //積分画像の生成 cv::Mat integral; cv::integral(binary, integral); CV_Assert(integral.channels() == 1 && integral.type() == CV_32SC1); showImage(integral); cv::imwrite("integral.jpg", integral); //積分画像を見やすくする処理 cv::Mat integralVisible; double max; double min; cv::minMaxLoc(integral, &min, &max);//最大値だけほしいので第3引数まで。最小値は0のはずだが本当に0か確認するために使う CV_Assert(min == 0.0);//本当に最小値が0になっているか確認 integral.convertTo(integralVisible, CV_8UC1, 255.0 / max); //betaは使わない。0-255の値をとるようにalphaを与える。 showImage(integralVisible); cv::imwrite("integralVisible.jpg", integralVisible); //横方向 //文字のない範囲を受け取る変数 vector<Range> horizontalRanges; findSameValueHorizontal(integral, horizontalRanges); //1チャンネルの原画像から3チャンネルの画像を作る cv::Mat srcArray[] = {image, image, image}; cv::Mat srcColor; cv::merge(srcArray, 3, srcColor); const cv::Scalar colorVertical(0, 0, 255); const cv::Scalar colorHorizontal(240, 176, 0); //文字のない範囲を書き込む画像 cv::Mat horizontalRangeDst; drawRange(srcColor, horizontalRanges, ImageScrap::RANGE_COLS, horizontalRangeDst, colorHorizontal); showImage(horizontalRangeDst); cv::imwrite("horizontalDst.jpg", horizontalRangeDst); //縦方向 //文字のない範囲を受け取る変数 vector<Range> verticalRanges; findSameValueVertical(integral, verticalRanges); //文字のない範囲を書き込む画像 cv::Mat verticalRangeDst; drawRange(srcColor, verticalRanges, ImageScrap::RANGE_ROWS, verticalRangeDst, colorVertical); showImage(verticalRangeDst); //縦横で文字のない範囲を書き込む cv::imwrite("verticalDst.jpg", verticalRangeDst); drawRange(horizontalRangeDst, verticalRanges, ImageScrap::RANGE_ROWS, horizontalRangeDst, colorVertical); showImage(horizontalRangeDst); cv::imwrite("horizontalVerticalDst.jpg", horizontalRangeDst); }<|endoftext|>
<commit_before>#include <iostream> int main() { cout << "Hello World" << endl; return 0; } <commit_msg>delete CPP dir<commit_after><|endoftext|>
<commit_before>#include "bochs.h" #include "cpu/extdb.h" #ifdef WIN32 # include <windows.h> #else # error "extdb.cc only supported in win32 environment" #endif TRegs regs; char debug_loaded = 0; void (*call_debugger)(TRegs *,Bit8u *, Bit32u); #if BX_SUPPORT_X86_64 void bx_external_debugger(BX_CPU_C *cpu) { //printf("Calling debugger state=%d\n",regs.debug_state); switch (regs.debug_state) { case debug_run: return; case debug_count: if (--regs.debug_counter) return; regs.debug_state = debug_step; break; case debug_skip: if (cpu->dword.eip != regs.debug_eip || cpu->sregs[1].selector.value != regs.debug_cs) return; regs.debug_state = debug_step; break; } regs.rax = cpu->gen_reg[0].rrx; regs.rcx = cpu->gen_reg[1].rrx; regs.rdx = cpu->gen_reg[2].rrx; regs.rbx = cpu->gen_reg[3].rrx; regs.rsp = cpu->gen_reg[4].rrx; regs.rbp = cpu->gen_reg[5].rrx; regs.rsi = cpu->gen_reg[6].rrx; regs.rdi = cpu->gen_reg[7].rrx; regs.r8 = cpu->gen_reg[8].rrx; regs.r9 = cpu->gen_reg[9].rrx; regs.r10 = cpu->gen_reg[10].rrx; regs.r11 = cpu->gen_reg[11].rrx; regs.r12 = cpu->gen_reg[12].rrx; regs.r13 = cpu->gen_reg[13].rrx; regs.r14 = cpu->gen_reg[14].rrx; regs.r15 = cpu->gen_reg[15].rrx; regs.rip = cpu->rip; regs.rflags = cpu->read_eflags(); regs.es = cpu->sregs[0].selector.value; regs.cs = cpu->sregs[1].selector.value; regs.ss = cpu->sregs[2].selector.value; regs.ds = cpu->sregs[3].selector.value; regs.fs = cpu->sregs[4].selector.value; regs.gs = cpu->sregs[5].selector.value; regs.gdt.base = cpu->gdtr.base; regs.gdt.limit = cpu->gdtr.limit; regs.idt.base = cpu->idtr.base; regs.idt.limit = cpu->idtr.limit; regs.ldt = cpu->ldtr.selector.value; regs.cr0 = cpu->cr0.val32; regs.cr1 = cpu->cr1; regs.cr2 = cpu->cr2; regs.cr3 = cpu->cr3; regs.cr4 = cpu->cr4.val32; //regs.cr5 = cpu->cr5; //regs.cr6 = cpu->cr6; //regs.cr7 = cpu->cr7; regs.efer = (BX_CPU_THIS_PTR msr.sce << 0) | (BX_CPU_THIS_PTR msr.lme << 8) | (BX_CPU_THIS_PTR msr.lma << 10); if (debug_loaded == 0) { HINSTANCE hdbg; debug_loaded = 1; hdbg = LoadLibrary("debug.dll"); call_debugger = (void (*)(TRegs *,Bit8u *, Bit32u)) GetProcAddress(hdbg,"call_debugger"); if (call_debugger != NULL) debug_loaded = 2; } if (debug_loaded == 2) { bx_vga.timer(); call_debugger(&regs,cpu->mem->vector,cpu->mem->len); } } #else // x86-32 void bx_external_debugger(BX_CPU_C *cpu) { switch (regs.debug_state) { case debug_run: return; case debug_count: if (--regs.debug_counter) return; regs.debug_state = debug_step; break; case debug_skip: if (cpu->dword.eip != regs.debug_eip || cpu->sregs[1].selector.value != regs.debug_cs) return; regs.debug_state = debug_step; break; } regs.eax = cpu->gen_reg[0].dword.erx; regs.ecx = cpu->gen_reg[1].dword.erx; regs.edx = cpu->gen_reg[2].dword.erx; regs.ebx = cpu->gen_reg[3].dword.erx; regs.esp = cpu->gen_reg[4].dword.erx; regs.ebp = cpu->gen_reg[5].dword.erx; regs.esi = cpu->gen_reg[6].dword.erx; regs.edi = cpu->gen_reg[7].dword.erx; regs.eip = cpu->dword.eip; regs.eflags = cpu->read_eflags(); regs.es = cpu->sregs[0].selector.value; regs.cs = cpu->sregs[1].selector.value; regs.ss = cpu->sregs[2].selector.value; regs.ds = cpu->sregs[3].selector.value; regs.fs = cpu->sregs[4].selector.value; regs.gs = cpu->sregs[5].selector.value; regs.gdt.base = cpu->gdtr.base; regs.gdt.limit = cpu->gdtr.limit; regs.idt.base = cpu->idtr.base; regs.idt.limit = cpu->idtr.limit; regs.ldt = cpu->ldtr.selector.value; regs.cr0 = cpu->cr0.val32; regs.cr1 = cpu->cr1; regs.cr2 = cpu->cr2; regs.cr3 = cpu->cr3; if (debug_loaded == 0) { HINSTANCE hdbg; debug_loaded = 1; hdbg = LoadLibrary("debug.dll"); call_debugger = (void (*)(TRegs *,Bit8u *, Bit32u)) GetProcAddress(hdbg,"call_debugger"); if (call_debugger != NULL) debug_loaded = 2; } if (debug_loaded == 2) call_debugger(&regs,cpu->mem->vector,cpu->mem->len); } #end // #if BX_SUPPORT_X86_64 <commit_msg>Fixed CR4 reference in extdb.cc to use the new accessor model. Also, deleted the old 32-bit path in there as Peter said it's no longer useful to him.<commit_after>#include "bochs.h" #include "cpu/extdb.h" #ifdef WIN32 # include <windows.h> #else # error "extdb.cc only supported in win32 environment" #endif TRegs regs; char debug_loaded = 0; void (*call_debugger)(TRegs *,Bit8u *, Bit32u); void bx_external_debugger(BX_CPU_C *cpu) { //printf("Calling debugger state=%d\n",regs.debug_state); switch (regs.debug_state) { case debug_run: return; case debug_count: if (--regs.debug_counter) return; regs.debug_state = debug_step; break; case debug_skip: if (cpu->dword.eip != regs.debug_eip || cpu->sregs[1].selector.value != regs.debug_cs) return; regs.debug_state = debug_step; break; } regs.rax = cpu->gen_reg[0].rrx; regs.rcx = cpu->gen_reg[1].rrx; regs.rdx = cpu->gen_reg[2].rrx; regs.rbx = cpu->gen_reg[3].rrx; regs.rsp = cpu->gen_reg[4].rrx; regs.rbp = cpu->gen_reg[5].rrx; regs.rsi = cpu->gen_reg[6].rrx; regs.rdi = cpu->gen_reg[7].rrx; regs.r8 = cpu->gen_reg[8].rrx; regs.r9 = cpu->gen_reg[9].rrx; regs.r10 = cpu->gen_reg[10].rrx; regs.r11 = cpu->gen_reg[11].rrx; regs.r12 = cpu->gen_reg[12].rrx; regs.r13 = cpu->gen_reg[13].rrx; regs.r14 = cpu->gen_reg[14].rrx; regs.r15 = cpu->gen_reg[15].rrx; regs.rip = cpu->rip; regs.rflags = cpu->read_eflags(); regs.es = cpu->sregs[0].selector.value; regs.cs = cpu->sregs[1].selector.value; regs.ss = cpu->sregs[2].selector.value; regs.ds = cpu->sregs[3].selector.value; regs.fs = cpu->sregs[4].selector.value; regs.gs = cpu->sregs[5].selector.value; regs.gdt.base = cpu->gdtr.base; regs.gdt.limit = cpu->gdtr.limit; regs.idt.base = cpu->idtr.base; regs.idt.limit = cpu->idtr.limit; regs.ldt = cpu->ldtr.selector.value; regs.cr0 = cpu->cr0.val32; regs.cr1 = cpu->cr1; regs.cr2 = cpu->cr2; regs.cr3 = cpu->cr3; regs.cr4 = cpu->cr4.getRegister(); //regs.cr5 = cpu->cr5; //regs.cr6 = cpu->cr6; //regs.cr7 = cpu->cr7; regs.efer = (BX_CPU_THIS_PTR msr.sce << 0) | (BX_CPU_THIS_PTR msr.lme << 8) | (BX_CPU_THIS_PTR msr.lma << 10); if (debug_loaded == 0) { HINSTANCE hdbg; debug_loaded = 1; hdbg = LoadLibrary("debug.dll"); call_debugger = (void (*)(TRegs *,Bit8u *, Bit32u)) GetProcAddress(hdbg,"call_debugger"); if (call_debugger != NULL) debug_loaded = 2; } if (debug_loaded == 2) { bx_vga.timer(); call_debugger(&regs,cpu->mem->vector,cpu->mem->len); } } <|endoftext|>
<commit_before>/* Copyright DaiMysha (c) 2015, All rights reserved. DaiMysha@gmail.com https://github.com/DaiMysha 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <SFML/OpenGL.hpp> #include <DMUtils/sfml.hpp> #include <LightSystem/LightSystem.hpp> #include <LightSystem/staticData/staticData.hpp> #include <LightSystem/ShadowSystem.hpp> namespace dm { namespace ls { const sf::RenderStates LightSystem::_multiplyState(sf::BlendMultiply); const sf::RenderStates LightSystem::_addState(sf::BlendAdd); //const sf::RenderStates LightSystem::_subtractState(sf::BlendMode(sf::BlendMode::One, sf::BlendMode::One, sf::BlendMode::ReverseSubtract)); const sf::RenderStates LightSystem::_subtractState(sf::BlendMode(sf::BlendMode::Zero, sf::BlendMode::OneMinusSrcColor, sf::BlendMode::Add)); LightSystem::LightSystem() : _ambiant(sf::Color::Black), _isometric(false), _autoDelete(true), _updateLightMapImage(true) { /*if(!_lightAttenuationShader.loadFromFile("shaders/lightAttenuation.frag",sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; }*/ if(!_lightAttenuationShader.loadFromMemory(dm::ls::StaticData::LIGHT_ATTENUATION_SHADER,sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; } _shadowSystem = new ShadowSystem(); } LightSystem::~LightSystem() { reset(); delete _shadowSystem; } void LightSystem::addLight(Light* l) { if(l==nullptr) return; l->setIsometric(_isometric);//ignore what user set before l->preRender(&_lightAttenuationShader); if(l->isEmissive()) _emissiveLights.emplace_back(l); else if(l->isNegative()) _negativeLights.emplace_back(l); else _lights.emplace_back(l); l->setSystem(this); _updateLightMapImage = true; } void LightSystem::removeLight(Light* l) { if(l==nullptr) return; if(l->isEmissive()) _emissiveLights.remove(l); else if(l->isNegative()) _negativeLights.remove(l); else _lights.remove(l); } void LightSystem::reset() { for(Light* l : _lights) { l->setSystem(nullptr); if(_autoDelete) delete l; } for(Light* l : _negativeLights) { l->setSystem(nullptr); if(_autoDelete) delete l; } for(Light* l : _emissiveLights) { l->setSystem(nullptr); if(_autoDelete) delete l; } _lights.empty(); _negativeLights.empty(); _emissiveLights.empty(); if(_shadowSystem) _shadowSystem->clear(); } void LightSystem::addWall(const sf::ConvexShape& s) { if(_shadowSystem) _shadowSystem->addWall(s); } void LightSystem::render(const sf::View& screenView, sf::RenderTarget& target) { debugRender(screenView,target,LightSystem::DebugFlags::DEFAULT); } void LightSystem::debugRender(const sf::View& screenView, sf::RenderTarget& target, int flags) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates stAdd(_addState); sf::RenderStates stRm(_subtractState); sf::RenderStates stMp(_multiplyState); sf::Transform t; t.translate(-_sprite.getPosition()); stAdd.transform.combine(t); stRm.transform.combine(t); stMp.transform.combine(t); sf::FloatRect screenRect(screen); for(Light* l : _lights) { if(l->getAABB().intersects(screen)) { if(flags & DebugFlags::SHADER_OFF) l->debugRender(_renderTexture,stAdd); else { _buffer.clear(sf::Color::Black); //sf::FloatRect rect(l->getAABB().left,l->getAABB().top,l->getAABB().width,l->getAABB().height); l->calcShadow(_shadowSystem->getWalls()); //l->render(screen,_renderTexture,&_lightAttenuationShader,stAdd); l->render(screen,_buffer,&_lightAttenuationShader,stMp); _buffer.display(); _renderTexture.draw(_bufferSprite,_addState); } } } for(Light* l : _negativeLights) { if(l->getAABB().intersects(screen)) { if(flags & DebugFlags::SHADER_OFF) l->debugRender(_renderTexture,stRm); else { _buffer.clear(sf::Color::Black); //sf::FloatRect rect(l->getAABB().left,l->getAABB().top,l->getAABB().width,l->getAABB().height); l->calcShadow(_shadowSystem->getWalls()); //l->render(screen,_renderTexture,&_lightAttenuationShader,stAdd); l->render(screen,_buffer,&_lightAttenuationShader,stMp); _buffer.display(); _renderTexture.draw(_bufferSprite,_subtractState); } } } _renderTexture.display(); _updateLightMapImage = true; if(flags & DebugFlags::LIGHTMAP_ONLY) target.clear(sf::Color::White); } void LightSystem::draw(const sf::View& screenView, sf::RenderTarget& target) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); target.draw(_sprite,_multiplyState); for(Light* l : _emissiveLights) { if(l->getAABB().intersects(screen)) { l->render(screen,target,nullptr); } } } void LightSystem::drawAABB(const sf::View& screen, sf::RenderTarget& target) { drawAABB(DMUtils::sfml::getViewInWorldAABB(screen),target); } void LightSystem::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) { for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } for(Light* l : _negativeLights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } for(Light* l : _emissiveLights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } } void LightSystem::drawWalls(const sf::View& screenView, sf::RenderTarget& target) { //sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); if(_shadowSystem) { //for(Light* l : _lights) if(l->getAABB().intersects(screen)) _shadowSystem->debugDraw(l,screenView,target); //for(Light* l : _negativeLights) if(l->getAABB().intersects(screen)) _shadowSystem->debugDraw(l,screenView,target); _shadowSystem->draw(screenView,target); } } void LightSystem::update() { for(Light* l : _lights) update(l); for(Light* l : _negativeLights) update(l); for(Light* l : _emissiveLights) update(l); } void LightSystem::update(Light* l) { l->preRender(&_lightAttenuationShader); _updateLightMapImage = true; } size_t LightSystem::getLightsCount() const { return getNormalLightsCount() + getNegativeLightsCount() + getEmissiveLightsCount(); } size_t LightSystem::getNormalLightsCount() const { return _lights.size(); } size_t LightSystem::getNegativeLightsCount() const { return _negativeLights.size(); } size_t LightSystem::getEmissiveLightsCount() const { return _emissiveLights.size(); } sf::Image LightSystem::getLightMap() { if(_updateLightMapImage) { _lightMapImage = _renderTexture.getTexture().copyToImage(); _updateLightMapImage = false; } return _lightMapImage; } sf::Color LightSystem::getLightMapPixel(const sf::View& view, unsigned int x, unsigned int y) { sf::Image lightMap = getLightMap(); x -= view.getViewport().left; y -= view.getViewport().top; if(x>=0&&y>=0&&x<lightMap.getSize().x&&y<lightMap.getSize().y) return lightMap.getPixel(x,y); else return sf::Color::Black; } sf::Color LightSystem::getLightMapPixel(const sf::View& view, sf::Vector2f p) { return getLightMapPixel(view,p.x,p.y); } void LightSystem::setAmbiantLight(sf::Color c) { _ambiant = c; } sf::Color LightSystem::getAmbiantLight() const { return _ambiant; } /*void LightSystem::setIsometric(bool i) { _isometric = i; update(); } bool LightSystem::isIsometric() const { return _isometric; }*/ void LightSystem::setAutoDelete(bool ad) { _autoDelete = ad; } void LightSystem::setView(const sf::View& view) { _renderTexture.create(view.getSize().x,view.getSize().y); _buffer.create(view.getSize().x,view.getSize().y); _sprite.setTexture(_renderTexture.getTexture(),true); _bufferSprite.setTexture(_buffer.getTexture(),true); } } } <commit_msg>Switched to reversed substract<commit_after>/* Copyright DaiMysha (c) 2015, All rights reserved. DaiMysha@gmail.com https://github.com/DaiMysha 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <SFML/OpenGL.hpp> #include <DMUtils/sfml.hpp> #include <LightSystem/LightSystem.hpp> #include <LightSystem/staticData/staticData.hpp> #include <LightSystem/ShadowSystem.hpp> namespace dm { namespace ls { const sf::RenderStates LightSystem::_multiplyState(sf::BlendMultiply); const sf::RenderStates LightSystem::_addState(sf::BlendAdd); const sf::RenderStates LightSystem::_subtractState(sf::BlendMode(sf::BlendMode::One, sf::BlendMode::One, sf::BlendMode::ReverseSubtract)); LightSystem::LightSystem() : _ambiant(sf::Color::Black), _isometric(false), _autoDelete(true), _updateLightMapImage(true) { /*if(!_lightAttenuationShader.loadFromFile("shaders/lightAttenuation.frag",sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; }*/ if(!_lightAttenuationShader.loadFromMemory(dm::ls::StaticData::LIGHT_ATTENUATION_SHADER,sf::Shader::Fragment)) { std::cerr << "Missing light attenuation Shader. System won't work" << std::endl; } _shadowSystem = new ShadowSystem(); } LightSystem::~LightSystem() { reset(); delete _shadowSystem; } void LightSystem::addLight(Light* l) { if(l==nullptr) return; l->setIsometric(_isometric);//ignore what user set before l->preRender(&_lightAttenuationShader); if(l->isEmissive()) _emissiveLights.emplace_back(l); else if(l->isNegative()) _negativeLights.emplace_back(l); else _lights.emplace_back(l); l->setSystem(this); _updateLightMapImage = true; } void LightSystem::removeLight(Light* l) { if(l==nullptr) return; if(l->isEmissive()) _emissiveLights.remove(l); else if(l->isNegative()) _negativeLights.remove(l); else _lights.remove(l); } void LightSystem::reset() { for(Light* l : _lights) { l->setSystem(nullptr); if(_autoDelete) delete l; } for(Light* l : _negativeLights) { l->setSystem(nullptr); if(_autoDelete) delete l; } for(Light* l : _emissiveLights) { l->setSystem(nullptr); if(_autoDelete) delete l; } _lights.empty(); _negativeLights.empty(); _emissiveLights.empty(); if(_shadowSystem) _shadowSystem->clear(); } void LightSystem::addWall(const sf::ConvexShape& s) { if(_shadowSystem) _shadowSystem->addWall(s); } void LightSystem::render(const sf::View& screenView, sf::RenderTarget& target) { debugRender(screenView,target,LightSystem::DebugFlags::DEFAULT); } void LightSystem::debugRender(const sf::View& screenView, sf::RenderTarget& target, int flags) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); _sprite.setPosition(screen.left,screen.top); _renderTexture.clear(_ambiant); sf::RenderStates stAdd(_addState); sf::RenderStates stRm(_subtractState); sf::RenderStates stMp(_multiplyState); sf::Transform t; t.translate(-_sprite.getPosition()); stAdd.transform.combine(t); stRm.transform.combine(t); stMp.transform.combine(t); sf::FloatRect screenRect(screen); for(Light* l : _lights) { if(l->getAABB().intersects(screen)) { if(flags & DebugFlags::SHADER_OFF) l->debugRender(_renderTexture,stAdd); else { _buffer.clear(sf::Color::Black); //sf::FloatRect rect(l->getAABB().left,l->getAABB().top,l->getAABB().width,l->getAABB().height); l->calcShadow(_shadowSystem->getWalls()); //l->render(screen,_renderTexture,&_lightAttenuationShader,stAdd); l->render(screen,_buffer,&_lightAttenuationShader,stMp); _buffer.display(); _renderTexture.draw(_bufferSprite,_addState); } } } for(Light* l : _negativeLights) { if(l->getAABB().intersects(screen)) { if(flags & DebugFlags::SHADER_OFF) l->debugRender(_renderTexture,stRm); else { _buffer.clear(sf::Color::Black); //sf::FloatRect rect(l->getAABB().left,l->getAABB().top,l->getAABB().width,l->getAABB().height); l->calcShadow(_shadowSystem->getWalls()); //l->render(screen,_renderTexture,&_lightAttenuationShader,stAdd); l->render(screen,_buffer,&_lightAttenuationShader,stMp); _buffer.display(); _renderTexture.draw(_bufferSprite,_subtractState); } } } _renderTexture.display(); _updateLightMapImage = true; if(flags & DebugFlags::LIGHTMAP_ONLY) target.clear(sf::Color::White); } void LightSystem::draw(const sf::View& screenView, sf::RenderTarget& target) { sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); target.draw(_sprite,_multiplyState); for(Light* l : _emissiveLights) { if(l->getAABB().intersects(screen)) { l->render(screen,target,nullptr); } } } void LightSystem::drawAABB(const sf::View& screen, sf::RenderTarget& target) { drawAABB(DMUtils::sfml::getViewInWorldAABB(screen),target); } void LightSystem::drawAABB(const sf::IntRect& screen, sf::RenderTarget& target) { for(Light* l : _lights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } for(Light* l : _negativeLights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } for(Light* l : _emissiveLights) { if(l->getAABB().intersects(screen)) l->drawAABB(screen,target); } } void LightSystem::drawWalls(const sf::View& screenView, sf::RenderTarget& target) { //sf::IntRect screen = DMUtils::sfml::getViewInWorldAABB(screenView); if(_shadowSystem) { //for(Light* l : _lights) if(l->getAABB().intersects(screen)) _shadowSystem->debugDraw(l,screenView,target); //for(Light* l : _negativeLights) if(l->getAABB().intersects(screen)) _shadowSystem->debugDraw(l,screenView,target); _shadowSystem->draw(screenView,target); } } void LightSystem::update() { for(Light* l : _lights) update(l); for(Light* l : _negativeLights) update(l); for(Light* l : _emissiveLights) update(l); } void LightSystem::update(Light* l) { l->preRender(&_lightAttenuationShader); _updateLightMapImage = true; } size_t LightSystem::getLightsCount() const { return getNormalLightsCount() + getNegativeLightsCount() + getEmissiveLightsCount(); } size_t LightSystem::getNormalLightsCount() const { return _lights.size(); } size_t LightSystem::getNegativeLightsCount() const { return _negativeLights.size(); } size_t LightSystem::getEmissiveLightsCount() const { return _emissiveLights.size(); } sf::Image LightSystem::getLightMap() { if(_updateLightMapImage) { _lightMapImage = _renderTexture.getTexture().copyToImage(); _updateLightMapImage = false; } return _lightMapImage; } sf::Color LightSystem::getLightMapPixel(const sf::View& view, unsigned int x, unsigned int y) { sf::Image lightMap = getLightMap(); x -= view.getViewport().left; y -= view.getViewport().top; if(x>=0&&y>=0&&x<lightMap.getSize().x&&y<lightMap.getSize().y) return lightMap.getPixel(x,y); else return sf::Color::Black; } sf::Color LightSystem::getLightMapPixel(const sf::View& view, sf::Vector2f p) { return getLightMapPixel(view,p.x,p.y); } void LightSystem::setAmbiantLight(sf::Color c) { _ambiant = c; } sf::Color LightSystem::getAmbiantLight() const { return _ambiant; } /*void LightSystem::setIsometric(bool i) { _isometric = i; update(); } bool LightSystem::isIsometric() const { return _isometric; }*/ void LightSystem::setAutoDelete(bool ad) { _autoDelete = ad; } void LightSystem::setView(const sf::View& view) { _renderTexture.create(view.getSize().x,view.getSize().y); _buffer.create(view.getSize().x,view.getSize().y); _sprite.setTexture(_renderTexture.getTexture(),true); _bufferSprite.setTexture(_buffer.getTexture(),true); } } } <|endoftext|>
<commit_before>#include "wled.h" /* * Handles playlists, timed sequences of presets */ typedef struct PlaylistEntry { uint8_t preset; //ID of the preset to apply uint16_t dur; //Duration of the entry (in tenths of seconds) uint16_t tr; //Duration of the transition TO this entry (in tenths of seconds) } ple; byte playlistRepeat = 1; //how many times to repeat the playlist (0 = infinitely) byte playlistEndPreset = 0; //what preset to apply after playlist end (0 = stay on last preset) byte playlistOptions = 0; //bit 0: shuffle playlist after each iteration. bits 1-7 TBD PlaylistEntry *playlistEntries = nullptr; byte playlistLen; //number of playlist entries int8_t playlistIndex = -1; uint16_t playlistEntryDur = 0; //duration of the current entry in tenths of seconds //values we need to keep about the parent playlist while inside sub-playlist //int8_t parentPlaylistIndex = -1; //byte parentPlaylistRepeat = 0; //byte parentPlaylistPresetId = 0; //for re-loading void shufflePlaylist() { int currentIndex = playlistLen; PlaylistEntry temporaryValue; // While there remain elements to shuffle... while (currentIndex--) { // Pick a random element... int randomIndex = random(0, currentIndex); // And swap it with the current element. temporaryValue = playlistEntries[currentIndex]; playlistEntries[currentIndex] = playlistEntries[randomIndex]; playlistEntries[randomIndex] = temporaryValue; } DEBUG_PRINTLN(F("Playlist shuffle.")); } void unloadPlaylist() { if (playlistEntries != nullptr) { delete[] playlistEntries; playlistEntries = nullptr; } currentPlaylist = playlistIndex = -1; playlistLen = playlistEntryDur = playlistOptions = 0; DEBUG_PRINTLN(F("Playlist unloaded.")); } int16_t loadPlaylist(JsonObject playlistObj, byte presetId) { unloadPlaylist(); JsonArray presets = playlistObj["ps"]; playlistLen = presets.size(); if (playlistLen == 0) return -1; if (playlistLen > 100) playlistLen = 100; playlistEntries = new PlaylistEntry[playlistLen]; if (playlistEntries == nullptr) return -1; byte it = 0; for (int ps : presets) { if (it >= playlistLen) break; playlistEntries[it].preset = ps; it++; } it = 0; JsonArray durations = playlistObj["dur"]; if (durations.isNull()) { playlistEntries[0].dur = playlistObj["dur"] | 100; //10 seconds as fallback it = 1; } else { for (int dur : durations) { if (it >= playlistLen) break; playlistEntries[it].dur = (dur > 1) ? dur : 100; it++; } } for (int i = it; i < playlistLen; i++) playlistEntries[i].dur = playlistEntries[it -1].dur; it = 0; JsonArray tr = playlistObj[F("transition")]; if (tr.isNull()) { playlistEntries[0].tr = playlistObj[F("transition")] | (transitionDelay / 100); it = 1; } else { for (int transition : tr) { if (it >= playlistLen) break; playlistEntries[it].tr = transition; it++; } } for (int i = it; i < playlistLen; i++) playlistEntries[i].tr = playlistEntries[it -1].tr; int rep = playlistObj[F("repeat")]; bool shuffle = false; if (rep < 0) { //support negative values as infinite + shuffle rep = 0; shuffle = true; } playlistRepeat = rep; if (playlistRepeat > 0) playlistRepeat++; //add one extra repetition immediately since it will be deducted on first start playlistEndPreset = playlistObj[F("end")] | 0; shuffle = shuffle || playlistObj["r"]; if (shuffle) playlistOptions += PL_OPTION_SHUFFLE; currentPlaylist = presetId; DEBUG_PRINTLN(F("Playlist loaded.")); return currentPlaylist; } void handlePlaylist() { static unsigned long presetCycledTime = 0; if (currentPlaylist < 0 || playlistEntries == nullptr) return; if (millis() - presetCycledTime > (100*playlistEntryDur)) { presetCycledTime = millis(); if (bri == 0 || nightlightActive) return; ++playlistIndex %= playlistLen; // -1 at 1st run (limit to playlistLen) // playlist roll-over if (!playlistIndex) { if (playlistRepeat == 1) { //stop if all repetitions are done unloadPlaylist(); if (playlistEndPreset) applyPreset(playlistEndPreset); return; } if (playlistRepeat > 1) playlistRepeat--; // decrease repeat count on each index reset if not an endless playlist // playlistRepeat == 0: endless loop if (playlistOptions & PL_OPTION_SHUFFLE) shufflePlaylist(); // shuffle playlist and start over } jsonTransitionOnce = true; transitionDelayTemp = playlistEntries[playlistIndex].tr * 100; playlistEntryDur = playlistEntries[playlistIndex].dur; applyPreset(playlistEntries[playlistIndex].preset); } } <commit_msg>Playlist corrupting JSON buffer bugfix.<commit_after>#include "wled.h" /* * Handles playlists, timed sequences of presets */ typedef struct PlaylistEntry { uint8_t preset; //ID of the preset to apply uint16_t dur; //Duration of the entry (in tenths of seconds) uint16_t tr; //Duration of the transition TO this entry (in tenths of seconds) } ple; byte playlistRepeat = 1; //how many times to repeat the playlist (0 = infinitely) byte playlistEndPreset = 0; //what preset to apply after playlist end (0 = stay on last preset) byte playlistOptions = 0; //bit 0: shuffle playlist after each iteration. bits 1-7 TBD PlaylistEntry *playlistEntries = nullptr; byte playlistLen; //number of playlist entries int8_t playlistIndex = -1; uint16_t playlistEntryDur = 0; //duration of the current entry in tenths of seconds //values we need to keep about the parent playlist while inside sub-playlist //int8_t parentPlaylistIndex = -1; //byte parentPlaylistRepeat = 0; //byte parentPlaylistPresetId = 0; //for re-loading void shufflePlaylist() { int currentIndex = playlistLen; PlaylistEntry temporaryValue; // While there remain elements to shuffle... while (currentIndex--) { // Pick a random element... int randomIndex = random(0, currentIndex); // And swap it with the current element. temporaryValue = playlistEntries[currentIndex]; playlistEntries[currentIndex] = playlistEntries[randomIndex]; playlistEntries[randomIndex] = temporaryValue; } DEBUG_PRINTLN(F("Playlist shuffle.")); } void unloadPlaylist() { if (playlistEntries != nullptr) { delete[] playlistEntries; playlistEntries = nullptr; } currentPlaylist = playlistIndex = -1; playlistLen = playlistEntryDur = playlistOptions = 0; DEBUG_PRINTLN(F("Playlist unloaded.")); } int16_t loadPlaylist(JsonObject playlistObj, byte presetId) { unloadPlaylist(); JsonArray presets = playlistObj["ps"]; playlistLen = presets.size(); if (playlistLen == 0) return -1; if (playlistLen > 100) playlistLen = 100; playlistEntries = new PlaylistEntry[playlistLen]; if (playlistEntries == nullptr) return -1; byte it = 0; for (int ps : presets) { if (it >= playlistLen) break; playlistEntries[it].preset = ps; it++; } it = 0; JsonArray durations = playlistObj["dur"]; if (durations.isNull()) { playlistEntries[0].dur = playlistObj["dur"] | 100; //10 seconds as fallback it = 1; } else { for (int dur : durations) { if (it >= playlistLen) break; playlistEntries[it].dur = (dur > 1) ? dur : 100; it++; } } for (int i = it; i < playlistLen; i++) playlistEntries[i].dur = playlistEntries[it -1].dur; it = 0; JsonArray tr = playlistObj[F("transition")]; if (tr.isNull()) { playlistEntries[0].tr = playlistObj[F("transition")] | (transitionDelay / 100); it = 1; } else { for (int transition : tr) { if (it >= playlistLen) break; playlistEntries[it].tr = transition; it++; } } for (int i = it; i < playlistLen; i++) playlistEntries[i].tr = playlistEntries[it -1].tr; int rep = playlistObj[F("repeat")]; bool shuffle = false; if (rep < 0) { //support negative values as infinite + shuffle rep = 0; shuffle = true; } playlistRepeat = rep; if (playlistRepeat > 0) playlistRepeat++; //add one extra repetition immediately since it will be deducted on first start playlistEndPreset = playlistObj[F("end")] | 0; shuffle = shuffle || playlistObj["r"]; if (shuffle) playlistOptions += PL_OPTION_SHUFFLE; currentPlaylist = presetId; DEBUG_PRINTLN(F("Playlist loaded.")); return currentPlaylist; } void handlePlaylist() { static unsigned long presetCycledTime = 0; // if fileDoc is not null JSON buffer is in use so just quit if (currentPlaylist < 0 || playlistEntries == nullptr || fileDoc != nullptr) return; if (millis() - presetCycledTime > (100*playlistEntryDur)) { presetCycledTime = millis(); if (bri == 0 || nightlightActive) return; ++playlistIndex %= playlistLen; // -1 at 1st run (limit to playlistLen) // playlist roll-over if (!playlistIndex) { if (playlistRepeat == 1) { //stop if all repetitions are done unloadPlaylist(); if (playlistEndPreset) applyPreset(playlistEndPreset); return; } if (playlistRepeat > 1) playlistRepeat--; // decrease repeat count on each index reset if not an endless playlist // playlistRepeat == 0: endless loop if (playlistOptions & PL_OPTION_SHUFFLE) shufflePlaylist(); // shuffle playlist and start over } jsonTransitionOnce = true; transitionDelayTemp = playlistEntries[playlistIndex].tr * 100; playlistEntryDur = playlistEntries[playlistIndex].dur; applyPreset(playlistEntries[playlistIndex].preset); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageToSurfaceFilter.h" #include <vtkImageData.h> #include <vtkDecimatePro.h> mitk::ImageToSurfaceFilter::ImageToSurfaceFilter() : m_Smooth(false), m_Decimate(false), m_TargetReduction(0.05f){}; mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter(){}; void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold) { //Inkrement Referenzcounter Counter (hier: RC) vtkimage->Register(NULL); vtkPolyData *polydata = vtkPolyData::New(); polydata->Register(NULL);// RC++ //MarchingCube -->create Surface vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New(); skinExtractor->SetInput(vtkimage);//RC++ vtkimage->Delete();//RC-- skinExtractor->SetValue(0, threshold); polydata = skinExtractor->GetOutput(); if (m_Smooth) { int spIterations =50; float spRelaxation =0.1; vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New(); //read poly1 (poly1 can be the original polygon, or the decimated polygon) smoother->SetInput(polydata);//RC++ polydata->Delete();//RC-- smoother->SetNumberOfIterations( spIterations ); smoother->SetRelaxationFactor( spRelaxation ); smoother->SetFeatureAngle( 60 ); smoother->FeatureEdgeSmoothingOff(); smoother->BoundarySmoothingOff(); smoother->SetConvergence( 0 ); polydata = smoother->GetOutput(); } //decimate = to reduce number of polygons if(m_Decimate) { vtkDecimatePro *decimate = vtkDecimatePro::New(); decimate->SplittingOff(); decimate->SetErrorIsAbsolute(5); decimate->SetFeatureAngle(30); decimate->PreserveTopologyOn(); decimate->BoundaryVertexDeletionOff(); decimate->SetDegree(10); //std-value is 25! decimate->SetInput(polydata);//RC++ polydata->Delete();//RC-- decimate->SetTargetReduction(m_TargetReduction); decimate->SetMaximumError(0.002); polydata = decimate->GetOutput(); } surface->SetVtkPolyData(polydata, time); } void mitk::ImageToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); mitk::Image * image = (mitk::Image*)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst int t; for( t=tstart; t < tmax; ++t) { vtkImageData *vtkimagedata = image->GetVtkImageData(t); CreateSurface(t,vtkimagedata,surface,m_Threshold); } } void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) ); } const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Image * > ( this->ProcessObject::GetInput(0) ); } void mitk::ImageToSurfaceFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput(); //mitk::Image *inputImage = (mitk::Image*)this->GetImage(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; //Set Data } <commit_msg>FIX: pipline problem<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile$ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageToSurfaceFilter.h" #include <vtkImageData.h> #include <vtkDecimatePro.h> mitk::ImageToSurfaceFilter::ImageToSurfaceFilter() : m_Smooth(false), m_Decimate(false), m_TargetReduction(0.05f){}; mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter(){}; void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold) { //Inkrement Referenzcounter Counter (hier: RC) vtkimage->Register(NULL); vtkPolyData *polydata = vtkPolyData::New(); polydata->Register(NULL);// RC++ //MarchingCube -->create Surface vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New(); skinExtractor->SetInput(vtkimage);//RC++ vtkimage->Delete();//RC-- skinExtractor->SetValue(0, threshold); polydata = skinExtractor->GetOutput(); if (m_Smooth) { int spIterations =50; float spRelaxation =0.1; vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New(); //read poly1 (poly1 can be the original polygon, or the decimated polygon) smoother->SetInput(polydata);//RC++ polydata->Delete();//RC-- smoother->SetNumberOfIterations( spIterations ); smoother->SetRelaxationFactor( spRelaxation ); smoother->SetFeatureAngle( 60 ); smoother->FeatureEdgeSmoothingOff(); smoother->BoundarySmoothingOff(); smoother->SetConvergence( 0 ); polydata = smoother->GetOutput(); } //decimate = to reduce number of polygons if(m_Decimate) { vtkDecimatePro *decimate = vtkDecimatePro::New(); decimate->SplittingOff(); decimate->SetErrorIsAbsolute(5); decimate->SetFeatureAngle(30); decimate->PreserveTopologyOn(); decimate->BoundaryVertexDeletionOff(); decimate->SetDegree(10); //std-value is 25! decimate->SetInput(polydata);//RC++ polydata->Delete();//RC-- decimate->SetTargetReduction(m_TargetReduction); decimate->SetMaximumError(0.002); polydata = decimate->GetOutput(); } // // HACK! Symptombekmpfung wegen stndiger Pipeline ausfhrung beim navigieren durch das Bild // Disconnect the result from the vtk pipeline. // vtkSource* source = polydata->GetSource(); polydata->Update(); polydata->SetSource(NULL); surface->SetVtkPolyData(polydata, time); source->Delete(); } void mitk::ImageToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); mitk::Image * image = (mitk::Image*)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart=outputRegion.GetIndex(3); int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst int t; for( t=tstart; t < tmax; ++t) { vtkImageData *vtkimagedata = image->GetVtkImageData(t); CreateSurface(t,vtkimagedata,surface,m_Threshold); } } void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) ); } const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void) { if (this->GetNumberOfInputs() < 1) { return 0; } return static_cast<const mitk::Image * > ( this->ProcessObject::GetInput(0) ); } void mitk::ImageToSurfaceFilter::GenerateOutputInformation() { mitk::Image::ConstPointer inputImage =(mitk::Image*) this->GetInput(); //mitk::Image *inputImage = (mitk::Image*)this->GetImage(); mitk::Surface::Pointer output = this->GetOutput(); itkDebugMacro(<<"GenerateOutputInformation()"); if(inputImage.IsNull()) return; //Set Data } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: logfile.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: cd $ $Date: 2001-07-06 10:41:38 $ * * 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: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _RTL_LOGFILE_HXX_ #define _RTL_LOGFILE_HXX_ #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _RTL_LOGFILE_H_ #include <rtl/logfile.h> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif namespace rtl { /** @descr The intended use for class Logfile is to write time stamp information for profiling purposes. The class calls rtl_logfile_trace which uses the traditional C fopen/fprintf family instead of the new C++ ofstream class because of a (hopefully) lower time penalty: Logging should not distort the logged data. Profiling output should only be generated for a special product version of OpenOffice which is compiled with a defined preprocessor symbol 'PROFILE'. Therefore we have provided a set of macros that uses the class Logfile only if this symbol is defined. If the macros are not sufficient, i.e. you need more then three arguments for a printf style message, then you have to insert an #ifdef PROFILE/#endif brace yourself. Additionally the environment variable RTL_LOGFILE has to be defined in order to generate profiling data. It can be used as a run time switch for enabling or disabling the logging. Note that this variable is evaluated only once at the first attempt to write a message. The class LogFile collects runtime data within its constructor and destructor. It can be used for timing whole functions. If you want to write timing data without context you can use the RTL_LOGFILE_TRACE-macros which are defined inside <rtl/logfile.h>. The class LogFile should not be used directly, instead use the RTL_LOGFILE_CONTEXT/ RTL_LOGFILE_TRACE-macros. The lines written to the log file consist of the following space separated elements: 1. The time relative to the start of the global timer in milliseconds. The times is started typically for the first logged line. 2. Thread id. It's absolut value is probably of less interest than providing a way to distinguish different threads. 3. a. An opening or closing curly brace indicating the start or end of a scope. 4a. Function name or general scope identifier. b. A vertical line indicating an arbitrary message. 4b optional function name or general scope identifier. 5b A colon followed by a space and a free form message terminated by a newline. */ class Logfile { public: inline Logfile( const sal_Char *name ); inline ~Logfile(); inline const sal_Char *getName(); private: ::rtl::OString m_sName; }; inline Logfile::Logfile( const sal_Char *name ) : m_sName( name ) { rtl_logfile_trace( "%06lu %lu { %s\n", osl_getGlobalTimer(), osl_getThreadIdentifier( 0 ), name ); } inline Logfile::~Logfile() { rtl_logfile_trace( "%06lu %lu } %s\n", osl_getGlobalTimer(), osl_getThreadIdentifier(0), m_sName.pData->buffer ); } inline const sal_Char * Logfile::getName() { return m_sName.getStr(); } } #ifdef PROFILE #define RTL_LOGFILE_CONTEXT( instance, name ) ::rtl::Logfile instance( name ) #define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) \ rtl_logfile_trace( "%06lu %lu | %s : %s\n", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName(), \ message ) #define RTL_LOGFILE_CONTEXT_TRACE1( instance , frmt, arg1 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 ); \ rtl_logfile_trace( "\n" ) #define RTL_LOGFILE_CONTEXT_TRACE2( instance , frmt, arg1 , arg2 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 , arg2 ); \ rtl_logfile_trace( "\n" ) #define RTL_LOGFILE_CONTEXT_TRACE3( instance , frmt, arg1 , arg2 , arg3 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 , arg2 , arg3 ); \ rtl_logfile_trace( "\n" ) #else #define RTL_LOGFILE_CONTEXT( instance,name ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE1( instance, frmt, arg1 ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE2( instance, frmt, arg1, arg2 ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE3( instance, frmt, arg1, arg2 , arg3 ) ((void)0) #endif #endif <commit_msg>#88409# more usage infos added<commit_after>/************************************************************************* * * $RCSfile: logfile.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cd $ $Date: 2001-07-06 12:16:20 $ * * 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: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _RTL_LOGFILE_HXX_ #define _RTL_LOGFILE_HXX_ #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #ifndef _OSL_THREAD_H_ #include <osl/thread.h> #endif #ifndef _RTL_LOGFILE_H_ #include <rtl/logfile.h> #endif #ifndef _RTL_STRING_HXX_ #include <rtl/string.hxx> #endif namespace rtl { /** @descr The intended use for class Logfile is to write time stamp information for profiling purposes. Profiling output should only be generated for a special product version of OpenOffice which is compiled with a defined preprocessor symbol 'PROFILE'. Therefore we have provided a set of macros that uses the class Logfile only if this symbol is defined. If the macros are not sufficient, i.e. you need more then three arguments for a printf style message, then you have to insert an #ifdef PROFILE/#endif brace yourself. Additionally the environment variable RTL_LOGFILE has to be defined in order to generate logging information. If the variable is not empty, it creates a file with the name $(RTL_LOGFILE)_$(PID).log, where $(PID) is the process id of the running process. It can be used as a run time switch for enabling or disabling the logging. Note that this variable is evaluated only once at the first attempt to write a message. The class LogFile collects runtime data within its constructor and destructor. It can be used for timing whole functions. If you want to write timing data without context you can use the RTL_LOGFILE_TRACE-macros which are defined inside <rtl/logfile.h>. The class LogFile should not be used directly, instead use the RTL_LOGFILE_CONTEXT/ RTL_LOGFILE_TRACE-macros. Macro usage: ------------ RTL_LOGFILE_CONTEXT( instance, name ); This macro creates an instance of class LogFile with the name "instance" and writes the current time, thread id and "name" to the log file. Example: RTL_LOGFILE_CONTEXT( aLog, "Timing for foo-method" ); RTL_LOGFILE_CONTEXT_TRACE( instance, mesage ); RTL_LOGFILE_CONTEXT_TRACEn( instance, frmt, arg1, .., arg3 ); These macros can be used to log information in a "instance" context. The "instance" object is used to log message informations. All macros with "frmt" uses printf notation to log timing infos. Example: RTL_LOGFILE_CONTEXT_TRACE( aLog, "Now we call an expensive function" ); RTL_LOGFIlE_CONTEXT_TRACE1( aLog, "Config entries read: %u", (unsigned short)i ); RTL_LOGFILE_TRACE( string ); RTL_LOGFILE_TRACEn( frmt, arg1, .., arg3 ); These macros can be used to log information outside a context. The macro directly calls rtl_logfile_trace to write the info to the log file. All macros with "frmt" uses printf notation to log timing infos. Example: RTL_LOGFILE_TRACE( "Timing for loading a file" ); RTL_LOGFILE_TRACE1( aLog, "Timing for loading file: %s", aFileName ); The lines written to the log file consist of the following space separated elements: 1. The time relative to the start of the global timer in milliseconds. The times is started typically for the first logged line. 2. Thread id. It's absolut value is probably of less interest than providing a way to distinguish different threads. 3. a. An opening or closing curly brace indicating the start or end of a scope. 4a. Function name or general scope identifier. b. A vertical line indicating an arbitrary message. 4b optional function name or general scope identifier. 5b A colon followed by a space and a free form message terminated by a newline. */ class Logfile { public: inline Logfile( const sal_Char *name ); inline ~Logfile(); inline const sal_Char *getName(); private: ::rtl::OString m_sName; }; inline Logfile::Logfile( const sal_Char *name ) : m_sName( name ) { rtl_logfile_trace( "%06lu %lu { %s\n", osl_getGlobalTimer(), osl_getThreadIdentifier( 0 ), name ); } inline Logfile::~Logfile() { rtl_logfile_trace( "%06lu %lu } %s\n", osl_getGlobalTimer(), osl_getThreadIdentifier(0), m_sName.pData->buffer ); } inline const sal_Char * Logfile::getName() { return m_sName.getStr(); } } #ifdef PROFILE #define RTL_LOGFILE_CONTEXT( instance, name ) ::rtl::Logfile instance( name ) #define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) \ rtl_logfile_trace( "%06lu %lu | %s : %s\n", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName(), \ message ) #define RTL_LOGFILE_CONTEXT_TRACE1( instance , frmt, arg1 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 ); \ rtl_logfile_trace( "\n" ) #define RTL_LOGFILE_CONTEXT_TRACE2( instance , frmt, arg1 , arg2 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 , arg2 ); \ rtl_logfile_trace( "\n" ) #define RTL_LOGFILE_CONTEXT_TRACE3( instance , frmt, arg1 , arg2 , arg3 ) \ rtl_logfile_trace( "%06lu %lu | %s : ", \ osl_getGlobalTimer(), \ osl_getThreadIdentifier( 0 ), \ instance.getName() ); \ rtl_logfile_trace( frmt , arg1 , arg2 , arg3 ); \ rtl_logfile_trace( "\n" ) #else #define RTL_LOGFILE_CONTEXT( instance,name ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE( instance, message ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE1( instance, frmt, arg1 ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE2( instance, frmt, arg1, arg2 ) ((void)0) #define RTL_LOGFILE_CONTEXT_TRACE3( instance, frmt, arg1, arg2 , arg3 ) ((void)0) #endif #endif <|endoftext|>
<commit_before>#include "ingameelements/heroes/mccree.h" #include "datastructures.h" #include "spriteloader.h" #include "animation.h" #include "gamestate.h" #include "engine.h" #include "ingameelements/projectiles/flashbang.h" #include <memory> #include <cmath> #include <allegro5/allegro_primitives.h> Mccree::Mccree(uint64_t id_, Gamestate *state, EntityPtr owner_) : Character(id_, state, owner_, constructparameters(id_, state, owner_)), rollanim("heroes/mccree/roll/"), flashbanganim("heroes/mccree/flashbang/"), rollcooldown(8), flashbangcooldown(10), ultwalkanim("heroes/mccree/ultwalk/"), ulting(std::bind(&Mccree::resetafterult, this, state), 6), deadeyetargets() { rollanim.active(false); rollcooldown.active = false; flashbanganim.active(false); flashbangcooldown.active = false; ulting.active = false; } Mccree::~Mccree() { //dtor } void Mccree::render(Renderer *renderer, Gamestate *state) { Character::render(renderer, state); al_set_target_bitmap(renderer->midground); std::string mainsprite; ALLEGRO_BITMAP *sprite; int spriteoffset_x; int spriteoffset_y; if (flashbanganim.active()) { std::string armsprite = flashbanganim.getframepath(); sprite = renderer->spriteloader.requestsprite(armsprite); spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(armsprite); spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(armsprite); if (isflipped) { // Flip horizontally al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); } else { al_draw_bitmap(sprite, x-spriteoffset_x - renderer->cam_x, y-spriteoffset_y - renderer->cam_y, 0); } } mainsprite = getsprite(state, false); sprite = renderer->spriteloader.requestsprite(mainsprite); spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite); spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite); std::string outlinesprite = mainsprite+"_outline"; ALLEGRO_BITMAP *outline = renderer->spriteloader.requestsprite(outlinesprite); int outlinespriteoffset_x = renderer->spriteloader.get_spriteoffset_x(outlinesprite); int outlinespriteoffset_y = renderer->spriteloader.get_spriteoffset_y(outlinesprite); ALLEGRO_COLOR outlinecolor; if (state->get<Player>(renderer->myself)->team == team) { // Draw friendly outline outlinecolor = al_map_rgb(0, 145, 181); } else { // Draw enemy outline outlinecolor = al_map_rgb(225, 17, 17); } if (isflipped) { // Flip horizontally al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, outlinespriteoffset_x, outlinespriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); } else { al_draw_bitmap(sprite, x-spriteoffset_x - renderer->cam_x, y-spriteoffset_y - renderer->cam_y, 0); al_draw_tinted_bitmap(outline, outlinecolor, x-outlinespriteoffset_x - renderer->cam_x, y-outlinespriteoffset_y - renderer->cam_y, 0); } state->get<Weapon>(weapon)->render(renderer, state); } void Mccree::drawhud(Renderer *renderer, Gamestate *state) { Character::drawhud(renderer, state); double space = 3; float r[8]; ALLEGRO_BITMAP *sprite; Rect spriterect = renderer->spriteloader.get_rect("ui/ingame/mccree/rolling"); if (rollcooldown.active) { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/rollingcooldown"); } else { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/rolling"); } spriterect.x = renderer->WINDOW_WIDTH*6/7.0 - spriterect.w*2 - space; spriterect.y = renderer->WINDOW_HEIGHT*hudheight()-spriterect.h; al_draw_bitmap(sprite, spriterect.x, spriterect.y, 0); if (rollcooldown.active) { // Draw the fill-in r[0] = spriterect.x+17*rollcooldown.getpercent(); r[1] = spriterect.y+2+34*(1-rollcooldown.getpercent()); r[2] = spriterect.x; r[3] = spriterect.y+spriterect.h-2; r[4] = spriterect.x+39; r[5] = spriterect.y+spriterect.h-2; r[6] = spriterect.x+17*rollcooldown.getpercent()+39; r[7] = spriterect.y+2+34*(1-rollcooldown.getpercent()); al_draw_filled_polygon(r, 4, al_premul_rgba_f(239/255.0, 179/255.0, 89/255.0, 0.5)); al_draw_text(renderer->font10, al_map_rgb(255, 255, 255), spriterect.x+spriterect.w/2.0+2, spriterect.y+spriterect.h/2.0-al_get_font_line_height(renderer->font10)/2.0, ALLEGRO_ALIGN_CENTER, std::to_string((int)std::ceil(rollcooldown.duration - rollcooldown.timer)).c_str()); } if (flashbangcooldown.active) { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/flashbangcooldown"); } else { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/flashbang"); } spriterect.x = spriterect.x + spriterect.w+space; al_draw_bitmap(sprite, spriterect.x, spriterect.y, 0); if (flashbangcooldown.active) { // Draw the fill-in r[0] = spriterect.x+17*flashbangcooldown.getpercent(); r[1] = spriterect.y+2+34*(1-flashbangcooldown.getpercent()); r[2] = spriterect.x; r[3] = spriterect.y+spriterect.h-2; r[4] = spriterect.x+39; r[5] = spriterect.y+spriterect.h-2; r[6] = spriterect.x+17*flashbangcooldown.getpercent()+39; r[7] = spriterect.y+2+34*(1-flashbangcooldown.getpercent()); al_draw_filled_polygon(r, 4, al_premul_rgba_f(239/255.0, 179/255.0, 89/255.0, 0.5)); al_draw_text(renderer->font10, al_map_rgb(255, 255, 255), spriterect.x+spriterect.w/2.0+2, spriterect.y+spriterect.h/2.0-al_get_font_line_height(renderer->font10)/2.0, ALLEGRO_ALIGN_CENTER, std::to_string((int)std::ceil(flashbangcooldown.duration - flashbangcooldown.timer)).c_str()); } } void Mccree::midstep(Gamestate *state, double frametime) { Character::midstep(state, frametime); rollanim.update(state, frametime); if (rollanim.active()) { if (isflipped) { hspeed = -360; } else { hspeed = 360; } } flashbanganim.update(state, frametime); rollcooldown.update(state, frametime); flashbangcooldown.update(state, frametime); ulting.update(state, frametime); if (isflipped) { ultwalkanim.update(state, -hspeed*frametime); } else { ultwalkanim.update(state, hspeed*frametime); } if (canuseabilities(state)) { if (heldkeys.ABILITY_1 and not rollcooldown.active and onground(state) and state->engine->isserver) { useability1(state); state->engine->sendbuffer->write<uint8_t>(ABILITY1_USED); state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner)); } if (heldkeys.ABILITY_2 and not flashbangcooldown.active and state->engine->isserver) { useability2(state); state->engine->sendbuffer->write<uint8_t>(ABILITY2_USED); state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner)); } } if (ulting.active) { for (auto p : state->playerlist) { Player *player = state->get<Player>(p); if (player->team != SPECTATOR and player->team != team) { Character *c = player->getcharacter(state); if (c != 0) { if (state->currentmap->collideline(getweapon(state)->x, getweapon(state)->y, c->x, c->y)) { if (deadeyetargets.count(p) == 0) { deadeyetargets[p] = 0; } deadeyetargets[p] += frametime*170; } } } } } } void Mccree::interpolate(Entity *prev_entity, Entity *next_entity, double alpha) { Character::interpolate(prev_entity, next_entity, alpha); Mccree *p = static_cast<Mccree*>(prev_entity); Mccree *n = static_cast<Mccree*>(next_entity); rollanim.interpolate(&(p->rollanim), &(n->rollanim), alpha); rollcooldown.interpolate(&(p->rollcooldown), &(n->rollcooldown), alpha); flashbanganim.interpolate(&(p->flashbanganim), &(n->flashbanganim), alpha); flashbangcooldown.interpolate(&(p->flashbangcooldown), &(n->flashbangcooldown), alpha); ulting.interpolate(&(p->ulting), &(n->ulting), alpha); ultwalkanim.interpolate(&(p->ultwalkanim), &(n->ultwalkanim), alpha); } void Mccree::useability1(Gamestate *state) { if (heldkeys.LEFT and not heldkeys.RIGHT) { isflipped = true; } else if (heldkeys.RIGHT and not heldkeys.LEFT) { isflipped = false; } // Lets roll rollanim.reset(); rollcooldown.reset(); Peacemaker *w = reinterpret_cast<Peacemaker*>(getweapon(state)); w->clip = w->getclipsize(); w->reloadanim.active(0); w->isfthing = false; w->fthanim.active(false); vspeed = 0; } void Mccree::useability2(Gamestate *state) { // Flashbang flashbanganim.reset(); flashbangcooldown.reset(); Flashbang *f = state->get<Flashbang>(state->make_entity<Flashbang>(state, owner)); f->x = x; f->y = y; double dir = std::atan2(mouse_y-y, mouse_x-x); f->hspeed = std::cos(dir) * 300; f->vspeed = std::sin(dir) * 300; } void Mccree::useultimate(Gamestate *state) { ulting.reset(); deadeyetargets.clear(); } void Mccree::resetafterult(Gamestate *state) { ulting.active = false; ultwalkanim.reset(); Player *ownerplayer = state->get<Player>(owner); ownerplayer->ultcharge.active = true; } void Mccree::stun(Gamestate *state) { Character::stun(state); if (ulting.active) { resetafterult(state); } rollanim.active(false); } Rect Mccree::getcollisionrect(Gamestate *state) { if (crouchanim.active()) { return state->engine->maskloader.get_rect_from_json("heroes/"+getcharacterfolder()+"crouch/").offset(x, y); } return getstandingcollisionrect(state); } Rect Mccree::getstandingcollisionrect(Gamestate *state) { return state->engine->maskloader.get_rect_from_json("heroes/"+getcharacterfolder()).offset(x, y); } std::string Mccree::getsprite(Gamestate *state, bool mask) { if (stunanim.active()) { return stunanim.getframepath(); } if (ulting.active) { if (std::fabs(hspeed) < 5.0 and not heldkeys.LEFT and not heldkeys.RIGHT) { return "heroes/"+getcharacterfolder()+"ult/1"; } return ultwalkanim.getframepath(); } if (rollanim.active()) { return rollanim.getframepath(); } if (crouchanim.active()) { return crouchanim.getframepath(); } if (not ongroundsmooth.active) { if (vspeed > 100) { return "heroes/"+getcharacterfolder()+"falling/1"; } else { return "heroes/"+getcharacterfolder()+"jump/1"; } } if (std::fabs(hspeed) < 11.0 and not heldkeys.LEFT and not heldkeys.RIGHT) { return "heroes/"+getcharacterfolder()+"idle/1"; } return runanim.getframepath(); } CharacterChildParameters Mccree::constructparameters(uint64_t id_, Gamestate *state, EntityPtr owner_) { CharacterChildParameters p; p.runpower = 1.8; p.weapon = state->make_entity<Peacemaker>(state, owner_); p.maxhp.normal = 200; p.maxhp.armor = 0; p.maxhp.shields = 0; p.characterfolder = "heroes/mccree/"; return p; } Health Mccree::getmaxhp() { Health maxhp; maxhp.normal = 200; maxhp.armor = 0; maxhp.shields = 0; return maxhp; } <commit_msg>Temp commit for pc change, bug discovered.<commit_after>#include "ingameelements/heroes/mccree.h" #include "datastructures.h" #include "spriteloader.h" #include "animation.h" #include "gamestate.h" #include "engine.h" #include "ingameelements/projectiles/flashbang.h" #include <memory> #include <cmath> #include <allegro5/allegro_primitives.h> Mccree::Mccree(uint64_t id_, Gamestate *state, EntityPtr owner_) : Character(id_, state, owner_, constructparameters(id_, state, owner_)), rollanim("heroes/mccree/roll/"), flashbanganim("heroes/mccree/flashbang/"), rollcooldown(8), flashbangcooldown(10), ultwalkanim("heroes/mccree/ultwalk/"), ulting(std::bind(&Mccree::resetafterult, this, state), 6), deadeyetargets() { rollanim.active(false); rollcooldown.active = false; flashbanganim.active(false); flashbangcooldown.active = false; ulting.active = false; } Mccree::~Mccree() { //dtor } void Mccree::render(Renderer *renderer, Gamestate *state) { Character::render(renderer, state); al_set_target_bitmap(renderer->midground); std::string mainsprite; ALLEGRO_BITMAP *sprite; int spriteoffset_x; int spriteoffset_y; if (flashbanganim.active()) { std::string armsprite = flashbanganim.getframepath(); sprite = renderer->spriteloader.requestsprite(armsprite); spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(armsprite); spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(armsprite); if (isflipped) { // Flip horizontally al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); } else { al_draw_bitmap(sprite, x-spriteoffset_x - renderer->cam_x, y-spriteoffset_y - renderer->cam_y, 0); } } mainsprite = getsprite(state, false); sprite = renderer->spriteloader.requestsprite(mainsprite); spriteoffset_x = renderer->spriteloader.get_spriteoffset_x(mainsprite); spriteoffset_y = renderer->spriteloader.get_spriteoffset_y(mainsprite); std::string outlinesprite = mainsprite+"_outline"; ALLEGRO_BITMAP *outline = renderer->spriteloader.requestsprite(outlinesprite); int outlinespriteoffset_x = renderer->spriteloader.get_spriteoffset_x(outlinesprite); int outlinespriteoffset_y = renderer->spriteloader.get_spriteoffset_y(outlinesprite); ALLEGRO_COLOR outlinecolor; if (state->get<Player>(renderer->myself)->team == team) { // Draw friendly outline outlinecolor = al_map_rgb(0, 145, 181); } else { // Draw enemy outline outlinecolor = al_map_rgb(225, 17, 17); } if (isflipped) { // Flip horizontally al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, outlinespriteoffset_x, outlinespriteoffset_y, x-renderer->cam_x, y-renderer->cam_y, -1, 1, 0, 0); } else { al_draw_bitmap(sprite, x-spriteoffset_x - renderer->cam_x, y-spriteoffset_y - renderer->cam_y, 0); al_draw_tinted_bitmap(outline, outlinecolor, x-outlinespriteoffset_x - renderer->cam_x, y-outlinespriteoffset_y - renderer->cam_y, 0); } state->get<Weapon>(weapon)->render(renderer, state); } void Mccree::drawhud(Renderer *renderer, Gamestate *state) { Character::drawhud(renderer, state); double space = 3; float r[8]; ALLEGRO_BITMAP *sprite; Rect spriterect = renderer->spriteloader.get_rect("ui/ingame/mccree/rolling"); if (rollcooldown.active) { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/rollingcooldown"); } else { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/rolling"); } spriterect.x = renderer->WINDOW_WIDTH*6/7.0 - spriterect.w*2 - space; spriterect.y = renderer->WINDOW_HEIGHT*hudheight()-spriterect.h; al_draw_bitmap(sprite, spriterect.x, spriterect.y, 0); if (rollcooldown.active) { // Draw the fill-in r[0] = spriterect.x+17*rollcooldown.getpercent(); r[1] = spriterect.y+2+34*(1-rollcooldown.getpercent()); r[2] = spriterect.x; r[3] = spriterect.y+spriterect.h-2; r[4] = spriterect.x+39; r[5] = spriterect.y+spriterect.h-2; r[6] = spriterect.x+17*rollcooldown.getpercent()+39; r[7] = spriterect.y+2+34*(1-rollcooldown.getpercent()); al_draw_filled_polygon(r, 4, al_premul_rgba_f(239/255.0, 179/255.0, 89/255.0, 0.5)); al_draw_text(renderer->font10, al_map_rgb(255, 255, 255), spriterect.x+spriterect.w/2.0+2, spriterect.y+spriterect.h/2.0-al_get_font_line_height(renderer->font10)/2.0, ALLEGRO_ALIGN_CENTER, std::to_string((int)std::ceil(rollcooldown.duration - rollcooldown.timer)).c_str()); } if (flashbangcooldown.active) { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/flashbangcooldown"); } else { sprite = renderer->spriteloader.requestsprite("ui/ingame/mccree/flashbang"); } spriterect.x = spriterect.x + spriterect.w+space; al_draw_bitmap(sprite, spriterect.x, spriterect.y, 0); if (flashbangcooldown.active) { // Draw the fill-in r[0] = spriterect.x+17*flashbangcooldown.getpercent(); r[1] = spriterect.y+2+34*(1-flashbangcooldown.getpercent()); r[2] = spriterect.x; r[3] = spriterect.y+spriterect.h-2; r[4] = spriterect.x+39; r[5] = spriterect.y+spriterect.h-2; r[6] = spriterect.x+17*flashbangcooldown.getpercent()+39; r[7] = spriterect.y+2+34*(1-flashbangcooldown.getpercent()); al_draw_filled_polygon(r, 4, al_premul_rgba_f(239/255.0, 179/255.0, 89/255.0, 0.5)); al_draw_text(renderer->font10, al_map_rgb(255, 255, 255), spriterect.x+spriterect.w/2.0+2, spriterect.y+spriterect.h/2.0-al_get_font_line_height(renderer->font10)/2.0, ALLEGRO_ALIGN_CENTER, std::to_string((int)std::ceil(flashbangcooldown.duration - flashbangcooldown.timer)).c_str()); } } void Mccree::midstep(Gamestate *state, double frametime) { Character::midstep(state, frametime); rollanim.update(state, frametime); if (rollanim.active()) { if (isflipped) { hspeed = -360; } else { hspeed = 360; } } flashbanganim.update(state, frametime); rollcooldown.update(state, frametime); flashbangcooldown.update(state, frametime); ulting.update(state, frametime); if (isflipped) { ultwalkanim.update(state, -hspeed*frametime); } else { ultwalkanim.update(state, hspeed*frametime); } if (canuseabilities(state)) { if (heldkeys.ABILITY_1 and not rollcooldown.active and onground(state) and state->engine->isserver) { useability1(state); state->engine->sendbuffer->write<uint8_t>(ABILITY1_USED); state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner)); } if (heldkeys.ABILITY_2 and not flashbangcooldown.active and state->engine->isserver) { useability2(state); state->engine->sendbuffer->write<uint8_t>(ABILITY2_USED); state->engine->sendbuffer->write<uint8_t>(state->findplayerid(owner)); } } if (ulting.active) { for (auto p : state->playerlist) { Player *player = state->get<Player>(p); if (player->team != SPECTATOR and player->team != team) { Character *c = player->getcharacter(state); if (c != 0) { printf("\n%d %d %d %d", getweapon(state)->x, getweapon(state)->y, c->x, c->y); if (not state->currentmap->collideline(getweapon(state)->x, getweapon(state)->y, c->x, c->y)) { if (deadeyetargets.count(p) == 0) { deadeyetargets[p] = 0; } deadeyetargets[p] += frametime*170; } } } } } } void Mccree::interpolate(Entity *prev_entity, Entity *next_entity, double alpha) { Character::interpolate(prev_entity, next_entity, alpha); Mccree *p = static_cast<Mccree*>(prev_entity); Mccree *n = static_cast<Mccree*>(next_entity); rollanim.interpolate(&(p->rollanim), &(n->rollanim), alpha); rollcooldown.interpolate(&(p->rollcooldown), &(n->rollcooldown), alpha); flashbanganim.interpolate(&(p->flashbanganim), &(n->flashbanganim), alpha); flashbangcooldown.interpolate(&(p->flashbangcooldown), &(n->flashbangcooldown), alpha); ulting.interpolate(&(p->ulting), &(n->ulting), alpha); ultwalkanim.interpolate(&(p->ultwalkanim), &(n->ultwalkanim), alpha); } void Mccree::useability1(Gamestate *state) { if (heldkeys.LEFT and not heldkeys.RIGHT) { isflipped = true; } else if (heldkeys.RIGHT and not heldkeys.LEFT) { isflipped = false; } // Lets roll rollanim.reset(); rollcooldown.reset(); Peacemaker *w = reinterpret_cast<Peacemaker*>(getweapon(state)); w->clip = w->getclipsize(); w->reloadanim.active(0); w->isfthing = false; w->fthanim.active(false); vspeed = 0; } void Mccree::useability2(Gamestate *state) { // Flashbang flashbanganim.reset(); flashbangcooldown.reset(); Flashbang *f = state->get<Flashbang>(state->make_entity<Flashbang>(state, owner)); f->x = x; f->y = y; double dir = std::atan2(mouse_y-y, mouse_x-x); f->hspeed = std::cos(dir) * 300; f->vspeed = std::sin(dir) * 300; } void Mccree::useultimate(Gamestate *state) { ulting.reset(); deadeyetargets.clear(); } void Mccree::resetafterult(Gamestate *state) { ulting.active = false; ultwalkanim.reset(); Player *ownerplayer = state->get<Player>(owner); ownerplayer->ultcharge.active = true; } void Mccree::stun(Gamestate *state) { Character::stun(state); if (ulting.active) { resetafterult(state); } rollanim.active(false); } Rect Mccree::getcollisionrect(Gamestate *state) { if (crouchanim.active()) { return state->engine->maskloader.get_rect_from_json("heroes/"+getcharacterfolder()+"crouch/").offset(x, y); } return getstandingcollisionrect(state); } Rect Mccree::getstandingcollisionrect(Gamestate *state) { return state->engine->maskloader.get_rect_from_json("heroes/"+getcharacterfolder()).offset(x, y); } std::string Mccree::getsprite(Gamestate *state, bool mask) { if (stunanim.active()) { return stunanim.getframepath(); } if (ulting.active) { if (std::fabs(hspeed) < 5.0 and not heldkeys.LEFT and not heldkeys.RIGHT) { return "heroes/"+getcharacterfolder()+"ult/1"; } return ultwalkanim.getframepath(); } if (rollanim.active()) { return rollanim.getframepath(); } if (crouchanim.active()) { return crouchanim.getframepath(); } if (not ongroundsmooth.active) { if (vspeed > 100) { return "heroes/"+getcharacterfolder()+"falling/1"; } else { return "heroes/"+getcharacterfolder()+"jump/1"; } } if (std::fabs(hspeed) < 11.0 and not heldkeys.LEFT and not heldkeys.RIGHT) { return "heroes/"+getcharacterfolder()+"idle/1"; } return runanim.getframepath(); } CharacterChildParameters Mccree::constructparameters(uint64_t id_, Gamestate *state, EntityPtr owner_) { CharacterChildParameters p; p.runpower = 1.8; p.weapon = state->make_entity<Peacemaker>(state, owner_); p.maxhp.normal = 200; p.maxhp.armor = 0; p.maxhp.shields = 0; p.characterfolder = "heroes/mccree/"; return p; } Health Mccree::getmaxhp() { Health maxhp; maxhp.normal = 200; maxhp.armor = 0; maxhp.shields = 0; return maxhp; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/flight/server.h" #include "arrow/flight/protocol-internal.h" #include <signal.h> #include <atomic> #include <cstdint> #include <memory> #include <string> #include <utility> #include "arrow/util/config.h" #ifdef GRPCPP_PP_INCLUDE #include <grpcpp/grpcpp.h> #else #include <grpc++/grpc++.h> #endif #include "arrow/ipc/dictionary.h" #include "arrow/ipc/reader.h" #include "arrow/ipc/writer.h" #include "arrow/memory_pool.h" #include "arrow/record_batch.h" #include "arrow/status.h" #include "arrow/util/logging.h" #include "arrow/flight/internal.h" #include "arrow/flight/serialization-internal.h" #include "arrow/flight/types.h" using FlightService = arrow::flight::protocol::FlightService; using ServerContext = grpc::ServerContext; template <typename T> using ServerWriter = grpc::ServerWriter<T>; namespace pb = arrow::flight::protocol; namespace arrow { namespace flight { #define CHECK_ARG_NOT_NULL(VAL, MESSAGE) \ if (VAL == nullptr) { \ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, MESSAGE); \ } class FlightMessageReaderImpl : public FlightMessageReader { public: FlightMessageReaderImpl(const FlightDescriptor& descriptor, std::shared_ptr<Schema> schema, grpc::ServerReader<pb::FlightData>* reader) : descriptor_(descriptor), schema_(schema), reader_(reader), stream_finished_(false) {} const FlightDescriptor& descriptor() const override { return descriptor_; } std::shared_ptr<Schema> schema() const override { return schema_; } Status ReadNext(std::shared_ptr<RecordBatch>* out) override { if (stream_finished_) { *out = nullptr; return Status::OK(); } internal::FlightData data; // Pretend to be pb::FlightData and intercept in SerializationTraits #ifndef _WIN32 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif if (reader_->Read(reinterpret_cast<pb::FlightData*>(&data))) { #ifndef _WIN32 #pragma GCC diagnostic pop #endif std::unique_ptr<ipc::Message> message; // Validate IPC message RETURN_NOT_OK(ipc::Message::Open(data.metadata, data.body, &message)); if (message->type() == ipc::Message::Type::RECORD_BATCH) { return ipc::ReadRecordBatch(*message, schema_, out); } else { return Status(StatusCode::Invalid, "Unrecognized message in Flight stream"); } } else { // Stream is completed stream_finished_ = true; *out = nullptr; return Status::OK(); } } private: FlightDescriptor descriptor_; std::shared_ptr<Schema> schema_; grpc::ServerReader<pb::FlightData>* reader_; bool stream_finished_; }; // This class glues an implementation of FlightServerBase together with the // gRPC service definition, so the latter is not exposed in the public API class FlightServiceImpl : public FlightService::Service { public: explicit FlightServiceImpl(FlightServerBase* server) : server_(server) {} template <typename UserType, typename Iterator, typename ProtoType> grpc::Status WriteStream(Iterator* iterator, ServerWriter<ProtoType>* writer) { if (!iterator) { return grpc::Status(grpc::StatusCode::INTERNAL, "No items to iterate"); } // Write flight info to stream until listing is exhausted ProtoType pb_value; std::unique_ptr<UserType> value; while (true) { GRPC_RETURN_NOT_OK(iterator->Next(&value)); if (!value) { break; } GRPC_RETURN_NOT_OK(internal::ToProto(*value, &pb_value)); // Blocking write if (!writer->Write(pb_value)) { // Write returns false if the stream is closed break; } } return grpc::Status::OK; } template <typename UserType, typename ProtoType> grpc::Status WriteStream(const std::vector<UserType>& values, ServerWriter<ProtoType>* writer) { // Write flight info to stream until listing is exhausted ProtoType pb_value; for (const UserType& value : values) { GRPC_RETURN_NOT_OK(internal::ToProto(value, &pb_value)); // Blocking write if (!writer->Write(pb_value)) { // Write returns false if the stream is closed break; } } return grpc::Status::OK; } grpc::Status ListFlights(ServerContext* context, const pb::Criteria* request, ServerWriter<pb::FlightGetInfo>* writer) { // Retrieve the listing from the implementation std::unique_ptr<FlightListing> listing; Criteria criteria; if (request) { GRPC_RETURN_NOT_OK(internal::FromProto(*request, &criteria)); } GRPC_RETURN_NOT_OK(server_->ListFlights(&criteria, &listing)); if (!listing) { // Treat null listing as no flights available return grpc::Status::OK; } return WriteStream<FlightInfo>(listing.get(), writer); } grpc::Status GetFlightInfo(ServerContext* context, const pb::FlightDescriptor* request, pb::FlightGetInfo* response) { CHECK_ARG_NOT_NULL(request, "FlightDescriptor cannot be null"); FlightDescriptor descr; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &descr)); std::unique_ptr<FlightInfo> info; GRPC_RETURN_NOT_OK(server_->GetFlightInfo(descr, &info)); if (!info) { // Treat null listing as no flights available return grpc::Status(grpc::StatusCode::NOT_FOUND, "Flight not found"); } GRPC_RETURN_NOT_OK(internal::ToProto(*info, response)); return grpc::Status::OK; } grpc::Status DoGet(ServerContext* context, const pb::Ticket* request, ServerWriter<pb::FlightData>* writer) { CHECK_ARG_NOT_NULL(request, "ticket cannot be null"); Ticket ticket; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &ticket)); std::unique_ptr<FlightDataStream> data_stream; GRPC_RETURN_NOT_OK(server_->DoGet(ticket, &data_stream)); if (!data_stream) { return grpc::Status(grpc::StatusCode::NOT_FOUND, "No data in this flight"); } // Write the schema as the first message in the stream FlightPayload schema_payload; MemoryPool* pool = default_memory_pool(); ipc::DictionaryMemo dictionary_memo; GRPC_RETURN_NOT_OK(ipc::internal::GetSchemaPayload( *data_stream->schema(), pool, &dictionary_memo, &schema_payload.ipc_message)); // Pretend to be pb::FlightData, we cast back to FlightPayload in // SerializationTraits #ifndef _WIN32 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif writer->Write(*reinterpret_cast<const pb::FlightData*>(&schema_payload), grpc::WriteOptions()); while (true) { FlightPayload payload; GRPC_RETURN_NOT_OK(data_stream->Next(&payload)); if (payload.ipc_message.metadata == nullptr || !writer->Write(*reinterpret_cast<const pb::FlightData*>(&payload), grpc::WriteOptions())) { // No more messages to write, or connection terminated for some other // reason break; } } #ifndef _WIN32 #pragma GCC diagnostic pop #endif return grpc::Status::OK; } grpc::Status DoPut(ServerContext* context, grpc::ServerReader<pb::FlightData>* reader, pb::PutResult* response) { // Get metadata internal::FlightData data; if (reader->Read(reinterpret_cast<pb::FlightData*>(&data))) { // Message only lives as long as data std::unique_ptr<ipc::Message> message; GRPC_RETURN_NOT_OK(ipc::Message::Open(data.metadata, data.body, &message)); if (!message || message->type() != ipc::Message::Type::SCHEMA) { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "DoPut must start with schema/descriptor")); } else if (!data.descriptor) { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "DoPut must start with non-null descriptor")); } else { std::shared_ptr<Schema> schema; GRPC_RETURN_NOT_OK(ipc::ReadSchema(*message, &schema)); auto message_reader = std::unique_ptr<FlightMessageReader>( new FlightMessageReaderImpl(*data.descriptor.get(), schema, reader)); return internal::ToGrpcStatus(server_->DoPut(std::move(message_reader))); } } else { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "Client provided malformed message or did not provide message")); } } grpc::Status ListActions(ServerContext* context, const pb::Empty* request, ServerWriter<pb::ActionType>* writer) { // Retrieve the listing from the implementation std::vector<ActionType> types; GRPC_RETURN_NOT_OK(server_->ListActions(&types)); return WriteStream<ActionType>(types, writer); } grpc::Status DoAction(ServerContext* context, const pb::Action* request, ServerWriter<pb::Result>* writer) { CHECK_ARG_NOT_NULL(request, "Action cannot be null"); Action action; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &action)); std::unique_ptr<ResultStream> results; GRPC_RETURN_NOT_OK(server_->DoAction(action, &results)); if (!results) { return grpc::Status::CANCELLED; } while (true) { std::unique_ptr<Result> result; GRPC_RETURN_NOT_OK(results->Next(&result)); if (!result) { // No more results break; } pb::Result pb_result; GRPC_RETURN_NOT_OK(internal::ToProto(*result, &pb_result)); if (!writer->Write(pb_result)) { // Stream may be closed break; } } return grpc::Status::OK; } private: FlightServerBase* server_; }; #if (ATOMIC_INT_LOCK_FREE != 2 || ATOMIC_POINTER_LOCK_FREE != 2) #error "atomic ints and atomic pointers not always lock-free!" #endif struct FlightServerBase::Impl { std::string address_; std::unique_ptr<FlightServiceImpl> service_; std::unique_ptr<grpc::Server> server_; // Signal handling std::vector<int> signals_; std::vector<struct sigaction> old_signal_handlers_; std::atomic<int> got_signal_; static thread_local std::atomic<Impl*> running_instance_; static void HandleSignal(int signum); void DoHandleSignal(int signum) { got_signal_ = signum; server_->Shutdown(); } }; thread_local std::atomic<FlightServerBase::Impl*> FlightServerBase::Impl::running_instance_; void FlightServerBase::Impl::HandleSignal(int signum) { auto instance = running_instance_.load(); if (instance != nullptr) { instance->DoHandleSignal(signum); } } FlightServerBase::FlightServerBase() { impl_.reset(new Impl); } FlightServerBase::~FlightServerBase() {} Status FlightServerBase::Init(int port) { impl_->address_ = "localhost:" + std::to_string(port); impl_->service_.reset(new FlightServiceImpl(this)); grpc::ServerBuilder builder; // Allow uploading messages of any length builder.SetMaxReceiveMessageSize(-1); builder.AddListeningPort(impl_->address_, grpc::InsecureServerCredentials()); builder.RegisterService(impl_->service_.get()); impl_->server_ = builder.BuildAndStart(); return Status::OK(); } Status FlightServerBase::SetShutdownOnSignals(const std::vector<int> sigs) { impl_->signals_ = sigs; impl_->old_signal_handlers_.clear(); return Status::OK(); } Status FlightServerBase::Serve() { impl_->got_signal_ = 0; impl_->running_instance_ = impl_.get(); // Setup signal handlers impl_->old_signal_handlers_.clear(); for (size_t i = 0; i < impl_->signals_.size(); ++i) { int signum = impl_->signals_[i]; // Override with our own handler so as to stop the server. struct sigaction sa, old_handler; sa.sa_handler = &Impl::HandleSignal; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); int ret = sigaction(signum, &sa, &old_handler); if (ret != 0) { return Status::IOError("sigaction call failed"); } impl_->old_signal_handlers_.push_back(old_handler); } // TODO(wesm): How can we tell if the server failed to start for some reason? impl_->server_->Wait(); impl_->running_instance_ = nullptr; // Restore signal handlers for (size_t i = 0; i < impl_->signals_.size(); ++i) { int ret = sigaction(impl_->signals_[i], &impl_->old_signal_handlers_[i], nullptr); if (ret != 0) { return Status::IOError("sigaction call failed"); } } return Status::OK(); } int FlightServerBase::GotSignal() const { return impl_->got_signal_; } void FlightServerBase::Shutdown() { DCHECK(impl_->server_); impl_->server_->Shutdown(); } Status FlightServerBase::ListFlights(const Criteria* criteria, std::unique_ptr<FlightListing>* listings) { return Status::NotImplemented("NYI"); } Status FlightServerBase::GetFlightInfo(const FlightDescriptor& request, std::unique_ptr<FlightInfo>* info) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoGet(const Ticket& request, std::unique_ptr<FlightDataStream>* data_stream) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoPut(std::unique_ptr<FlightMessageReader> reader) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoAction(const Action& action, std::unique_ptr<ResultStream>* result) { return Status::NotImplemented("NYI"); } Status FlightServerBase::ListActions(std::vector<ActionType>* actions) { return Status::NotImplemented("NYI"); } // ---------------------------------------------------------------------- // Implement RecordBatchStream RecordBatchStream::RecordBatchStream(const std::shared_ptr<RecordBatchReader>& reader) : pool_(default_memory_pool()), reader_(reader) {} std::shared_ptr<Schema> RecordBatchStream::schema() { return reader_->schema(); } Status RecordBatchStream::Next(FlightPayload* payload) { std::shared_ptr<RecordBatch> batch; RETURN_NOT_OK(reader_->ReadNext(&batch)); if (!batch) { // Signal that iteration is over payload->ipc_message.metadata = nullptr; return Status::OK(); } else { return ipc::internal::GetRecordBatchPayload(*batch, pool_, &payload->ipc_message); } } } // namespace flight } // namespace arrow <commit_msg>ARROW-4984: Check if Flight gRPC server starts properly<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/flight/server.h" #include "arrow/flight/protocol-internal.h" #include <signal.h> #include <atomic> #include <cstdint> #include <memory> #include <string> #include <utility> #include "arrow/util/config.h" #ifdef GRPCPP_PP_INCLUDE #include <grpcpp/grpcpp.h> #else #include <grpc++/grpc++.h> #endif #include "arrow/ipc/dictionary.h" #include "arrow/ipc/reader.h" #include "arrow/ipc/writer.h" #include "arrow/memory_pool.h" #include "arrow/record_batch.h" #include "arrow/status.h" #include "arrow/util/logging.h" #include "arrow/flight/internal.h" #include "arrow/flight/serialization-internal.h" #include "arrow/flight/types.h" using FlightService = arrow::flight::protocol::FlightService; using ServerContext = grpc::ServerContext; template <typename T> using ServerWriter = grpc::ServerWriter<T>; namespace pb = arrow::flight::protocol; namespace arrow { namespace flight { #define CHECK_ARG_NOT_NULL(VAL, MESSAGE) \ if (VAL == nullptr) { \ return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, MESSAGE); \ } class FlightMessageReaderImpl : public FlightMessageReader { public: FlightMessageReaderImpl(const FlightDescriptor& descriptor, std::shared_ptr<Schema> schema, grpc::ServerReader<pb::FlightData>* reader) : descriptor_(descriptor), schema_(schema), reader_(reader), stream_finished_(false) {} const FlightDescriptor& descriptor() const override { return descriptor_; } std::shared_ptr<Schema> schema() const override { return schema_; } Status ReadNext(std::shared_ptr<RecordBatch>* out) override { if (stream_finished_) { *out = nullptr; return Status::OK(); } internal::FlightData data; // Pretend to be pb::FlightData and intercept in SerializationTraits #ifndef _WIN32 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif if (reader_->Read(reinterpret_cast<pb::FlightData*>(&data))) { #ifndef _WIN32 #pragma GCC diagnostic pop #endif std::unique_ptr<ipc::Message> message; // Validate IPC message RETURN_NOT_OK(ipc::Message::Open(data.metadata, data.body, &message)); if (message->type() == ipc::Message::Type::RECORD_BATCH) { return ipc::ReadRecordBatch(*message, schema_, out); } else { return Status(StatusCode::Invalid, "Unrecognized message in Flight stream"); } } else { // Stream is completed stream_finished_ = true; *out = nullptr; return Status::OK(); } } private: FlightDescriptor descriptor_; std::shared_ptr<Schema> schema_; grpc::ServerReader<pb::FlightData>* reader_; bool stream_finished_; }; // This class glues an implementation of FlightServerBase together with the // gRPC service definition, so the latter is not exposed in the public API class FlightServiceImpl : public FlightService::Service { public: explicit FlightServiceImpl(FlightServerBase* server) : server_(server) {} template <typename UserType, typename Iterator, typename ProtoType> grpc::Status WriteStream(Iterator* iterator, ServerWriter<ProtoType>* writer) { if (!iterator) { return grpc::Status(grpc::StatusCode::INTERNAL, "No items to iterate"); } // Write flight info to stream until listing is exhausted ProtoType pb_value; std::unique_ptr<UserType> value; while (true) { GRPC_RETURN_NOT_OK(iterator->Next(&value)); if (!value) { break; } GRPC_RETURN_NOT_OK(internal::ToProto(*value, &pb_value)); // Blocking write if (!writer->Write(pb_value)) { // Write returns false if the stream is closed break; } } return grpc::Status::OK; } template <typename UserType, typename ProtoType> grpc::Status WriteStream(const std::vector<UserType>& values, ServerWriter<ProtoType>* writer) { // Write flight info to stream until listing is exhausted ProtoType pb_value; for (const UserType& value : values) { GRPC_RETURN_NOT_OK(internal::ToProto(value, &pb_value)); // Blocking write if (!writer->Write(pb_value)) { // Write returns false if the stream is closed break; } } return grpc::Status::OK; } grpc::Status ListFlights(ServerContext* context, const pb::Criteria* request, ServerWriter<pb::FlightGetInfo>* writer) { // Retrieve the listing from the implementation std::unique_ptr<FlightListing> listing; Criteria criteria; if (request) { GRPC_RETURN_NOT_OK(internal::FromProto(*request, &criteria)); } GRPC_RETURN_NOT_OK(server_->ListFlights(&criteria, &listing)); if (!listing) { // Treat null listing as no flights available return grpc::Status::OK; } return WriteStream<FlightInfo>(listing.get(), writer); } grpc::Status GetFlightInfo(ServerContext* context, const pb::FlightDescriptor* request, pb::FlightGetInfo* response) { CHECK_ARG_NOT_NULL(request, "FlightDescriptor cannot be null"); FlightDescriptor descr; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &descr)); std::unique_ptr<FlightInfo> info; GRPC_RETURN_NOT_OK(server_->GetFlightInfo(descr, &info)); if (!info) { // Treat null listing as no flights available return grpc::Status(grpc::StatusCode::NOT_FOUND, "Flight not found"); } GRPC_RETURN_NOT_OK(internal::ToProto(*info, response)); return grpc::Status::OK; } grpc::Status DoGet(ServerContext* context, const pb::Ticket* request, ServerWriter<pb::FlightData>* writer) { CHECK_ARG_NOT_NULL(request, "ticket cannot be null"); Ticket ticket; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &ticket)); std::unique_ptr<FlightDataStream> data_stream; GRPC_RETURN_NOT_OK(server_->DoGet(ticket, &data_stream)); if (!data_stream) { return grpc::Status(grpc::StatusCode::NOT_FOUND, "No data in this flight"); } // Write the schema as the first message in the stream FlightPayload schema_payload; MemoryPool* pool = default_memory_pool(); ipc::DictionaryMemo dictionary_memo; GRPC_RETURN_NOT_OK(ipc::internal::GetSchemaPayload( *data_stream->schema(), pool, &dictionary_memo, &schema_payload.ipc_message)); // Pretend to be pb::FlightData, we cast back to FlightPayload in // SerializationTraits #ifndef _WIN32 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif writer->Write(*reinterpret_cast<const pb::FlightData*>(&schema_payload), grpc::WriteOptions()); while (true) { FlightPayload payload; GRPC_RETURN_NOT_OK(data_stream->Next(&payload)); if (payload.ipc_message.metadata == nullptr || !writer->Write(*reinterpret_cast<const pb::FlightData*>(&payload), grpc::WriteOptions())) { // No more messages to write, or connection terminated for some other // reason break; } } #ifndef _WIN32 #pragma GCC diagnostic pop #endif return grpc::Status::OK; } grpc::Status DoPut(ServerContext* context, grpc::ServerReader<pb::FlightData>* reader, pb::PutResult* response) { // Get metadata internal::FlightData data; if (reader->Read(reinterpret_cast<pb::FlightData*>(&data))) { // Message only lives as long as data std::unique_ptr<ipc::Message> message; GRPC_RETURN_NOT_OK(ipc::Message::Open(data.metadata, data.body, &message)); if (!message || message->type() != ipc::Message::Type::SCHEMA) { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "DoPut must start with schema/descriptor")); } else if (!data.descriptor) { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "DoPut must start with non-null descriptor")); } else { std::shared_ptr<Schema> schema; GRPC_RETURN_NOT_OK(ipc::ReadSchema(*message, &schema)); auto message_reader = std::unique_ptr<FlightMessageReader>( new FlightMessageReaderImpl(*data.descriptor.get(), schema, reader)); return internal::ToGrpcStatus(server_->DoPut(std::move(message_reader))); } } else { return internal::ToGrpcStatus( Status(StatusCode::Invalid, "Client provided malformed message or did not provide message")); } } grpc::Status ListActions(ServerContext* context, const pb::Empty* request, ServerWriter<pb::ActionType>* writer) { // Retrieve the listing from the implementation std::vector<ActionType> types; GRPC_RETURN_NOT_OK(server_->ListActions(&types)); return WriteStream<ActionType>(types, writer); } grpc::Status DoAction(ServerContext* context, const pb::Action* request, ServerWriter<pb::Result>* writer) { CHECK_ARG_NOT_NULL(request, "Action cannot be null"); Action action; GRPC_RETURN_NOT_OK(internal::FromProto(*request, &action)); std::unique_ptr<ResultStream> results; GRPC_RETURN_NOT_OK(server_->DoAction(action, &results)); if (!results) { return grpc::Status::CANCELLED; } while (true) { std::unique_ptr<Result> result; GRPC_RETURN_NOT_OK(results->Next(&result)); if (!result) { // No more results break; } pb::Result pb_result; GRPC_RETURN_NOT_OK(internal::ToProto(*result, &pb_result)); if (!writer->Write(pb_result)) { // Stream may be closed break; } } return grpc::Status::OK; } private: FlightServerBase* server_; }; #if (ATOMIC_INT_LOCK_FREE != 2 || ATOMIC_POINTER_LOCK_FREE != 2) #error "atomic ints and atomic pointers not always lock-free!" #endif struct FlightServerBase::Impl { std::string address_; std::unique_ptr<FlightServiceImpl> service_; std::unique_ptr<grpc::Server> server_; // Signal handling std::vector<int> signals_; std::vector<struct sigaction> old_signal_handlers_; std::atomic<int> got_signal_; static thread_local std::atomic<Impl*> running_instance_; static void HandleSignal(int signum); void DoHandleSignal(int signum) { got_signal_ = signum; server_->Shutdown(); } }; thread_local std::atomic<FlightServerBase::Impl*> FlightServerBase::Impl::running_instance_; void FlightServerBase::Impl::HandleSignal(int signum) { auto instance = running_instance_.load(); if (instance != nullptr) { instance->DoHandleSignal(signum); } } FlightServerBase::FlightServerBase() { impl_.reset(new Impl); } FlightServerBase::~FlightServerBase() {} Status FlightServerBase::Init(int port) { impl_->address_ = "localhost:" + std::to_string(port); impl_->service_.reset(new FlightServiceImpl(this)); grpc::ServerBuilder builder; // Allow uploading messages of any length builder.SetMaxReceiveMessageSize(-1); builder.AddListeningPort(impl_->address_, grpc::InsecureServerCredentials()); builder.RegisterService(impl_->service_.get()); impl_->server_ = builder.BuildAndStart(); if (!impl_->server_) { return Status::UnknownError("Server did not start properly"); } return Status::OK(); } Status FlightServerBase::SetShutdownOnSignals(const std::vector<int> sigs) { impl_->signals_ = sigs; impl_->old_signal_handlers_.clear(); return Status::OK(); } Status FlightServerBase::Serve() { if (!impl_->server_) { return Status::UnknownError("Server did not start properly"); } impl_->got_signal_ = 0; impl_->running_instance_ = impl_.get(); // Setup signal handlers impl_->old_signal_handlers_.clear(); for (size_t i = 0; i < impl_->signals_.size(); ++i) { int signum = impl_->signals_[i]; // Override with our own handler so as to stop the server. struct sigaction sa, old_handler; sa.sa_handler = &Impl::HandleSignal; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); int ret = sigaction(signum, &sa, &old_handler); if (ret != 0) { return Status::IOError("sigaction call failed"); } impl_->old_signal_handlers_.push_back(old_handler); } impl_->server_->Wait(); impl_->running_instance_ = nullptr; // Restore signal handlers for (size_t i = 0; i < impl_->signals_.size(); ++i) { int ret = sigaction(impl_->signals_[i], &impl_->old_signal_handlers_[i], nullptr); if (ret != 0) { return Status::IOError("sigaction call failed"); } } return Status::OK(); } int FlightServerBase::GotSignal() const { return impl_->got_signal_; } void FlightServerBase::Shutdown() { DCHECK(impl_->server_); impl_->server_->Shutdown(); } Status FlightServerBase::ListFlights(const Criteria* criteria, std::unique_ptr<FlightListing>* listings) { return Status::NotImplemented("NYI"); } Status FlightServerBase::GetFlightInfo(const FlightDescriptor& request, std::unique_ptr<FlightInfo>* info) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoGet(const Ticket& request, std::unique_ptr<FlightDataStream>* data_stream) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoPut(std::unique_ptr<FlightMessageReader> reader) { return Status::NotImplemented("NYI"); } Status FlightServerBase::DoAction(const Action& action, std::unique_ptr<ResultStream>* result) { return Status::NotImplemented("NYI"); } Status FlightServerBase::ListActions(std::vector<ActionType>* actions) { return Status::NotImplemented("NYI"); } // ---------------------------------------------------------------------- // Implement RecordBatchStream RecordBatchStream::RecordBatchStream(const std::shared_ptr<RecordBatchReader>& reader) : pool_(default_memory_pool()), reader_(reader) {} std::shared_ptr<Schema> RecordBatchStream::schema() { return reader_->schema(); } Status RecordBatchStream::Next(FlightPayload* payload) { std::shared_ptr<RecordBatch> batch; RETURN_NOT_OK(reader_->ReadNext(&batch)); if (!batch) { // Signal that iteration is over payload->ipc_message.metadata = nullptr; return Status::OK(); } else { return ipc::internal::GetRecordBatchPayload(*batch, pool_, &payload->ipc_message); } } } // namespace flight } // namespace arrow <|endoftext|>
<commit_before>/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "host/commands/wifirouter/router.h" #include <cerrno> #include <cstddef> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace cvd { namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); // Get hash for mac address serialized to 6 bytes of data starting at specified // location. // We don't care about byte ordering as much as we do about having all bytes // there. Byte order does not matter, we want to use it as a key in our map. uint64_t GetMacHash(const void* macaddr) { auto typed = reinterpret_cast<const uint16_t*>(macaddr); return (1ull * typed[0] << 32) | (typed[1] << 16) | typed[2]; } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void RegisterForHWSimNotifications(nl_sock* sock, int family) { std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, family, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock, msg.get()); auto res = nl_wait_for_ack(sock); if (res < 0) { LOG(ERROR) << "Could not register for notifications: " << nl_geterror(res); exit(1); } } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. int CreateWifiRouterServerSocket() { auto fd = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (fd <= 0) { LOG(ERROR) << "Could not create unix socket: " << strerror(-fd); exit(1); } sockaddr_un addr{}; addr.sun_family = AF_UNIX; auto len = std::min(sizeof(addr.sun_path) - 2, FLAGS_socket_name.size()); strncpy(&addr.sun_path[1], FLAGS_socket_name.c_str(), len); len += offsetof(sockaddr_un, sun_path) + 1; // include heading \0 byte. auto res = bind(fd, reinterpret_cast<sockaddr*>(&addr), len); if (res < 0) { LOG(ERROR) << "Could not bind unix socket: " << strerror(-res); exit(1); } listen(fd, 4); return fd; } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void AcceptNewClient(int server_fd, ClientsTable* clients) { auto client = accept(server_fd, nullptr, nullptr); if (client < 0) { LOG(ERROR) << "Could not accept client: " << strerror(errno); return; } clients->insert(client); LOG(INFO) << "Client " << client << " added."; } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void RemoveClient(int client, ClientsTable* clients, MacToClientsTable* targets) { close(client); clients->erase(client); for (auto iter = targets->begin(); iter != targets->end();) { if (iter->second == client) { iter = targets->erase(iter); } else { ++iter; } } LOG(INFO) << "Client " << client << " removed."; } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void RouteWIFIPacket(nl_sock* nl, int simfamily, ClientsTable* clients, MacToClientsTable* targets) { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(nl, &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != simfamily) return; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rep( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(rep.get(), 0, 0, 0, 0, 0, WIFIROUTER_CMD_NOTIFY, 0); // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; auto addr = attrs[HWSIM_ATTR_ADDR_TRANSMITTER]; if (addr != nullptr) { nla_put(rep.get(), WIFIROUTER_ATTR_MAC, nla_len(addr), nla_data(addr)); nla_put(rep.get(), WIFIROUTER_ATTR_PACKET, len, buf); auto hdr = nlmsg_hdr(rep.get()); auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); LOG(INFO) << "Received netlink packet from " << std::hex << key; for (auto it = targets->find(key); it != targets->end() && it->first == key; ++it) { auto num_written = send(it->second, hdr, hdr->nlmsg_len, MSG_NOSIGNAL); if (num_written != static_cast<int64_t>(hdr->nlmsg_len)) { pending_removals.insert(it->second); } } for (auto client : pending_removals) { RemoveClient(client, clients, targets); } } } bool HandleClientMessage(int client, MacToClientsTable* targets) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); int64_t size = recv(client, msg.get(), kMaxSupportedPacketSize, 0); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { return false; } int result = -EINVAL; genlmsghdr* ghdr = reinterpret_cast<genlmsghdr*>(nlmsg_data(msg.get())); switch (ghdr->cmd) { case WIFIROUTER_CMD_REGISTER: // Register client to receive notifications for specified MAC address. nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), sizeof(genlmsghdr), attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { targets->emplace(GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); result = 0; } } break; default: break; } nlmsgerr err{.error = result}; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rsp(nlmsg_alloc(), nlmsg_free); nlmsg_put(rsp.get(), msg->nlmsg_pid, msg->nlmsg_seq, NLMSG_ERROR, 0, 0); nlmsg_append(rsp.get(), &err, sizeof(err), 0); auto hdr = nlmsg_hdr(rsp.get()); if (send(client, hdr, hdr->nlmsg_len, MSG_NOSIGNAL) != static_cast<int64_t>(hdr->nlmsg_len)) { return false; } return true; } // Process incoming requests from netlink, server or clients. void ServerLoop(int server_fd, nl_sock* netlink_sock, int family) { ClientsTable clients; MacToClientsTable targets; int netlink_fd = nl_socket_get_fd(netlink_sock); while (true) { auto max_fd = server_fd; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd); fdset(netlink_fd); for (int client : clients) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd, &reads)) AcceptNewClient(server_fd, &clients); if (FD_ISSET(netlink_fd, &reads)) RouteWIFIPacket(netlink_sock, family, &clients, &targets); // Process any client messages left. Drop any client that is no longer // talking with us. for (auto client = clients.begin(); client != clients.end();) { auto cfd = *client++; // Is our client sending us data? if (FD_ISSET(cfd, &reads)) { if (!HandleClientMessage(cfd, &targets)) { // Client should be disconnected. RemoveClient(cfd, &clients, &targets); } } } } } } // namespace } // namespace cvd int main(int argc, char* argv[]) { using namespace cvd; google::ParseCommandLineFlags(&argc, &argv, true); #if !defined(ANDROID) // We should check for legitimate google logging here. google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); #endif std::unique_ptr<nl_sock, void (*)(nl_sock*)> sock(nl_socket_alloc(), nl_socket_free); auto res = nl_connect(sock.get(), NETLINK_GENERIC); if (res < 0) { LOG(ERROR) << "Could not connect to netlink generic: " << nl_geterror(res); exit(1); } auto mac80211_family = genl_ctrl_resolve(sock.get(), kWifiSimFamilyName); if (mac80211_family <= 0) { LOG(ERROR) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; exit(1); } RegisterForHWSimNotifications(sock.get(), mac80211_family); auto server_fd = CreateWifiRouterServerSocket(); ServerLoop(server_fd, sock.get(), mac80211_family); } <commit_msg>Re-register for HWSIM notifications upon creation of wifi interface.<commit_after>/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "host/commands/wifirouter/router.h" #include <cerrno> #include <cstddef> #include <map> #include <memory> #include <set> #include <gflags/gflags.h> #include <glog/logging.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/netlink.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> DEFINE_string(socket_name, "cvd-wifirouter", "Name of the unix-domain socket providing access for routing. " "Socket will be created in abstract namespace."); namespace cvd { namespace { using MacHash = uint64_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; // Copied out of mac80211_hwsim.h header. constexpr int HWSIM_CMD_REGISTER = 1; constexpr int HWSIM_ATTR_ADDR_TRANSMITTER = 2; constexpr int HWSIM_ATTR_MAX = 19; // Name of the WIFI SIM Netlink Family. constexpr char kWifiSimFamilyName[] = "MAC80211_HWSIM"; const int kMaxSupportedPacketSize = getpagesize(); class WifiRouter { public: using MacHash = uint16_t; using MacToClientsTable = std::multimap<MacHash, int>; using ClientsTable = std::set<int>; WifiRouter() : sock_(nullptr, nl_socket_free) {} ~WifiRouter() = default; void Init(); void ServerLoop(); private: MacHash GetMacHash(const void* macaddr); void CreateWifiRouterServerSocket(); void RegisterForHWSimNotifications(); void RouteWIFIPacket(); void AcceptNewClient(); bool HandleClientMessage(int client); void RemoveClient(int client); std::unique_ptr<nl_sock, void(*)(nl_sock*)> sock_; int server_fd_ = 0; int mac80211_family_ = 0; ClientsTable registered_clients_; MacToClientsTable registered_addresses_; }; MacHash WifiRouter::GetMacHash(const void* macaddr) { const uint8_t* t = reinterpret_cast<const uint8_t*>(macaddr); // This is guaranteed to be unique. Address here is assigned at creation time // and is (well) non-mutable. This is a unique ID of the MAC80211 HWSIM // interface. return t[3] << 8 | t[4]; } void WifiRouter::Init() { CreateWifiRouterServerSocket(); RegisterForHWSimNotifications(); } // Enable asynchronous notifications from MAC80211_HWSIM. // - `sock` is a valid netlink socket connected to NETLINK_GENERIC, // - `family` is MAC80211_HWSIM genl family number. // // Upon failure, this function will terminate execution of the program. void WifiRouter::RegisterForHWSimNotifications() { sock_.reset(nl_socket_alloc()); auto res = nl_connect(sock_.get(), NETLINK_GENERIC); if (res < 0) { LOG(ERROR) << "Could not connect to netlink generic: " << nl_geterror(res); exit(1); } mac80211_family_ = genl_ctrl_resolve(sock_.get(), kWifiSimFamilyName); if (mac80211_family_ <= 0) { LOG(ERROR) << "Could not find MAC80211 HWSIM. Please make sure module " << "'mac80211_hwsim' is loaded on your system."; exit(1); } std::unique_ptr<nl_msg, void (*)(nl_msg*)> msg( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(msg.get(), NL_AUTO_PID, NL_AUTO_SEQ, mac80211_family_, 0, NLM_F_REQUEST, HWSIM_CMD_REGISTER, 0); nl_send_auto(sock_.get(), msg.get()); res = nl_wait_for_ack(sock_.get()); if (res < 0) { LOG(ERROR) << "Could not register for notifications: " << nl_geterror(res); exit(1); } } // Create and configure WIFI Router server socket. // This function is guaranteed to success. If at any point an error is detected, // the function will terminate execution of the program. void WifiRouter::CreateWifiRouterServerSocket() { server_fd_ = socket(AF_UNIX, SOCK_SEQPACKET, 0); if (server_fd_ < 0) { LOG(ERROR) << "Could not create unix socket: " << strerror(-errno); exit(1); } sockaddr_un addr{}; addr.sun_family = AF_UNIX; auto len = std::min(sizeof(addr.sun_path) - 2, FLAGS_socket_name.size()); strncpy(&addr.sun_path[1], FLAGS_socket_name.c_str(), len); len += offsetof(sockaddr_un, sun_path) + 1; // include heading \0 byte. auto res = bind(server_fd_, reinterpret_cast<sockaddr*>(&addr), len); if (res < 0) { LOG(ERROR) << "Could not bind unix socket: " << strerror(-errno); exit(1); } listen(server_fd_, 4); } // Accept new WIFI Router client. When successful, client will be placed in // clients table. void WifiRouter::AcceptNewClient() { auto client = accept(server_fd_, nullptr, nullptr); if (client < 0) { LOG(ERROR) << "Could not accept client: " << strerror(-errno); return; } registered_clients_.insert(client); LOG(INFO) << "Client " << client << " added."; } // Disconnect and remove client from list of registered clients and recipients // of WLAN traffic. void WifiRouter::RemoveClient(int client) { close(client); registered_clients_.erase(client); for (auto iter = registered_addresses_.begin(); iter != registered_addresses_.end();) { if (iter->second == client) { iter = registered_addresses_.erase(iter); } else { ++iter; } } LOG(INFO) << "Client " << client << " removed."; } // Read MAC80211HWSIM packet, find the originating MAC address and redirect it // to proper sink. void WifiRouter::RouteWIFIPacket() { sockaddr_nl tmp; uint8_t* buf; const auto len = nl_recv(sock_.get(), &tmp, &buf, nullptr); if (len < 0) { LOG(ERROR) << "Could not read from netlink: " << nl_geterror(len); return; } std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(buf), [](nlmsghdr* m) { free(m); }); // Discard messages that originate from anything else than MAC80211_HWSIM. if (msg->nlmsg_type != mac80211_family_) return; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rep( nlmsg_alloc(), [](nl_msg* m) { nlmsg_free(m); }); genlmsg_put(rep.get(), 0, 0, 0, 0, 0, WIFIROUTER_CMD_NOTIFY, 0); // Note, this is generic netlink message, and uses different parsing // technique. nlattr* attrs[HWSIM_ATTR_MAX + 1]; if (genlmsg_parse(msg.get(), 0, attrs, HWSIM_ATTR_MAX, nullptr)) return; std::set<int> pending_removals; auto addr = attrs[HWSIM_ATTR_ADDR_TRANSMITTER]; if (addr != nullptr) { nla_put(rep.get(), WIFIROUTER_ATTR_MAC, nla_len(addr), nla_data(addr)); nla_put(rep.get(), WIFIROUTER_ATTR_PACKET, len, buf); auto hdr = nlmsg_hdr(rep.get()); auto key = GetMacHash(nla_data(attrs[HWSIM_ATTR_ADDR_TRANSMITTER])); LOG(INFO) << "Received netlink packet from " << std::hex << key; for (auto it = registered_addresses_.find(key); it != registered_addresses_.end() && it->first == key; ++it) { auto num_written = send(it->second, hdr, hdr->nlmsg_len, MSG_NOSIGNAL); if (num_written != static_cast<int64_t>(hdr->nlmsg_len)) { pending_removals.insert(it->second); } } for (auto client : pending_removals) RemoveClient(client); } } bool WifiRouter::HandleClientMessage(int client) { std::unique_ptr<nlmsghdr, void (*)(nlmsghdr*)> msg( reinterpret_cast<nlmsghdr*>(malloc(kMaxSupportedPacketSize)), [](nlmsghdr* h) { free(h); }); int64_t size = recv(client, msg.get(), kMaxSupportedPacketSize, 0); // Invalid message or no data -> client invalid or disconnected. if (size == 0 || size != msg->nlmsg_len || size < sizeof(nlmsghdr)) { return false; } int result = -EINVAL; genlmsghdr* ghdr = reinterpret_cast<genlmsghdr*>(nlmsg_data(msg.get())); switch (ghdr->cmd) { case WIFIROUTER_CMD_REGISTER: // Register client to receive notifications for specified MAC address. nlattr* attrs[WIFIROUTER_ATTR_MAX]; if (!nlmsg_parse(msg.get(), sizeof(genlmsghdr), attrs, WIFIROUTER_ATTR_MAX - 1, nullptr)) { if (attrs[WIFIROUTER_ATTR_MAC] != nullptr) { LOG(INFO) << "Registering new client to receive data for " << GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])); registered_addresses_.emplace( GetMacHash(nla_data(attrs[WIFIROUTER_ATTR_MAC])), client); // This is unfortunate, but it is a bug in mac80211_hwsim stack. // Apparently, the imperfect medium will not receive notifications for // newly created wifi interfaces. How about that... RegisterForHWSimNotifications(); result = 0; } } break; default: break; } nlmsgerr err{.error = result}; std::unique_ptr<nl_msg, void (*)(nl_msg*)> rsp(nlmsg_alloc(), nlmsg_free); nlmsg_put(rsp.get(), msg->nlmsg_pid, msg->nlmsg_seq, NLMSG_ERROR, 0, 0); nlmsg_append(rsp.get(), &err, sizeof(err), 0); auto hdr = nlmsg_hdr(rsp.get()); if (send(client, hdr, hdr->nlmsg_len, MSG_NOSIGNAL) != static_cast<int64_t>(hdr->nlmsg_len)) { return false; } return true; } // Process incoming requests from netlink, server or clients. void WifiRouter::ServerLoop() { while (true) { auto max_fd = 0; fd_set reads{}; auto fdset = [&max_fd, &reads](int fd) { FD_SET(fd, &reads); max_fd = std::max(max_fd, fd); }; fdset(server_fd_); fdset(nl_socket_get_fd(sock_.get())); for (int client : registered_clients_) fdset(client); if (select(max_fd + 1, &reads, nullptr, nullptr, nullptr) <= 0) continue; if (FD_ISSET(server_fd_, &reads)) AcceptNewClient(); if (FD_ISSET(nl_socket_get_fd(sock_.get()), &reads)) RouteWIFIPacket(); // Process any client messages left. Drop any client that is no longer // talking with us. for (auto client = registered_clients_.begin(); client != registered_clients_.end();) { auto cfd = *client++; // Is our client sending us data? if (FD_ISSET(cfd, &reads)) { if (!HandleClientMessage(cfd)) RemoveClient(cfd); } } } } } // namespace } // namespace cvd int main(int argc, char* argv[]) { using namespace cvd; google::ParseCommandLineFlags(&argc, &argv, true); #if !defined(ANDROID) // We should check for legitimate google logging here. google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); #endif WifiRouter r; r.Init(); r.ServerLoop(); } <|endoftext|>
<commit_before><commit_msg>Typo: s -> e<commit_after><|endoftext|>
<commit_before>#include "ostree_repo.h" #include "logging/logging.h" OSTreeObject::ptr OSTreeRepo::GetObject(const uint8_t sha256[32], const OstreeObjectType type) const { return GetObject(OSTreeHash(sha256), type); } OSTreeObject::ptr OSTreeRepo::GetObject(const OSTreeHash hash, const OstreeObjectType type) const { otable::const_iterator it; it = ObjectTable.find(hash); if (it != ObjectTable.end()) { return it->second; } const std::string exts[] = {".filez", ".dirtree", ".dirmeta", ".commit"}; const std::string objpath = hash.string().insert(2, 1, '/'); OSTreeObject::ptr object; int ext_index = -1; switch (type) { case OstreeObjectType::OSTREE_OBJECT_TYPE_FILE: ext_index = 0; break; case OstreeObjectType::OSTREE_OBJECT_TYPE_DIR_TREE: ext_index = 1; break; case OstreeObjectType::OSTREE_OBJECT_TYPE_DIR_META: ext_index = 2; break; case OstreeObjectType::OSTREE_OBJECT_TYPE_COMMIT: ext_index = 3; break; case OstreeObjectType::OSTREE_OBJECT_TYPE_UNKNOWN: default: break; } for (int i = 0; i < 3; ++i) { if (i > 0) { LOG_WARNING << "OSTree hash " << hash << " not found. Retrying (attempt " << i << " of 3)"; } if (type != OstreeObjectType::OSTREE_OBJECT_TYPE_UNKNOWN) { if (CheckForObject(hash, objpath + exts[ext_index], object)) { return object; } } else { for (const std::string &ext : exts) { if (CheckForObject(hash, objpath + ext, object)) { return object; } } } } throw OSTreeObjectMissing(hash); } bool OSTreeRepo::CheckForObject(const OSTreeHash &hash, const std::string &path, OSTreeObject::ptr &object) const { if (FetchObject(std::string("objects/") + path)) { object = OSTreeObject::ptr(new OSTreeObject(*this, path)); ObjectTable[hash] = object; LOG_DEBUG << "Fetched OSTree object " << path; return true; } return false; } <commit_msg>Refactor object type discovery to use a map.<commit_after>#include "ostree_repo.h" #include "logging/logging.h" OSTreeObject::ptr OSTreeRepo::GetObject(const uint8_t sha256[32], const OstreeObjectType type) const { return GetObject(OSTreeHash(sha256), type); } OSTreeObject::ptr OSTreeRepo::GetObject(const OSTreeHash hash, const OstreeObjectType type) const { otable::const_iterator obj_it = ObjectTable.find(hash); if (obj_it != ObjectTable.cend()) { return obj_it->second; } const std::map<OstreeObjectType, std::string> exts{{OstreeObjectType::OSTREE_OBJECT_TYPE_FILE, ".filez"}, {OstreeObjectType::OSTREE_OBJECT_TYPE_DIR_TREE, ".dirtree"}, {OstreeObjectType::OSTREE_OBJECT_TYPE_DIR_META, ".dirmeta"}, {OstreeObjectType::OSTREE_OBJECT_TYPE_COMMIT, ".commit"}}; const std::string objpath = hash.string().insert(2, 1, '/'); OSTreeObject::ptr object; for (int i = 0; i < 3; ++i) { if (i > 0) { LOG_WARNING << "OSTree hash " << hash << " not found. Retrying (attempt " << i << " of 3)"; } if (type != OstreeObjectType::OSTREE_OBJECT_TYPE_UNKNOWN) { if (CheckForObject(hash, objpath + exts.at(type), object)) { return object; } } else { for (auto it = exts.cbegin(); it != exts.cend(); ++it) { if (CheckForObject(hash, objpath + it->second, object)) { return object; } } } } throw OSTreeObjectMissing(hash); } bool OSTreeRepo::CheckForObject(const OSTreeHash &hash, const std::string &path, OSTreeObject::ptr &object) const { if (FetchObject(std::string("objects/") + path)) { object = OSTreeObject::ptr(new OSTreeObject(*this, path)); ObjectTable[hash] = object; LOG_DEBUG << "Fetched OSTree object " << path; return true; } return false; } <|endoftext|>
<commit_before>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2009 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation and included in the file LICENSE. 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. Bacula® is a registered trademark of Kern Sibbald. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id$ * * MediaList Class * * Dirk Bartley, March 2007 * */ #include "bat.h" #include <QAbstractEventDispatcher> #include <QMenu> #include <math.h> #include "medialist.h" #include "mediaedit/mediaedit.h" #include "joblist/joblist.h" #include "relabel/relabel.h" #include "run/run.h" #include "util/fmtwidgetitem.h" MediaList::MediaList() { setupUi(this); m_name = tr("Media"); pgInitialize(); QTreeWidgetItem* thisitem = mainWin->getFromHash(this); thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png"))); /* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */ m_populated = false; m_checkcurwidget = true; m_closeable = false; /* add context sensitive menu items specific to this classto the page * selector tree. m_contextActions is QList of QActions */ m_contextActions.append(actionRefreshMediaList); dockPage(); } MediaList::~MediaList() { if (m_populated) writeExpandedSettings(); } /* * The main meat of the class!! The function that querries the director and * creates the widgets with appropriate values. */ void MediaList::populateTree() { if (m_populated) writeExpandedSettings(); m_populated = true; Freeze frz(*mp_treeWidget); /* disable updating*/ QStringList headerlist = (QStringList() << tr("Volume Name") << tr("Id") << tr("Status") << tr("Enabled") << tr("Bytes") << tr("Files") << tr("Jobs") << tr("Retention") << tr("Media Type") << tr("Slot") << tr("Use Duration") << tr("Max Jobs") << tr("Max Files") << tr("Max Bytes") << tr("Recycle") << tr("RecyclePool") << tr("Last Written")); m_checkcurwidget = false; mp_treeWidget->clear(); m_checkcurwidget = true; mp_treeWidget->setColumnCount(headerlist.count()); m_topItem = new QTreeWidgetItem(mp_treeWidget); m_topItem->setText(0, tr("Pools")); m_topItem->setData(0, Qt::UserRole, 0); m_topItem->setExpanded(true); mp_treeWidget->setHeaderLabels(headerlist); QSettings settings(m_console->m_dir->name(), "bat"); settings.beginGroup("MediaListTreeExpanded"); QString query; QTreeWidgetItem *pooltreeitem; /* Comma separated list of pools first */ bool first = true; QString pool_comsep(""); foreach (QString pool_listItem, m_console->pool_list) { if (first) { pool_comsep += "'" + pool_listItem + "'"; first = false; } else pool_comsep += ",'" + pool_listItem + "'"; } /* Now use pool_comsep list to perform just one query */ if (pool_comsep != "") { query = "SELECT Pool.Name AS pul," " Media.VolumeName AS Media, " " Media.MediaId AS Id, Media.VolStatus AS VolStatus," " Media.Enabled AS Enabled, Media.VolBytes AS Bytes," " Media.VolFiles AS FileCount, Media.VolJobs AS JobCount," " Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType," " Media.InChanger AS InChanger, Media.Slot AS Slot, " " Media.VolUseDuration AS UseDuration," " Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles," " Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle," " Pol.Name AS RecyclePool, Media.LastWritten AS LastWritten" " FROM Media" " JOIN Pool ON (Media.PoolId=Pool.PoolId)" " LEFT OUTER JOIN Pool AS Pol ON (Media.RecyclePoolId=Pol.PoolId)" " WHERE "; query += " Pool.Name IN (" + pool_comsep + ")"; query += " ORDER BY Pool.Name, Media"; if (mainWin->m_sqlDebug) { Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data()); } QStringList results; int counter = 0; if (m_console->sql_cmd(query, results)) { QStringList fieldlist; QString prev_pool(""); QString this_pool(""); /* Iterate through the lines of results. */ foreach (QString resultline, results) { fieldlist = resultline.split("\t"); this_pool = fieldlist.takeFirst(); if (prev_pool != this_pool) { prev_pool = this_pool; pooltreeitem = new QTreeWidgetItem(m_topItem); pooltreeitem->setText(0, this_pool); pooltreeitem->setData(0, Qt::UserRole, 1); } if(settings.contains(this_pool)) { pooltreeitem->setExpanded(settings.value(this_pool).toBool()); } else { pooltreeitem->setExpanded(true); } if (fieldlist.size() < 18) continue; // some fields missing, ignore row int index = 0; TreeItemFormatter mediaitem(*pooltreeitem, 2); /* Iterate through fields in the record */ QStringListIterator fld(fieldlist); /* volname */ mediaitem.setTextFld(index++, fld.next()); /* id */ mediaitem.setNumericFld(index++, fld.next()); /* status */ mediaitem.setVolStatusFld(index++, fld.next()); /* enabled */ mediaitem.setBoolFld(index++, fld.next()); /* bytes */ mediaitem.setBytesFld(index++, fld.next()); /* files */ mediaitem.setNumericFld(index++, fld.next()); /* jobs */ mediaitem.setNumericFld(index++, fld.next()); /* retention */ mediaitem.setDurationFld(index++, fld.next()); /* media type */ mediaitem.setTextFld(index++, fld.next()); /* inchanger + slot */ int inchanger = fld.next().toInt(); if (inchanger) { mediaitem.setNumericFld(index++, fld.next()); } else { /* volume not in changer, show blank slot */ mediaitem.setNumericFld(index++, ""); fld.next(); } /* use duration */ mediaitem.setDurationFld(index++, fld.next()); /* max jobs */ mediaitem.setNumericFld(index++, fld.next()); /* max files */ mediaitem.setNumericFld(index++, fld.next()); /* max bytes */ mediaitem.setBytesFld(index++, fld.next()); /* recycle */ mediaitem.setBoolFld(index++, fld.next()); /* recycle pool */ mediaitem.setTextFld(index++, fld.next()); /* last written */ mediaitem.setTextFld(index++, fld.next()); } /* foreach resultline */ counter += 1; } /* if results from query */ } /* foreach pool_listItem */ settings.endGroup(); /* Resize the columns */ for(int cnter=0; cnter<headerlist.count(); cnter++) { mp_treeWidget->resizeColumnToContents(cnter); } } /* * Called from the signal of the context sensitive menu! */ void MediaList::editVolume() { MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId); connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree())); } /* * Called from the signal of the context sensitive menu! */ void MediaList::showJobs() { QTreeWidgetItem *parentItem = mainWin->getFromHash(this); mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem); } /* * When the treeWidgetItem in the page selector tree is singleclicked, Make sure * The tree has been populated. */ void MediaList::PgSeltreeWidgetClicked() { if (!m_populated) { populateTree(); createContextMenu(); } } /* * Added to set the context menu policy based on currently active treeWidgetItem * signaled by currentItemChanged */ void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem ) { /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */ if (m_checkcurwidget) { /* The Previous item */ if (previouswidgetitem) { /* avoid a segfault if first time */ foreach(QAction* mediaAction, mp_treeWidget->actions()) { mp_treeWidget->removeAction(mediaAction); } } int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt(); m_currentVolumeName=currentwidgetitem->text(0); mp_treeWidget->addAction(actionRefreshMediaList); if (treedepth == 2){ m_currentVolumeId=currentwidgetitem->text(1); mp_treeWidget->addAction(actionEditVolume); mp_treeWidget->addAction(actionListJobsOnVolume); mp_treeWidget->addAction(actionDeleteVolume); mp_treeWidget->addAction(actionPruneVolume); mp_treeWidget->addAction(actionPurgeVolume); mp_treeWidget->addAction(actionRelabelVolume); mp_treeWidget->addAction(actionVolumeFromPool); } else if (treedepth == 1) { mp_treeWidget->addAction(actionAllVolumesFromPool); } } } /* * Setup a context menu * Made separate from populate so that it would not create context menu over and * over as the tree is repopulated. */ void MediaList::createContextMenu() { mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu); connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume())); connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs())); connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume())); connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume())); connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume())); connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume())); connect(mp_treeWidget, SIGNAL( currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *))); /* connect to the action specific to this pages class */ connect(actionRefreshMediaList, SIGNAL(triggered()), this, SLOT(populateTree())); connect(actionAllVolumes, SIGNAL(triggered()), this, SLOT(allVolumes())); connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool())); connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool())); } /* * Virtual function which is called when this page is visible on the stack */ void MediaList::currentStackItem() { if(!m_populated) { populateTree(); /* Create the context menu for the medialist tree */ createContextMenu(); } } /* * Called from the signal of the context sensitive menu to delete a volume! */ void MediaList::deleteVolume() { if (QMessageBox::warning(this, "Bat", tr("Are you sure you want to delete?? !!!.\n" "This delete command is used to delete a Volume record and all associated catalog" " records that were created. This command operates only on the Catalog" " database and has no effect on the actual data written to a Volume. This" " command can be dangerous and we strongly recommend that you do not use" " it unless you know what you are doing. All Jobs and all associated" " records (File and JobMedia) will be deleted from the catalog." "Press OK to proceed with delete operation.?"), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { return; } QString cmd("delete volume="); cmd += m_currentVolumeName; consoleCommand(cmd); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::purgeVolume() { if (QMessageBox::warning(this, "Bat", tr("Are you sure you want to purge ?? !!!.\n" "The Purge command will delete associated Catalog database records from Jobs and" " Volumes without considering the retention period. Purge works only on the" " Catalog database and does not affect data written to Volumes. This command can" " be dangerous because you can delete catalog records associated with current" " backups of files, and we recommend that you do not use it unless you know what" " you are doing.\n" "Press OK to proceed with the purge operation?"), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { return; } QString cmd("purge volume="); cmd += m_currentVolumeName; consoleCommand(cmd); populateTree(); } /* * Called from the signal of the context sensitive menu to prune! */ void MediaList::pruneVolume() { new prunePage(m_currentVolumeName, ""); } /* * Called from the signal of the context sensitive menu to relabel! */ void MediaList::relabelVolume() { setConsoleCurrent(); new relabelDialog(m_console, m_currentVolumeName); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::allVolumesFromPool() { QString cmd = "update volume AllFromPool=" + m_currentVolumeName; consoleCommand(cmd); populateTree(); } void MediaList::allVolumes() { QString cmd = "update volume allfrompools"; consoleCommand(cmd); populateTree(); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::volumeFromPool() { QTreeWidgetItem *currentItem = mp_treeWidget->currentItem(); QTreeWidgetItem *parent = currentItem->parent(); QString pool = parent->text(0); QString cmd; cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool; consoleCommand(cmd); populateTree(); } /* * Write settings to save expanded states of the pools */ void MediaList::writeExpandedSettings() { if (m_topItem) { QSettings settings(m_console->m_dir->name(), "bat"); settings.beginGroup("MediaListTreeExpanded"); int childcount = m_topItem->childCount(); for (int cnt=0; cnt<childcount; cnt++) { QTreeWidgetItem *poolitem = m_topItem->child(cnt); settings.setValue(poolitem->text(0), poolitem->isExpanded()); } settings.endGroup(); } } <commit_msg>Add columns to the tree to show read/write time, scratch pool, recycle count.<commit_after>/* Bacula® - The Network Backup Solution Copyright (C) 2007-2009 Free Software Foundation Europe e.V. The main author of Bacula is Kern Sibbald, with contributions from many others, a complete list can be found in the file AUTHORS. This program is Free Software; you can redistribute it and/or modify it under the terms of version two of the GNU General Public License as published by the Free Software Foundation and included in the file LICENSE. 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. Bacula® is a registered trademark of Kern Sibbald. The licensor of Bacula is the Free Software Foundation Europe (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich, Switzerland, email:ftf@fsfeurope.org. */ /* * Version $Id$ * * MediaList Class * * Dirk Bartley, March 2007 * */ #include "bat.h" #include <QAbstractEventDispatcher> #include <QMenu> #include <math.h> #include "medialist.h" #include "mediaedit/mediaedit.h" #include "joblist/joblist.h" #include "relabel/relabel.h" #include "run/run.h" #include "util/fmtwidgetitem.h" MediaList::MediaList() { setupUi(this); m_name = tr("Media"); pgInitialize(); QTreeWidgetItem* thisitem = mainWin->getFromHash(this); thisitem->setIcon(0,QIcon(QString::fromUtf8(":images/cartridge.png"))); /* mp_treeWidget, Storage Tree Tree Widget inherited from ui_medialist.h */ m_populated = false; m_checkcurwidget = true; m_closeable = false; /* add context sensitive menu items specific to this classto the page * selector tree. m_contextActions is QList of QActions */ m_contextActions.append(actionRefreshMediaList); dockPage(); } MediaList::~MediaList() { if (m_populated) writeExpandedSettings(); } /* * The main meat of the class!! The function that querries the director and * creates the widgets with appropriate values. */ void MediaList::populateTree() { if (m_populated) writeExpandedSettings(); m_populated = true; Freeze frz(*mp_treeWidget); /* disable updating*/ QStringList headerlist = (QStringList() << tr("Volume Name") << tr("Id") << tr("Status") << tr("Enabled") << tr("Bytes") << tr("Files") << tr("Jobs") << tr("Retention") << tr("Media Type") << tr("Slot") << tr("Use Duration") << tr("Max Jobs") << tr("Max Files") << tr("Max Bytes") << tr("Recycle") << tr("Last Written") << tr("First Written") << tr("Read Time") << tr("Write Time") << tr("Recycle Count") << tr("Recycle Pool") << tr("Scratch Pool")); m_checkcurwidget = false; mp_treeWidget->clear(); m_checkcurwidget = true; mp_treeWidget->setColumnCount(headerlist.count()); m_topItem = new QTreeWidgetItem(mp_treeWidget); m_topItem->setText(0, tr("Pools")); m_topItem->setData(0, Qt::UserRole, 0); m_topItem->setExpanded(true); mp_treeWidget->setHeaderLabels(headerlist); QSettings settings(m_console->m_dir->name(), "bat"); settings.beginGroup("MediaListTreeExpanded"); QString query; QTreeWidgetItem *pooltreeitem; /* Comma separated list of pools first */ bool first = true; QString pool_comsep(""); foreach (QString pool_listItem, m_console->pool_list) { if (first) { pool_comsep += "'" + pool_listItem + "'"; first = false; } else pool_comsep += ",'" + pool_listItem + "'"; } /* Now use pool_comsep list to perform just one query */ if (pool_comsep != "") { query = "SELECT Pool.Name AS pul," " Media.VolumeName AS Media, " " Media.MediaId AS Id, Media.VolStatus AS VolStatus," " Media.Enabled AS Enabled, Media.VolBytes AS Bytes," " Media.VolFiles AS FileCount, Media.VolJobs AS JobCount," " Media.VolRetention AS VolumeRetention, Media.MediaType AS MediaType," " Media.InChanger AS InChanger, Media.Slot AS Slot, " " Media.VolUseDuration AS UseDuration," " Media.MaxVolJobs AS MaxJobs, Media.MaxVolFiles AS MaxFiles," " Media.MaxVolBytes AS MaxBytes, Media.Recycle AS Recycle," " Media.LastWritten AS LastWritten," " Media.FirstWritten AS FirstWritten," " (VolReadTime/1000000) AS ReadTime, (VolWriteTime/1000000) AS WriteTime," " RecycleCount AS ReCyCount," " RecPool.Name AS RecyclePool, ScrPool.Name AS ScratchPool" " FROM Media" " JOIN Pool ON (Media.PoolId=Pool.PoolId)" " LEFT OUTER JOIN Pool AS RecPool ON (Media.RecyclePoolId=RecPool.PoolId)" " LEFT OUTER JOIN Pool AS ScrPool ON (Media.ScratchPoolId=ScrPool.PoolId)" " WHERE "; query += " Pool.Name IN (" + pool_comsep + ")"; query += " ORDER BY Pool.Name, Media"; if (mainWin->m_sqlDebug) { Pmsg1(000, "MediaList query cmd : %s\n",query.toUtf8().data()); } QStringList results; int counter = 0; if (m_console->sql_cmd(query, results)) { QStringList fieldlist; QString prev_pool(""); QString this_pool(""); /* Iterate through the lines of results. */ foreach (QString resultline, results) { fieldlist = resultline.split("\t"); this_pool = fieldlist.takeFirst(); if (prev_pool != this_pool) { prev_pool = this_pool; pooltreeitem = new QTreeWidgetItem(m_topItem); pooltreeitem->setText(0, this_pool); pooltreeitem->setData(0, Qt::UserRole, 1); } if(settings.contains(this_pool)) { pooltreeitem->setExpanded(settings.value(this_pool).toBool()); } else { pooltreeitem->setExpanded(true); } if (fieldlist.size() < 18) continue; // some fields missing, ignore row int index = 0; TreeItemFormatter mediaitem(*pooltreeitem, 2); /* Iterate through fields in the record */ QStringListIterator fld(fieldlist); /* volname */ mediaitem.setTextFld(index++, fld.next()); /* id */ mediaitem.setNumericFld(index++, fld.next()); /* status */ mediaitem.setVolStatusFld(index++, fld.next()); /* enabled */ mediaitem.setBoolFld(index++, fld.next()); /* bytes */ mediaitem.setBytesFld(index++, fld.next()); /* files */ mediaitem.setNumericFld(index++, fld.next()); /* jobs */ mediaitem.setNumericFld(index++, fld.next()); /* retention */ mediaitem.setDurationFld(index++, fld.next()); /* media type */ mediaitem.setTextFld(index++, fld.next()); /* inchanger + slot */ int inchanger = fld.next().toInt(); if (inchanger) { mediaitem.setNumericFld(index++, fld.next()); } else { /* volume not in changer, show blank slot */ mediaitem.setNumericFld(index++, ""); fld.next(); } /* use duration */ mediaitem.setDurationFld(index++, fld.next()); /* max jobs */ mediaitem.setNumericFld(index++, fld.next()); /* max files */ mediaitem.setNumericFld(index++, fld.next()); /* max bytes */ mediaitem.setBytesFld(index++, fld.next()); /* recycle */ mediaitem.setBoolFld(index++, fld.next()); /* last written */ mediaitem.setTextFld(index++, fld.next()); /* first written */ mediaitem.setTextFld(index++, fld.next()); /* read time */ mediaitem.setDurationFld(index++, fld.next()); /* write time */ mediaitem.setDurationFld(index++, fld.next()); /* Recycle Count */ mediaitem.setNumericFld(index++, fld.next()); /* recycle pool */ mediaitem.setTextFld(index++, fld.next()); /* Scratch pool */ mediaitem.setTextFld(index++, fld.next()); } /* foreach resultline */ counter += 1; } /* if results from query */ } /* foreach pool_listItem */ settings.endGroup(); /* Resize the columns */ for(int cnter=0; cnter<headerlist.count(); cnter++) { mp_treeWidget->resizeColumnToContents(cnter); } } /* * Called from the signal of the context sensitive menu! */ void MediaList::editVolume() { MediaEdit* edit = new MediaEdit(mainWin->getFromHash(this), m_currentVolumeId); connect(edit, SIGNAL(destroyed()), this, SLOT(populateTree())); } /* * Called from the signal of the context sensitive menu! */ void MediaList::showJobs() { QTreeWidgetItem *parentItem = mainWin->getFromHash(this); mainWin->createPageJobList(m_currentVolumeName, "", "", "", parentItem); } /* * When the treeWidgetItem in the page selector tree is singleclicked, Make sure * The tree has been populated. */ void MediaList::PgSeltreeWidgetClicked() { if (!m_populated) { populateTree(); createContextMenu(); } } /* * Added to set the context menu policy based on currently active treeWidgetItem * signaled by currentItemChanged */ void MediaList::treeItemChanged(QTreeWidgetItem *currentwidgetitem, QTreeWidgetItem *previouswidgetitem ) { /* m_checkcurwidget checks to see if this is during a refresh, which will segfault */ if (m_checkcurwidget) { /* The Previous item */ if (previouswidgetitem) { /* avoid a segfault if first time */ foreach(QAction* mediaAction, mp_treeWidget->actions()) { mp_treeWidget->removeAction(mediaAction); } } int treedepth = currentwidgetitem->data(0, Qt::UserRole).toInt(); m_currentVolumeName=currentwidgetitem->text(0); mp_treeWidget->addAction(actionRefreshMediaList); if (treedepth == 2){ m_currentVolumeId=currentwidgetitem->text(1); mp_treeWidget->addAction(actionEditVolume); mp_treeWidget->addAction(actionListJobsOnVolume); mp_treeWidget->addAction(actionDeleteVolume); mp_treeWidget->addAction(actionPruneVolume); mp_treeWidget->addAction(actionPurgeVolume); mp_treeWidget->addAction(actionRelabelVolume); mp_treeWidget->addAction(actionVolumeFromPool); } else if (treedepth == 1) { mp_treeWidget->addAction(actionAllVolumesFromPool); } } } /* * Setup a context menu * Made separate from populate so that it would not create context menu over and * over as the tree is repopulated. */ void MediaList::createContextMenu() { mp_treeWidget->setContextMenuPolicy(Qt::ActionsContextMenu); connect(actionEditVolume, SIGNAL(triggered()), this, SLOT(editVolume())); connect(actionListJobsOnVolume, SIGNAL(triggered()), this, SLOT(showJobs())); connect(actionDeleteVolume, SIGNAL(triggered()), this, SLOT(deleteVolume())); connect(actionPurgeVolume, SIGNAL(triggered()), this, SLOT(purgeVolume())); connect(actionPruneVolume, SIGNAL(triggered()), this, SLOT(pruneVolume())); connect(actionRelabelVolume, SIGNAL(triggered()), this, SLOT(relabelVolume())); connect(mp_treeWidget, SIGNAL( currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(treeItemChanged(QTreeWidgetItem *, QTreeWidgetItem *))); /* connect to the action specific to this pages class */ connect(actionRefreshMediaList, SIGNAL(triggered()), this, SLOT(populateTree())); connect(actionAllVolumes, SIGNAL(triggered()), this, SLOT(allVolumes())); connect(actionAllVolumesFromPool, SIGNAL(triggered()), this, SLOT(allVolumesFromPool())); connect(actionVolumeFromPool, SIGNAL(triggered()), this, SLOT(volumeFromPool())); } /* * Virtual function which is called when this page is visible on the stack */ void MediaList::currentStackItem() { if(!m_populated) { populateTree(); /* Create the context menu for the medialist tree */ createContextMenu(); } } /* * Called from the signal of the context sensitive menu to delete a volume! */ void MediaList::deleteVolume() { if (QMessageBox::warning(this, "Bat", tr("Are you sure you want to delete?? !!!.\n" "This delete command is used to delete a Volume record and all associated catalog" " records that were created. This command operates only on the Catalog" " database and has no effect on the actual data written to a Volume. This" " command can be dangerous and we strongly recommend that you do not use" " it unless you know what you are doing. All Jobs and all associated" " records (File and JobMedia) will be deleted from the catalog." "Press OK to proceed with delete operation.?"), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { return; } QString cmd("delete volume="); cmd += m_currentVolumeName; consoleCommand(cmd); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::purgeVolume() { if (QMessageBox::warning(this, "Bat", tr("Are you sure you want to purge ?? !!!.\n" "The Purge command will delete associated Catalog database records from Jobs and" " Volumes without considering the retention period. Purge works only on the" " Catalog database and does not affect data written to Volumes. This command can" " be dangerous because you can delete catalog records associated with current" " backups of files, and we recommend that you do not use it unless you know what" " you are doing.\n" "Press OK to proceed with the purge operation?"), QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) { return; } QString cmd("purge volume="); cmd += m_currentVolumeName; consoleCommand(cmd); populateTree(); } /* * Called from the signal of the context sensitive menu to prune! */ void MediaList::pruneVolume() { new prunePage(m_currentVolumeName, ""); } /* * Called from the signal of the context sensitive menu to relabel! */ void MediaList::relabelVolume() { setConsoleCurrent(); new relabelDialog(m_console, m_currentVolumeName); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::allVolumesFromPool() { QString cmd = "update volume AllFromPool=" + m_currentVolumeName; consoleCommand(cmd); populateTree(); } void MediaList::allVolumes() { QString cmd = "update volume allfrompools"; consoleCommand(cmd); populateTree(); } /* * Called from the signal of the context sensitive menu to purge! */ void MediaList::volumeFromPool() { QTreeWidgetItem *currentItem = mp_treeWidget->currentItem(); QTreeWidgetItem *parent = currentItem->parent(); QString pool = parent->text(0); QString cmd; cmd = "update volume=" + m_currentVolumeName + " frompool=" + pool; consoleCommand(cmd); populateTree(); } /* * Write settings to save expanded states of the pools */ void MediaList::writeExpandedSettings() { if (m_topItem) { QSettings settings(m_console->m_dir->name(), "bat"); settings.beginGroup("MediaListTreeExpanded"); int childcount = m_topItem->childCount(); for (int cnt=0; cnt<childcount; cnt++) { QTreeWidgetItem *poolitem = m_topItem->child(cnt); settings.setValue(poolitem->text(0), poolitem->isExpanded()); } settings.endGroup(); } } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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 "libtorrent/time.hpp" // for total_seconds #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include "libtorrent/broadcast_socket.hpp" // for cidr_distance #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #ifdef TORRENT_DEBUG o->m_in_constructor = false; #endif return o; } traversal_algorithm::traversal_algorithm( node_impl& node , node_id target) : m_ref_count(0) , m_node(node) , m_target(target) , m_invoke_count(0) , m_branch_factor(3) , m_responses(0) , m_timeouts(0) , m_num_target_nodes(m_node.m_table.bucket_size() * 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target; #endif } bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs) { TORRENT_ASSERT(lhs->target_addr().is_v4() == rhs->target_addr().is_v4()); // the number of bits in the IPs that may match. If // more bits that this matches, something suspicious is // going on and we shouldn't add the second one to our // routing table int cutoff = rhs->target_addr().is_v4() ? 4 : 64; int dist = cidr_distance(lhs->target_addr(), rhs->target_addr()); return dist <= cutoff; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] failed to allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { if (m_node.settings().restrict_search_ips) { // don't allow multiple entries from IPs very close to each other std::vector<observer_ptr>::iterator j = std::find_if( m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o)); if (j != m_results.end()) { // we already have a node in this search with an IP very // close to this one. We know that it's not the same, because // it claims a different node-ID. Ignore this to avoid attacks #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id() << " " << o->target_addr() << " existing node: " << (*j)->id() << " " << (*j)->target_addr(); #endif return; } } TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) m_results.resize(100); } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name() << "] WARNING: node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; TORRENT_ASSERT(o->flags & observer::flag_queried); o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id(), o->target_ep()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } namespace { bool bitwise_nand(unsigned char lhs, unsigned char rhs) { return (lhs & rhs) == 0; } } void traversal_algorithm::add_requests() { int results_target = m_num_target_nodes; // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; l.first_timeout = 0; int last_sent = INT_MAX; ptime now = time_now(); for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { observer& o = **i; if (o.flags & observer::flag_queried) { last_sent = (std::min)(last_sent, total_seconds(now - o.sent())); if (o.has_short_timeout()) ++l.first_timeout; continue; } ++l.nodes_left; } l.last_sent = last_sent; } } } // namespace libtorrent::dht <commit_msg>fix DHT cidr check<commit_after>/* Copyright (c) 2006, Arvid Norberg & Daniel Wallin 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 "libtorrent/time.hpp" // for total_seconds #include <libtorrent/kademlia/traversal_algorithm.hpp> #include <libtorrent/kademlia/routing_table.hpp> #include <libtorrent/kademlia/rpc_manager.hpp> #include <libtorrent/kademlia/node.hpp> #include <libtorrent/session_status.hpp> #include "libtorrent/broadcast_socket.hpp" // for cidr_distance #include <boost/bind.hpp> namespace libtorrent { namespace dht { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_DEFINE_LOG(traversal) #endif observer_ptr traversal_algorithm::new_observer(void* ptr , udp::endpoint const& ep, node_id const& id) { observer_ptr o(new (ptr) null_observer(boost::intrusive_ptr<traversal_algorithm>(this), ep, id)); #ifdef TORRENT_DEBUG o->m_in_constructor = false; #endif return o; } traversal_algorithm::traversal_algorithm( node_impl& node , node_id target) : m_ref_count(0) , m_node(node) , m_target(target) , m_invoke_count(0) , m_branch_factor(3) , m_responses(0) , m_timeouts(0) , m_num_target_nodes(m_node.m_table.bucket_size() * 2) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << "] new traversal process. Target: " << target; #endif } // returns true of lhs and rhs are too close to each other to appear // in the same DHT search under different node IDs bool compare_ip_cidr(observer_ptr const& lhs, observer_ptr const& rhs) { if (lhs->target_addr().is_v4() != rhs->target_addr().is_v4()) return false; // the number of bits in the IPs that may match. If // more bits that this matches, something suspicious is // going on and we shouldn't add the second one to our // routing table int cutoff = rhs->target_addr().is_v4() ? 4 : 64; int dist = cidr_distance(lhs->target_addr(), rhs->target_addr()); return dist <= cutoff; } void traversal_algorithm::add_entry(node_id const& id, udp::endpoint addr, unsigned char flags) { TORRENT_ASSERT(m_node.m_rpc.allocation_size() >= sizeof(find_data_observer)); void* ptr = m_node.m_rpc.allocate_observer(); if (ptr == 0) { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] failed to allocate memory for observer. aborting!"; #endif done(); return; } observer_ptr o = new_observer(ptr, addr, id); if (id.is_all_zeros()) { o->set_id(generate_id()); o->flags |= observer::flag_no_id; } o->flags |= flags; std::vector<observer_ptr>::iterator i = std::lower_bound( m_results.begin() , m_results.end() , o , boost::bind( compare_ref , boost::bind(&observer::id, _1) , boost::bind(&observer::id, _2) , m_target ) ); if (i == m_results.end() || (*i)->id() != id) { if (m_node.settings().restrict_search_ips) { // don't allow multiple entries from IPs very close to each other std::vector<observer_ptr>::iterator j = std::find_if( m_results.begin(), m_results.end(), boost::bind(&compare_ip_cidr, _1, o)); if (j != m_results.end()) { // we already have a node in this search with an IP very // close to this one. We know that it's not the same, because // it claims a different node-ID. Ignore this to avoid attacks #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "ignoring DHT search entry: " << o->id() << " " << o->target_addr() << " existing node: " << (*j)->id() << " " << (*j)->target_addr(); #endif return; } } TORRENT_ASSERT(std::find_if(m_results.begin(), m_results.end() , boost::bind(&observer::id, _1) == id) == m_results.end()); #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << "[" << this << ":" << name() << "] adding result: " << id << " " << addr; #endif i = m_results.insert(i, o); } if (m_results.size() > 100) m_results.resize(100); } void traversal_algorithm::start() { // in case the routing table is empty, use the // router nodes in the table if (m_results.empty()) add_router_entries(); init(); add_requests(); } void* traversal_algorithm::allocate_observer() { return m_node.m_rpc.allocate_observer(); } void traversal_algorithm::free_observer(void* ptr) { m_node.m_rpc.free_observer(ptr); } void traversal_algorithm::traverse(node_id const& id, udp::endpoint addr) { #ifdef TORRENT_DHT_VERBOSE_LOGGING if (id.is_all_zeros()) TORRENT_LOG(traversal) << time_now_string() << "[" << this << ":" << name() << "] WARNING: node returned a list which included a node with id 0"; #endif add_entry(id, addr, 0); } void traversal_algorithm::finished(observer_ptr o) { #ifdef TORRENT_DEBUG std::vector<observer_ptr>::iterator i = std::find( m_results.begin(), m_results.end(), o); TORRENT_ASSERT(i != m_results.end() || m_results.size() == 100); #endif // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; TORRENT_ASSERT(o->flags & observer::flag_queried); o->flags |= observer::flag_alive; ++m_responses; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); add_requests(); if (m_invoke_count == 0) done(); } // prevent request means that the total number of requests has // overflown. This query failed because it was the oldest one. // So, if this is true, don't make another request void traversal_algorithm::failed(observer_ptr o, int flags) { TORRENT_ASSERT(m_invoke_count >= 0); if (m_results.empty()) return; TORRENT_ASSERT(o->flags & observer::flag_queried); if (flags & short_timeout) { // short timeout means that it has been more than // two seconds since we sent the request, and that // we'll most likely not get a response. But, in case // we do get a late response, keep the handler // around for some more, but open up the slot // by increasing the branch factor if ((o->flags & observer::flag_short_timeout) == 0) ++m_branch_factor; o->flags |= observer::flag_short_timeout; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] first chance timeout: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif } else { o->flags |= observer::flag_failed; // if this flag is set, it means we increased the // branch factor for it, and we should restore it if (o->flags & observer::flag_short_timeout) --m_branch_factor; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "] failed: " << o->id() << " " << o->target_ep() << " branch-factor: " << m_branch_factor << " invoke-count: " << m_invoke_count; #endif // don't tell the routing table about // node ids that we just generated ourself if ((o->flags & observer::flag_no_id) == 0) m_node.m_table.node_failed(o->id(), o->target_ep()); ++m_timeouts; --m_invoke_count; TORRENT_ASSERT(m_invoke_count >= 0); } if (flags & prevent_request) { --m_branch_factor; if (m_branch_factor <= 0) m_branch_factor = 1; } add_requests(); if (m_invoke_count == 0) done(); } void traversal_algorithm::done() { // delete all our references to the observer objects so // they will in turn release the traversal algorithm m_results.clear(); } namespace { bool bitwise_nand(unsigned char lhs, unsigned char rhs) { return (lhs & rhs) == 0; } } void traversal_algorithm::add_requests() { int results_target = m_num_target_nodes; // Find the first node that hasn't already been queried. for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end && results_target > 0 && m_invoke_count < m_branch_factor; ++i) { if ((*i)->flags & observer::flag_alive) --results_target; if ((*i)->flags & observer::flag_queried) continue; #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " [" << this << ":" << name() << "]" << " nodes-left: " << (m_results.end() - i) << " invoke-count: " << m_invoke_count << " branch-factor: " << m_branch_factor; #endif if (invoke(*i)) { TORRENT_ASSERT(m_invoke_count >= 0); ++m_invoke_count; (*i)->flags |= observer::flag_queried; } } } void traversal_algorithm::add_router_entries() { #ifdef TORRENT_DHT_VERBOSE_LOGGING TORRENT_LOG(traversal) << " using router nodes to initiate traversal algorithm. " << std::distance(m_node.m_table.router_begin(), m_node.m_table.router_end()) << " routers"; #endif for (routing_table::router_iterator i = m_node.m_table.router_begin() , end(m_node.m_table.router_end()); i != end; ++i) { add_entry(node_id(0), *i, observer::flag_initial); } } void traversal_algorithm::init() { // update the last activity of this bucket m_node.m_table.touch_bucket(m_target); m_branch_factor = m_node.branch_factor(); m_node.add_traversal_algorithm(this); } traversal_algorithm::~traversal_algorithm() { m_node.remove_traversal_algorithm(this); } void traversal_algorithm::status(dht_lookup& l) { l.timeouts = m_timeouts; l.responses = m_responses; l.outstanding_requests = m_invoke_count; l.branch_factor = m_branch_factor; l.type = name(); l.nodes_left = 0; l.first_timeout = 0; int last_sent = INT_MAX; ptime now = time_now(); for (std::vector<observer_ptr>::iterator i = m_results.begin() , end(m_results.end()); i != end; ++i) { observer& o = **i; if (o.flags & observer::flag_queried) { last_sent = (std::min)(last_sent, total_seconds(now - o.sent())); if (o.has_short_timeout()) ++l.first_timeout; continue; } ++l.nodes_left; } l.last_sent = last_sent; } } } // namespace libtorrent::dht <|endoftext|>
<commit_before><commit_msg>remove unnecessary calls to copy c'tor<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu) All rights reserved. This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe) Dynacoe was released under the MIT License, as detailed below. 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 <Dynacoe/Modules/Graphics.h> #include <Dynacoe/Util/Math.h> #include <vector> #include <cmath> #include <sstream> #include <Dynacoe/Util/Chain.h> #include <Dynacoe/Util/Random.h> #include <Dynacoe/FontAsset.h> #include <Dynacoe/Components/Shape2D.h> #include <Dynacoe/Util/Time.h> #include <Dynacoe/Dynacoe.h> #include <Dynacoe/Modules/ViewManager.h> #include <Dynacoe/Components/Text2D.h> #include <unordered_map> #include <Dynacoe/Util/Chain.h> #include <Dynacoe/Util/Vector.h> #include <Dynacoe/Util/TransformMatrix.h> #include <Dynacoe/Util/Filesys.h> static const float DISPLAY_PIXEL_COORD_RATIO = 1/(256.f); using namespace Dynacoe; using namespace std; float * Graphics::transformResult; float * Graphics::transformResult2; float * Graphics::quadVertices2D; AssetID Graphics::fontID; bool Graphics::autoRefresh; int Graphics::filter; Image * Graphics::errorImage; Renderer * Graphics::drawBuffer; AssetID Graphics::lastDisplayID; Graphics::GraphicsState Graphics::state; Graphics::FontSpec Graphics::defaultFontSpec; // The default coords for a quad being drawn via triangles static float quadTex[] { 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f }; /* DisplayTransform: A condensed implementation of the original OpenGL matrix transformation functions. It gives you more control, as you decide if / when these transformations are uploaded to the renderer. You can even give Transform the points that you wish to eventually render and obtain the corresponding homogenous points. Though, how you wish to optimize is up to you. Johnathan Corkery, 2014 */ static std::string fSearch(const std::string &); void Graphics::Init() { static bool spawned = false; if (spawned) return; spawned = true; errorImage = new Image( "BadImage"); fontID = AssetID(); autoRefresh = true; filter = true; // immediate init quadVertices2D = new float[24]; transformResult = new float[24]; transformResult2 = new float[24]; quadVertices2D[2] = quadVertices2D[6] = quadVertices2D[10] = quadVertices2D[14] = quadVertices2D[18] = quadVertices2D[22] = 0.f; quadVertices2D[3] = quadVertices2D[7] = quadVertices2D[11] = quadVertices2D[15] = quadVertices2D[19] = quadVertices2D[23] = 1.f; drawBuffer = (Renderer*)Backend::CreateDefaultRenderer(); TransformMatrix identity; identity.SetToIdentity(); identity.ReverseMajority(); state.alpha = Renderer::AlphaRule::Opaque; state.polygon = Renderer::Polygon::Line; state.dim = Renderer::Dimension::D_2D; //state.currentCamera2D = GetCamera2D().GetID(); SetCamera2D(GetCamera2D()); state.currentCamera2D.IdentifyAs<Camera>()->SetType(Camera::Type::Orthographic2D); state.currentCamera3D = GetCamera3D().GetID(); state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers( drawBuffer->GetStaticViewingMatrixID(), drawBuffer->GetStaticProjectionMatrixID() ); state.currentCamera3D.IdentifyAs<Camera>()->SetType(Camera::Type::Perspective3D); SetRenderCamera(*state.currentCamera2D.IdentifyAs<Camera>()); //GetCamera2D().node.local.reverse = true; Graphics::storeSystemImages(); // TODO: make proper. It should be that images stored with no renderer initialized are just cached until a display is given. setDisplayMode(Renderer::Polygon::Triangle, Renderer::Dimension::D_2D, Renderer::AlphaRule::Allow); } Backend * Graphics::GetBackend() { return Graphics::GetRenderer(); } void Graphics::InitAfter() { Engine::AttachManager(state.currentCamera3D); Engine::AttachManager(state.currentCamera2D); Engine::AttachManager(state.currentCameraTarget); } void Graphics::DrawBefore() { } void Graphics::DrawAfter() { } void Graphics::RunBefore() { } void Graphics::RunAfter() { } static Renderer::Render2DStaticParameters params2D; void Graphics::UpdateCameraTransforms(Camera * c) { Camera * cam2D = &Graphics::GetCamera2D(); if (cam2D == c) { Graphics::GetRenderer()->Render2DVertices(params2D); params2D.contextWidth = cam2D->Width(); params2D.contextHeight = cam2D->Height(); params2D.contextTransform = cam2D->GetGlobalTransform().GetData(); } } void Graphics::Draw(Render2D & aspect) { aspect.CheckUpdate(); Camera * cam2d = &GetCamera2D(); if (!cam2d) return; setDisplayMode(aspect.GetPolygon(), Renderer::Dimension::D_2D, aspect.mode == Render2D::RenderMode::Translucent ? Renderer::AlphaRule::Translucent : Renderer::AlphaRule::Allow); if (round(params2D.contextWidth) != cam2d->Width() || round(params2D.contextHeight) != cam2d->Height()) { UpdateCameraTransforms(cam2d); } drawBuffer->Queue2DVertices( &aspect.GetVertexIDs()[0], aspect.GetVertexIDs().size() ); } void Graphics::Draw(RenderMesh & aspect) { // flush out any queued dynamic actions setDisplayMode(aspect.GetRenderPrimitive(), Renderer::Dimension::D_3D, Renderer::AlphaRule::Allow); drawBuffer->Render2DVertices(params2D); aspect.RenderSelf(drawBuffer); // if applicable, recursively draw children /* if (aspect.NumChildren()) { RenderMesh * ptr; for(uint32_t i = 0; i < aspect.NumChildren(); ++i) { if ((ptr = (RenderMesh*)&aspect.GetChild(i)) && ptr != &aspect) Draw(*ptr); } }*/ } void Graphics::setDisplayMode(Renderer::Polygon p, Renderer::Dimension d, Renderer::AlphaRule a) { if (state.polygon != p || state.alpha != a || state.dim != d) { // Settings with which to draw have changed, so we commit what we have and start over drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha); drawBuffer->Render2DVertices(params2D); state.alpha = a; state.polygon = p; state.dim = d; drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha); } } Renderer * Graphics::GetRenderer() { return drawBuffer; } void Graphics::SetRenderer(Renderer * r) { drawBuffer = r; } void Graphics::Commit() { //GetRenderCamera().GetFramebuffer()->RunCommand("dump-texture", nullptr); //GetRenderCamera().GetFramebuffer()->RunCommand("fill-debug", nullptr); drawBuffer->Render2DVertices(params2D); setDisplayMode(Renderer::Polygon::Triangle, Renderer::Dimension::D_2D, Renderer::AlphaRule::Allow); Display * d = ViewManager::Get(ViewManager::GetCurrent()); if (d) d->Update(); Camera * c = &GetRenderCamera(); if (c && c->autoRefresh) { c->Refresh(); } } void Graphics::DrawEachFrame(bool doIt) { autoRefresh = doIt; } bool Graphics::DrawEachFrame() { return autoRefresh; } void Graphics::EnableFiltering(bool doIt) { if (!doIt) { drawBuffer->SetTextureFilter(Renderer::TexFilter::NoFilter); filter = false; } else { drawBuffer->SetTextureFilter(Renderer::TexFilter::Linear); filter = true; } } /* Image * Graphics::_getPNG(string path) { InputBuffer i(path); if (!i.Size()) return NULL; return _getTilesetPNG(path, 1, 1); } Image * Graphics::_getTilesetPNG(string path, int wImages, int hImages) { RawImage_PNG img(path, wImages, hImages, drawBuffer); return img.getImage(); } void Graphics::drawTranslucent(bool doIt) { translucent = doIt; } */ void Graphics::storeFont() { /* string path = Params::GetDynacoeDirectory() + STR(IMG_PATH) + "font.png"; Image * img = _getTilesetPNG(path, 21, 21); img->path = "font$SYS"; addToCache(img); fontID = img->index; defaultFontSpec.height = getImage(fontID).height; defaultFontSpec.width = getImage(fontID).width / 2.0; defaultFontSpec.fontFlyphScaleWidth = .5f; */ defaultFontSpec.height = Assets::Get<Image>(fontID).frames[0].Height(); defaultFontSpec.width = Assets::Get<Image>(fontID).frames[0].Width(); defaultFontSpec.fontGlyphScaleWidth = 1.0f; //^ how much space does the width of the glyph take up the frame? } void Graphics::SetCamera3D(Camera & c) { state.currentCamera3D = c.GetID(); state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers( drawBuffer->GetStaticViewingMatrixID(), drawBuffer->GetStaticProjectionMatrixID() ); } void Graphics::SetCamera2D(Camera & c) { auto cam = state.currentCamera2D.IdentifyAs<Camera>(); if (cam) { cam->node.SetReverseTranslation(false); } state.currentCamera2D = c.GetID(); c.node.SetReverseTranslation(true); cam->Invalidate(); } void Graphics::SetRenderCamera(Camera & c) { Camera * cam = &c; if (!cam) return; drawBuffer->Render2DVertices(params2D); Display * d = ViewManager::Get(ViewManager::GetCurrent()); Framebuffer * fb = cam->GetFramebuffer(); drawBuffer->AttachTarget(fb); std::vector<ViewID> views = ViewManager::ListViews(); for(uint32_t i = 0; i < views.size(); ++i) { ViewManager::Get(views[i])->AttachSource(fb); } state.currentCameraTarget = c.GetID(); c.Step(); } Camera & Graphics::GetCamera3D() { if (!state.currentCamera3D.IdentifyAs<Camera>()) { state.currentCamera3D = Entity::Create<Camera>(); state.currentCamera3D.Identify()->SetName("Camera3D"); } return *state.currentCamera3D.IdentifyAs<Camera>(); } Camera & Graphics::GetCamera2D() { if (!state.currentCamera2D.IdentifyAs<Camera>()) { state.currentCamera2D = Entity::Create<Camera>(); state.currentCamera2D.Identify()->SetName("Camera2D"); } return *state.currentCamera2D.IdentifyAs<Camera>(); } Camera & Graphics::GetRenderCamera() { if (!state.currentCameraTarget.IdentifyAs<Camera>()) { state.currentCameraTarget = Entity::Create<Camera>(); state.currentCameraTarget.Identify()->SetName("RenderCamera"); } return *state.currentCameraTarget.IdentifyAs<Camera>(); } void Graphics::Flush2D() { drawBuffer->Render2DVertices(params2D); } /// statics /// string fSearch(const string & file) { Filesys fs; string cd = fs.GetCWD(); fs.ChangeDir(Engine::GetBaseDirectory()); string fullPath = fs.FindFile(file); fs.ChangeDir(cd); return fullPath; } <commit_msg>dev: FIxed bug with re-updating a 2D camera after attachment with graphics<commit_after>/* Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu) All rights reserved. This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe) Dynacoe was released under the MIT License, as detailed below. 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 <Dynacoe/Modules/Graphics.h> #include <Dynacoe/Util/Math.h> #include <vector> #include <cmath> #include <sstream> #include <Dynacoe/Util/Chain.h> #include <Dynacoe/Util/Random.h> #include <Dynacoe/FontAsset.h> #include <Dynacoe/Components/Shape2D.h> #include <Dynacoe/Util/Time.h> #include <Dynacoe/Dynacoe.h> #include <Dynacoe/Modules/ViewManager.h> #include <Dynacoe/Components/Text2D.h> #include <unordered_map> #include <Dynacoe/Util/Chain.h> #include <Dynacoe/Util/Vector.h> #include <Dynacoe/Util/TransformMatrix.h> #include <Dynacoe/Util/Filesys.h> static const float DISPLAY_PIXEL_COORD_RATIO = 1/(256.f); using namespace Dynacoe; using namespace std; float * Graphics::transformResult; float * Graphics::transformResult2; float * Graphics::quadVertices2D; AssetID Graphics::fontID; bool Graphics::autoRefresh; int Graphics::filter; Image * Graphics::errorImage; Renderer * Graphics::drawBuffer; AssetID Graphics::lastDisplayID; Graphics::GraphicsState Graphics::state; Graphics::FontSpec Graphics::defaultFontSpec; // The default coords for a quad being drawn via triangles static float quadTex[] { 0.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f, 0.f, 1.f, 1.f, 1.f, 0.f }; /* DisplayTransform: A condensed implementation of the original OpenGL matrix transformation functions. It gives you more control, as you decide if / when these transformations are uploaded to the renderer. You can even give Transform the points that you wish to eventually render and obtain the corresponding homogenous points. Though, how you wish to optimize is up to you. Johnathan Corkery, 2014 */ static std::string fSearch(const std::string &); void Graphics::Init() { static bool spawned = false; if (spawned) return; spawned = true; errorImage = new Image( "BadImage"); fontID = AssetID(); autoRefresh = true; filter = true; // immediate init quadVertices2D = new float[24]; transformResult = new float[24]; transformResult2 = new float[24]; quadVertices2D[2] = quadVertices2D[6] = quadVertices2D[10] = quadVertices2D[14] = quadVertices2D[18] = quadVertices2D[22] = 0.f; quadVertices2D[3] = quadVertices2D[7] = quadVertices2D[11] = quadVertices2D[15] = quadVertices2D[19] = quadVertices2D[23] = 1.f; drawBuffer = (Renderer*)Backend::CreateDefaultRenderer(); TransformMatrix identity; identity.SetToIdentity(); identity.ReverseMajority(); state.alpha = Renderer::AlphaRule::Opaque; state.polygon = Renderer::Polygon::Line; state.dim = Renderer::Dimension::D_2D; //state.currentCamera2D = GetCamera2D().GetID(); SetCamera2D(GetCamera2D()); state.currentCamera2D.IdentifyAs<Camera>()->SetType(Camera::Type::Orthographic2D); state.currentCamera3D = GetCamera3D().GetID(); state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers( drawBuffer->GetStaticViewingMatrixID(), drawBuffer->GetStaticProjectionMatrixID() ); state.currentCamera3D.IdentifyAs<Camera>()->SetType(Camera::Type::Perspective3D); SetRenderCamera(*state.currentCamera2D.IdentifyAs<Camera>()); //GetCamera2D().node.local.reverse = true; Graphics::storeSystemImages(); // TODO: make proper. It should be that images stored with no renderer initialized are just cached until a display is given. setDisplayMode(Renderer::Polygon::Triangle, Renderer::Dimension::D_2D, Renderer::AlphaRule::Allow); } Backend * Graphics::GetBackend() { return Graphics::GetRenderer(); } void Graphics::InitAfter() { Engine::AttachManager(state.currentCamera3D); Engine::AttachManager(state.currentCamera2D); Engine::AttachManager(state.currentCameraTarget); } void Graphics::DrawBefore() { } void Graphics::DrawAfter() { } void Graphics::RunBefore() { } void Graphics::RunAfter() { } static Renderer::Render2DStaticParameters params2D; void Graphics::UpdateCameraTransforms(Camera * c) { Camera * cam2D = &Graphics::GetCamera2D(); if (cam2D == c) { Graphics::GetRenderer()->Render2DVertices(params2D); params2D.contextWidth = cam2D->Width(); params2D.contextHeight = cam2D->Height(); params2D.contextTransform = cam2D->GetGlobalTransform().GetData(); } } void Graphics::Draw(Render2D & aspect) { aspect.CheckUpdate(); Camera * cam2d = &GetCamera2D(); if (!cam2d) return; setDisplayMode(aspect.GetPolygon(), Renderer::Dimension::D_2D, aspect.mode == Render2D::RenderMode::Translucent ? Renderer::AlphaRule::Translucent : Renderer::AlphaRule::Allow); if (round(params2D.contextWidth) != cam2d->Width() || round(params2D.contextHeight) != cam2d->Height()) { UpdateCameraTransforms(cam2d); } drawBuffer->Queue2DVertices( &aspect.GetVertexIDs()[0], aspect.GetVertexIDs().size() ); } void Graphics::Draw(RenderMesh & aspect) { // flush out any queued dynamic actions setDisplayMode(aspect.GetRenderPrimitive(), Renderer::Dimension::D_3D, Renderer::AlphaRule::Allow); drawBuffer->Render2DVertices(params2D); aspect.RenderSelf(drawBuffer); // if applicable, recursively draw children /* if (aspect.NumChildren()) { RenderMesh * ptr; for(uint32_t i = 0; i < aspect.NumChildren(); ++i) { if ((ptr = (RenderMesh*)&aspect.GetChild(i)) && ptr != &aspect) Draw(*ptr); } }*/ } void Graphics::setDisplayMode(Renderer::Polygon p, Renderer::Dimension d, Renderer::AlphaRule a) { if (state.polygon != p || state.alpha != a || state.dim != d) { // Settings with which to draw have changed, so we commit what we have and start over drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha); drawBuffer->Render2DVertices(params2D); state.alpha = a; state.polygon = p; state.dim = d; drawBuffer->SetDrawingMode(state.polygon, state.dim, state.alpha); } } Renderer * Graphics::GetRenderer() { return drawBuffer; } void Graphics::SetRenderer(Renderer * r) { drawBuffer = r; } void Graphics::Commit() { //GetRenderCamera().GetFramebuffer()->RunCommand("dump-texture", nullptr); //GetRenderCamera().GetFramebuffer()->RunCommand("fill-debug", nullptr); drawBuffer->Render2DVertices(params2D); setDisplayMode(Renderer::Polygon::Triangle, Renderer::Dimension::D_2D, Renderer::AlphaRule::Allow); Display * d = ViewManager::Get(ViewManager::GetCurrent()); if (d) d->Update(); Camera * c = &GetRenderCamera(); if (c && c->autoRefresh) { c->Refresh(); } } void Graphics::DrawEachFrame(bool doIt) { autoRefresh = doIt; } bool Graphics::DrawEachFrame() { return autoRefresh; } void Graphics::EnableFiltering(bool doIt) { if (!doIt) { drawBuffer->SetTextureFilter(Renderer::TexFilter::NoFilter); filter = false; } else { drawBuffer->SetTextureFilter(Renderer::TexFilter::Linear); filter = true; } } /* Image * Graphics::_getPNG(string path) { InputBuffer i(path); if (!i.Size()) return NULL; return _getTilesetPNG(path, 1, 1); } Image * Graphics::_getTilesetPNG(string path, int wImages, int hImages) { RawImage_PNG img(path, wImages, hImages, drawBuffer); return img.getImage(); } void Graphics::drawTranslucent(bool doIt) { translucent = doIt; } */ void Graphics::storeFont() { /* string path = Params::GetDynacoeDirectory() + STR(IMG_PATH) + "font.png"; Image * img = _getTilesetPNG(path, 21, 21); img->path = "font$SYS"; addToCache(img); fontID = img->index; defaultFontSpec.height = getImage(fontID).height; defaultFontSpec.width = getImage(fontID).width / 2.0; defaultFontSpec.fontFlyphScaleWidth = .5f; */ defaultFontSpec.height = Assets::Get<Image>(fontID).frames[0].Height(); defaultFontSpec.width = Assets::Get<Image>(fontID).frames[0].Width(); defaultFontSpec.fontGlyphScaleWidth = 1.0f; //^ how much space does the width of the glyph take up the frame? } void Graphics::SetCamera3D(Camera & c) { state.currentCamera3D = c.GetID(); state.currentCamera3D.IdentifyAs<Camera>()->BindTransformBuffers( drawBuffer->GetStaticViewingMatrixID(), drawBuffer->GetStaticProjectionMatrixID() ); } void Graphics::SetCamera2D(Camera & c) { auto cam = state.currentCamera2D.IdentifyAs<Camera>(); if (cam) { cam->node.SetReverseTranslation(false); } state.currentCamera2D = c.GetID(); c.node.SetReverseTranslation(true); c.Invalidate(); } void Graphics::SetRenderCamera(Camera & c) { Camera * cam = &c; if (!cam) return; drawBuffer->Render2DVertices(params2D); Display * d = ViewManager::Get(ViewManager::GetCurrent()); Framebuffer * fb = cam->GetFramebuffer(); drawBuffer->AttachTarget(fb); std::vector<ViewID> views = ViewManager::ListViews(); for(uint32_t i = 0; i < views.size(); ++i) { ViewManager::Get(views[i])->AttachSource(fb); } state.currentCameraTarget = c.GetID(); c.Step(); } Camera & Graphics::GetCamera3D() { if (!state.currentCamera3D.IdentifyAs<Camera>()) { state.currentCamera3D = Entity::Create<Camera>(); state.currentCamera3D.Identify()->SetName("Camera3D"); } return *state.currentCamera3D.IdentifyAs<Camera>(); } Camera & Graphics::GetCamera2D() { if (!state.currentCamera2D.IdentifyAs<Camera>()) { state.currentCamera2D = Entity::Create<Camera>(); state.currentCamera2D.Identify()->SetName("Camera2D"); } return *state.currentCamera2D.IdentifyAs<Camera>(); } Camera & Graphics::GetRenderCamera() { if (!state.currentCameraTarget.IdentifyAs<Camera>()) { state.currentCameraTarget = Entity::Create<Camera>(); state.currentCameraTarget.Identify()->SetName("RenderCamera"); } return *state.currentCameraTarget.IdentifyAs<Camera>(); } void Graphics::Flush2D() { drawBuffer->Render2DVertices(params2D); } /// statics /// string fSearch(const string & file) { Filesys fs; string cd = fs.GetCWD(); fs.ChangeDir(Engine::GetBaseDirectory()); string fullPath = fs.FindFile(file); fs.ChangeDir(cd); return fullPath; } <|endoftext|>
<commit_before><commit_msg>another memory leak based on release().release()<commit_after><|endoftext|>
<commit_before><commit_msg>CID#703984 Unchecked return value (CHECKED_RETURN)<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: indexmap.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-07-21 11:29:56 $ * * 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_sc.hxx" #include <memory.h> #include "indexmap.hxx" ScIndexMap::ScIndexMap( USHORT nEntries ) { nCount = nEntries; ULONG nC = nEntries ? ((ULONG) nEntries * 2) : 2; pMap = new USHORT [ nC ]; memset( pMap, 0, nC * sizeof(USHORT) ); } ScIndexMap::~ScIndexMap() { delete [] pMap; } void ScIndexMap::SetPair( USHORT nEntry, USHORT nIndex1, USHORT nIndex2 ) { if ( nEntry < nCount ) { ULONG nOff = (ULONG) nEntry * 2; pMap[nOff] = nIndex1; pMap[nOff+1] = nIndex2; } } USHORT ScIndexMap::Find( USHORT nIndex1 ) const { USHORT* pStop = pMap + (ULONG) nCount * 2; for ( USHORT* pOff = pMap; pOff < pStop; pOff += 2 ) { if ( *pOff == nIndex1 ) return *(pOff+1); } return nIndex1; } <commit_msg>INTEGRATION: CWS changefileheader (1.3.492); FILE MERGED 2008/03/31 17:14:16 rt 1.3.492.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: indexmap.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" #include <memory.h> #include "indexmap.hxx" ScIndexMap::ScIndexMap( USHORT nEntries ) { nCount = nEntries; ULONG nC = nEntries ? ((ULONG) nEntries * 2) : 2; pMap = new USHORT [ nC ]; memset( pMap, 0, nC * sizeof(USHORT) ); } ScIndexMap::~ScIndexMap() { delete [] pMap; } void ScIndexMap::SetPair( USHORT nEntry, USHORT nIndex1, USHORT nIndex2 ) { if ( nEntry < nCount ) { ULONG nOff = (ULONG) nEntry * 2; pMap[nOff] = nIndex1; pMap[nOff+1] = nIndex2; } } USHORT ScIndexMap::Find( USHORT nIndex1 ) const { USHORT* pStop = pMap + (ULONG) nCount * 2; for ( USHORT* pOff = pMap; pOff < pStop; pOff += 2 ) { if ( *pOff == nIndex1 ) return *(pOff+1); } return nIndex1; } <|endoftext|>
<commit_before><commit_msg>fix assert with invalid sting length<commit_after><|endoftext|>
<commit_before><commit_msg>fdo#43534: Reset tab index for SingleRefToVars() call.<commit_after><|endoftext|>
<commit_before>/* ** Author: Abhilash ** Date: 18.04.2015 */ // Bottom up computation // #include <bits/stdc++.h> #define sf scanf #define pf printf typedef long long ll; using namespace std; const ll N = 1e6+3; const ll inf = 1e18; ll DP[N][3]; ll cost[N][3]; ll n; ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}}; ll dp() { DP[n][0] = cost[n][0]+cost[n][1]; DP[n][1] = cost[n][1]; DP[n][2] = inf; ll r, c, ans; for (int i = n-1; i >= 1; --i) { for (int j = 2; j >= 0; --j) { ans = inf; for (int k = 0; k < 4; ++k) { r = i + move[k][0]; c = j + move[k][1]; if (c >= 0 && c <= 2) { ans = min(ans, cost[i][j] + DP[r][c]); } } DP[i][j] = ans; } } return DP[1][1]; } int main() { sf("%lld", &n); ll T = 1; while (n) { for (int i = 0; i < n; ++i) sf("%lld %lld %lld", &cost[i+1][0], &cost[i+1][1], &cost[i+1][2]); pf("%lld. %lld\n", T++, dp()); sf("%lld", &n); } return 0; } <commit_msg>Update ACPC10D.cpp<commit_after>/* ** Author: Abhilash ** Date: 18.04.2015 */ // Bottom up computation // #include <bits/stdc++.h> #define sf scanf #define pf printf typedef long long ll; using namespace std; const ll N = 1e6+3; const ll inf = 1e18; ll DP[N][3]; ll cost[N][3]; ll n; ll move[4][2] = {{1, -1}, {0, 1}, {1, 1}, {1, 0}}; ll dp() { DP[n][0] = cost[n][0] + cost[n][1]; DP[n][1] = cost[n][1]; DP[n][2] = inf; ll r, c, ans; for (int i = n - 1; i >= 1; --i) { for (int j = 2; j >= 0; --j) { ans = inf; for (int k = 0; k < 4; ++k) { r = i + move[k][0]; c = j + move[k][1]; if (c >= 0 && c <= 2) { ans = min(ans, cost[i][j] + DP[r][c]); } } DP[i][j] = ans; } } return DP[1][1]; } int main() { sf("%lld", &n); ll T = 1; while (n) { for (int i = 0; i < n; ++i) sf("%lld %lld %lld", &cost[i+1][0], &cost[i+1][1], &cost[i+1][2]); pf("%lld. %lld\n", T++, dp()); sf("%lld", &n); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: excel.cxx,v $ * * $Revision: 1.24 $ * * last change: $Author: kz $ $Date: 2006-07-21 11:47:43 $ * * 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_sc.hxx" // ============================================================================ #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SVSTOR_HXX #include <sot/storage.hxx> #endif #ifndef _SOT_EXCHANGE_HXX #include <sot/exchange.hxx> #endif #ifndef _GLOBNAME_HXX #include <tools/globname.hxx> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef SC_FILTER_HXX #include "filter.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_XLDUMPER_HXX #include "xldumper.hxx" #endif #ifndef SC_XISTREAM_HXX #include "xistream.hxx" #endif #include "scerrors.hxx" #include "root.hxx" #include "imp_op.hxx" #include "excimp8.hxx" #include "exp_op.hxx" FltError ScImportExcel( SfxMedium& r, ScDocument* p ) { return ScImportExcel( r, p, EIF_AUTO ); } FltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen #if SCF_INCL_DUMPER { ::scf::dump::xls::Dumper aDumper( rMedium, pDocument->GetDocumentShell() ); aDumper.Dump(); if( !aDumper.IsImportEnabled() ) return ERRCODE_ABORT; } #endif /* Import all BIFF versions regardless on eFormat, needed for import of external cells (file type detection returns Excel4.0). */ if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) ) { DBG_ERRORFILE( "::ScImportExcel - wrong file format specification" ); return eERR_FORMAT; } // check the input stream from medium SvStream* pMedStrm = rMedium.GetInStream(); DBG_ASSERT( pMedStrm, "::ScImportExcel - medium without input stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen SvStream* pBookStrm = 0; // The "Book"/"Workbook" stream containing main data. XclBiff eBiff = EXC_BIFF_UNKNOWN; // The BIFF version of the main stream. // try to open an OLE storage SotStorageRef xRootStrg; SotStorageStreamRef xStrgStrm; if( SotStorage::IsStorageFile( pMedStrm ) ) { xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) xRootStrg = 0; } // try to open "Book" or "Workbook" stream in OLE storage if( xRootStrg.Is() ) { // try to open the "Book" stream SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK ); XclBiff eBookStrm5Biff = xBookStrm5.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN; // try to open the "Workbook" stream SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK ); XclBiff eBookStrm8Biff = xBookStrm8.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN; // decide which stream to use if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) ) { /* Only "Workbook" stream exists; or both streams exist, and "Workbook" has higher BIFF version than "Book" stream. */ xStrgStrm = xBookStrm8; eBiff = eBookStrm8Biff; } else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN ) { /* Only "Book" stream exists; or both streams exist, and "Book" has higher BIFF version than "Workbook" stream. */ xStrgStrm = xBookStrm5; eBiff = eBookStrm5Biff; } pBookStrm = xStrgStrm; } // no "Book" or "Workbook" stream found, try plain input stream from medium (even for BIFF5+) if( !pBookStrm ) { eBiff = XclImpStream::DetectBiffVersion( *pMedStrm ); if( eBiff != EXC_BIFF_UNKNOWN ) pBookStrm = pMedStrm; } // try to import the file FltError eRet = eERR_UNKN_BIFF; if( pBookStrm ) { pBookStrm->SetBufferSize( 0x8000 ); // still needed? XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 ); ::std::auto_ptr< ImportExcel > xFilter; switch( eBiff ) { case EXC_BIFF2: case EXC_BIFF3: case EXC_BIFF4: case EXC_BIFF5: xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) ); break; case EXC_BIFF8: xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) ); break; default: DBG_ERROR_BIFF(); } eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN; } return eRet; } FltError ScExportExcel234( SvStream &aStream, ScDocument *pDoc, ExportFormatExcel eFormat, CharSet eNach ) { FltError eRet = eERR_NI; return eRet; } FltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument, const BOOL bBiff8, CharSet eNach ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen // check the output stream from medium SvStream* pMedStrm = rMedium.GetOutStream(); DBG_ASSERT( pMedStrm, "::ScExportExcel5 - medium without output stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen // try to open an OLE storage SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) return eERR_OPEN; // create BIFF dependent strings String aStrmName, aClipName, aClassName; if( bBiff8 ) { aStrmName = EXC_STREAM_WORKBOOK; aClipName = CREATE_STRING( "Biff8" ); aClassName = CREATE_STRING( "Microsoft Excel 97-Tabelle" ); } else { aStrmName = EXC_STREAM_BOOK; aClipName = CREATE_STRING( "Biff5" ); aClassName = CREATE_STRING( "Microsoft Excel 5.0-Tabelle" ); } // open the "Book"/"Workbook" stream SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName ); if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN; xStrgStrm->SetBufferSize( 0x8000 ); // still needed? FltError eRet = eERR_UNKN_BIFF; XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach ); if ( bBiff8 ) { ExportBiff8 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } else { ExportBiff5 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } if( eRet == eERR_RNGOVRFLW ) eRet = SCWARN_EXPORT_MAXROW; SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 ); sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName ); xRootStrg->SetClass( aGlobName, nClip, aClassName ); xStrgStrm->Commit(); xRootStrg->Commit(); return eRet; } <commit_msg>INTEGRATION: CWS calcwarnings (1.24.108); FILE MERGED 2006/12/01 14:42:22 dr 1.24.108.1: #i69284# remove compiler warnings for wntmsci10<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: excel.cxx,v $ * * $Revision: 1.25 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:21:24 $ * * 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_sc.hxx" // ============================================================================ #ifndef _SFXDOCFILE_HXX #include <sfx2/docfile.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SVSTOR_HXX #include <sot/storage.hxx> #endif #ifndef _SOT_EXCHANGE_HXX #include <sot/exchange.hxx> #endif #ifndef _GLOBNAME_HXX #include <tools/globname.hxx> #endif #ifndef SC_ITEMS_HXX #include "scitems.hxx" #endif #ifndef _SFXSTRITEM_HXX #include <svtools/stritem.hxx> #endif #ifndef SC_FILTER_HXX #include "filter.hxx" #endif #ifndef SC_DOCUMENT_HXX #include "document.hxx" #endif #ifndef SC_XLDUMPER_HXX #include "xldumper.hxx" #endif #ifndef SC_XISTREAM_HXX #include "xistream.hxx" #endif #include "scerrors.hxx" #include "root.hxx" #include "imp_op.hxx" #include "excimp8.hxx" #include "exp_op.hxx" FltError ScImportExcel( SfxMedium& r, ScDocument* p ) { return ScImportExcel( r, p, EIF_AUTO ); } FltError ScImportExcel( SfxMedium& rMedium, ScDocument* pDocument, const EXCIMPFORMAT eFormat ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen #if SCF_INCL_DUMPER { ::scf::dump::xls::Dumper aDumper( rMedium, pDocument->GetDocumentShell() ); aDumper.Dump(); if( !aDumper.IsImportEnabled() ) return ERRCODE_ABORT; } #endif /* Import all BIFF versions regardless on eFormat, needed for import of external cells (file type detection returns Excel4.0). */ if( (eFormat != EIF_AUTO) && (eFormat != EIF_BIFF_LE4) && (eFormat != EIF_BIFF5) && (eFormat != EIF_BIFF8) ) { DBG_ERRORFILE( "::ScImportExcel - wrong file format specification" ); return eERR_FORMAT; } // check the input stream from medium SvStream* pMedStrm = rMedium.GetInStream(); DBG_ASSERT( pMedStrm, "::ScImportExcel - medium without input stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen SvStream* pBookStrm = 0; // The "Book"/"Workbook" stream containing main data. XclBiff eBiff = EXC_BIFF_UNKNOWN; // The BIFF version of the main stream. // try to open an OLE storage SotStorageRef xRootStrg; SotStorageStreamRef xStrgStrm; if( SotStorage::IsStorageFile( pMedStrm ) ) { xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) xRootStrg = 0; } // try to open "Book" or "Workbook" stream in OLE storage if( xRootStrg.Is() ) { // try to open the "Book" stream SotStorageStreamRef xBookStrm5 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_BOOK ); XclBiff eBookStrm5Biff = xBookStrm5.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm5 ) : EXC_BIFF_UNKNOWN; // try to open the "Workbook" stream SotStorageStreamRef xBookStrm8 = ScfTools::OpenStorageStreamRead( xRootStrg, EXC_STREAM_WORKBOOK ); XclBiff eBookStrm8Biff = xBookStrm8.Is() ? XclImpStream::DetectBiffVersion( *xBookStrm8 ) : EXC_BIFF_UNKNOWN; // decide which stream to use if( (eBookStrm8Biff != EXC_BIFF_UNKNOWN) && ((eBookStrm5Biff == EXC_BIFF_UNKNOWN) || (eBookStrm8Biff > eBookStrm5Biff)) ) { /* Only "Workbook" stream exists; or both streams exist, and "Workbook" has higher BIFF version than "Book" stream. */ xStrgStrm = xBookStrm8; eBiff = eBookStrm8Biff; } else if( eBookStrm5Biff != EXC_BIFF_UNKNOWN ) { /* Only "Book" stream exists; or both streams exist, and "Book" has higher BIFF version than "Workbook" stream. */ xStrgStrm = xBookStrm5; eBiff = eBookStrm5Biff; } pBookStrm = xStrgStrm; } // no "Book" or "Workbook" stream found, try plain input stream from medium (even for BIFF5+) if( !pBookStrm ) { eBiff = XclImpStream::DetectBiffVersion( *pMedStrm ); if( eBiff != EXC_BIFF_UNKNOWN ) pBookStrm = pMedStrm; } // try to import the file FltError eRet = eERR_UNKN_BIFF; if( pBookStrm ) { pBookStrm->SetBufferSize( 0x8000 ); // still needed? XclImpRootData aImpData( eBiff, rMedium, xRootStrg, *pDocument, RTL_TEXTENCODING_MS_1252 ); ::std::auto_ptr< ImportExcel > xFilter; switch( eBiff ) { case EXC_BIFF2: case EXC_BIFF3: case EXC_BIFF4: case EXC_BIFF5: xFilter.reset( new ImportExcel( aImpData, *pBookStrm ) ); break; case EXC_BIFF8: xFilter.reset( new ImportExcel8( aImpData, *pBookStrm ) ); break; default: DBG_ERROR_BIFF(); } eRet = xFilter.get() ? xFilter->Read() : eERR_INTERN; } return eRet; } FltError ScExportExcel234( SvStream& /*aStream*/, ScDocument* /*pDoc*/, ExportFormatExcel /*eFormat*/, CharSet /*eNach*/ ) { FltError eRet = eERR_NI; return eRet; } FltError ScExportExcel5( SfxMedium& rMedium, ScDocument *pDocument, const BOOL bBiff8, CharSet eNach ) { // check the passed Calc document DBG_ASSERT( pDocument, "::ScImportExcel - no document" ); if( !pDocument ) return eERR_INTERN; // should not happen // check the output stream from medium SvStream* pMedStrm = rMedium.GetOutStream(); DBG_ASSERT( pMedStrm, "::ScExportExcel5 - medium without output stream" ); if( !pMedStrm ) return eERR_OPEN; // should not happen // try to open an OLE storage SotStorageRef xRootStrg = new SotStorage( pMedStrm, FALSE ); if( xRootStrg->GetError() ) return eERR_OPEN; // create BIFF dependent strings String aStrmName, aClipName, aClassName; if( bBiff8 ) { aStrmName = EXC_STREAM_WORKBOOK; aClipName = CREATE_STRING( "Biff8" ); aClassName = CREATE_STRING( "Microsoft Excel 97-Tabelle" ); } else { aStrmName = EXC_STREAM_BOOK; aClipName = CREATE_STRING( "Biff5" ); aClassName = CREATE_STRING( "Microsoft Excel 5.0-Tabelle" ); } // open the "Book"/"Workbook" stream SotStorageStreamRef xStrgStrm = ScfTools::OpenStorageStreamWrite( xRootStrg, aStrmName ); if( !xStrgStrm.Is() || xStrgStrm->GetError() ) return eERR_OPEN; xStrgStrm->SetBufferSize( 0x8000 ); // still needed? FltError eRet = eERR_UNKN_BIFF; XclExpRootData aExpData( bBiff8 ? EXC_BIFF8 : EXC_BIFF5, rMedium, xRootStrg, *pDocument, eNach ); if ( bBiff8 ) { ExportBiff8 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } else { ExportBiff5 aFilter( aExpData, *xStrgStrm ); eRet = aFilter.Write(); } if( eRet == eERR_RNGOVRFLW ) eRet = SCWARN_EXPORT_MAXROW; SvGlobalName aGlobName( 0x00020810, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 ); sal_uInt32 nClip = SotExchange::RegisterFormatName( aClipName ); xRootStrg->SetClass( aGlobName, nClip, aClassName ); xStrgStrm->Commit(); xRootStrg->Commit(); return eRet; } <|endoftext|>
<commit_before>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 "simdindexjoin.h" #include <annis/operators/operator.h> // for Operator #include <annis/util/comparefunctions.h> // for checkAnnotationEqual #include <algorithm> // for move #include <future> // for future, async, launch, laun... #include <list> // for list #include "annis/iterators.h" // for AnnoIt, Iterator #include "annis/types.h" // for Match, Annotation, nodeid_t #include "annis/util/threadpool.h" // for ThreadPool #include <Vc/Vc> using namespace annis; SIMDIndexJoin::SIMDIndexJoin(std::shared_ptr<Iterator> lhs, size_t lhsIdx, std::shared_ptr<Operator> op, const AnnoStorage<nodeid_t>& annos, Annotation rhsAnnoToFind) : lhs(lhs), lhsIdx(lhsIdx), op(op), annos(annos), rhsAnnoToFind(rhsAnnoToFind) { } bool SIMDIndexJoin::next(std::vector<Match> &tuple) { tuple.clear(); do { while(!matchBuffer.empty()) { const MatchPair& m = matchBuffer.front(); tuple.reserve(m.lhs.size()+1); tuple.insert(tuple.begin(), m.lhs.begin(), m.lhs.end()); tuple.push_back({m.rhs, rhsAnnoToFind}); matchBuffer.pop_front(); return true; } } while (nextMatchBuffer()); return false; } void SIMDIndexJoin::reset() { if(lhs) { lhs->reset(); } matchBuffer.clear(); } bool SIMDIndexJoin::nextMatchBuffer() { std::vector<Match> currentLHS; Vc::uint32_v valueTemplate(rhsAnnoToFind.val); while(matchBuffer.empty() && lhs->next(currentLHS)) { std::unique_ptr<AnnoIt> reachableNodesIt = op->retrieveMatches(currentLHS[lhsIdx]); if(reachableNodesIt) { const bool annoDefDifferent = rhsAnnoToFind.ns != currentLHS[lhsIdx].anno.ns || rhsAnnoToFind.name != currentLHS[lhsIdx].anno.name; constexpr size_t SIMD_VECTOR_SIZE = Vc::uint32_v::size(); Vc::uint32_v vAnnoVals; Vc::Mask<uint32_t> maskFoundAnnos; // use an aligned memory allocator to make SIMD faster uint32_t annoVals[SIMD_VECTOR_SIZE]; uint32_t reachableNodes[SIMD_VECTOR_SIZE]; Match m; bool foundRHS = false; do { foundRHS = false; // fill each element of the vector for(size_t i=0; i < SIMD_VECTOR_SIZE; i++) { if(reachableNodesIt->next(m)) { std::vector<Annotation> foundAnnos = annos.getAnnotations(m.node, rhsAnnoToFind.ns, rhsAnnoToFind.name); annoVals[i] = (foundAnnos.empty() ? 0 : foundAnnos[0].val); reachableNodes[i] = (m.node); foundRHS = true; } else { annoVals[i] = 0; reachableNodes[i] = 0; } } // transform the data to SIMD vAnnoVals.load(annoVals, Vc::Aligned); // search for values that are the same as a SIMD instruction maskFoundAnnos = (vAnnoVals == valueTemplate); if(Vc::any_of(maskFoundAnnos)) { for(size_t foundIdx=static_cast<size_t>(maskFoundAnnos.firstOne()); foundIdx < maskFoundAnnos.size(); foundIdx++) { if(maskFoundAnnos[foundIdx]) { if(annoDefDifferent || op->isReflexive() || currentLHS[lhsIdx].node != reachableNodes[foundIdx]) { matchBuffer.push_back({currentLHS, reachableNodes[foundIdx]}); } } } } } while(foundRHS); } // end if reachable nodes iterator valide } // end while LHS valid and nothing found yet return !matchBuffer.empty(); } SIMDIndexJoin::~SIMDIndexJoin() { } <commit_msg>Some smaller performance improvements.<commit_after>/* Copyright 2017 Thomas Krause <thomaskrause@posteo.de> 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 "simdindexjoin.h" #include <annis/operators/operator.h> // for Operator #include <annis/util/comparefunctions.h> // for checkAnnotationEqual #include <algorithm> // for move #include <future> // for future, async, launch, laun... #include <list> // for list #include "annis/iterators.h" // for AnnoIt, Iterator #include "annis/types.h" // for Match, Annotation, nodeid_t #include "annis/util/threadpool.h" // for ThreadPool #include <Vc/Vc> using namespace annis; SIMDIndexJoin::SIMDIndexJoin(std::shared_ptr<Iterator> lhs, size_t lhsIdx, std::shared_ptr<Operator> op, const AnnoStorage<nodeid_t>& annos, Annotation rhsAnnoToFind) : lhs(lhs), lhsIdx(lhsIdx), op(op), annos(annos), rhsAnnoToFind(rhsAnnoToFind) { } bool SIMDIndexJoin::next(std::vector<Match> &tuple) { tuple.clear(); do { while(!matchBuffer.empty()) { const MatchPair& m = matchBuffer.front(); tuple.reserve(m.lhs.size()+1); tuple.insert(tuple.begin(), m.lhs.begin(), m.lhs.end()); tuple.push_back({m.rhs, rhsAnnoToFind}); matchBuffer.pop_front(); return true; } } while (nextMatchBuffer()); return false; } void SIMDIndexJoin::reset() { if(lhs) { lhs->reset(); } matchBuffer.clear(); } bool SIMDIndexJoin::nextMatchBuffer() { std::vector<Match> currentLHS; Vc::uint32_v valueTemplate(rhsAnnoToFind.val); while(matchBuffer.empty() && lhs->next(currentLHS)) { std::unique_ptr<AnnoIt> reachableNodesIt = op->retrieveMatches(currentLHS[lhsIdx]); if(reachableNodesIt) { const bool annoDefDifferent = rhsAnnoToFind.ns != currentLHS[lhsIdx].anno.ns || rhsAnnoToFind.name != currentLHS[lhsIdx].anno.name; constexpr size_t SIMD_VECTOR_SIZE = Vc::uint32_v::size(); Vc::uint32_v vAnnoVals; Vc::Mask<uint32_t> maskFoundAnnos; // use an aligned memory allocator to make SIMD faster uint32_t annoVals[SIMD_VECTOR_SIZE]; uint32_t reachableNodes[SIMD_VECTOR_SIZE]; bool foundRHS = false; do { foundRHS = false; // fill each element of the vector for(size_t i=0; i < SIMD_VECTOR_SIZE; i++) { Match m; if(reachableNodesIt->next(m)) { std::vector<Annotation> foundAnnos = annos.getAnnotations(m.node, rhsAnnoToFind.ns, rhsAnnoToFind.name); annoVals[i] = (foundAnnos.empty() ? 0 : foundAnnos[0].val); reachableNodes[i] = (m.node); foundRHS = true; } else { annoVals[i] = 0; } } // transform the data to SIMD vAnnoVals.load(annoVals, Vc::Aligned); // search for values that are the same as a SIMD instruction maskFoundAnnos = (vAnnoVals == valueTemplate); if(Vc::any_of(maskFoundAnnos)) { for(size_t foundIdx : Vc::where(maskFoundAnnos)) { if(annoDefDifferent || op->isReflexive() || currentLHS[lhsIdx].node != reachableNodes[foundIdx]) { matchBuffer.push_back({currentLHS, reachableNodes[foundIdx]}); } } } } while(foundRHS); } // end if reachable nodes iterator valide } // end while LHS valid and nothing found yet return !matchBuffer.empty(); } SIMDIndexJoin::~SIMDIndexJoin() { } <|endoftext|>
<commit_before>#include "RidgeEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" #include <boost/shared_array.hpp> namespace fast { RidgeEdgeModel::RidgeEdgeModel() { mMinimumDepth = 0; mLineLength = 0; mLineSampleSpacing = 0; mIntensityDifferenceThreshold = 20; mSizes.push_back(1); } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile, const float intensityThreshold, std::vector<int> sizes) { // Pre calculate partial sum const int line_length = intensityProfile.size(); boost::shared_array<float> sum_k(new float[line_length]()); float totalSum = 0.0f; for(int k = 0; k < line_length; ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int size : sizes) { for(int k = 1; k < line_length - size; ++k) { float score = 0.0f; // A 1 float average1 = sum_k[k] / k; for(int t = 0; t <= k; ++t) { score += fabs(average1 - intensityProfile[t]); } // A 2 float average2 = (sum_k[k+size] - sum_k[k]) / (size); for(int t = k+1; t <= k+size; ++t) { score += fabs(average2 - intensityProfile[t]); } // A 3 float average3 = (sum_k[line_length-1] - sum_k[k+size]) / (line_length - k - size); for(int t = k + size + 1; t < line_length; ++t) { score += fabs(average3 - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; float weight1 = (float)(k) / (line_length - size); float weight2 = (float)(line_length - k - size) / (line_length - size); bestHeightDifference = average2 - (average1*weight1 + average2*weight2); } } } DetectedEdge edge; if(bestHeightDifference < intensityThreshold) { edge.edgeIndex = -1; } else { edge.edgeIndex = bestK; edge.uncertainty = 1.0f/fabs(bestHeightDifference); } return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> RidgeEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the RidgeEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // Convert sizes to pixels, also make sure it is dividible by 2 std::vector<int> sizesInSteps; for(float size : mSizes) { // Convert from mm to steps (approx) int steps = round(size / mLineSampleSpacing); // Make divisible by 2 for convienience if(steps % 2 != 0) { steps++; } sizesInSteps.push_back(steps); reportInfo() << "Added step size: " << steps << reportEnd(); } // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile, mIntensityDifferenceThreshold, sizesInSteps); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y() / spacing.y())); if(position.y() < mMinimumDepth) continue; try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile, mIntensityDifferenceThreshold, sizesInSteps); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void RidgeEdgeModel::setRidgeSizes(std::vector<float> sizes) { mSizes = sizes; } void RidgeEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void RidgeEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } void RidgeEdgeModel::setIntensityDifferenceThreshold(float threshold) { if(threshold <= 0) throw Exception("Intensity difference threshold must be > 0"); mIntensityDifferenceThreshold = threshold; } void RidgeEdgeModel::setMinimumDepth(float depth) { if(depth < 0) throw Exception("Minimum depth must be > 0 in RidgeEdgeModel"); mMinimumDepth = depth; } } <commit_msg>fixed some calculations in new ridge edge model<commit_after>#include "RidgeEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" #include <boost/shared_array.hpp> namespace fast { RidgeEdgeModel::RidgeEdgeModel() { mMinimumDepth = 0; mLineLength = 0; mLineSampleSpacing = 0; mIntensityDifferenceThreshold = 20; std::vector<float> sizes = {1, 1.5, 2, 2.5, 3, 3.5, 4}; mSizes = sizes; } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile, const float intensityThreshold, std::vector<int> sizes) { // Pre calculate partial sum const int line_length = intensityProfile.size(); boost::shared_array<float> sum_k(new float[line_length]()); float totalSum = 0.0f; for(int k = 0; k < line_length; ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int size : sizes) { for(int k = 1; k < line_length - size; ++k) { float score = 0.0f; // A 1 float average1 = sum_k[k] / (k+1); for(int t = 0; t <= k; ++t) { score += fabs(average1 - intensityProfile[t]); } // A 2 float average2 = (sum_k[k+size] - sum_k[k]) / (size); for(int t = k+1; t <= k+size; ++t) { score += fabs(average2 - intensityProfile[t]); } // A 3 float average3 = (sum_k[line_length-1] - sum_k[k+size]) / (line_length - 1 - k - size); for(int t = k + size + 1; t < line_length; ++t) { score += fabs(average3 - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; float weight1 = (float)(k) / (line_length - size); float weight2 = (float)(line_length - k - size) / (line_length - size); bestHeightDifference = average2 - (average1*weight1 + average2*weight2); } } } DetectedEdge edge; if(bestHeightDifference < intensityThreshold) { edge.edgeIndex = -1; } else { edge.edgeIndex = bestK; edge.uncertainty = 1.0f/fabs(bestHeightDifference); } return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> RidgeEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the RidgeEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // Convert sizes to pixels, also make sure it is dividible by 2 std::vector<int> sizesInSteps; for(float size : mSizes) { // Convert from mm to steps (approx) int steps = round(size / mLineSampleSpacing); // Make divisible by 2 for convienience if(steps % 2 != 0 && steps == 0) { steps++; } sizesInSteps.push_back(steps); } // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile, mIntensityDifferenceThreshold, sizesInSteps); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y() / spacing.y())); if(position.y() < mMinimumDepth) continue; try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile, mIntensityDifferenceThreshold, sizesInSteps); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void RidgeEdgeModel::setRidgeSizes(std::vector<float> sizes) { mSizes = sizes; } void RidgeEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void RidgeEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } void RidgeEdgeModel::setIntensityDifferenceThreshold(float threshold) { if(threshold <= 0) throw Exception("Intensity difference threshold must be > 0"); mIntensityDifferenceThreshold = threshold; } void RidgeEdgeModel::setMinimumDepth(float depth) { if(depth < 0) throw Exception("Minimum depth must be > 0 in RidgeEdgeModel"); mMinimumDepth = depth; } } <|endoftext|>
<commit_before>#include <iostream> #include "chain.h" using namespace std; int main (int argc, char *argv[]){ if(argc < 2) { cout << "Enter the file name as input" <<endl; return 0; } //Creates new chain chain *mychain = new chain(100); int multOf = 5; // Read the file with filename stored in argv[1]. Store the numbers in mychain. mychain->readAndStoreFromFile(argv[1]); //Print mychain cout<<"\n\n The list is : "<<endl; mychain->output(); // Delete all entries from mychain which contain element that is multiple of variable multOf mychain->eraseModuloValue(multOf); //Print mychain cout<<"\n\n The list after removal of elements with multiple of 5 is : "<<endl; mychain->output(); //Reorder mychain such that all odd numbers precede all even numbers. //Note that the original ordering between odd (even) numbers should remain intact. //Example: 3 4 5 1 2 will become 3 5 1 4 2. But, 5 1 3 4 2 is not valid. mychain->oddAndEvenOrdering(); //Print mychain cout<<"\n\n The list after odd and even ordering is : "<<endl; mychain->output(); cout<<"\n\n cats: "<<endl; //Reverse the mychain mychain->reverse(); //Print mychain cout<<"\n\n The reversed list is : "<<endl; mychain->output(); } <commit_msg>Update main.cpp<commit_after>#include <iostream> #include "chain.h" using namespace std; int main (int argc, char *argv[]){ if(argc < 2) { cout << "Enter the file name as input" <<endl; return 0; } //Creates new chain chain *mychain = new chain(100); int multOf = 5; // Read the file with filename stored in argv[1]. Store the numbers in mychain. mychain->readAndStoreFromFile(argv[1]); //Print mychain cout<<"\n\n The list is : "<<endl; mychain->output(); // Delete all entries from mychain which contain element that is multiple of variable multOf mychain->eraseModuloValue(multOf); //Print mychain cout<<"\n\n The list after removal of elements with multiple of 5 is : "<<endl; mychain->output(); //Reorder mychain such that all odd numbers precede all even numbers. //Note that the original ordering between odd (even) numbers should remain intact. //Example: 3 4 5 1 2 will become 3 5 1 4 2. But, 5 1 3 4 2 is not valid. mychain->oddAndEvenOrdering(); //Print mychain cout<<"\n\n The list after odd and even ordering is : "<<endl; mychain->output(); //Reverse the mychain mychain->reverse(); //Print mychain cout<<"\n\n The reversed list is : "<<endl; mychain->output(); } <|endoftext|>
<commit_before>#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define __STDC_FORMAT_MACROS 1 #include <inttypes.h> #include <cstdint> #include <iostream> #include <algorithm> #include <vector> #include <list> #include <queue> #ifdef __cplusplus extern "C" { #endif #include "benchmark.h" #include "numbersfromtextfiles.h" #ifdef __cplusplus } #endif #ifdef MEMTRACKED #include "memtrackingallocator.h" #else size_t memory_usage; #endif void initializeMemUsageCounter() { memory_usage = 0; } uint64_t getMemUsageInBytes() { return memory_usage; } #ifdef MEMTRACKED typedef std::vector<uint32_t,MemoryCountingAllocator<uint32_t> > vector; #else typedef std::vector<uint32_t> vector; #endif static vector fast_logicalor(size_t n, const vector **inputs) { class StdVectorPtr { public: StdVectorPtr(const vector *p, bool o) : ptr(p), own(o) {} const vector *ptr; bool own; // whether to clean bool operator<(const StdVectorPtr &o) const { return o.ptr->size() < ptr->size(); // backward on purpose } }; if (n == 0) { return vector(); } if (n == 1) { return vector(*inputs[0]); } std::priority_queue<StdVectorPtr> pq; for (size_t i = 0; i < n; i++) { // could use emplace pq.push(StdVectorPtr(inputs[i], false)); } while (pq.size() > 2) { StdVectorPtr x1 = pq.top(); pq.pop(); StdVectorPtr x2 = pq.top(); pq.pop(); vector * buffer = new vector(); std::set_union(x1.ptr->begin(), x1.ptr->end(),x2.ptr->begin(), x2.ptr->end(),std::back_inserter(*buffer)); if (x1.own) { delete x1.ptr; } if (x2.own) { delete x2.ptr; } pq.push(StdVectorPtr(buffer, true)); } StdVectorPtr x1 = pq.top(); pq.pop(); StdVectorPtr x2 = pq.top(); pq.pop(); vector container; std::set_union(x1.ptr->begin(), x1.ptr->end(),x2.ptr->begin(), x2.ptr->end(),std::back_inserter(container)); if (x1.own) { delete x1.ptr; } if (x2.own) { delete x2.ptr; } return container; } /** * Once you have collected all the integers, build the bitmaps. */ static std::vector<vector > create_all_bitmaps(size_t *howmany, uint32_t **numbers, size_t count) { if (numbers == NULL) return std::vector<vector >(); std::vector<vector > answer(count); for (size_t i = 0; i < count; i++) { vector & bm = answer[i]; uint32_t * mynumbers = numbers[i]; for(size_t j = 0; j < howmany[i] ; ++j) { bm.push_back(mynumbers[j]); } bm.shrink_to_fit(); } return answer; } static void printusage(char *command) { printf( " Try %s directory \n where directory could be " "benchmarks/realdata/census1881\n", command); ; printf("the -v flag turns on verbose mode"); } int main(int argc, char **argv) { int c; const char *extension = ".txt"; bool verbose = false; uint64_t data[6]; initializeMemUsageCounter(); while ((c = getopt(argc, argv, "ve:h")) != -1) switch (c) { case 'e': extension = optarg; break; case 'v': verbose = true; break; case 'h': printusage(argv[0]); return 0; default: abort(); } if (optind >= argc) { printusage(argv[0]); return -1; } char *dirname = argv[optind]; size_t count; size_t *howmany = NULL; uint32_t **numbers = read_all_integer_files(dirname, extension, &howmany, &count); if (numbers == NULL) { printf( "I could not find or load any data file with extension %s in " "directory %s.\n", extension, dirname); return -1; } uint32_t maxvalue = 0; for (size_t i = 0; i < count; i++) { if( howmany[i] > 0 ) { if(maxvalue < numbers[i][howmany[i]-1]) { maxvalue = numbers[i][howmany[i]-1]; } } } uint64_t totalcard = 0; for (size_t i = 0; i < count; i++) { totalcard += howmany[i]; } uint64_t successivecard = 0; for (size_t i = 1; i < count; i++) { successivecard += howmany[i-1] + howmany[i]; } uint64_t cycles_start = 0, cycles_final = 0; RDTSC_START(cycles_start); std::vector<vector> bitmaps = create_all_bitmaps(howmany, numbers, count); RDTSC_FINAL(cycles_final); if (bitmaps.empty()) return -1; if(verbose) printf("Loaded %d bitmaps from directory %s \n", (int)count, dirname); uint64_t totalsize = getMemUsageInBytes(); data[0] = totalsize; if(verbose) printf("Total size in bytes = %" PRIu64 " \n", totalsize); uint64_t successive_and = 0; uint64_t successive_or = 0; uint64_t total_or = 0; RDTSC_START(cycles_start); for (int i = 0; i < (int)count - 1; ++i) { vector v; std::set_intersection(bitmaps[i].begin(), bitmaps[i].end(),bitmaps[i+1].begin(), bitmaps[i+1].end(),std::back_inserter(v)); successive_and += v.size(); } RDTSC_FINAL(cycles_final); data[1] = cycles_final - cycles_start; if(verbose) printf("Successive intersections on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); for (int i = 0; i < (int)count - 1; ++i) { vector v; std::set_union(bitmaps[i].begin(), bitmaps[i].end(),bitmaps[i+1].begin(), bitmaps[i+1].end(),std::back_inserter(v)); successive_or += v.size(); } RDTSC_FINAL(cycles_final); data[2] = cycles_final - cycles_start; if(verbose) printf("Successive unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); if(count>1) { vector v; std::set_union(bitmaps[0].begin(), bitmaps[0].end(),bitmaps[1].begin(), bitmaps[1].end(),std::back_inserter(v)); for (int i = 2; i < (int)count ; ++i) { vector newv; std::set_union(v.begin(), v.end(),bitmaps[i].begin(), bitmaps[i].end(),std::back_inserter(newv)); v.swap(newv); } total_or = v.size(); } RDTSC_FINAL(cycles_final); data[3] = cycles_final - cycles_start; if(verbose) printf("Total naive unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); if(count>1) { const vector ** allofthem = new const vector* [count]; for(int i = 0 ; i < (int) count; ++i) allofthem[i] = & bitmaps[i]; vector totalorbitmap = fast_logicalor(count, allofthem); total_or = totalorbitmap.size(); delete[] allofthem; } RDTSC_FINAL(cycles_final); data[4] = cycles_final - cycles_start; if(verbose) printf("Total heap unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); uint64_t quartcount = 0; for (size_t i = 0; i < count ; ++i) { auto X1 = std::find(bitmaps[i].begin(),bitmaps[i].end(),maxvalue/4 ); if(X1 != bitmaps[i].end()) quartcount ++; auto X2 = std::find(bitmaps[i].begin(),bitmaps[i].end(),maxvalue/2 ); if(X2 != bitmaps[i].end()) quartcount ++; auto X3 = std::find(bitmaps[i].begin(),bitmaps[i].end(),3*maxvalue/4 ); if(X3 != bitmaps[i].end()) quartcount ++; } RDTSC_FINAL(cycles_final); data[5] = cycles_final - cycles_start; if(verbose) printf("Quartile queries on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); if(verbose) printf("Collected stats %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",successive_and,successive_or,total_or,quartcount); printf(" %20.2f %20.2f %20.2f %20.2f %20.2f %20.2f \n", data[0]*8.0/totalcard, data[1]*1.0/successivecard, data[2]*1.0/successivecard, data[3]*1.0/totalcard, data[4]*1.0/totalcard, data[5]*1.0/(3*count) ); for (int i = 0; i < (int)count; ++i) { free(numbers[i]); numbers[i] = NULL; // paranoid } free(howmany); free(numbers); return 0; } <commit_msg>Switching to binary search.<commit_after>#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #define __STDC_FORMAT_MACROS 1 #include <inttypes.h> #include <cstdint> #include <iostream> #include <algorithm> #include <vector> #include <list> #include <queue> #ifdef __cplusplus extern "C" { #endif #include "benchmark.h" #include "numbersfromtextfiles.h" #ifdef __cplusplus } #endif #ifdef MEMTRACKED #include "memtrackingallocator.h" #else size_t memory_usage; #endif void initializeMemUsageCounter() { memory_usage = 0; } uint64_t getMemUsageInBytes() { return memory_usage; } #ifdef MEMTRACKED typedef std::vector<uint32_t,MemoryCountingAllocator<uint32_t> > vector; #else typedef std::vector<uint32_t> vector; #endif static vector fast_logicalor(size_t n, const vector **inputs) { class StdVectorPtr { public: StdVectorPtr(const vector *p, bool o) : ptr(p), own(o) {} const vector *ptr; bool own; // whether to clean bool operator<(const StdVectorPtr &o) const { return o.ptr->size() < ptr->size(); // backward on purpose } }; if (n == 0) { return vector(); } if (n == 1) { return vector(*inputs[0]); } std::priority_queue<StdVectorPtr> pq; for (size_t i = 0; i < n; i++) { // could use emplace pq.push(StdVectorPtr(inputs[i], false)); } while (pq.size() > 2) { StdVectorPtr x1 = pq.top(); pq.pop(); StdVectorPtr x2 = pq.top(); pq.pop(); vector * buffer = new vector(); std::set_union(x1.ptr->begin(), x1.ptr->end(),x2.ptr->begin(), x2.ptr->end(),std::back_inserter(*buffer)); if (x1.own) { delete x1.ptr; } if (x2.own) { delete x2.ptr; } pq.push(StdVectorPtr(buffer, true)); } StdVectorPtr x1 = pq.top(); pq.pop(); StdVectorPtr x2 = pq.top(); pq.pop(); vector container; std::set_union(x1.ptr->begin(), x1.ptr->end(),x2.ptr->begin(), x2.ptr->end(),std::back_inserter(container)); if (x1.own) { delete x1.ptr; } if (x2.own) { delete x2.ptr; } return container; } /** * Once you have collected all the integers, build the bitmaps. */ static std::vector<vector > create_all_bitmaps(size_t *howmany, uint32_t **numbers, size_t count) { if (numbers == NULL) return std::vector<vector >(); std::vector<vector > answer(count); for (size_t i = 0; i < count; i++) { vector & bm = answer[i]; uint32_t * mynumbers = numbers[i]; for(size_t j = 0; j < howmany[i] ; ++j) { bm.push_back(mynumbers[j]); } bm.shrink_to_fit(); } return answer; } static void printusage(char *command) { printf( " Try %s directory \n where directory could be " "benchmarks/realdata/census1881\n", command); ; printf("the -v flag turns on verbose mode"); } int main(int argc, char **argv) { int c; const char *extension = ".txt"; bool verbose = false; uint64_t data[6]; initializeMemUsageCounter(); while ((c = getopt(argc, argv, "ve:h")) != -1) switch (c) { case 'e': extension = optarg; break; case 'v': verbose = true; break; case 'h': printusage(argv[0]); return 0; default: abort(); } if (optind >= argc) { printusage(argv[0]); return -1; } char *dirname = argv[optind]; size_t count; size_t *howmany = NULL; uint32_t **numbers = read_all_integer_files(dirname, extension, &howmany, &count); if (numbers == NULL) { printf( "I could not find or load any data file with extension %s in " "directory %s.\n", extension, dirname); return -1; } uint32_t maxvalue = 0; for (size_t i = 0; i < count; i++) { if( howmany[i] > 0 ) { if(maxvalue < numbers[i][howmany[i]-1]) { maxvalue = numbers[i][howmany[i]-1]; } } } uint64_t totalcard = 0; for (size_t i = 0; i < count; i++) { totalcard += howmany[i]; } uint64_t successivecard = 0; for (size_t i = 1; i < count; i++) { successivecard += howmany[i-1] + howmany[i]; } uint64_t cycles_start = 0, cycles_final = 0; RDTSC_START(cycles_start); std::vector<vector> bitmaps = create_all_bitmaps(howmany, numbers, count); RDTSC_FINAL(cycles_final); if (bitmaps.empty()) return -1; if(verbose) printf("Loaded %d bitmaps from directory %s \n", (int)count, dirname); uint64_t totalsize = getMemUsageInBytes(); data[0] = totalsize; if(verbose) printf("Total size in bytes = %" PRIu64 " \n", totalsize); uint64_t successive_and = 0; uint64_t successive_or = 0; uint64_t total_or = 0; RDTSC_START(cycles_start); for (int i = 0; i < (int)count - 1; ++i) { vector v; std::set_intersection(bitmaps[i].begin(), bitmaps[i].end(),bitmaps[i+1].begin(), bitmaps[i+1].end(),std::back_inserter(v)); successive_and += v.size(); } RDTSC_FINAL(cycles_final); data[1] = cycles_final - cycles_start; if(verbose) printf("Successive intersections on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); for (int i = 0; i < (int)count - 1; ++i) { vector v; std::set_union(bitmaps[i].begin(), bitmaps[i].end(),bitmaps[i+1].begin(), bitmaps[i+1].end(),std::back_inserter(v)); successive_or += v.size(); } RDTSC_FINAL(cycles_final); data[2] = cycles_final - cycles_start; if(verbose) printf("Successive unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); if(count>1) { vector v; std::set_union(bitmaps[0].begin(), bitmaps[0].end(),bitmaps[1].begin(), bitmaps[1].end(),std::back_inserter(v)); for (int i = 2; i < (int)count ; ++i) { vector newv; std::set_union(v.begin(), v.end(),bitmaps[i].begin(), bitmaps[i].end(),std::back_inserter(newv)); v.swap(newv); } total_or = v.size(); } RDTSC_FINAL(cycles_final); data[3] = cycles_final - cycles_start; if(verbose) printf("Total naive unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); if(count>1) { const vector ** allofthem = new const vector* [count]; for(int i = 0 ; i < (int) count; ++i) allofthem[i] = & bitmaps[i]; vector totalorbitmap = fast_logicalor(count, allofthem); total_or = totalorbitmap.size(); delete[] allofthem; } RDTSC_FINAL(cycles_final); data[4] = cycles_final - cycles_start; if(verbose) printf("Total heap unions on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); RDTSC_START(cycles_start); uint64_t quartcount = 0; for (size_t i = 0; i < count ; ++i) { if ( std::binary_search(bitmaps[i].begin(),bitmaps[i].end(),maxvalue/4 ) ) quartcount ++; if ( std::binary_search(bitmaps[i].begin(),bitmaps[i].end(),maxvalue/2 ) ) quartcount ++; if ( std::binary_search(bitmaps[i].begin(),bitmaps[i].end(),3*maxvalue/4 ) ) quartcount ++; } RDTSC_FINAL(cycles_final); data[5] = cycles_final - cycles_start; if(verbose) printf("Quartile queries on %zu bitmaps took %" PRIu64 " cycles\n", count, cycles_final - cycles_start); if(verbose) printf("Collected stats %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",successive_and,successive_or,total_or,quartcount); printf(" %20.2f %20.2f %20.2f %20.2f %20.2f %20.2f \n", data[0]*8.0/totalcard, data[1]*1.0/successivecard, data[2]*1.0/successivecard, data[3]*1.0/totalcard, data[4]*1.0/totalcard, data[5]*1.0/(3*count) ); for (int i = 0; i < (int)count; ++i) { free(numbers[i]); numbers[i] = NULL; // paranoid } free(howmany); free(numbers); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: defltuno.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: sab $ $Date: 2001-03-29 15:38:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #include <svtools/smplhint.hxx> #include <svtools/itemprop.hxx> #include <svx/unomid.hxx> #include <com/sun/star/beans/PropertyAttribute.hpp> #include "scitems.hxx" #include "defltuno.hxx" #include "miscuno.hxx" #include "docsh.hxx" #include "docpool.hxx" #include "unoguard.hxx" #include "unonames.hxx" #include "docoptio.hxx" using namespace ::com::sun::star; //------------------------------------------------------------------------ const SfxItemPropertyMap* lcl_GetDocDefaultsMap() { static SfxItemPropertyMap aDocDefaultsMap_Impl[] = { {MAP_CHAR_LEN(SC_UNONAME_CFCHARS), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNO_CJK_CFCHARS), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNO_CTL_CFCHARS), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNONAME_CFFAMIL), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNO_CJK_CFFAMIL), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNO_CTL_CFFAMIL), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNONAME_CFNAME), ATTR_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNO_CJK_CFNAME), ATTR_CJK_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNO_CTL_CFNAME), ATTR_CTL_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNONAME_CFPITCH), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNO_CJK_CFPITCH), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNO_CTL_CFPITCH), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNONAME_CFSTYLE), ATTR_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_CJK_CFSTYLE), ATTR_CJK_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_CTL_CFSTYLE), ATTR_CTL_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_STANDARDDEC), 0, &getCppuType((sal_Int16*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNO_TABSTOPDIS), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {0,0,0,0} }; return aDocDefaultsMap_Impl; } //------------------------------------------------------------------------ SC_SIMPLE_SERVICE_INFO( ScDocDefaultsObj, "ScDocDefaultsObj", "com.sun.star.sheet.Defaults" ) //------------------------------------------------------------------------ ScDocDefaultsObj::ScDocDefaultsObj(ScDocShell* pDocSh) : pDocShell( pDocSh ) { pDocShell->GetDocument()->AddUnoObject(*this); } ScDocDefaultsObj::~ScDocDefaultsObj() { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScDocDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // document gone } } void ScDocDefaultsObj::ItemsChanged() { if (pDocShell) { //! if not in XML import, adjust row heights pDocShell->PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID ); } } // XPropertySet uno::Reference<beans::XPropertySetInfo> SAL_CALL ScDocDefaultsObj::getPropertySetInfo() throw(uno::RuntimeException) { ScUnoGuard aGuard; static uno::Reference<beans::XPropertySetInfo> aRef = new SfxItemPropertySetInfo( lcl_GetDocDefaultsMap() ); return aRef; } void SAL_CALL ScDocDefaultsObj::setPropertyValue( const rtl::OUString& aPropertyName, const uno::Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if(!pMap->nWID) { if(aPropertyName.compareToAscii(SC_UNO_STANDARDDEC) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { ScDocOptions aDocOpt(pDoc->GetDocOptions()); sal_Int16 nValue; if (aValue >>= nValue) { aDocOpt.SetStdPrecision(static_cast<sal_uInt8> (nValue)); pDoc->SetDocOptions(aDocOpt); } } else throw uno::RuntimeException(); } else if (aPropertyName.compareToAscii(SC_UNO_TABSTOPDIS) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { ScDocOptions aDocOpt(pDoc->GetDocOptions()); sal_Int32 nValue; if (aValue >>= nValue) { aDocOpt.SetTabDistance(static_cast<sal_uInt8> (nValue)); pDoc->SetDocOptions(aDocOpt); } } else throw uno::RuntimeException(); } } else { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); SfxPoolItem* pNewItem = pPool->GetDefaultItem(pMap->nWID).Clone(); if( !pNewItem->PutValue( aValue, pMap->nMemberId ) ) throw lang::IllegalArgumentException(); pPool->SetPoolDefaultItem( *pNewItem ); delete pNewItem; // copied in SetPoolDefaultItem ItemsChanged(); } } uno::Any SAL_CALL ScDocDefaultsObj::getPropertyValue( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { // use pool default if set ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); uno::Any aRet; const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if (!pMap->nWID) { if(aPropertyName.compareToAscii(SC_UNO_STANDARDDEC) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { const ScDocOptions& aDocOpt = pDoc->GetDocOptions(); aRet <<= static_cast<sal_Int16> (aDocOpt.GetStdPrecision()); } else throw uno::RuntimeException(); } else if (aPropertyName.compareToAscii(SC_UNO_TABSTOPDIS) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { const ScDocOptions& aDocOpt = pDoc->GetDocOptions(); aRet <<= static_cast<sal_Int32> (aDocOpt.GetTabDistance()); } else throw uno::RuntimeException(); } } else { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); const SfxPoolItem& rItem = pPool->GetDefaultItem( pMap->nWID ); rItem.QueryValue( aRet, pMap->nMemberId ); } return aRet; } SC_IMPL_DUMMY_PROPERTY_LISTENER( ScDocDefaultsObj ) // XPropertyState beans::PropertyState SAL_CALL ScDocDefaultsObj::getPropertyState( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; USHORT nWID = pMap->nWID; if ( nWID == ATTR_FONT || nWID == ATTR_CJK_FONT || nWID == ATTR_CTL_FONT || !nWID ) { // static default for font is system-dependent, // so font default is always treated as "direct value". eRet = beans::PropertyState_DIRECT_VALUE; } else { // check if pool default is set ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); if ( pPool->GetPoolDefaultItem( nWID ) != NULL ) eRet = beans::PropertyState_DIRECT_VALUE; } return eRet; } uno::Sequence<beans::PropertyState> SAL_CALL ScDocDefaultsObj::getPropertyStates( const uno::Sequence<rtl::OUString>& aPropertyNames ) throw(beans::UnknownPropertyException, uno::RuntimeException) { // the simple way: call getPropertyState ScUnoGuard aGuard; const rtl::OUString* pNames = aPropertyNames.getConstArray(); uno::Sequence<beans::PropertyState> aRet(aPropertyNames.getLength()); beans::PropertyState* pStates = aRet.getArray(); for(sal_Int32 i = 0; i < aPropertyNames.getLength(); i++) pStates[i] = getPropertyState(pNames[i]); return aRet; } void SAL_CALL ScDocDefaultsObj::setPropertyToDefault( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if (pMap->nWID) { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); pPool->ResetPoolDefaultItem( pMap->nWID ); ItemsChanged(); } } uno::Any SAL_CALL ScDocDefaultsObj::getPropertyDefault( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { // always use static default ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); uno::Any aRet; if (pMap->nWID) { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); const SfxPoolItem* pItem = pPool->GetItem( pMap->nWID, SFX_ITEMS_STATICDEFAULT ); if (pItem) pItem->QueryValue( aRet, pMap->nMemberId ); } return aRet; } <commit_msg>#80363#; have to convert Twips and Hmm; cast with a sal_uInt16 and not a sal_uInt8<commit_after>/************************************************************************* * * $RCSfile: defltuno.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: sab $ $Date: 2001-04-12 11:55:13 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop #include <svtools/smplhint.hxx> #include <svtools/itemprop.hxx> #include <svx/unomid.hxx> #include <com/sun/star/beans/PropertyAttribute.hpp> #include "scitems.hxx" #include "defltuno.hxx" #include "miscuno.hxx" #include "docsh.hxx" #include "docpool.hxx" #include "unoguard.hxx" #include "unonames.hxx" #include "docoptio.hxx" #ifndef _TOOLS_SOLMATH_HXX #include <tools/solmath.hxx> #endif using namespace ::com::sun::star; //------------------------------------------------------------------------ const SfxItemPropertyMap* lcl_GetDocDefaultsMap() { static SfxItemPropertyMap aDocDefaultsMap_Impl[] = { {MAP_CHAR_LEN(SC_UNONAME_CFCHARS), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNO_CJK_CFCHARS), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNO_CTL_CFCHARS), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_CHAR_SET }, {MAP_CHAR_LEN(SC_UNONAME_CFFAMIL), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNO_CJK_CFFAMIL), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNO_CTL_CFFAMIL), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_FAMILY }, {MAP_CHAR_LEN(SC_UNONAME_CFNAME), ATTR_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNO_CJK_CFNAME), ATTR_CJK_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNO_CTL_CFNAME), ATTR_CTL_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_FAMILY_NAME }, {MAP_CHAR_LEN(SC_UNONAME_CFPITCH), ATTR_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNO_CJK_CFPITCH), ATTR_CJK_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNO_CTL_CFPITCH), ATTR_CTL_FONT, &getCppuType((sal_Int16*)0), 0, MID_FONT_PITCH }, {MAP_CHAR_LEN(SC_UNONAME_CFSTYLE), ATTR_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_CJK_CFSTYLE), ATTR_CJK_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_CTL_CFSTYLE), ATTR_CTL_FONT, &getCppuType((rtl::OUString*)0), 0, MID_FONT_STYLE_NAME }, {MAP_CHAR_LEN(SC_UNO_STANDARDDEC), 0, &getCppuType((sal_Int16*)0), 0, 0 }, {MAP_CHAR_LEN(SC_UNO_TABSTOPDIS), 0, &getCppuType((sal_Int32*)0), 0, 0 }, {0,0,0,0} }; return aDocDefaultsMap_Impl; } inline long TwipsToHMM(long nTwips) { return (nTwips * 127 + 36) / 72; } inline long HMMToTwips(long nHMM) { return (nHMM * 72 + 63) / 127; } inline long TwipsToEvenHMM(long nTwips) { return ( (nTwips * 127 + 72) / 144 ) * 2; } //------------------------------------------------------------------------ SC_SIMPLE_SERVICE_INFO( ScDocDefaultsObj, "ScDocDefaultsObj", "com.sun.star.sheet.Defaults" ) //------------------------------------------------------------------------ ScDocDefaultsObj::ScDocDefaultsObj(ScDocShell* pDocSh) : pDocShell( pDocSh ) { pDocShell->GetDocument()->AddUnoObject(*this); } ScDocDefaultsObj::~ScDocDefaultsObj() { if (pDocShell) pDocShell->GetDocument()->RemoveUnoObject(*this); } void ScDocDefaultsObj::Notify( SfxBroadcaster& rBC, const SfxHint& rHint ) { if ( rHint.ISA( SfxSimpleHint ) && ((const SfxSimpleHint&)rHint).GetId() == SFX_HINT_DYING ) { pDocShell = NULL; // document gone } } void ScDocDefaultsObj::ItemsChanged() { if (pDocShell) { //! if not in XML import, adjust row heights pDocShell->PostPaint( 0,0,0, MAXCOL,MAXROW,MAXTAB, PAINT_GRID ); } } // XPropertySet uno::Reference<beans::XPropertySetInfo> SAL_CALL ScDocDefaultsObj::getPropertySetInfo() throw(uno::RuntimeException) { ScUnoGuard aGuard; static uno::Reference<beans::XPropertySetInfo> aRef = new SfxItemPropertySetInfo( lcl_GetDocDefaultsMap() ); return aRef; } void SAL_CALL ScDocDefaultsObj::setPropertyValue( const rtl::OUString& aPropertyName, const uno::Any& aValue ) throw(beans::UnknownPropertyException, beans::PropertyVetoException, lang::IllegalArgumentException, lang::WrappedTargetException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if(!pMap->nWID) { if(aPropertyName.compareToAscii(SC_UNO_STANDARDDEC) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { ScDocOptions aDocOpt(pDoc->GetDocOptions()); sal_Int16 nValue; if (aValue >>= nValue) { aDocOpt.SetStdPrecision(static_cast<sal_uInt8> (nValue)); pDoc->SetDocOptions(aDocOpt); } } else throw uno::RuntimeException(); } else if (aPropertyName.compareToAscii(SC_UNO_TABSTOPDIS) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { ScDocOptions aDocOpt(pDoc->GetDocOptions()); sal_Int32 nValue; if (aValue >>= nValue) { aDocOpt.SetTabDistance(static_cast<sal_uInt16>(HMMToTwips(nValue))); pDoc->SetDocOptions(aDocOpt); } } else throw uno::RuntimeException(); } } else { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); SfxPoolItem* pNewItem = pPool->GetDefaultItem(pMap->nWID).Clone(); if( !pNewItem->PutValue( aValue, pMap->nMemberId ) ) throw lang::IllegalArgumentException(); pPool->SetPoolDefaultItem( *pNewItem ); delete pNewItem; // copied in SetPoolDefaultItem ItemsChanged(); } } uno::Any SAL_CALL ScDocDefaultsObj::getPropertyValue( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { // use pool default if set ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); uno::Any aRet; const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if (!pMap->nWID) { if(aPropertyName.compareToAscii(SC_UNO_STANDARDDEC) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { const ScDocOptions& aDocOpt = pDoc->GetDocOptions(); aRet <<= static_cast<sal_Int16> (aDocOpt.GetStdPrecision()); } else throw uno::RuntimeException(); } else if (aPropertyName.compareToAscii(SC_UNO_TABSTOPDIS) == 0) { ScDocument* pDoc = pDocShell->GetDocument(); if (pDoc) { const ScDocOptions& aDocOpt = pDoc->GetDocOptions(); sal_Int32 nValue (TwipsToEvenHMM(aDocOpt.GetTabDistance())); aRet <<= nValue; } else throw uno::RuntimeException(); } } else { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); const SfxPoolItem& rItem = pPool->GetDefaultItem( pMap->nWID ); rItem.QueryValue( aRet, pMap->nMemberId ); } return aRet; } SC_IMPL_DUMMY_PROPERTY_LISTENER( ScDocDefaultsObj ) // XPropertyState beans::PropertyState SAL_CALL ScDocDefaultsObj::getPropertyState( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); beans::PropertyState eRet = beans::PropertyState_DEFAULT_VALUE; USHORT nWID = pMap->nWID; if ( nWID == ATTR_FONT || nWID == ATTR_CJK_FONT || nWID == ATTR_CTL_FONT || !nWID ) { // static default for font is system-dependent, // so font default is always treated as "direct value". eRet = beans::PropertyState_DIRECT_VALUE; } else { // check if pool default is set ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); if ( pPool->GetPoolDefaultItem( nWID ) != NULL ) eRet = beans::PropertyState_DIRECT_VALUE; } return eRet; } uno::Sequence<beans::PropertyState> SAL_CALL ScDocDefaultsObj::getPropertyStates( const uno::Sequence<rtl::OUString>& aPropertyNames ) throw(beans::UnknownPropertyException, uno::RuntimeException) { // the simple way: call getPropertyState ScUnoGuard aGuard; const rtl::OUString* pNames = aPropertyNames.getConstArray(); uno::Sequence<beans::PropertyState> aRet(aPropertyNames.getLength()); beans::PropertyState* pStates = aRet.getArray(); for(sal_Int32 i = 0; i < aPropertyNames.getLength(); i++) pStates[i] = getPropertyState(pNames[i]); return aRet; } void SAL_CALL ScDocDefaultsObj::setPropertyToDefault( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, uno::RuntimeException) { ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); if (pMap->nWID) { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); pPool->ResetPoolDefaultItem( pMap->nWID ); ItemsChanged(); } } uno::Any SAL_CALL ScDocDefaultsObj::getPropertyDefault( const rtl::OUString& aPropertyName ) throw(beans::UnknownPropertyException, lang::WrappedTargetException, uno::RuntimeException) { // always use static default ScUnoGuard aGuard; if ( !pDocShell ) throw uno::RuntimeException(); const SfxItemPropertyMap* pMap = SfxItemPropertyMap::GetByName( lcl_GetDocDefaultsMap(), aPropertyName ); if ( !pMap ) throw beans::UnknownPropertyException(); uno::Any aRet; if (pMap->nWID) { ScDocumentPool* pPool = pDocShell->GetDocument()->GetPool(); const SfxPoolItem* pItem = pPool->GetItem( pMap->nWID, SFX_ITEMS_STATICDEFAULT ); if (pItem) pItem->QueryValue( aRet, pMap->nMemberId ); } return aRet; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "cdev_platform.hpp" #include <string> #include <map> #include "vfile.h" #include "../CDev.hpp" #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "DevMgr.hpp" using namespace std; using namespace DriverFramework; const cdev::px4_file_operations_t cdev::CDev::fops = {}; pthread_mutex_t devmutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; px4_sem_t lockstep_sem; bool sim_lockstep = false; volatile bool sim_delay = false; #define PX4_MAX_FD 350 static map<string, void *> devmap; static cdev::file_t filemap[PX4_MAX_FD] = {}; extern "C" { int px4_errno; static cdev::CDev *getDev(const char *path) { PX4_DEBUG("CDev::getDev"); pthread_mutex_lock(&devmutex); auto item = devmap.find(path); if (item != devmap.end()) { pthread_mutex_unlock(&devmutex); return (cdev::CDev *)item->second; } pthread_mutex_unlock(&devmutex); return nullptr; } static cdev::CDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd].vdev); cdev::CDev *dev; if (valid) { dev = (cdev::CDev *)(filemap[fd].vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int register_driver(const char *name, const cdev::px4_file_operations_t *fops, cdev::mode_t mode, void *data) { PX4_DEBUG("CDev::register_driver %s", name); int ret = 0; if (name == nullptr || data == nullptr) { return -EINVAL; } pthread_mutex_lock(&devmutex); // Make sure the device does not already exist auto item = devmap.find(name); if (item != devmap.end()) { pthread_mutex_unlock(&devmutex); return -EEXIST; } devmap[name] = (void *)data; PX4_DEBUG("Registered DEV %s", name); pthread_mutex_unlock(&devmutex); return ret; } int unregister_driver(const char *name) { PX4_DEBUG("CDev::unregister_driver %s", name); int ret = -EINVAL; if (name == nullptr) { return -EINVAL; } pthread_mutex_lock(&devmutex); if (devmap.erase(name) > 0) { PX4_DEBUG("Unregistered DEV %s", name); ret = 0; } pthread_mutex_unlock(&devmutex); return ret; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); cdev::CDev *dev = getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & PX4_F_WRONLY) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, int); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = cdev::VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i].vdev == nullptr) { filemap[i] = cdev::file_t(flags, dev); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(&filemap[i]); } else { const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; PX4_WARN("%s: exceeded maximum number of file descriptors, accessing %s", thread_name, path); #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } PX4_BACKTRACE(); #endif ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { return -1; } PX4_DEBUG("px4_open fd = %d", i); return i; } int px4_close(int fd) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(&filemap[fd]); filemap[fd].vdev = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(&filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(&filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; cdev::CDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(&filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { if (nfds == 0) { PX4_WARN("px4_poll with no fds"); return -1; } px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } #endif while (sim_delay) { px4_usleep(100); } PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // sem use case is a signal px4_sem_setprotocol(&sem, SEM_PRIO_NONE); // Go through all fds and check them for a pollable state bool fd_pollable = false; for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = nullptr; cdev::CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(setup) %d", thread_name, fds[i].fd); ret = dev->poll(&filemap[fds[i].fd], &fds[i], true); if (ret < 0) { PX4_WARN("%s: px4_poll() error: %s", thread_name, strerror(errno)); break; } if (ret >= 0) { fd_pollable = true; } } } // If any FD can be polled, lock the semaphore and // check for new data if (fd_pollable) { if (timeout > 0) { // Get the current time struct timespec ts; // Note, we can't actually use CLOCK_MONOTONIC on macOS // but that's hidden and implemented in px4_clock_gettime. px4_clock_gettime(CLOCK_MONOTONIC, &ts); // Calculate an absolute time in the future const unsigned billion = (1000 * 1000 * 1000); uint64_t nsecs = ts.tv_nsec + (timeout * 1000 * 1000); ts.tv_sec += nsecs / billion; nsecs -= (nsecs / billion) * billion; ts.tv_nsec = nsecs; ret = px4_sem_timedwait(&sem, &ts); if (ret && errno != ETIMEDOUT) { PX4_WARN("%s: px4_poll() sem error: %s", thread_name, strerror(errno)); } } else if (timeout < 0) { px4_sem_wait(&sem); } // We have waited now (or not, depending on timeout), // go through all fds and count how many have data for (i = 0; i < nfds; ++i) { cdev::CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(teardown) %d", thread_name, fds[i].fd); ret = dev->poll(&filemap[fds[i].fd], &fds[i], false); if (ret < 0) { PX4_WARN("%s: px4_poll() 2nd poll fail", thread_name); break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); // Return the positive count if present, // return the negative error number if failed return (count) ? count : ret; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } cdev::CDev *dev = getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { int i = 0; PX4_INFO("PX4 Devices:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/dev/", 5) == 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); PX4_INFO("DF Devices:"); const char *dev_path; unsigned int index = 0; i = 0; do { // Each look increments index and returns -1 if end reached i = DevMgr::getNextDeviceName(index, &dev_path); if (i == 0) { PX4_INFO(" %s", dev_path); } } while (i == 0); } void px4_show_topics() { PX4_INFO("Devices:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/obj/", 5) == 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); } void px4_show_files() { PX4_INFO("Files:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/obj/", 5) != 0 && strncmp(dev.first.c_str(), "/dev/", 5) != 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); } } // extern "C" <commit_msg>cdev_platform: remove unused code (sim_delay)<commit_after>/**************************************************************************** * * Copyright (c) 2015 Mark Charlebois. All rights reserved. * Copyright (c) 2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "cdev_platform.hpp" #include <string> #include <map> #include "vfile.h" #include "../CDev.hpp" #include <px4_log.h> #include <px4_posix.h> #include <px4_time.h> #include "DevMgr.hpp" using namespace std; using namespace DriverFramework; const cdev::px4_file_operations_t cdev::CDev::fops = {}; pthread_mutex_t devmutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t filemutex = PTHREAD_MUTEX_INITIALIZER; #define PX4_MAX_FD 350 static map<string, void *> devmap; static cdev::file_t filemap[PX4_MAX_FD] = {}; extern "C" { int px4_errno; static cdev::CDev *getDev(const char *path) { PX4_DEBUG("CDev::getDev"); pthread_mutex_lock(&devmutex); auto item = devmap.find(path); if (item != devmap.end()) { pthread_mutex_unlock(&devmutex); return (cdev::CDev *)item->second; } pthread_mutex_unlock(&devmutex); return nullptr; } static cdev::CDev *get_vdev(int fd) { pthread_mutex_lock(&filemutex); bool valid = (fd < PX4_MAX_FD && fd >= 0 && filemap[fd].vdev); cdev::CDev *dev; if (valid) { dev = (cdev::CDev *)(filemap[fd].vdev); } else { dev = nullptr; } pthread_mutex_unlock(&filemutex); return dev; } int register_driver(const char *name, const cdev::px4_file_operations_t *fops, cdev::mode_t mode, void *data) { PX4_DEBUG("CDev::register_driver %s", name); int ret = 0; if (name == nullptr || data == nullptr) { return -EINVAL; } pthread_mutex_lock(&devmutex); // Make sure the device does not already exist auto item = devmap.find(name); if (item != devmap.end()) { pthread_mutex_unlock(&devmutex); return -EEXIST; } devmap[name] = (void *)data; PX4_DEBUG("Registered DEV %s", name); pthread_mutex_unlock(&devmutex); return ret; } int unregister_driver(const char *name) { PX4_DEBUG("CDev::unregister_driver %s", name); int ret = -EINVAL; if (name == nullptr) { return -EINVAL; } pthread_mutex_lock(&devmutex); if (devmap.erase(name) > 0) { PX4_DEBUG("Unregistered DEV %s", name); ret = 0; } pthread_mutex_unlock(&devmutex); return ret; } int px4_open(const char *path, int flags, ...) { PX4_DEBUG("px4_open"); cdev::CDev *dev = getDev(path); int ret = 0; int i; mode_t mode; if (!dev && (flags & PX4_F_WRONLY) != 0 && strncmp(path, "/obj/", 5) != 0 && strncmp(path, "/dev/", 5) != 0) { va_list p; va_start(p, flags); mode = va_arg(p, int); va_end(p); // Create the file PX4_DEBUG("Creating virtual file %s", path); dev = cdev::VFile::createFile(path, mode); } if (dev) { pthread_mutex_lock(&filemutex); for (i = 0; i < PX4_MAX_FD; ++i) { if (filemap[i].vdev == nullptr) { filemap[i] = cdev::file_t(flags, dev); break; } } pthread_mutex_unlock(&filemutex); if (i < PX4_MAX_FD) { ret = dev->open(&filemap[i]); } else { const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; PX4_WARN("%s: exceeded maximum number of file descriptors, accessing %s", thread_name, path); #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } PX4_BACKTRACE(); #endif ret = -ENOENT; } } else { ret = -EINVAL; } if (ret < 0) { return -1; } PX4_DEBUG("px4_open fd = %d", i); return i; } int px4_close(int fd) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { pthread_mutex_lock(&filemutex); ret = dev->close(&filemap[fd]); filemap[fd].vdev = nullptr; pthread_mutex_unlock(&filemutex); PX4_DEBUG("px4_close fd = %d", fd); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_read(int fd, void *buffer, size_t buflen) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_read fd = %d", fd); ret = dev->read(&filemap[fd], (char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } ssize_t px4_write(int fd, const void *buffer, size_t buflen) { int ret; cdev::CDev *dev = get_vdev(fd); if (dev) { PX4_DEBUG("px4_write fd = %d", fd); ret = dev->write(&filemap[fd], (const char *)buffer, buflen); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; ret = PX4_ERROR; } return ret; } int px4_ioctl(int fd, int cmd, unsigned long arg) { PX4_DEBUG("px4_ioctl fd = %d", fd); int ret = 0; cdev::CDev *dev = get_vdev(fd); if (dev) { ret = dev->ioctl(&filemap[fd], cmd, arg); } else { ret = -EINVAL; } if (ret < 0) { px4_errno = -ret; } return ret; } int px4_poll(px4_pollfd_struct_t *fds, nfds_t nfds, int timeout) { if (nfds == 0) { PX4_WARN("px4_poll with no fds"); return -1; } px4_sem_t sem; int count = 0; int ret = -1; unsigned int i; const unsigned NAMELEN = 32; char thread_name[NAMELEN] = {}; #ifndef __PX4_QURT int nret = pthread_getname_np(pthread_self(), thread_name, NAMELEN); if (nret || thread_name[0] == 0) { PX4_WARN("failed getting thread name"); } #endif PX4_DEBUG("Called px4_poll timeout = %d", timeout); px4_sem_init(&sem, 0, 0); // sem use case is a signal px4_sem_setprotocol(&sem, SEM_PRIO_NONE); // Go through all fds and check them for a pollable state bool fd_pollable = false; for (i = 0; i < nfds; ++i) { fds[i].sem = &sem; fds[i].revents = 0; fds[i].priv = nullptr; cdev::CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(setup) %d", thread_name, fds[i].fd); ret = dev->poll(&filemap[fds[i].fd], &fds[i], true); if (ret < 0) { PX4_WARN("%s: px4_poll() error: %s", thread_name, strerror(errno)); break; } if (ret >= 0) { fd_pollable = true; } } } // If any FD can be polled, lock the semaphore and // check for new data if (fd_pollable) { if (timeout > 0) { // Get the current time struct timespec ts; // Note, we can't actually use CLOCK_MONOTONIC on macOS // but that's hidden and implemented in px4_clock_gettime. px4_clock_gettime(CLOCK_MONOTONIC, &ts); // Calculate an absolute time in the future const unsigned billion = (1000 * 1000 * 1000); uint64_t nsecs = ts.tv_nsec + (timeout * 1000 * 1000); ts.tv_sec += nsecs / billion; nsecs -= (nsecs / billion) * billion; ts.tv_nsec = nsecs; ret = px4_sem_timedwait(&sem, &ts); if (ret && errno != ETIMEDOUT) { PX4_WARN("%s: px4_poll() sem error: %s", thread_name, strerror(errno)); } } else if (timeout < 0) { px4_sem_wait(&sem); } // We have waited now (or not, depending on timeout), // go through all fds and count how many have data for (i = 0; i < nfds; ++i) { cdev::CDev *dev = get_vdev(fds[i].fd); // If fd is valid if (dev) { PX4_DEBUG("%s: px4_poll: CDev->poll(teardown) %d", thread_name, fds[i].fd); ret = dev->poll(&filemap[fds[i].fd], &fds[i], false); if (ret < 0) { PX4_WARN("%s: px4_poll() 2nd poll fail", thread_name); break; } if (fds[i].revents) { count += 1; } } } } px4_sem_destroy(&sem); // Return the positive count if present, // return the negative error number if failed return (count) ? count : ret; } int px4_fsync(int fd) { return 0; } int px4_access(const char *pathname, int mode) { if (mode != F_OK) { errno = EINVAL; return -1; } cdev::CDev *dev = getDev(pathname); return (dev != nullptr) ? 0 : -1; } void px4_show_devices() { int i = 0; PX4_INFO("PX4 Devices:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/dev/", 5) == 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); PX4_INFO("DF Devices:"); const char *dev_path; unsigned int index = 0; i = 0; do { // Each look increments index and returns -1 if end reached i = DevMgr::getNextDeviceName(index, &dev_path); if (i == 0) { PX4_INFO(" %s", dev_path); } } while (i == 0); } void px4_show_topics() { PX4_INFO("Devices:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/obj/", 5) == 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); } void px4_show_files() { PX4_INFO("Files:"); pthread_mutex_lock(&devmutex); for (const auto &dev : devmap) { if (strncmp(dev.first.c_str(), "/obj/", 5) != 0 && strncmp(dev.first.c_str(), "/dev/", 5) != 0) { PX4_INFO(" %s", dev.first.c_str()); } } pthread_mutex_unlock(&devmutex); } } // extern "C" <|endoftext|>
<commit_before>#include "scanner/engine/python_kernel.h" #include "scanner/util/tinyformat.h" #include "scanner/util/util.h" #include <pybind11/eval.h> #include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace scanner { namespace py = pybind11; using namespace pybind11::literals; void gen_random(char* s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } PythonKernel::PythonKernel(const KernelConfig &config, const std::string &op_name, const std::string &kernel_code, const std::string &pickled_config, const bool can_batch, const bool can_stencil) : StenciledBatchedKernel(config), config_(config), device_(config.devices[0]), op_name_(op_name) { py::gil_scoped_acquire acquire; can_batch_ = can_batch; can_stencil_ = can_stencil; // Remove uuid from op_name op_name_ = op_name_.substr(0, op_name_.find(":")); char rand[256]; gen_random(rand, 256); kernel_name_ = tfm::format("%s_kernel_%s", op_name_, rand); std::string kernel_ns_name_ = tfm::format("ns_%s", op_name_); try { py::module main = py::module::import("__main__"); py::object scope = main.attr("__dict__"); // FIXME((apoms): for some reason, serializing the config object in release // mode on MacOS fails.... main.attr(kernel_ns_name_.c_str()) = py::dict( "kernel_code"_a=py::bytes(kernel_code), "user_config_str"_a=py::bytes(pickled_config), "config"_a=config); std::string pycode = tfm::format(R"( def %s_fn(): import pickle import cloudpickle import traceback from scannerpy import Config, DeviceType, DeviceHandle, KernelConfig from scannerpy.protobuf_generator import ProtobufGenerator n = %s user_config = pickle.loads(n['user_config_str']) protobufs = ProtobufGenerator(user_config) kernel_config = KernelConfig(n['config']) kernel_config.protobufs = protobufs return cloudpickle.loads(n['kernel_code'])(kernel_config) %s = %s_fn() )", kernel_name_, kernel_ns_name_, kernel_name_, kernel_name_); py::exec(pycode, scope); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } PythonKernel::~PythonKernel() { py::gil_scoped_acquire acquire; try { py::module::import("__main__").attr(kernel_name_.c_str()).attr("close")(); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::reset() { py::gil_scoped_acquire acquire; try { py::module::import("__main__").attr(kernel_name_.c_str()).attr("reset")(); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::new_stream(const std::vector<u8> &args) { py::gil_scoped_acquire acquire; try { py::module main = py::module::import("__main__"); py::object kernel = main.attr(kernel_name_.c_str()); main.attr("args_str") = py::bytes(reinterpret_cast<const char *>(args.data()), args.size()); std::string pycode = tfm::format(R"( import pickle if len(args_str) == 0: args = None else: args = pickle.loads(args_str) %s.new_stream(args))", kernel_name_); py::exec(pycode.c_str(), main.attr("__dict__")); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::execute(const StenciledBatchedElements &input_columns, BatchedElements &output_columns) { i32 input_count = (i32)input_columns[0].size(); py::gil_scoped_acquire acquire; try { py::object kernel = py::module::import("__main__").attr(kernel_name_.c_str()); std::vector<std::vector<std::vector<py::object>>> batched_cols; for (i32 j = 0; j < input_columns.size(); ++j) { batched_cols.emplace_back(); } for (i32 j = 0; j < input_columns.size(); ++j) { std::vector<std::vector<py::object>> &batched_col = batched_cols[j]; if (config_.input_column_types[j] == proto::ColumnType::Video) { for (i32 i = 0; i < input_count; ++i) { batched_col.emplace_back(); std::vector<py::object> &col = batched_col.back(); for (i32 k = 0; k < input_columns[j][i].size(); ++k) { const Frame *frame = input_columns[j][i][k].as_const_frame(); std::string dtype; u32 dtype_size; if (frame->type == FrameType::U8) { dtype = py::format_descriptor<u8>::format(); dtype_size = 1; } else if (frame->type == FrameType::F32) { dtype = py::format_descriptor<f32>::format(); dtype_size = 4; } else if (frame->type == FrameType::F64) { dtype = py::format_descriptor<f64>::format(); dtype_size = 8; } py::buffer_info buffer; if (frame->channels() == 3) { buffer = py::buffer_info( frame->data, (size_t)dtype_size, dtype, 3, {(long int)frame->height(), (long int)frame->width(), (long int)frame->channels()}, {(long int)frame->width() * frame->channels() * dtype_size, (long int)frame->channels() * dtype_size, (long int)dtype_size}); } else { buffer = py::buffer_info( frame->data, (size_t)dtype_size, dtype, 1, {(long int)frame->height()}, {(long int)dtype_size}); } if (frame->type == FrameType::U8) { col.push_back(py::object(py::array_t<u8>(buffer))); } else if (frame->type == FrameType::F32) { col.push_back(py::object(py::array_t<f32>(buffer))); } else if (frame->type == FrameType::F64) { col.push_back(py::object(py::array_t<f64>(buffer))); } } } } else { for (i32 i = 0; i < input_count; ++i) { batched_col.emplace_back(); std::vector<py::object> &col = batched_col.back(); for (i32 k = 0; k < input_columns[j][i].size(); ++k) { std::string s((char const *)input_columns[j][i][k].buffer, input_columns[j][i][k].size); col.push_back(py::object(py::bytes(s))); } } } } std::vector<std::vector<py::object>> batched_out_cols; if (can_batch_ && can_stencil_) { py::tuple out_cols = kernel.attr("execute")(batched_cols) .cast<py::tuple>(); for (i32 j = 0; j < out_cols.size(); ++j) { batched_out_cols.push_back(out_cols[j].cast<std::vector<py::object>>()); } } else if (can_stencil_) { // Remove the batch dimension since we are only stenciling std::vector<std::vector<py::object>> in_row(batched_cols.size()); for (size_t i = 0; i < batched_cols.size(); ++i) { in_row[i] = batched_cols[i][0]; } py::tuple out_row = kernel.attr("execute")(in_row) .cast<py::tuple>(); for (i32 j = 0; j < output_columns.size(); ++j) { batched_out_cols.emplace_back(); } for (i32 j = 0; j < out_row.size(); ++j) { batched_out_cols[j].push_back(out_row[j]); } } else if (can_batch_) { // Remove the stencil dimension since we are only batching std::vector<std::vector<py::object>> in_row(batched_cols.size()); for (size_t i = 0; i < batched_cols.size(); ++i) { for (size_t j = 0; j < batched_cols[i].size(); ++j) { in_row[i].push_back(batched_cols[i][j][0]); } } py::tuple out_cols = kernel.attr("execute")(in_row) .cast<py::tuple>(); for (i32 j = 0; j < out_cols.size(); ++j) { batched_out_cols.push_back(out_cols[j].cast<std::vector<py::object>>()); } } else { // Remove both the stencil and batch dimension std::vector<py::object> in_row; for (i32 j = 0; j < batched_cols.size(); ++j) { in_row.push_back(batched_cols[j][0][0]); } py::tuple out_row = kernel.attr("execute")(in_row).cast<py::tuple>(); for (i32 j = 0; j < output_columns.size(); ++j) { batched_out_cols.emplace_back(); } for (i32 j = 0; j < out_row.size(); ++j) { batched_out_cols[j].push_back(out_row[j]); } } LOG_IF(FATAL, batched_out_cols.size() != output_columns.size()) << "Incorrect number of output columns. Expected " << output_columns.size() << ", got " << batched_out_cols.size(); for (i32 j = 0; j < output_columns.size(); ++j) { // push all rows to that column LOG_IF(FATAL, batched_out_cols[j].size() != input_count) << "Incorrect number of output rows at column " << j << ". Expected " << input_count << ", got " << batched_out_cols[j].size(); if (config_.output_column_types[j] == proto::ColumnType::Video) { for (i32 i = 0; i < input_count; ++i) { py::array frame_np = batched_out_cols[j][i].cast<py::array>(); FrameType frame_type; if (frame_np.dtype().is(py::dtype("uint8"))) { frame_type = FrameType::U8; } else if (frame_np.dtype().is(py::dtype("float32"))) { frame_type = FrameType::F32; } else if (frame_np.dtype().is(py::dtype("float64"))) { frame_type = FrameType::F64; } else { LOG(FATAL) << "Invalid numpy dtype: " << frame_np.dtype(); } i32 ndim = frame_np.ndim(); if (ndim > 3) { LOG(FATAL) << "Invalid number of dimensions (must be less than 4): " << ndim; } std::vector<i32> shapes; std::vector<i32> strides; for (int n = 0; n < ndim; ++n) { shapes.push_back(frame_np.shape(n)); strides.push_back(frame_np.strides(n)); if (frame_np.strides(n) < 0) { LOG(FATAL) << "We do not yet support negative strides in PythonKernel!"; } } FrameInfo frame_info(shapes, frame_type); Frame *frame = new_frame(CPU_DEVICE, frame_info); const char *frame_data = (const char *)frame_np.data(); if (ndim == 3) { assert(strides[1] % strides[2] == 0); for (int i = 0; i < shapes[0]; ++i) { u64 offset = strides[0] * i; memcpy(frame->data + offset, frame_data + offset, shapes[2] * shapes[1] * strides[2]); } } else { LOG(FATAL) << "Can not support ndim != 3."; } insert_frame(output_columns[j], frame); } } else { std::vector<std::string> outputs; size_t total_size = 0; for (i32 i = 0; i < input_count; ++i) { std::string field = batched_out_cols[j][i].cast<std::string>(); outputs.push_back(field); total_size += field.size(); } u8 *output_block = new_block_buffer(CPU_DEVICE, total_size, input_count); for (i32 i = 0; i < input_count; ++i) { u8 *buf = output_block; memcpy_buffer(buf, CPU_DEVICE, (u8 *)outputs[i].data(), CPU_DEVICE, outputs[i].size()); insert_element(output_columns[j], buf, outputs[i].size()); output_block += outputs[i].size(); } } } } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } } <commit_msg>Fix python kernel not using proper offset for output frames<commit_after>#include "scanner/engine/python_kernel.h" #include "scanner/util/tinyformat.h" #include "scanner/util/util.h" #include <pybind11/eval.h> #include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace scanner { namespace py = pybind11; using namespace pybind11::literals; void gen_random(char* s, const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; for (int i = 0; i < len; ++i) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } PythonKernel::PythonKernel(const KernelConfig &config, const std::string &op_name, const std::string &kernel_code, const std::string &pickled_config, const bool can_batch, const bool can_stencil) : StenciledBatchedKernel(config), config_(config), device_(config.devices[0]), op_name_(op_name) { py::gil_scoped_acquire acquire; can_batch_ = can_batch; can_stencil_ = can_stencil; // Remove uuid from op_name op_name_ = op_name_.substr(0, op_name_.find(":")); char rand[256]; gen_random(rand, 256); kernel_name_ = tfm::format("%s_kernel_%s", op_name_, rand); std::string kernel_ns_name_ = tfm::format("ns_%s", op_name_); try { py::module main = py::module::import("__main__"); py::object scope = main.attr("__dict__"); // FIXME((apoms): for some reason, serializing the config object in release // mode on MacOS fails.... main.attr(kernel_ns_name_.c_str()) = py::dict( "kernel_code"_a=py::bytes(kernel_code), "user_config_str"_a=py::bytes(pickled_config), "config"_a=config); std::string pycode = tfm::format(R"( def %s_fn(): import pickle import cloudpickle import traceback from scannerpy import Config, DeviceType, DeviceHandle, KernelConfig from scannerpy.protobuf_generator import ProtobufGenerator n = %s user_config = pickle.loads(n['user_config_str']) protobufs = ProtobufGenerator(user_config) kernel_config = KernelConfig(n['config']) kernel_config.protobufs = protobufs return cloudpickle.loads(n['kernel_code'])(kernel_config) %s = %s_fn() )", kernel_name_, kernel_ns_name_, kernel_name_, kernel_name_); py::exec(pycode, scope); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } PythonKernel::~PythonKernel() { py::gil_scoped_acquire acquire; try { py::module::import("__main__").attr(kernel_name_.c_str()).attr("close")(); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::reset() { py::gil_scoped_acquire acquire; try { py::module::import("__main__").attr(kernel_name_.c_str()).attr("reset")(); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::new_stream(const std::vector<u8> &args) { py::gil_scoped_acquire acquire; try { py::module main = py::module::import("__main__"); py::object kernel = main.attr(kernel_name_.c_str()); main.attr("args_str") = py::bytes(reinterpret_cast<const char *>(args.data()), args.size()); std::string pycode = tfm::format(R"( import pickle if len(args_str) == 0: args = None else: args = pickle.loads(args_str) %s.new_stream(args))", kernel_name_); py::exec(pycode.c_str(), main.attr("__dict__")); } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } void PythonKernel::execute(const StenciledBatchedElements &input_columns, BatchedElements &output_columns) { i32 input_count = (i32)input_columns[0].size(); py::gil_scoped_acquire acquire; try { py::object kernel = py::module::import("__main__").attr(kernel_name_.c_str()); std::vector<std::vector<std::vector<py::object>>> batched_cols; for (i32 j = 0; j < input_columns.size(); ++j) { batched_cols.emplace_back(); } for (i32 j = 0; j < input_columns.size(); ++j) { std::vector<std::vector<py::object>> &batched_col = batched_cols[j]; if (config_.input_column_types[j] == proto::ColumnType::Video) { for (i32 i = 0; i < input_count; ++i) { batched_col.emplace_back(); std::vector<py::object> &col = batched_col.back(); for (i32 k = 0; k < input_columns[j][i].size(); ++k) { const Frame *frame = input_columns[j][i][k].as_const_frame(); std::string dtype; u32 dtype_size; if (frame->type == FrameType::U8) { dtype = py::format_descriptor<u8>::format(); dtype_size = 1; } else if (frame->type == FrameType::F32) { dtype = py::format_descriptor<f32>::format(); dtype_size = 4; } else if (frame->type == FrameType::F64) { dtype = py::format_descriptor<f64>::format(); dtype_size = 8; } py::buffer_info buffer; if (frame->channels() == 3) { buffer = py::buffer_info( frame->data, (size_t)dtype_size, dtype, 3, {(long int)frame->height(), (long int)frame->width(), (long int)frame->channels()}, {(long int)frame->width() * frame->channels() * dtype_size, (long int)frame->channels() * dtype_size, (long int)dtype_size}); } else { buffer = py::buffer_info( frame->data, (size_t)dtype_size, dtype, 1, {(long int)frame->height()}, {(long int)dtype_size}); } if (frame->type == FrameType::U8) { col.push_back(py::object(py::array_t<u8>(buffer))); } else if (frame->type == FrameType::F32) { col.push_back(py::object(py::array_t<f32>(buffer))); } else if (frame->type == FrameType::F64) { col.push_back(py::object(py::array_t<f64>(buffer))); } } } } else { for (i32 i = 0; i < input_count; ++i) { batched_col.emplace_back(); std::vector<py::object> &col = batched_col.back(); for (i32 k = 0; k < input_columns[j][i].size(); ++k) { std::string s((char const *)input_columns[j][i][k].buffer, input_columns[j][i][k].size); col.push_back(py::object(py::bytes(s))); } } } } std::vector<std::vector<py::object>> batched_out_cols; if (can_batch_ && can_stencil_) { py::tuple out_cols = kernel.attr("execute")(batched_cols) .cast<py::tuple>(); for (i32 j = 0; j < out_cols.size(); ++j) { batched_out_cols.push_back(out_cols[j].cast<std::vector<py::object>>()); } } else if (can_stencil_) { // Remove the batch dimension since we are only stenciling std::vector<std::vector<py::object>> in_row(batched_cols.size()); for (size_t i = 0; i < batched_cols.size(); ++i) { in_row[i] = batched_cols[i][0]; } py::tuple out_row = kernel.attr("execute")(in_row) .cast<py::tuple>(); for (i32 j = 0; j < output_columns.size(); ++j) { batched_out_cols.emplace_back(); } for (i32 j = 0; j < out_row.size(); ++j) { batched_out_cols[j].push_back(out_row[j]); } } else if (can_batch_) { // Remove the stencil dimension since we are only batching std::vector<std::vector<py::object>> in_row(batched_cols.size()); for (size_t i = 0; i < batched_cols.size(); ++i) { for (size_t j = 0; j < batched_cols[i].size(); ++j) { in_row[i].push_back(batched_cols[i][j][0]); } } py::tuple out_cols = kernel.attr("execute")(in_row) .cast<py::tuple>(); for (i32 j = 0; j < out_cols.size(); ++j) { batched_out_cols.push_back(out_cols[j].cast<std::vector<py::object>>()); } } else { // Remove both the stencil and batch dimension std::vector<py::object> in_row; for (i32 j = 0; j < batched_cols.size(); ++j) { in_row.push_back(batched_cols[j][0][0]); } py::tuple out_row = kernel.attr("execute")(in_row).cast<py::tuple>(); for (i32 j = 0; j < output_columns.size(); ++j) { batched_out_cols.emplace_back(); } for (i32 j = 0; j < out_row.size(); ++j) { batched_out_cols[j].push_back(out_row[j]); } } LOG_IF(FATAL, batched_out_cols.size() != output_columns.size()) << "Incorrect number of output columns. Expected " << output_columns.size() << ", got " << batched_out_cols.size(); for (i32 j = 0; j < output_columns.size(); ++j) { // push all rows to that column LOG_IF(FATAL, batched_out_cols[j].size() != input_count) << "Incorrect number of output rows at column " << j << ". Expected " << input_count << ", got " << batched_out_cols[j].size(); if (config_.output_column_types[j] == proto::ColumnType::Video) { for (i32 i = 0; i < input_count; ++i) { py::array frame_np = batched_out_cols[j][i].cast<py::array>(); FrameType frame_type; if (frame_np.dtype().is(py::dtype("uint8"))) { frame_type = FrameType::U8; } else if (frame_np.dtype().is(py::dtype("float32"))) { frame_type = FrameType::F32; } else if (frame_np.dtype().is(py::dtype("float64"))) { frame_type = FrameType::F64; } else { LOG(FATAL) << "Invalid numpy dtype: " << frame_np.dtype(); } i32 ndim = frame_np.ndim(); if (ndim > 3) { LOG(FATAL) << "Invalid number of dimensions (must be less than 4): " << ndim; } std::vector<i32> shapes; std::vector<i32> strides; for (int n = 0; n < ndim; ++n) { shapes.push_back(frame_np.shape(n)); strides.push_back(frame_np.strides(n)); if (frame_np.strides(n) < 0) { LOG(FATAL) << "We do not yet support negative strides in PythonKernel!"; } } FrameInfo frame_info(shapes, frame_type); Frame *frame = new_frame(CPU_DEVICE, frame_info); const char *frame_data = (const char *)frame_np.data(); if (ndim == 3) { assert(strides[1] % strides[2] == 0); u64 dest_offset = 0; for (int i = 0; i < shapes[0]; ++i) { u64 source_offset = strides[0] * i; memcpy(frame->data + dest_offset, frame_data + source_offset, shapes[2] * shapes[1] * strides[2]); dest_offset += shapes[2] * shapes[1] * strides[2]; } } else { LOG(FATAL) << "Can not support ndim != 3."; } insert_frame(output_columns[j], frame); } } else { std::vector<std::string> outputs; size_t total_size = 0; for (i32 i = 0; i < input_count; ++i) { std::string field = batched_out_cols[j][i].cast<std::string>(); outputs.push_back(field); total_size += field.size(); } u8 *output_block = new_block_buffer(CPU_DEVICE, total_size, input_count); for (i32 i = 0; i < input_count; ++i) { u8 *buf = output_block; memcpy_buffer(buf, CPU_DEVICE, (u8 *)outputs[i].data(), CPU_DEVICE, outputs[i].size()); insert_element(output_columns[j], buf, outputs[i].size()); output_block += outputs[i].size(); } } } } catch (py::error_already_set &e) { LOG(FATAL) << e.what(); } } } <|endoftext|>
<commit_before>// @(#)root/graf:$Name: $:$Id: TArrow.cxx,v 1.11 2004/02/07 08:54:03 brun Exp $ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TArrow.h" #include "TVirtualPad.h" ClassImp(TArrow) //______________________________________________________________________________ // Different arrow formats as explained in TArrow::TArrow or in // the picture below are provided. // Once an arrow is drawn on the screen: // - One can click on one of the edges and move this edge. // - One can click on any other arrow part to move the entire arrow. //Begin_Html /* <img src="gif/arrow.gif"> */ //End_Html // //______________________________________________________________________________ TArrow::TArrow(): TLine(),TAttFill() { //*-*-*-*-*-*-*-*-*-*-*arrow default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== fAngle = 60; } //______________________________________________________________________________ TArrow::TArrow(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Float_t arrowsize ,Option_t *option) :TLine(x1,y1,x2,y2), TAttFill(0,1001) { //*-*-*-*-*-*-*-*-*-*-*arrow normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== // Define an arrow between points x1,y1 and x2,y2 // the arrowsize is in percentage of the pad height // Opening angle between the two sides of the arrow is fAngle (60 degrees) // option = ">" --------> // option = "<" <-------- // option = "->-" ---->---- // option = "-<-" ----<---- // option = "-|>-" ---|>---- // option = "<>" <-------> // option = "<|>" <|-----|> arrow defined by a triangle // If FillColor == 0 draw open triangle // else draw full triangle with fillcolor // fAngle = 60; fArrowSize = arrowsize; fOption = option; SetLineColor(1); SetLineStyle(1); } //______________________________________________________________________________ TArrow::~TArrow() { //*-*-*-*-*-*-*-*-*-*-*arrow default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== } //______________________________________________________________________________ TArrow::TArrow(const TArrow &arrow) : TLine(arrow), TAttFill(arrow) { ((TArrow&)arrow).Copy(*this); } //______________________________________________________________________________ void TArrow::Copy(TObject &obj) const { //*-*-*-*-*-*-*-*-*-*-*Copy this arrow to arrow*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TLine::Copy(obj); TAttFill::Copy(((TArrow&)obj)); ((TArrow&)obj).fAngle = fAngle; ((TArrow&)obj).fArrowSize = fArrowSize; ((TArrow&)obj).fOption = fOption; } //______________________________________________________________________________ void TArrow::Draw(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with its current attributes*-*-*-*-*-*-* //*-* =========================================== Option_t *opt; if (strlen(option)) opt = option; else opt = (char*)GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TArrow::DrawArrow(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Float_t arrowsize ,Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with new coordinates*-*-*-*-*-*-*-*-*-* //*-* ==================================== // if arrowsize is <= 0, arrowsize will be the current arrow size // if option="", option will be the current arrow option Float_t size = arrowsize; if (size <= 0) size = fArrowSize; if (size <= 0) size = 0.05; const char* opt = option; if (!opt || strlen(opt) == 0) opt = fOption.Data(); if (!opt || strlen(opt) == 0) opt = "|>"; TArrow *newarrow = new TArrow(x1,y1,x2,y2,size,opt); newarrow->SetAngle(fAngle); TAttLine::Copy(*newarrow); TAttFill::Copy(*newarrow); newarrow->AppendPad(opt); } //______________________________________________________________________________ void TArrow::Paint(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Paint this arrow with its current attributes*-*-*-*-*-*-* //*-* ============================================ PaintArrow(gPad->XtoPad(fX1),gPad->YtoPad(fY1),gPad->XtoPad(fX2),gPad->YtoPad(fY2), fArrowSize, option); } //______________________________________________________________________________ void TArrow::PaintArrow(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Float_t arrowsize, Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with new coordinates*-*-*-*-*-*-*-*-*-* //*-* ==================================== // // (P2) // - // . - // . - // . - // -------------------------------------------.(P0)------- (P1) // . - // . - // . - // - // (P3) // // TString opt = option; opt.ToLower(); TAttLine::Modify(); TAttFill::Modify(); //*-*- take u1,v1 as origin. take arrow line as new x axis Int_t px1 = gPad->XtoAbsPixel(x1); Int_t py1 = gPad->YtoAbsPixel(y1); Int_t px2 = gPad->XtoAbsPixel(x2); Int_t py2 = gPad->YtoAbsPixel(y2); Float_t lp = TMath::Sqrt(Double_t((px2-px1)*(px2-px1) + (py2-py1)*(py2-py1))); Float_t rSiz = arrowsize*gPad->GetAbsHNDC()*gPad->GetWh(); Float_t dSiz = rSiz*TMath::Tan(3.141592*fAngle/360); if (lp <= 0) return; Double_t ct = (px2-px1)/lp; Double_t st = (py1-py2)/lp; Int_t P2x,P2y,P3x,P3y,P0x,P0y; // Otto start: define default line before move of origin of arrow Double_t XP0; Double_t YP0; Double_t XP0L; Double_t YP0L; XP0 = gPad->AbsPixeltoX(px2); YP0 = gPad->AbsPixeltoY(py2); XP0L = gPad->AbsPixeltoX(px1); YP0L = gPad->AbsPixeltoY(py1); // move origin of arrow if (opt.Contains("-") && opt.Contains(">")) { px1 = Int_t(0.5 *(px2 + px1) + ct*rSiz/2); py1 = Int_t(0.5 *(py2 + py1) - st*rSiz/2); px2 = px1; py2 = py1; } if (opt.Contains("-") && opt.Contains("<")) { px1 = Int_t(0.5 *(px2 + px1) - ct*rSiz/2); py1 = Int_t(0.5 *(py2 + py1) + st*rSiz/2); px2 = px1; py2 = py1; } // ---------- if (opt.Contains(">")) { P2x = px2 - Int_t(rSiz*ct+st*dSiz-0.5); P2y = py2 + Int_t(rSiz*st-ct*dSiz+0.5); P3x = px2 - Int_t(rSiz*ct-st*dSiz-0.5); P3y = py2 + Int_t(rSiz*st+ct*dSiz+0.5); P0x = px2 - Int_t(rSiz*ct-0.5); P0y = py2 + Int_t(rSiz*st+0.5); } else { P2x = px2; P2y = py2; P3x = px2; P3y = py2; P0x = px2; P0y = py2; } Int_t P2xL,P2yL,P3xL,P3yL,P0xL,P0yL; if (opt.Contains("<")) { P2xL = px1 + Int_t(rSiz*ct-st*dSiz+0.5); P2yL = py1 - Int_t(rSiz*st+ct*dSiz-0.5); P3xL = px1 + Int_t(rSiz*ct+st*dSiz+0.5); P3yL = py1 - Int_t(rSiz*st-ct*dSiz-0.5); P0xL = px1 + Int_t(rSiz*ct+0.5); P0yL = py1 - Int_t(rSiz*st-0.5); } else { P2xL = px1; P2yL = py1; P3xL = px1; P3yL = py1; P0xL = px1; P0yL = py1; } Double_t XP2 = gPad->AbsPixeltoX(P2x); Double_t YP2 = gPad->AbsPixeltoY(P2y); Double_t XP3 = gPad->AbsPixeltoX(P3x); Double_t YP3 = gPad->AbsPixeltoY(P3y); Double_t XP2L = gPad->AbsPixeltoX(P2xL); Double_t YP2L = gPad->AbsPixeltoY(P2yL); Double_t XP3L = gPad->AbsPixeltoX(P3xL); Double_t YP3L = gPad->AbsPixeltoY(P3yL); // move up if (opt.Contains("|") && !opt.Contains("-")) { XP0 = gPad->AbsPixeltoX(P0x); YP0 = gPad->AbsPixeltoY(P0y); XP0L = gPad->AbsPixeltoX(P0xL); YP0L = gPad->AbsPixeltoY(P0yL); } gPad->PaintLine(XP0,YP0,XP0L,YP0L); //*-*- Convert points to pad reference system Double_t xp1[4],yp1[4],xp2[4],yp2[4]; xp1[0] = XP2; yp1[0] = YP2; xp1[1] = gPad->AbsPixeltoX(px2); yp1[1] = gPad->AbsPixeltoY(py2); xp1[2] = XP3; yp1[2] = YP3; xp1[3] = XP2; yp1[3] = YP2; xp2[0] = XP2L; yp2[0] = YP2L; xp2[1] = gPad->AbsPixeltoX(px1); yp2[1] = gPad->AbsPixeltoY(py1); xp2[2] = XP3L; yp2[2] = YP3L; xp2[3] = XP2L; yp2[3] = YP2L; if (opt.Contains(">")) { if (opt.Contains("|>")) { if (GetFillColor()) { gPad->PaintFillArea(3,xp1,yp1); gPad->PaintPolyLine(4,xp1,yp1); } else { gPad->PaintPolyLine(4,xp1,yp1); } } else { gPad->PaintPolyLine(3,xp1,yp1); } } if (opt.Contains("<")) { if (opt.Contains("<|")) { if (GetFillColor()) { gPad->PaintFillArea(3,xp2,yp2); gPad->PaintPolyLine(4,xp2,yp2); } else { gPad->PaintPolyLine(4,xp2,yp2); } } else { gPad->PaintPolyLine(3,xp2,yp2); } } } //______________________________________________________________________________ void TArrow::SavePrimitive(ofstream &out, Option_t *) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; if (gROOT->ClassSaved(TArrow::Class())) { out<<" "; } else { out<<" TArrow *"; } out<<"arrow = new TArrow("<<fX1<<","<<fY1<<","<<fX2<<","<<fY2 <<","<<fArrowSize<<","<<quote<<GetDrawOption()<<quote<<");"<<endl; SaveFillAttributes(out,"arrow",0,1); SaveLineAttributes(out,"arrow",1,1,1); if (fAngle !=60) { out << " arrow->SetAngle(" << GetAngle() << ");" << endl; } out<<" arrow->Draw();"<<endl; } <commit_msg>Fix in TArrow::Paint to take into account the default option set via the constructor.<commit_after>// @(#)root/graf:$Name: $:$Id: TArrow.cxx,v 1.12 2004/11/15 10:26:27 brun Exp $ // Author: Rene Brun 17/10/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TArrow.h" #include "TVirtualPad.h" ClassImp(TArrow) //______________________________________________________________________________ // Different arrow formats as explained in TArrow::TArrow or in // the picture below are provided. // Once an arrow is drawn on the screen: // - One can click on one of the edges and move this edge. // - One can click on any other arrow part to move the entire arrow. //Begin_Html /* <img src="gif/arrow.gif"> */ //End_Html // //______________________________________________________________________________ TArrow::TArrow(): TLine(),TAttFill() { //*-*-*-*-*-*-*-*-*-*-*arrow default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== fAngle = 60; } //______________________________________________________________________________ TArrow::TArrow(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Float_t arrowsize ,Option_t *option) :TLine(x1,y1,x2,y2), TAttFill(0,1001) { //*-*-*-*-*-*-*-*-*-*-*arrow normal constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== // Define an arrow between points x1,y1 and x2,y2 // the arrowsize is in percentage of the pad height // Opening angle between the two sides of the arrow is fAngle (60 degrees) // option = ">" --------> // option = "<" <-------- // option = "->-" ---->---- // option = "-<-" ----<---- // option = "-|>-" ---|>---- // option = "<>" <-------> // option = "<|>" <|-----|> arrow defined by a triangle // If FillColor == 0 draw open triangle // else draw full triangle with fillcolor // fAngle = 60; fArrowSize = arrowsize; fOption = option; SetLineColor(1); SetLineStyle(1); } //______________________________________________________________________________ TArrow::~TArrow() { //*-*-*-*-*-*-*-*-*-*-*arrow default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== } //______________________________________________________________________________ TArrow::TArrow(const TArrow &arrow) : TLine(arrow), TAttFill(arrow) { ((TArrow&)arrow).Copy(*this); } //______________________________________________________________________________ void TArrow::Copy(TObject &obj) const { //*-*-*-*-*-*-*-*-*-*-*Copy this arrow to arrow*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================== TLine::Copy(obj); TAttFill::Copy(((TArrow&)obj)); ((TArrow&)obj).fAngle = fAngle; ((TArrow&)obj).fArrowSize = fArrowSize; ((TArrow&)obj).fOption = fOption; } //______________________________________________________________________________ void TArrow::Draw(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with its current attributes*-*-*-*-*-*-* //*-* =========================================== Option_t *opt; if (option && strlen(option)) opt = option; else opt = (char*)GetOption(); AppendPad(opt); } //______________________________________________________________________________ void TArrow::DrawArrow(Double_t x1, Double_t y1,Double_t x2, Double_t y2, Float_t arrowsize ,Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with new coordinates*-*-*-*-*-*-*-*-*-* //*-* ==================================== // if arrowsize is <= 0, arrowsize will be the current arrow size // if option="", option will be the current arrow option Float_t size = arrowsize; if (size <= 0) size = fArrowSize; if (size <= 0) size = 0.05; const char* opt = option; if (!opt || strlen(opt) == 0) opt = fOption.Data(); if (!opt || strlen(opt) == 0) opt = "|>"; TArrow *newarrow = new TArrow(x1,y1,x2,y2,size,opt); newarrow->SetAngle(fAngle); TAttLine::Copy(*newarrow); TAttFill::Copy(*newarrow); newarrow->AppendPad(opt); } //______________________________________________________________________________ void TArrow::Paint(Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Paint this arrow with its current attributes*-*-*-*-*-*-* //*-* ============================================ Option_t *opt; if (option && strlen(option)) opt = option; else opt = (char*)GetOption(); PaintArrow(gPad->XtoPad(fX1),gPad->YtoPad(fY1),gPad->XtoPad(fX2),gPad->YtoPad(fY2), fArrowSize, opt); } //______________________________________________________________________________ void TArrow::PaintArrow(Double_t x1, Double_t y1, Double_t x2, Double_t y2, Float_t arrowsize, Option_t *option) { //*-*-*-*-*-*-*-*-*-*-*Draw this arrow with new coordinates*-*-*-*-*-*-*-*-*-* //*-* ==================================== // // (P2) // - // . - // . - // . - // -------------------------------------------.(P0)------- (P1) // . - // . - // . - // - // (P3) // // TString opt = option; opt.ToLower(); TAttLine::Modify(); TAttFill::Modify(); //*-*- take u1,v1 as origin. take arrow line as new x axis Int_t px1 = gPad->XtoAbsPixel(x1); Int_t py1 = gPad->YtoAbsPixel(y1); Int_t px2 = gPad->XtoAbsPixel(x2); Int_t py2 = gPad->YtoAbsPixel(y2); Float_t lp = TMath::Sqrt(Double_t((px2-px1)*(px2-px1) + (py2-py1)*(py2-py1))); Float_t rSiz = arrowsize*gPad->GetAbsHNDC()*gPad->GetWh(); Float_t dSiz = rSiz*TMath::Tan(3.141592*fAngle/360); if (lp <= 0) return; Double_t ct = (px2-px1)/lp; Double_t st = (py1-py2)/lp; Int_t P2x,P2y,P3x,P3y,P0x,P0y; // Otto start: define default line before move of origin of arrow Double_t XP0; Double_t YP0; Double_t XP0L; Double_t YP0L; XP0 = gPad->AbsPixeltoX(px2); YP0 = gPad->AbsPixeltoY(py2); XP0L = gPad->AbsPixeltoX(px1); YP0L = gPad->AbsPixeltoY(py1); // move origin of arrow if (opt.Contains("-") && opt.Contains(">")) { px1 = Int_t(0.5 *(px2 + px1) + ct*rSiz/2); py1 = Int_t(0.5 *(py2 + py1) - st*rSiz/2); px2 = px1; py2 = py1; } if (opt.Contains("-") && opt.Contains("<")) { px1 = Int_t(0.5 *(px2 + px1) - ct*rSiz/2); py1 = Int_t(0.5 *(py2 + py1) + st*rSiz/2); px2 = px1; py2 = py1; } // ---------- if (opt.Contains(">")) { P2x = px2 - Int_t(rSiz*ct+st*dSiz-0.5); P2y = py2 + Int_t(rSiz*st-ct*dSiz+0.5); P3x = px2 - Int_t(rSiz*ct-st*dSiz-0.5); P3y = py2 + Int_t(rSiz*st+ct*dSiz+0.5); P0x = px2 - Int_t(rSiz*ct-0.5); P0y = py2 + Int_t(rSiz*st+0.5); } else { P2x = px2; P2y = py2; P3x = px2; P3y = py2; P0x = px2; P0y = py2; } Int_t P2xL,P2yL,P3xL,P3yL,P0xL,P0yL; if (opt.Contains("<")) { P2xL = px1 + Int_t(rSiz*ct-st*dSiz+0.5); P2yL = py1 - Int_t(rSiz*st+ct*dSiz-0.5); P3xL = px1 + Int_t(rSiz*ct+st*dSiz+0.5); P3yL = py1 - Int_t(rSiz*st-ct*dSiz-0.5); P0xL = px1 + Int_t(rSiz*ct+0.5); P0yL = py1 - Int_t(rSiz*st-0.5); } else { P2xL = px1; P2yL = py1; P3xL = px1; P3yL = py1; P0xL = px1; P0yL = py1; } Double_t XP2 = gPad->AbsPixeltoX(P2x); Double_t YP2 = gPad->AbsPixeltoY(P2y); Double_t XP3 = gPad->AbsPixeltoX(P3x); Double_t YP3 = gPad->AbsPixeltoY(P3y); Double_t XP2L = gPad->AbsPixeltoX(P2xL); Double_t YP2L = gPad->AbsPixeltoY(P2yL); Double_t XP3L = gPad->AbsPixeltoX(P3xL); Double_t YP3L = gPad->AbsPixeltoY(P3yL); // move up if (opt.Contains("|") && !opt.Contains("-")) { XP0 = gPad->AbsPixeltoX(P0x); YP0 = gPad->AbsPixeltoY(P0y); XP0L = gPad->AbsPixeltoX(P0xL); YP0L = gPad->AbsPixeltoY(P0yL); } gPad->PaintLine(XP0,YP0,XP0L,YP0L); //*-*- Convert points to pad reference system Double_t xp1[4],yp1[4],xp2[4],yp2[4]; xp1[0] = XP2; yp1[0] = YP2; xp1[1] = gPad->AbsPixeltoX(px2); yp1[1] = gPad->AbsPixeltoY(py2); xp1[2] = XP3; yp1[2] = YP3; xp1[3] = XP2; yp1[3] = YP2; xp2[0] = XP2L; yp2[0] = YP2L; xp2[1] = gPad->AbsPixeltoX(px1); yp2[1] = gPad->AbsPixeltoY(py1); xp2[2] = XP3L; yp2[2] = YP3L; xp2[3] = XP2L; yp2[3] = YP2L; if (opt.Contains(">")) { if (opt.Contains("|>")) { if (GetFillColor()) { gPad->PaintFillArea(3,xp1,yp1); gPad->PaintPolyLine(4,xp1,yp1); } else { gPad->PaintPolyLine(4,xp1,yp1); } } else { gPad->PaintPolyLine(3,xp1,yp1); } } if (opt.Contains("<")) { if (opt.Contains("<|")) { if (GetFillColor()) { gPad->PaintFillArea(3,xp2,yp2); gPad->PaintPolyLine(4,xp2,yp2); } else { gPad->PaintPolyLine(4,xp2,yp2); } } else { gPad->PaintPolyLine(3,xp2,yp2); } } } //______________________________________________________________________________ void TArrow::SavePrimitive(ofstream &out, Option_t *) { // Save primitive as a C++ statement(s) on output stream out char quote = '"'; if (gROOT->ClassSaved(TArrow::Class())) { out<<" "; } else { out<<" TArrow *"; } out<<"arrow = new TArrow("<<fX1<<","<<fY1<<","<<fX2<<","<<fY2 <<","<<fArrowSize<<","<<quote<<GetDrawOption()<<quote<<");"<<endl; SaveFillAttributes(out,"arrow",0,1); SaveLineAttributes(out,"arrow",1,1,1); if (fAngle !=60) { out << " arrow->SetAngle(" << GetAngle() << ");" << endl; } out<<" arrow->Draw();"<<endl; } <|endoftext|>
<commit_before>/* * Discrete Logarithm Parameters * (C) 1999-2008,2015,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/dl_group.h> #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/pem.h> #include <botan/workfactor.h> #include <botan/internal/monty_exp.h> #include <map> namespace Botan { class DL_Group_Data final { public: DL_Group_Data(const BigInt& p, const BigInt& q, const BigInt& g) : m_p(p), m_q(q), m_g(g), m_mod_p(p), m_monty(monty_precompute(m_g, m_p, m_mod_p, /*window bits=*/4)), m_p_bits(p.bits()) {} ~DL_Group_Data() = default; DL_Group_Data(const DL_Group_Data& other) = delete; DL_Group_Data& operator=(const DL_Group_Data& other) = delete; const BigInt& p() const { return m_p; } const BigInt& q() const { return m_q; } const BigInt& g() const { return m_g; } BigInt mod_p(const BigInt& x) const { return m_mod_p.reduce(x); } BigInt multiply_mod_p(const BigInt& x, const BigInt& y) const { return m_mod_p.multiply(x, y); } size_t p_bits() const { return m_p_bits; } size_t p_bytes() const { return (m_p_bits + 7) / 8; } BigInt power_g_p(const BigInt& k) const { return monty_execute(*m_monty, k); } private: BigInt m_p; BigInt m_q; BigInt m_g; Modular_Reducer m_mod_p; std::shared_ptr<const Montgomery_Exponentation_State> m_monty; size_t m_p_bits; }; //static std::shared_ptr<DL_Group_Data> DL_Group::BER_decode_DL_group(const uint8_t data[], size_t data_len, DL_Group::Format format) { BigInt p, q, g; BER_Decoder decoder(data, data_len); BER_Decoder ber = decoder.start_cons(SEQUENCE); if(format == DL_Group::ANSI_X9_57) { ber.decode(p) .decode(q) .decode(g) .verify_end(); } else if(format == DL_Group::ANSI_X9_42) { ber.decode(p) .decode(g) .decode(q) .discard_remaining(); } else if(format == DL_Group::PKCS_3) { // q is left as zero ber.decode(p) .decode(g) .discard_remaining(); } else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); return std::make_shared<DL_Group_Data>(p, q, g); } //static std::shared_ptr<DL_Group_Data> DL_Group::load_DL_group_info(const char* p_str, const char* q_str, const char* g_str) { const BigInt p(p_str); const BigInt q(q_str); const BigInt g(g_str); return std::make_shared<DL_Group_Data>(p, q, g); } //static std::shared_ptr<DL_Group_Data> DL_Group::load_DL_group_info(const char* p_str, const char* g_str) { const BigInt p(p_str); const BigInt q = (p - 1) / 2; const BigInt g(g_str); return std::make_shared<DL_Group_Data>(p, q, g); } namespace { DL_Group::Format pem_label_to_dl_format(const std::string& label) { if(label == "DH PARAMETERS") return DL_Group::PKCS_3; else if(label == "DSA PARAMETERS") return DL_Group::ANSI_X9_57; else if(label == "X942 DH PARAMETERS" || label == "X9.42 DH PARAMETERS") return DL_Group::ANSI_X9_42; else throw Decoding_Error("DL_Group: Invalid PEM label " + label); } } /* * DL_Group Constructor */ DL_Group::DL_Group(const std::string& str) { // Either a name or a PEM block, try name first m_data = DL_group_info(str); if(m_data == nullptr) { try { std::string label; const std::vector<uint8_t> ber = unlock(PEM_Code::decode(str, label)); Format format = pem_label_to_dl_format(label); m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } catch(...) {} } if(m_data == nullptr) throw Invalid_Argument("DL_Group: Unknown group " + str); } namespace { /* * Create generator of the q-sized subgroup (DSA style generator) */ BigInt make_dsa_generator(const BigInt& p, const BigInt& q) { const BigInt e = (p - 1) / q; if(e == 0 || (p - 1) % q > 0) throw Invalid_Argument("make_dsa_generator q does not divide p-1"); for(size_t i = 0; i != PRIME_TABLE_SIZE; ++i) { // TODO precompute! BigInt g = power_mod(PRIMES[i], e, p); if(g > 1) return g; } throw Internal_Error("DL_Group: Couldn't create a suitable generator"); } } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, PrimeType type, size_t pbits, size_t qbits) { if(pbits < 1024) throw Invalid_Argument("DL_Group: prime size " + std::to_string(pbits) + " is too small"); if(type == Strong) { if(qbits != 0 && qbits != pbits - 1) throw Invalid_Argument("Cannot create strong-prime DL_Group with specified q bits"); const BigInt p = random_safe_prime(rng, pbits); const BigInt q = (p - 1) / 2; /* Always choose a generator that is quadratic reside mod p, this forces g to be a generator of the subgroup of size q. */ BigInt g = 2; if(jacobi(g, p) != 1) { // prime table does not contain 2 for(size_t i = 0; i < PRIME_TABLE_SIZE; ++i) { g = PRIMES[i]; if(jacobi(g, p) == 1) break; } } m_data = std::make_shared<DL_Group_Data>(p, q, g); } else if(type == Prime_Subgroup) { if(qbits == 0) qbits = dl_exponent_size(pbits); const BigInt q = random_prime(rng, qbits); Modular_Reducer mod_2q(2*q); BigInt X; BigInt p; while(p.bits() != pbits || !is_prime(p, rng)) { X.randomize(rng, pbits); p = X - mod_2q.reduce(X) + 1; } const BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } else if(type == DSA_Kosherizer) { if(qbits == 0) qbits = ((pbits <= 1024) ? 160 : 256); BigInt p, q; generate_dsa_primes(rng, p, q, pbits, qbits); const BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } else { throw Invalid_Argument("DL_Group unknown PrimeType"); } } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, const std::vector<uint8_t>& seed, size_t pbits, size_t qbits) { BigInt p, q; if(!generate_dsa_primes(rng, p, q, pbits, qbits, seed)) throw Invalid_Argument("DL_Group: The seed given does not generate a DSA group"); BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p, const BigInt& g) { m_data = std::make_shared<DL_Group_Data>(p, 0, g); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p, const BigInt& q, const BigInt& g) { m_data = std::make_shared<DL_Group_Data>(p, q, g); } const DL_Group_Data& DL_Group::data() const { if(m_data) return *m_data; throw Invalid_State("DL_Group uninitialized"); } /* * Verify the parameters */ bool DL_Group::verify_group(RandomNumberGenerator& rng, bool strong) const { const BigInt& p = get_p(); const BigInt& q = get_q(); const BigInt& g = get_g(); if(g < 2 || p < 3 || q < 0) return false; const size_t prob = (strong) ? 128 : 10; if(q != 0) { if((p - 1) % q != 0) { return false; } if(this->power_g_p(q) != 1) { return false; } if(!is_prime(q, rng, prob)) { return false; } } if(!is_prime(p, rng, prob)) { return false; } return true; } /* * Return the prime */ const BigInt& DL_Group::get_p() const { return data().p(); } /* * Return the generator */ const BigInt& DL_Group::get_g() const { return data().g(); } /* * Return the subgroup */ const BigInt& DL_Group::get_q() const { return data().q(); } size_t DL_Group::p_bits() const { return data().p_bits(); } size_t DL_Group::p_bytes() const { return data().p_bytes(); } BigInt DL_Group::inverse_mod_p(const BigInt& x) const { // precompute?? return inverse_mod(x, get_p()); } BigInt DL_Group::mod_p(const BigInt& x) const { return data().mod_p(x); } BigInt DL_Group::multiply_mod_p(const BigInt& x, const BigInt& y) const { return data().multiply_mod_p(x, y); } BigInt DL_Group::power_g_p(const BigInt& x) const { return data().power_g_p(x); } /* * DER encode the parameters */ std::vector<uint8_t> DL_Group::DER_encode(Format format) const { if(get_q().is_zero() && (format == ANSI_X9_57 || format == ANSI_X9_42)) throw Encoding_Error("Cannot encode DL_Group in ANSI formats when q param is missing"); if(format == ANSI_X9_57) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_q()) .encode(get_g()) .end_cons() .get_contents_unlocked(); } else if(format == ANSI_X9_42) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_g()) .encode(get_q()) .end_cons() .get_contents_unlocked(); } else if(format == PKCS_3) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_g()) .end_cons() .get_contents_unlocked(); } throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * PEM encode the parameters */ std::string DL_Group::PEM_encode(Format format) const { const std::vector<uint8_t> encoding = DER_encode(format); if(format == PKCS_3) return PEM_Code::encode(encoding, "DH PARAMETERS"); else if(format == ANSI_X9_57) return PEM_Code::encode(encoding, "DSA PARAMETERS"); else if(format == ANSI_X9_42) return PEM_Code::encode(encoding, "X9.42 DH PARAMETERS"); else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } DL_Group::DL_Group(const uint8_t ber[], size_t ber_len, Format format) { m_data = BER_decode_DL_group(ber, ber_len, format); } void DL_Group::BER_decode(const std::vector<uint8_t>& ber, Format format) { m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } /* * Decode PEM encoded parameters */ void DL_Group::PEM_decode(const std::string& pem) { std::string label; const std::vector<uint8_t> ber = unlock(PEM_Code::decode(pem, label)); Format format = pem_label_to_dl_format(label); m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } //static std::string DL_Group::PEM_for_named_group(const std::string& name) { DL_Group group(name); DL_Group::Format format = group.get_q().is_zero() ? DL_Group::PKCS_3 : DL_Group::ANSI_X9_42; return group.PEM_encode(format); } } <commit_msg>Remove unused include [ci skip]<commit_after>/* * Discrete Logarithm Parameters * (C) 1999-2008,2015,2018 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/dl_group.h> #include <botan/numthry.h> #include <botan/reducer.h> #include <botan/der_enc.h> #include <botan/ber_dec.h> #include <botan/pem.h> #include <botan/workfactor.h> #include <botan/internal/monty_exp.h> namespace Botan { class DL_Group_Data final { public: DL_Group_Data(const BigInt& p, const BigInt& q, const BigInt& g) : m_p(p), m_q(q), m_g(g), m_mod_p(p), m_monty(monty_precompute(m_g, m_p, m_mod_p, /*window bits=*/4)), m_p_bits(p.bits()) {} ~DL_Group_Data() = default; DL_Group_Data(const DL_Group_Data& other) = delete; DL_Group_Data& operator=(const DL_Group_Data& other) = delete; const BigInt& p() const { return m_p; } const BigInt& q() const { return m_q; } const BigInt& g() const { return m_g; } BigInt mod_p(const BigInt& x) const { return m_mod_p.reduce(x); } BigInt multiply_mod_p(const BigInt& x, const BigInt& y) const { return m_mod_p.multiply(x, y); } size_t p_bits() const { return m_p_bits; } size_t p_bytes() const { return (m_p_bits + 7) / 8; } BigInt power_g_p(const BigInt& k) const { return monty_execute(*m_monty, k); } private: BigInt m_p; BigInt m_q; BigInt m_g; Modular_Reducer m_mod_p; std::shared_ptr<const Montgomery_Exponentation_State> m_monty; size_t m_p_bits; }; //static std::shared_ptr<DL_Group_Data> DL_Group::BER_decode_DL_group(const uint8_t data[], size_t data_len, DL_Group::Format format) { BigInt p, q, g; BER_Decoder decoder(data, data_len); BER_Decoder ber = decoder.start_cons(SEQUENCE); if(format == DL_Group::ANSI_X9_57) { ber.decode(p) .decode(q) .decode(g) .verify_end(); } else if(format == DL_Group::ANSI_X9_42) { ber.decode(p) .decode(g) .decode(q) .discard_remaining(); } else if(format == DL_Group::PKCS_3) { // q is left as zero ber.decode(p) .decode(g) .discard_remaining(); } else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); return std::make_shared<DL_Group_Data>(p, q, g); } //static std::shared_ptr<DL_Group_Data> DL_Group::load_DL_group_info(const char* p_str, const char* q_str, const char* g_str) { const BigInt p(p_str); const BigInt q(q_str); const BigInt g(g_str); return std::make_shared<DL_Group_Data>(p, q, g); } //static std::shared_ptr<DL_Group_Data> DL_Group::load_DL_group_info(const char* p_str, const char* g_str) { const BigInt p(p_str); const BigInt q = (p - 1) / 2; const BigInt g(g_str); return std::make_shared<DL_Group_Data>(p, q, g); } namespace { DL_Group::Format pem_label_to_dl_format(const std::string& label) { if(label == "DH PARAMETERS") return DL_Group::PKCS_3; else if(label == "DSA PARAMETERS") return DL_Group::ANSI_X9_57; else if(label == "X942 DH PARAMETERS" || label == "X9.42 DH PARAMETERS") return DL_Group::ANSI_X9_42; else throw Decoding_Error("DL_Group: Invalid PEM label " + label); } } /* * DL_Group Constructor */ DL_Group::DL_Group(const std::string& str) { // Either a name or a PEM block, try name first m_data = DL_group_info(str); if(m_data == nullptr) { try { std::string label; const std::vector<uint8_t> ber = unlock(PEM_Code::decode(str, label)); Format format = pem_label_to_dl_format(label); m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } catch(...) {} } if(m_data == nullptr) throw Invalid_Argument("DL_Group: Unknown group " + str); } namespace { /* * Create generator of the q-sized subgroup (DSA style generator) */ BigInt make_dsa_generator(const BigInt& p, const BigInt& q) { const BigInt e = (p - 1) / q; if(e == 0 || (p - 1) % q > 0) throw Invalid_Argument("make_dsa_generator q does not divide p-1"); for(size_t i = 0; i != PRIME_TABLE_SIZE; ++i) { // TODO precompute! BigInt g = power_mod(PRIMES[i], e, p); if(g > 1) return g; } throw Internal_Error("DL_Group: Couldn't create a suitable generator"); } } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, PrimeType type, size_t pbits, size_t qbits) { if(pbits < 1024) throw Invalid_Argument("DL_Group: prime size " + std::to_string(pbits) + " is too small"); if(type == Strong) { if(qbits != 0 && qbits != pbits - 1) throw Invalid_Argument("Cannot create strong-prime DL_Group with specified q bits"); const BigInt p = random_safe_prime(rng, pbits); const BigInt q = (p - 1) / 2; /* Always choose a generator that is quadratic reside mod p, this forces g to be a generator of the subgroup of size q. */ BigInt g = 2; if(jacobi(g, p) != 1) { // prime table does not contain 2 for(size_t i = 0; i < PRIME_TABLE_SIZE; ++i) { g = PRIMES[i]; if(jacobi(g, p) == 1) break; } } m_data = std::make_shared<DL_Group_Data>(p, q, g); } else if(type == Prime_Subgroup) { if(qbits == 0) qbits = dl_exponent_size(pbits); const BigInt q = random_prime(rng, qbits); Modular_Reducer mod_2q(2*q); BigInt X; BigInt p; while(p.bits() != pbits || !is_prime(p, rng)) { X.randomize(rng, pbits); p = X - mod_2q.reduce(X) + 1; } const BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } else if(type == DSA_Kosherizer) { if(qbits == 0) qbits = ((pbits <= 1024) ? 160 : 256); BigInt p, q; generate_dsa_primes(rng, p, q, pbits, qbits); const BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } else { throw Invalid_Argument("DL_Group unknown PrimeType"); } } /* * DL_Group Constructor */ DL_Group::DL_Group(RandomNumberGenerator& rng, const std::vector<uint8_t>& seed, size_t pbits, size_t qbits) { BigInt p, q; if(!generate_dsa_primes(rng, p, q, pbits, qbits, seed)) throw Invalid_Argument("DL_Group: The seed given does not generate a DSA group"); BigInt g = make_dsa_generator(p, q); m_data = std::make_shared<DL_Group_Data>(p, q, g); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p, const BigInt& g) { m_data = std::make_shared<DL_Group_Data>(p, 0, g); } /* * DL_Group Constructor */ DL_Group::DL_Group(const BigInt& p, const BigInt& q, const BigInt& g) { m_data = std::make_shared<DL_Group_Data>(p, q, g); } const DL_Group_Data& DL_Group::data() const { if(m_data) return *m_data; throw Invalid_State("DL_Group uninitialized"); } /* * Verify the parameters */ bool DL_Group::verify_group(RandomNumberGenerator& rng, bool strong) const { const BigInt& p = get_p(); const BigInt& q = get_q(); const BigInt& g = get_g(); if(g < 2 || p < 3 || q < 0) return false; const size_t prob = (strong) ? 128 : 10; if(q != 0) { if((p - 1) % q != 0) { return false; } if(this->power_g_p(q) != 1) { return false; } if(!is_prime(q, rng, prob)) { return false; } } if(!is_prime(p, rng, prob)) { return false; } return true; } /* * Return the prime */ const BigInt& DL_Group::get_p() const { return data().p(); } /* * Return the generator */ const BigInt& DL_Group::get_g() const { return data().g(); } /* * Return the subgroup */ const BigInt& DL_Group::get_q() const { return data().q(); } size_t DL_Group::p_bits() const { return data().p_bits(); } size_t DL_Group::p_bytes() const { return data().p_bytes(); } BigInt DL_Group::inverse_mod_p(const BigInt& x) const { // precompute?? return inverse_mod(x, get_p()); } BigInt DL_Group::mod_p(const BigInt& x) const { return data().mod_p(x); } BigInt DL_Group::multiply_mod_p(const BigInt& x, const BigInt& y) const { return data().multiply_mod_p(x, y); } BigInt DL_Group::power_g_p(const BigInt& x) const { return data().power_g_p(x); } /* * DER encode the parameters */ std::vector<uint8_t> DL_Group::DER_encode(Format format) const { if(get_q().is_zero() && (format == ANSI_X9_57 || format == ANSI_X9_42)) throw Encoding_Error("Cannot encode DL_Group in ANSI formats when q param is missing"); if(format == ANSI_X9_57) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_q()) .encode(get_g()) .end_cons() .get_contents_unlocked(); } else if(format == ANSI_X9_42) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_g()) .encode(get_q()) .end_cons() .get_contents_unlocked(); } else if(format == PKCS_3) { return DER_Encoder() .start_cons(SEQUENCE) .encode(get_p()) .encode(get_g()) .end_cons() .get_contents_unlocked(); } throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } /* * PEM encode the parameters */ std::string DL_Group::PEM_encode(Format format) const { const std::vector<uint8_t> encoding = DER_encode(format); if(format == PKCS_3) return PEM_Code::encode(encoding, "DH PARAMETERS"); else if(format == ANSI_X9_57) return PEM_Code::encode(encoding, "DSA PARAMETERS"); else if(format == ANSI_X9_42) return PEM_Code::encode(encoding, "X9.42 DH PARAMETERS"); else throw Invalid_Argument("Unknown DL_Group encoding " + std::to_string(format)); } DL_Group::DL_Group(const uint8_t ber[], size_t ber_len, Format format) { m_data = BER_decode_DL_group(ber, ber_len, format); } void DL_Group::BER_decode(const std::vector<uint8_t>& ber, Format format) { m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } /* * Decode PEM encoded parameters */ void DL_Group::PEM_decode(const std::string& pem) { std::string label; const std::vector<uint8_t> ber = unlock(PEM_Code::decode(pem, label)); Format format = pem_label_to_dl_format(label); m_data = BER_decode_DL_group(ber.data(), ber.size(), format); } //static std::string DL_Group::PEM_for_named_group(const std::string& name) { DL_Group group(name); DL_Group::Format format = group.get_q().is_zero() ? DL_Group::PKCS_3 : DL_Group::ANSI_X9_42; return group.PEM_encode(format); } } <|endoftext|>
<commit_before>/* * Copyright 2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "stdafx.h" #include "spi.h" #include "Driver.h" #include "ConnectionInfo.h" #include "CdapException.h" #include "InvalidHandleException.h" #include "Argument.h" using namespace Cask::CdapOdbc; SQLRETURN SQL_SPI SQLCleanupConnectionPoolID( SQLHENV environmentHandle, POOLID poolID) { return SQL_ERROR; } SQLRETURN SQL_SPI SQLGetPoolID( SQLHDBC_INFO_TOKEN hDbcInfoToken, _Out_ POOLID* pPoolID) { return SQL_ERROR; } SQLRETURN SQL_SPI SQLPoolConnectW( SQLHDBC hdbc, SQLHDBC_INFO_TOKEN hDbcInfoToken, _Out_writes_opt_(cchConnStrOutMax) SQLWCHAR* szConnStrOut, SQLSMALLINT cchConnStrOutMax, _Out_opt_ SQLSMALLINT* pcchConnStrOut) { return SQL_ERROR; } SQLRETURN SQL_SPI SQLRateConnection( SQLHDBC_INFO_TOKEN hRequest, SQLHDBC hCandidateConnection, BOOL fRequiresTransactionEnlistment, TRANSID transId, _Out_ SQLConnPoolRating* pRating) { TRACE(L"SQLRateConnection(hRequest = %X, hCandidateConnection = %X)\n", hRequest, hCandidateConnection); try { auto& info = Driver::getInstance().getConnectionInfo(hRequest); auto& connection = Driver::getInstance().getConnection(hCandidateConnection); try { info.getSqlStatus().clear(); *pRating = static_cast<SQLConnPoolRating>(info.rateConnection(connection)); TRACE(L"SQLRateConnection returns SQL_SUCCESS\n"); return SQL_SUCCESS; } catch (CdapException& cex) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLRateConnection returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); return SQL_ERROR; } } SQLRETURN SQL_SPI SQLSetConnectAttrForDbcInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, SQLINTEGER Attribute, _In_reads_bytes_opt_(StringLength) SQLPOINTER Value, SQLINTEGER StringLength) { TRACE(L"SQLSetConnectAttrForDbcInfoW(hDbcInfoToken = %X, Attribute = %d)\n", hDbcInfoToken, Attribute); try { auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken); try { info.getSqlStatus().clear(); SQLULEN value = 0; switch (Attribute) { case SQL_ATTR_ASYNC_ENABLE: value = reinterpret_cast<SQLULEN>(Value); info.setAsync(value == SQL_ASYNC_ENABLE_ON); TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; case SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE: value = reinterpret_cast<SQLULEN>(Value); info.setFunctionsAsync(value == SQL_ASYNC_DBC_ENABLE_ON); TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; default: TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; } } catch (CdapException& cex) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); return SQL_ERROR; } } SQLRETURN SQL_SPI SQLSetConnectInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, _In_reads_(cchDSN) SQLWCHAR* szDSN, SQLSMALLINT cchDSN, _In_reads_(cchUID) SQLWCHAR* szUID, SQLSMALLINT cchUID, _In_reads_(cchAuthStr) SQLWCHAR* szAuthStr, SQLSMALLINT cchAuthStr) { // Used for SQLConnect call // Not supported TRACE(L"SQLSetConnectInfoW\n"); TRACE(L"SQLSetConnectInfoW returns SQL_ERROR\n"); return SQL_ERROR; } SQLRETURN SQL_SPI SQLSetDriverConnectInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, _In_reads_(cchConnStrIn) SQLWCHAR* szConnStrIn, SQLSMALLINT cchConnStrIn) { TRACE(L"SQLSetDriverConnectInfoW(hDbcInfoToken = %X, szConnStrIn = %s)\n", hDbcInfoToken, szConnStrIn); try { auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken); try { info.getSqlStatus().clear(); auto connectionString = Argument::toStdString(szConnStrIn, cchConnStrIn); if (connectionString) { info.setConnectionString(*connectionString); TRACE(L"SQLSetDriverConnectInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; } else { throw CdapException(L"Connection string cannot be empty."); } } catch (CdapException& cex) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); return SQL_ERROR; } }<commit_msg>SQLPoolConnect function.<commit_after>/* * Copyright 2016 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "stdafx.h" #include "spi.h" #include "Driver.h" #include "ConnectionInfo.h" #include "CdapException.h" #include "InvalidHandleException.h" #include "Argument.h" #include "Connection.h" using namespace Cask::CdapOdbc; SQLRETURN SQL_SPI SQLCleanupConnectionPoolID( SQLHENV environmentHandle, POOLID poolID) { return SQL_ERROR; } SQLRETURN SQL_SPI SQLGetPoolID( SQLHDBC_INFO_TOKEN hDbcInfoToken, _Out_ POOLID* pPoolID) { return SQL_ERROR; } SQLRETURN SQL_SPI SQLPoolConnectW( SQLHDBC hdbc, SQLHDBC_INFO_TOKEN hDbcInfoToken, _Out_writes_opt_(cchConnStrOutMax) SQLWCHAR* szConnStrOut, SQLSMALLINT cchConnStrOutMax, _Out_opt_ SQLSMALLINT* pcchConnStrOut) { TRACE(L"SQLPoolConnectW(hdbc = %X, hDbcInfoToken = %X)\n", hdbc, hDbcInfoToken); try { auto& connection = Driver::getInstance().getConnection(hdbc); auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken); try { auto connectionString = connection.getParams().getFullConnectionString(); if (connection.getIsFunctionsAsync()) { if (!connection.openAsync(connectionString)) { TRACE(L"SQLPoolConnectW returns SQL_STILL_EXECUTING, szConnStrOut = %s\n", szConnStrOut); return SQL_STILL_EXECUTING; } } else { connection.open(connectionString); } Argument::fromStdString(connectionString, szConnStrOut, cchConnStrOutMax, pcchConnStrOut); TRACE(L"SQLPoolConnectW returns SQL_SUCCESS, szConnStrOut = %s\n", szConnStrOut); return SQL_SUCCESS; } catch (CdapException& cex) { TRACE(L"SQLPoolConnectW returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLPoolConnectW returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLPoolConnectW returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLPoolConnectW returns SQL_ERROR\n"); return SQL_ERROR; } } SQLRETURN SQL_SPI SQLRateConnection( SQLHDBC_INFO_TOKEN hRequest, SQLHDBC hCandidateConnection, BOOL fRequiresTransactionEnlistment, TRANSID transId, _Out_ SQLConnPoolRating* pRating) { TRACE(L"SQLRateConnection(hRequest = %X, hCandidateConnection = %X)\n", hRequest, hCandidateConnection); try { auto& info = Driver::getInstance().getConnectionInfo(hRequest); auto& connection = Driver::getInstance().getConnection(hCandidateConnection); try { info.getSqlStatus().clear(); *pRating = static_cast<SQLConnPoolRating>(info.rateConnection(connection)); TRACE(L"SQLRateConnection returns SQL_SUCCESS\n"); return SQL_SUCCESS; } catch (CdapException& cex) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLRateConnection returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLRateConnection returns SQL_ERROR\n"); return SQL_ERROR; } } SQLRETURN SQL_SPI SQLSetConnectAttrForDbcInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, SQLINTEGER Attribute, _In_reads_bytes_opt_(StringLength) SQLPOINTER Value, SQLINTEGER StringLength) { TRACE(L"SQLSetConnectAttrForDbcInfoW(hDbcInfoToken = %X, Attribute = %d)\n", hDbcInfoToken, Attribute); try { auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken); try { info.getSqlStatus().clear(); SQLULEN value = 0; switch (Attribute) { case SQL_ATTR_ASYNC_ENABLE: value = reinterpret_cast<SQLULEN>(Value); info.setAsync(value == SQL_ASYNC_ENABLE_ON); TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; case SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE: value = reinterpret_cast<SQLULEN>(Value); info.setFunctionsAsync(value == SQL_ASYNC_DBC_ENABLE_ON); TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; default: TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; } } catch (CdapException& cex) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLSetConnectAttrForDbcInfoW returns SQL_ERROR\n"); return SQL_ERROR; } } SQLRETURN SQL_SPI SQLSetConnectInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, _In_reads_(cchDSN) SQLWCHAR* szDSN, SQLSMALLINT cchDSN, _In_reads_(cchUID) SQLWCHAR* szUID, SQLSMALLINT cchUID, _In_reads_(cchAuthStr) SQLWCHAR* szAuthStr, SQLSMALLINT cchAuthStr) { // Used for SQLConnect call // Not supported TRACE(L"SQLSetConnectInfoW\n"); TRACE(L"SQLSetConnectInfoW returns SQL_ERROR\n"); return SQL_ERROR; } SQLRETURN SQL_SPI SQLSetDriverConnectInfoW( SQLHDBC_INFO_TOKEN hDbcInfoToken, _In_reads_(cchConnStrIn) SQLWCHAR* szConnStrIn, SQLSMALLINT cchConnStrIn) { TRACE(L"SQLSetDriverConnectInfoW(hDbcInfoToken = %X, szConnStrIn = %s)\n", hDbcInfoToken, szConnStrIn); try { auto& info = Driver::getInstance().getConnectionInfo(hDbcInfoToken); try { info.getSqlStatus().clear(); auto connectionString = Argument::toStdString(szConnStrIn, cchConnStrIn); if (connectionString) { info.setConnectionString(*connectionString); TRACE(L"SQLSetDriverConnectInfoW returns SQL_SUCCESS\n"); return SQL_SUCCESS; } else { throw CdapException(L"Connection string cannot be empty."); } } catch (CdapException& cex) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(cex); return cex.getErrorCode(); } catch (std::exception& ex) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); info.getSqlStatus().addError(ex); return SQL_ERROR; } } catch (InvalidHandleException&) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_INVALID_HANDLE\n"); return SQL_INVALID_HANDLE; } catch (std::exception&) { TRACE(L"SQLSetDriverConnectInfoW returns SQL_ERROR\n"); return SQL_ERROR; } }<|endoftext|>
<commit_before>/* * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Sensing Module. * * With ideas from: * Created by ITead studio. Apr 20, 2010. * iteadstudio.com * * SVN Keywords * ---------------------------------- * $Author$ * $Date$ * $Revision$ * ---------------------------------- */ #include <stdlib.h> #include <string.h> #include <Ultrasonic.h> Ultrasonic::Ultrasonic(int tp, int ep) { pinMode(tp, OUTPUT); pinMode(ep, INPUT); _trigPin = tp; _echoPin = ep; _multiplier = MULTIPLIER_DEFAULT; /* Don't allow a maximum distance longer than the sensor supports. */ _maxDistance = _MAX_CM_DISTANCE; _pingTimeout = _maxDistance * _PING_OVERHEAD; _temp = _TEMP_CELSIUS_DEFAULT; } long Ultrasonic::timing(void) { digitalWrite(_trigPin, LOW); delayMicroseconds(2); digitalWrite(_trigPin, HIGH); delayMicroseconds(10); digitalWrite(_trigPin, LOW); return pulseIn(_echoPin, HIGH, _pingTimeout); } float Ultrasonic::convert(long microsec, int metric) { // 0.5 * 331.29 * (1 + _temp/273)^0.5 * (microsec * 0.0001) * _multiplier float dist = min(0.0165645 * pow(1 + _temp/273, 0.5) * microsec * _multiplier, _maxDistance); if(metric) return dist; else return dist * 0.3937; } void Ultrasonic::setMultiplier(float value) { _multiplier = value; } void Ultrasonic::setTemperature(float value) { _temp = value; } void Ultrasonic::setMaxDistance(int value) { _maxDistance = min(value, _MAX_CM_DISTANCE); _pingTimeout = _maxDistance * _PING_OVERHEAD; } #ifdef COMPILE_STD_DEV bool Ultrasonic::sampleCreate(size_t numBufs, ...) { bool result = false; va_list ap; _numBufs = numBufs; if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL) { va_start(ap, numBufs); BufCtl *buf; size_t smpSize; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; smpSize = va_arg(ap, size_t); if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL) { buf->pIndex = buf->pBegin; buf->length = smpSize; buf->filled = false; result = true; } else { result = false; break; } } va_end(ap); } if(!result) _freeBuffers(); return result; } void Ultrasonic::sampleClear() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; memset(buf, '\0', sizeof(float) * buf->length); buf->pIndex = buf->pBegin; buf->filled = false; } } } float Ultrasonic::unbiasedStdDev(float value, size_t bufNum) { float result = 0.0; if(_pBuffers) { BufCtl *buf = &_pBuffers[bufNum]; if(buf->length > 1) { _sampleUpdate(buf, float(value)); if(buf->filled) { float sum = 0.0, mean, tmp; for(size_t i = 0; i < buf->length; i++) sum += buf->pBegin[i]; mean = sum / buf->length; sum = 0.0; for(size_t i = 0; i < buf->length; i++) { tmp = buf->pBegin[i] - mean; sum += (tmp * tmp); } result = sqrt(sum / (buf->length - 1)); //Serial.print(bufNum); //Serial.print(" : "); //Serial.println(result); } } } return result; } void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec) { if(buf->pIndex >= (buf->pBegin + buf->length)) { buf->pIndex = buf->pBegin; buf->filled = true; } *(buf->pIndex++) = msec; } void Ultrasonic::_freeBuffers() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; free(buf->pBegin); } free(_pBuffers); } } #endif // COMPILE_STD_DEV <commit_msg>Updated header name.<commit_after>/* * Ultrasonic.cpp - Library for HC-SR04 Ultrasonic Sensing Module. * * With ideas from: * Created by ITead studio. Apr 20, 2010. * iteadstudio.com * * SVN Keywords * ---------------------------------- * $Author$ * $Date$ * $Revision$ * ---------------------------------- */ #include <stdlib.h> #include <string.h> #include <HCSR04Ultrasonic.h> Ultrasonic::Ultrasonic(int tp, int ep) { pinMode(tp, OUTPUT); pinMode(ep, INPUT); _trigPin = tp; _echoPin = ep; _multiplier = MULTIPLIER_DEFAULT; /* Don't allow a maximum distance farther than the sensor supports. */ _maxDistance = _MAX_CM_DISTANCE; _pingTimeout = _maxDistance * _PING_OVERHEAD; _temp = _TEMP_CELSIUS_DEFAULT; } long Ultrasonic::timing(void) { digitalWrite(_trigPin, LOW); delayMicroseconds(2); digitalWrite(_trigPin, HIGH); delayMicroseconds(10); digitalWrite(_trigPin, LOW); return pulseIn(_echoPin, HIGH, _pingTimeout); } float Ultrasonic::convert(long microsec, int metric) { // 0.5 * 331.29 * (1 + _temp/273)^0.5 * (microsec * 0.0001) * _multiplier float dist = min(0.0165645 * pow(1 + _temp/273, 0.5) * microsec * _multiplier, _maxDistance); if(metric) return dist; else return dist * 0.3937; } void Ultrasonic::setMultiplier(float value) { _multiplier = value; } void Ultrasonic::setTemperature(float value) { _temp = value; } void Ultrasonic::setMaxDistance(int value) { _maxDistance = min(value, _MAX_CM_DISTANCE); _pingTimeout = _maxDistance * _PING_OVERHEAD; } #ifdef COMPILE_STD_DEV bool Ultrasonic::sampleCreate(size_t numBufs, ...) { bool result = false; va_list ap; _numBufs = numBufs; if((_pBuffers = (BufCtl *) calloc(numBufs, sizeof(BufCtl))) != NULL) { va_start(ap, numBufs); BufCtl *buf; size_t smpSize; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; smpSize = va_arg(ap, size_t); if((buf->pBegin = (float *) calloc(smpSize, sizeof(float))) != NULL) { buf->pIndex = buf->pBegin; buf->length = smpSize; buf->filled = false; result = true; } else { result = false; break; } } va_end(ap); } if(!result) _freeBuffers(); return result; } void Ultrasonic::sampleClear() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; memset(buf, '\0', sizeof(float) * buf->length); buf->pIndex = buf->pBegin; buf->filled = false; } } } float Ultrasonic::unbiasedStdDev(float value, size_t bufNum) { float result = 0.0; if(_pBuffers) { BufCtl *buf = &_pBuffers[bufNum]; if(buf->length > 1) { _sampleUpdate(buf, float(value)); if(buf->filled) { float sum = 0.0, mean, tmp; for(size_t i = 0; i < buf->length; i++) sum += buf->pBegin[i]; mean = sum / buf->length; sum = 0.0; for(size_t i = 0; i < buf->length; i++) { tmp = buf->pBegin[i] - mean; sum += (tmp * tmp); } result = sqrt(sum / (buf->length - 1)); //Serial.print(bufNum); //Serial.print(" : "); //Serial.println(result); } } } return result; } void Ultrasonic::_sampleUpdate(BufCtl *buf, float msec) { if(buf->pIndex >= (buf->pBegin + buf->length)) { buf->pIndex = buf->pBegin; buf->filled = true; } *(buf->pIndex++) = msec; } void Ultrasonic::_freeBuffers() { if(_pBuffers) { BufCtl *buf; for(size_t i = 0; i < _numBufs; i++) { buf = &_pBuffers[i]; free(buf->pBegin); } free(_pBuffers); } } #endif // COMPILE_STD_DEV <|endoftext|>
<commit_before>#include "manageescrowdialog.h" #include "ui_manageescrowdialog.h" #include "guiutil.h" #include "syscoingui.h" #include "ui_interface.h" #include <QDataWidgetMapper> #include <QMessageBox> #include "rpcserver.h" using namespace std; extern const CRPCTable tableRPC; ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) : QDialog(parent), ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total) { ui->setupUi(this); EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter); ui->manageInfo->setText(tr("You are managing escrow ID: <b>%1</b> of an offer for <b>%2</b> totalling <b>%3</b>SYS. The buyer is <b>%4</b>, seller is <b>%5</b> and arbiter is <b>%6</b>").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter)); if(escrowType == None) { ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases.")); ui->releaseButton->setEnabled(false); ui->refundButton->setEnabled(false); } else if(status == "in-escrow") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer.")); ui->refundButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow, you may refund the coins back to the buyer.")); ui->releaseButton->setEnabled(false); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("You are the <b>arbiter</b> of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision.")); } } else if(status == "escrow released") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow. The payment of coins have been released to you, you may claim them now.")); ui->refundButton->setEnabled(false); ui->releaseButton->setText(tr("Claim Payment")); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } else if(status == "escrow refunded") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow. The coins have been refunded back to you, you may claim them now.")); ui->refundButton->setText(tr("Claim Refund")); ui->releaseButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } else if(status == "complete") { ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else { ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } void ManageEscrowDialog::on_cancelButton_clicked() { reject(); } ManageEscrowDialog::~ManageEscrowDialog() { delete ui; } void ManageEscrowDialog::on_releaseButton_clicked() { UniValue params(UniValue::VARR); string strMethod = string("escrowrelease"); params.push_back(escrow.toStdString()); try { UniValue result = tableRPC.execute(strMethod, params); QMessageBox::information(this, windowTitle(), tr("Escrow released successfully!"), QMessageBox::Ok, QMessageBox::Ok); ManageEscrowDialog::accept(); } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception releasing escrow"), QMessageBox::Ok, QMessageBox::Ok); } } void ManageEscrowDialog::on_refundButton_clicked() { UniValue params(UniValue::VARR); string strMethod = string("escrowrefund"); params.push_back(escrow.toStdString()); try { UniValue result = tableRPC.execute(strMethod, params); QMessageBox::information(this, windowTitle(), tr("Escrow refunded successfully!"), QMessageBox::Ok, QMessageBox::Ok); ManageEscrowDialog::accept(); } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception refunding escrow"), QMessageBox::Ok, QMessageBox::Ok); } } ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter) { if(isYourAlias(buyer)) return EscrowType::Buyer; else if(isYourAlias(seller)) return EscrowType::Seller; else if(isYourArbiter(arbiter)) return EscrowType::Arbiter; else return EscrowType::None; } bool ManageEscrowDialog::isYourAlias(const QString &alias) { string strMethod = string("aliasinfo"); UniValue params(UniValue::VARR); UniValue result ; string name_str; int expired = 0; params.push_back(alias.toStdString()); try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VOBJ) { const UniValue& o = result.get_obj(); const UniValue& mine_value = find_value(o, "ismine"); if (mine_value.type() == UniValue::VBOOL) return mine_value.get_bool(); } } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } return false; } <commit_msg>typo<commit_after>#include "manageescrowdialog.h" #include "ui_manageescrowdialog.h" #include "guiutil.h" #include "syscoingui.h" #include "ui_interface.h" #include <QDataWidgetMapper> #include <QMessageBox> #include "rpcserver.h" using namespace std; extern const CRPCTable tableRPC; ManageEscrowDialog::ManageEscrowDialog(const QString &escrow, const QString &buyer, const QString &seller, const QString &arbiter, const QString &status, const QString &offertitle, const QString &total,QWidget *parent) : QDialog(parent), ui(new Ui::ManageEscrowDialog), escrow(escrow), buyer(buyer), seller(seller), arbiter(arbiter), status(status),offertitle(offertitle), total(total) { ui->setupUi(this); EscrowType escrowType = findYourEscrowRoleFromAliases(buyer, seller, arbiter); ui->manageInfo->setText(tr("You are managing escrow ID: <b>%1</b> of an offer for <b>%2</b> totalling <b>%3</b>SYS. The buyer is <b>%4</b>, seller is <b>%5</b> and arbiter is <b>%6</b>").arg(escrow).arg(offertitle).arg(total).arg(buyer).arg(seller).arg(arbiter)); if(escrowType == None) { ui->manageInfo2->setText(tr("You cannot manage this escrow because you do not own one of either the buyer, seller or arbiter aliases.")); ui->releaseButton->setEnabled(false); ui->refundButton->setEnabled(false); } else if(status == "in-escrow") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow, you may release the coins to the seller once you have confirmed that you have recieved the item as per the description of the offer.")); ui->refundButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow, you may refund the coins back to the buyer.")); ui->releaseButton->setEnabled(false); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("You are the <b>arbiter</b> of the offer held in escrow, you may refund the coins back to the buyer if you have evidence that the seller did not honour the agreement to ship the offer item. You may also release the coins to the seller if the buyer has not released. You may use Syscoin messages to communicate with the buyer and seller to ensure you have adequeate proof for your decision.")); } } else if(status == "escrow released") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You may communicate with your arbiter or seller via Syscoin messages.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("You are the <b>seller</b> of the offer held in escrow. The payment of coins have been released to you, you may claim them now.")); ui->refundButton->setEnabled(false); ui->releaseButton->setText(tr("Claim Payment")); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("The escrow has already been released to the seller. You're job is done, if you were the one to release the coins you will recieve a commission as soon as the seller claims his payment.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } else if(status == "escrow refunded") { if(escrowType == Buyer) { ui->manageInfo2->setText(tr("You are the <b>buyer</b> of the offer held in escrow. The coins have been refunded back to you, you may claim them now.")); ui->refundButton->setText(tr("Claim Refund")); ui->releaseButton->setEnabled(false); } else if(escrowType == Seller) { ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else if(escrowType == Arbiter) { ui->manageInfo2->setText(tr("The escrow has already been refunded back to the buyer. You're job is done, if you were the one to refund the coins you will recieve a commission as soon as the buyer claims his refund.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } else if(status == "complete") { ui->manageInfo2->setText(tr("The escrow has been successfully claimed by the seller. The escrow is complete.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } else { ui->manageInfo2->setText(tr("The escrow status was not recognized. Please contact the Syscoin team.")); ui->refundButton->setEnabled(false); ui->releaseButton->setEnabled(false); } } void ManageEscrowDialog::on_cancelButton_clicked() { reject(); } ManageEscrowDialog::~ManageEscrowDialog() { delete ui; } void ManageEscrowDialog::on_releaseButton_clicked() { UniValue params(UniValue::VARR); string strMethod = string("escrowrelease"); params.push_back(escrow.toStdString()); try { UniValue result = tableRPC.execute(strMethod, params); QMessageBox::information(this, windowTitle(), tr("Escrow released successfully!"), QMessageBox::Ok, QMessageBox::Ok); ManageEscrowDialog::accept(); } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error releasing escrow: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception releasing escrow"), QMessageBox::Ok, QMessageBox::Ok); } } void ManageEscrowDialog::on_refundButton_clicked() { UniValue params(UniValue::VARR); string strMethod = string("escrowrefund"); params.push_back(escrow.toStdString()); try { UniValue result = tableRPC.execute(strMethod, params); QMessageBox::information(this, windowTitle(), tr("Escrow refunded successfully!"), QMessageBox::Ok, QMessageBox::Ok); ManageEscrowDialog::accept(); } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Error refunding escrow: \"%1\"").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("General exception refunding escrow"), QMessageBox::Ok, QMessageBox::Ok); } } ManageEscrowDialog::EscrowType ManageEscrowDialog::findYourEscrowRoleFromAliases(const QString &buyer, const QString &seller, const QString &arbiter) { if(isYourAlias(buyer)) return Buyer; else if(isYourAlias(seller)) return Seller; else if(isYourArbiter(arbiter)) return Arbiter; else return None; } bool ManageEscrowDialog::isYourAlias(const QString &alias) { string strMethod = string("aliasinfo"); UniValue params(UniValue::VARR); UniValue result ; string name_str; int expired = 0; params.push_back(alias.toStdString()); try { result = tableRPC.execute(strMethod, params); if (result.type() == UniValue::VOBJ) { const UniValue& o = result.get_obj(); const UniValue& mine_value = find_value(o, "ismine"); if (mine_value.type() == UniValue::VBOOL) return mine_value.get_bool(); } } catch (UniValue& objError) { string strError = find_value(objError, "message").get_str(); QMessageBox::critical(this, windowTitle(), tr("Could not refresh cert list: %1").arg(QString::fromStdString(strError)), QMessageBox::Ok, QMessageBox::Ok); } catch(std::exception& e) { QMessageBox::critical(this, windowTitle(), tr("There was an exception trying to refresh the cert list: ") + QString::fromStdString(e.what()), QMessageBox::Ok, QMessageBox::Ok); } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inputhdl.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:33:37 $ * * 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 SC_INPUTHDL_HXX #define SC_INPUTHDL_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif class ScDocument; class ScTabView; class ScTabViewShell; class ScInputWindow; class ScPatternAttr; class EditEngine; class ScEditEngineDefaulter; class EditView; class EditTextObject; class ScInputHdlState; class TypedStrCollection; class ScRangeFindList; class Timer; class KeyEvent; class CommandEvent; struct ESelection; //======================================================================== // ScInputHandler //======================================================================== class ScInputHandler { private: ScInputWindow* pInputWin; ScEditEngineDefaulter* pEngine; // editierte Daten in der Tabelle EditView* pTableView; // aktive EditView dazu EditView* pTopView; // EditView in der Eingabezeile TypedStrCollection* pColumnData; TypedStrCollection* pFormulaData; ULONG nTipVisible; String aManualTip; String aAutoSearch; USHORT nAutoPos; BOOL bUseTab; // Blaettern moeglich BOOL bTextValid; // Text noch nicht in Edit-Engine String aCurrentText; String aFormText; // fuer Funktions-Autopilot xub_StrLen nFormSelStart; // Selektion fuer Funktions-Autopilot xub_StrLen nFormSelEnd; USHORT nAutoPar; // autom.parentheses than can be overwritten ScAddress aCursorPos; ScInputMode eMode; BOOL bModified; BOOL bSelIsRef; BOOL bFormulaMode; BOOL bInRangeUpdate; BOOL bParenthesisShown; BOOL bCreatingFuncView; BOOL bInEnterHandler; BOOL bCommandErrorShown; BOOL bInOwnChange; BOOL bProtected; BOOL bCellHasPercentFormat; ULONG nValidation; USHORT nAttrAdjust; // enum SvxCellHorJustify Fraction aScaleX; // fuer Ref-MapMode Fraction aScaleY; ScTabViewShell* pRefViewSh; ScTabViewShell* pActiveViewSh; const ScPatternAttr* pLastPattern; SfxItemSet* pEditDefaults; BOOL bLastIsSymbol; ScInputHdlState* pLastState; Timer* pDelayTimer; ScRangeFindList* pRangeFindList; static BOOL bAutoComplete; // aus App-Optionen static BOOL bOptLoaded; #ifdef _INPUTHDL_CXX private: void UpdateActiveView(); void SetAllUpdateMode( BOOL bUpdate ); void SyncViews( EditView* pSourceView = NULL ); BOOL StartTable( sal_Unicode cTyped, BOOL bFromCommand ); void RemoveSelection(); void UpdateFormulaMode(); void InvalidateAttribs(); void ImplCreateEditEngine(); DECL_LINK( DelayTimer, Timer* ); void GetColData(); void UseColData(); void NextAutoEntry( BOOL bBack ); void UpdateAdjust( sal_Unicode cTyped ); void GetFormulaData(); void UseFormulaData(); void NextFormulaEntry( BOOL bBack ); void PasteFunctionData(); void PasteManualTip(); EditView* GetFuncEditView(); void RemoveAdjust(); void RemoveRangeFinder(); void DeleteRangeFinder(); void UpdateParenthesis(); void UpdateAutoCorrFlag(); void ResetAutoPar(); void AutoParAdded(); BOOL CursorAtClosingPar(); void SkipClosingPar(); void StopInputWinEngine( BOOL bAll ); DECL_LINK( ModifyHdl, void* ); #endif public: ScInputHandler(); virtual ~ScInputHandler(); void SetMode( ScInputMode eNewMode ); BOOL IsInputMode() const { return (eMode != SC_INPUT_NONE); } BOOL IsEditMode() const { return (eMode != SC_INPUT_NONE && eMode != SC_INPUT_TYPE); } BOOL IsTopMode() const { return (eMode == SC_INPUT_TOP); } const String& GetEditString(); const String& GetFormString() const { return aFormText; } BOOL GetTextAndFields( ScEditEngineDefaulter& rDestEngine ); BOOL KeyInput( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE ); void EnterHandler( BYTE nBlockMode = 0 ); void CancelHandler(); void SetReference( const ScRange& rRef, ScDocument* pDoc ); void AddRefEntry(); BOOL InputCommand( const CommandEvent& rCEvt, BOOL bForce ); void InsertFunction( const String& rFuncName, BOOL bAddPar = TRUE ); void ClearText(); void InputSelection( EditView* pView ); void InputChanged( EditView* pView, BOOL bFromNotify = FALSE ); void ViewShellGone(ScTabViewShell* pViewSh); void SetRefViewShell(ScTabViewShell* pRefVsh) {pRefViewSh=pRefVsh;} void NotifyChange( const ScInputHdlState* pState, BOOL bForce = FALSE, ScTabViewShell* pSourceSh = NULL, BOOL bStopEditing = TRUE); void ResetDelayTimer(); //BugId 54702 void HideTip(); void ShowTip( const String& rText ); // am Cursor void SetRefScale( const Fraction& rX, const Fraction& rY ); void UpdateRefDevice(); EditView* GetActiveView(); EditView* GetTableView() { return pTableView; } EditView* GetTopView() { return pTopView; } BOOL DataChanging( sal_Unicode cTyped = 0, BOOL bFromCommand = FALSE ); void DataChanged( BOOL bFromTopNotify = FALSE ); BOOL TakesReturn() const { return ( nTipVisible != 0 ); } void SetModified() { bModified = TRUE; } BOOL GetSelIsRef() const { return bSelIsRef; } void SetSelIsRef(BOOL bSet) { bSelIsRef = bSet; } void ShowRefFrame(); ScRangeFindList* GetRangeFindList() { return pRangeFindList; } void UpdateRange( USHORT nIndex, const ScRange& rNew ); // Kommunikation mit Funktionsautopilot void InputGetSelection ( xub_StrLen& rStart, xub_StrLen& rEnd ); void InputSetSelection ( xub_StrLen nStart, xub_StrLen nEnd ); void InputReplaceSelection ( const String& rStr ); String InputGetFormulaStr (); BOOL IsFormulaMode() const { return bFormulaMode; } ScInputWindow* GetInputWindow() { return pInputWin; } void SetInputWindow( ScInputWindow* pNew ) { pInputWin = pNew; } BOOL IsInEnterHandler() const { return bInEnterHandler; } BOOL IsInOwnChange() const { return bInOwnChange; } BOOL IsModalMode( SfxObjectShell* pDocSh ); void ActivateInputWindow( const String& rText, const ESelection& rSel ); void ForgetLastPattern(); void UpdateSpellSettings( BOOL bFromStartTab = FALSE ); void FormulaPreview(); Size GetTextSize(); // in 1/100mm // eigentlich private, fuer SID_INPUT_SUM public void InitRangeFinder( const String& rFormula ); static void SetAutoComplete(BOOL bSet) { bAutoComplete = bSet; } }; //======================================================================== // ScInputHdlState //======================================================================== class ScInputHdlState { friend class ScInputHandler; public: ScInputHdlState( const ScAddress& rCurPos, const ScAddress& rStartPos, const ScAddress& rEndPos, const String& rString, const EditTextObject* pData ); ScInputHdlState( const ScInputHdlState& rCpy ); ~ScInputHdlState(); ScInputHdlState& operator= ( const ScInputHdlState& r ); int operator==( const ScInputHdlState& r ) const; int operator!=( const ScInputHdlState& r ) const { return !operator==( r ); } const ScAddress& GetPos() const { return aCursorPos; } const ScAddress& GetStartPos() const { return aStartPos; } const ScAddress& GetEndPos() const { return aEndPos; } const String& GetString() const { return aString; } const EditTextObject* GetEditData() const { return pEditData; } private: ScAddress aCursorPos; ScAddress aStartPos; ScAddress aEndPos; String aString; EditTextObject* pEditData; }; #endif <commit_msg>INTEGRATION: CWS dr43 (1.13.42); FILE MERGED 2005/11/23 13:09:27 nn 1.13.42.1: #125841# StopInputWinEngine public<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: inputhdl.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: rt $ $Date: 2006-01-13 17:04:03 $ * * 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 SC_INPUTHDL_HXX #define SC_INPUTHDL_HXX #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif #ifndef _FRACT_HXX //autogen #include <tools/fract.hxx> #endif #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif class ScDocument; class ScTabView; class ScTabViewShell; class ScInputWindow; class ScPatternAttr; class EditEngine; class ScEditEngineDefaulter; class EditView; class EditTextObject; class ScInputHdlState; class TypedStrCollection; class ScRangeFindList; class Timer; class KeyEvent; class CommandEvent; struct ESelection; //======================================================================== // ScInputHandler //======================================================================== class ScInputHandler { private: ScInputWindow* pInputWin; ScEditEngineDefaulter* pEngine; // editierte Daten in der Tabelle EditView* pTableView; // aktive EditView dazu EditView* pTopView; // EditView in der Eingabezeile TypedStrCollection* pColumnData; TypedStrCollection* pFormulaData; ULONG nTipVisible; String aManualTip; String aAutoSearch; USHORT nAutoPos; BOOL bUseTab; // Blaettern moeglich BOOL bTextValid; // Text noch nicht in Edit-Engine String aCurrentText; String aFormText; // fuer Funktions-Autopilot xub_StrLen nFormSelStart; // Selektion fuer Funktions-Autopilot xub_StrLen nFormSelEnd; USHORT nAutoPar; // autom.parentheses than can be overwritten ScAddress aCursorPos; ScInputMode eMode; BOOL bModified; BOOL bSelIsRef; BOOL bFormulaMode; BOOL bInRangeUpdate; BOOL bParenthesisShown; BOOL bCreatingFuncView; BOOL bInEnterHandler; BOOL bCommandErrorShown; BOOL bInOwnChange; BOOL bProtected; BOOL bCellHasPercentFormat; ULONG nValidation; USHORT nAttrAdjust; // enum SvxCellHorJustify Fraction aScaleX; // fuer Ref-MapMode Fraction aScaleY; ScTabViewShell* pRefViewSh; ScTabViewShell* pActiveViewSh; const ScPatternAttr* pLastPattern; SfxItemSet* pEditDefaults; BOOL bLastIsSymbol; ScInputHdlState* pLastState; Timer* pDelayTimer; ScRangeFindList* pRangeFindList; static BOOL bAutoComplete; // aus App-Optionen static BOOL bOptLoaded; #ifdef _INPUTHDL_CXX private: void UpdateActiveView(); void SetAllUpdateMode( BOOL bUpdate ); void SyncViews( EditView* pSourceView = NULL ); BOOL StartTable( sal_Unicode cTyped, BOOL bFromCommand ); void RemoveSelection(); void UpdateFormulaMode(); void InvalidateAttribs(); void ImplCreateEditEngine(); DECL_LINK( DelayTimer, Timer* ); void GetColData(); void UseColData(); void NextAutoEntry( BOOL bBack ); void UpdateAdjust( sal_Unicode cTyped ); void GetFormulaData(); void UseFormulaData(); void NextFormulaEntry( BOOL bBack ); void PasteFunctionData(); void PasteManualTip(); EditView* GetFuncEditView(); void RemoveAdjust(); void RemoveRangeFinder(); void DeleteRangeFinder(); void UpdateParenthesis(); void UpdateAutoCorrFlag(); void ResetAutoPar(); void AutoParAdded(); BOOL CursorAtClosingPar(); void SkipClosingPar(); DECL_LINK( ModifyHdl, void* ); #endif public: ScInputHandler(); virtual ~ScInputHandler(); void SetMode( ScInputMode eNewMode ); BOOL IsInputMode() const { return (eMode != SC_INPUT_NONE); } BOOL IsEditMode() const { return (eMode != SC_INPUT_NONE && eMode != SC_INPUT_TYPE); } BOOL IsTopMode() const { return (eMode == SC_INPUT_TOP); } const String& GetEditString(); const String& GetFormString() const { return aFormText; } BOOL GetTextAndFields( ScEditEngineDefaulter& rDestEngine ); BOOL KeyInput( const KeyEvent& rKEvt, BOOL bStartEdit = FALSE ); void EnterHandler( BYTE nBlockMode = 0 ); void CancelHandler(); void SetReference( const ScRange& rRef, ScDocument* pDoc ); void AddRefEntry(); BOOL InputCommand( const CommandEvent& rCEvt, BOOL bForce ); void InsertFunction( const String& rFuncName, BOOL bAddPar = TRUE ); void ClearText(); void InputSelection( EditView* pView ); void InputChanged( EditView* pView, BOOL bFromNotify = FALSE ); void ViewShellGone(ScTabViewShell* pViewSh); void SetRefViewShell(ScTabViewShell* pRefVsh) {pRefViewSh=pRefVsh;} void NotifyChange( const ScInputHdlState* pState, BOOL bForce = FALSE, ScTabViewShell* pSourceSh = NULL, BOOL bStopEditing = TRUE); void ResetDelayTimer(); //BugId 54702 void HideTip(); void ShowTip( const String& rText ); // am Cursor void SetRefScale( const Fraction& rX, const Fraction& rY ); void UpdateRefDevice(); EditView* GetActiveView(); EditView* GetTableView() { return pTableView; } EditView* GetTopView() { return pTopView; } BOOL DataChanging( sal_Unicode cTyped = 0, BOOL bFromCommand = FALSE ); void DataChanged( BOOL bFromTopNotify = FALSE ); BOOL TakesReturn() const { return ( nTipVisible != 0 ); } void SetModified() { bModified = TRUE; } BOOL GetSelIsRef() const { return bSelIsRef; } void SetSelIsRef(BOOL bSet) { bSelIsRef = bSet; } void ShowRefFrame(); ScRangeFindList* GetRangeFindList() { return pRangeFindList; } void UpdateRange( USHORT nIndex, const ScRange& rNew ); // Kommunikation mit Funktionsautopilot void InputGetSelection ( xub_StrLen& rStart, xub_StrLen& rEnd ); void InputSetSelection ( xub_StrLen nStart, xub_StrLen nEnd ); void InputReplaceSelection ( const String& rStr ); String InputGetFormulaStr (); BOOL IsFormulaMode() const { return bFormulaMode; } ScInputWindow* GetInputWindow() { return pInputWin; } void SetInputWindow( ScInputWindow* pNew ) { pInputWin = pNew; } void StopInputWinEngine( BOOL bAll ); BOOL IsInEnterHandler() const { return bInEnterHandler; } BOOL IsInOwnChange() const { return bInOwnChange; } BOOL IsModalMode( SfxObjectShell* pDocSh ); void ActivateInputWindow( const String& rText, const ESelection& rSel ); void ForgetLastPattern(); void UpdateSpellSettings( BOOL bFromStartTab = FALSE ); void FormulaPreview(); Size GetTextSize(); // in 1/100mm // eigentlich private, fuer SID_INPUT_SUM public void InitRangeFinder( const String& rFormula ); static void SetAutoComplete(BOOL bSet) { bAutoComplete = bSet; } }; //======================================================================== // ScInputHdlState //======================================================================== class ScInputHdlState { friend class ScInputHandler; public: ScInputHdlState( const ScAddress& rCurPos, const ScAddress& rStartPos, const ScAddress& rEndPos, const String& rString, const EditTextObject* pData ); ScInputHdlState( const ScInputHdlState& rCpy ); ~ScInputHdlState(); ScInputHdlState& operator= ( const ScInputHdlState& r ); int operator==( const ScInputHdlState& r ) const; int operator!=( const ScInputHdlState& r ) const { return !operator==( r ); } const ScAddress& GetPos() const { return aCursorPos; } const ScAddress& GetStartPos() const { return aStartPos; } const ScAddress& GetEndPos() const { return aEndPos; } const String& GetString() const { return aString; } const EditTextObject* GetEditData() const { return pEditData; } private: ScAddress aCursorPos; ScAddress aStartPos; ScAddress aEndPos; String aString; EditTextObject* pEditData; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: navcitem.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:44:59 $ * * 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 SC_NAVCITEM_HXX #define SC_NAVCITEM_HXX #ifndef _SFXCTRLITEM_HXX //autogen #include <sfx2/ctrlitem.hxx> #endif //================================================================== class ScNavigatorDlg; class ScNavigatorControllerItem : public SfxControllerItem { public: ScNavigatorControllerItem( USHORT nId, ScNavigatorDlg& rDlg, SfxBindings& rBindings ); protected: virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pItem ); private: ScNavigatorDlg& rNavigatorDlg; }; #endif // SC_NAVCITEM_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.942); FILE MERGED 2005/09/05 15:05:36 rt 1.1.1.1.942.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: navcitem.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:39:27 $ * * 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 SC_NAVCITEM_HXX #define SC_NAVCITEM_HXX #ifndef _SFXCTRLITEM_HXX //autogen #include <sfx2/ctrlitem.hxx> #endif //================================================================== class ScNavigatorDlg; class ScNavigatorControllerItem : public SfxControllerItem { public: ScNavigatorControllerItem( USHORT nId, ScNavigatorDlg& rDlg, SfxBindings& rBindings ); protected: virtual void StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pItem ); private: ScNavigatorDlg& rNavigatorDlg; }; #endif // SC_NAVCITEM_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: irendermodule.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2006-12-13 14:37:00 $ * * 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 INCLUDED_CANVAS_IRENDERMODULE_HXX #define INCLUDED_CANVAS_IRENDERMODULE_HXX #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #include <boost/shared_ptr.hpp> #include <boost/utility.hpp> namespace basegfx { class B2DRange; class B2IRange; class B2IVector; class B2IPoint; } namespace canvas { struct ISurface; struct Vertex { float r,g,b,a; float u,v; float x,y,z; }; /** Output module interface for backend render implementations. Implement this interface for each operating system- or library-specific rendering backend, which needs coupling with the canvas rendering framework (which can be shared between all backend implementations). */ struct IRenderModule { /** Type of primitive passed to the render module via pushVertex() */ enum PrimitiveType { PRIMITIVE_TYPE_UNKNOWN, PRIMITIVE_TYPE_TRIANGLE, PRIMITIVE_TYPE_QUAD }; virtual ~IRenderModule() {} /// Lock rendermodule against concurrent access virtual void lock() const = 0; /// Unlock rendermodule for concurrent access virtual void unlock() const = 0; /** Maximal size of VRAM pages available This is typically the maximum texture size of the hardware, or some arbitrary limit if the backend is software. */ virtual ::basegfx::B2IVector getPageSize() = 0; /** Create a (possibly hardware-accelerated) surface @return a pointer to a surface, which is an abstraction of a piece of (possibly hardware-accelerated) texture memory. */ virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0; /** Begin rendering the given primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void beginPrimitive( PrimitiveType eType ) = 0; /** Finish rendering a primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void endPrimitive() = 0; /** Add given vertex to current primitive After issuing a beginPrimitive(), each pushVertex() adds a vertex to the active primitive. */ virtual void pushVertex( const Vertex& vertex ) = 0; /** Query error status @returns true, if an error occured during primitive construction. */ virtual bool isError() = 0; }; typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr; /// Little RAII wrapper for guarding access to IRenderModule interface class RenderModuleGuard : private ::boost::noncopyable { public: explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) : mpRenderModule( rRenderModule ) { mpRenderModule->lock(); } ~RenderModuleGuard() { mpRenderModule->unlock(); } private: const IRenderModuleSharedPtr mpRenderModule; }; } #endif /* INCLUDED_CANVAS_IRENDERMODULE_HXX */ <commit_msg>INTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008/04/01 15:03:04 thb 1.3.80.2: #i85898# Stripping all external header guards 2008/03/28 16:34:54 rt 1.3.80.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: irendermodule.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef INCLUDED_CANVAS_IRENDERMODULE_HXX #define INCLUDED_CANVAS_IRENDERMODULE_HXX #include <sal/types.h> #include <boost/shared_ptr.hpp> #include <boost/utility.hpp> namespace basegfx { class B2DRange; class B2IRange; class B2IVector; class B2IPoint; } namespace canvas { struct ISurface; struct Vertex { float r,g,b,a; float u,v; float x,y,z; }; /** Output module interface for backend render implementations. Implement this interface for each operating system- or library-specific rendering backend, which needs coupling with the canvas rendering framework (which can be shared between all backend implementations). */ struct IRenderModule { /** Type of primitive passed to the render module via pushVertex() */ enum PrimitiveType { PRIMITIVE_TYPE_UNKNOWN, PRIMITIVE_TYPE_TRIANGLE, PRIMITIVE_TYPE_QUAD }; virtual ~IRenderModule() {} /// Lock rendermodule against concurrent access virtual void lock() const = 0; /// Unlock rendermodule for concurrent access virtual void unlock() const = 0; /** Maximal size of VRAM pages available This is typically the maximum texture size of the hardware, or some arbitrary limit if the backend is software. */ virtual ::basegfx::B2IVector getPageSize() = 0; /** Create a (possibly hardware-accelerated) surface @return a pointer to a surface, which is an abstraction of a piece of (possibly hardware-accelerated) texture memory. */ virtual ::boost::shared_ptr<ISurface> createSurface( const ::basegfx::B2IVector& surfaceSize ) = 0; /** Begin rendering the given primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void beginPrimitive( PrimitiveType eType ) = 0; /** Finish rendering a primitive. Each beginPrimitive() call must be matched with an endPrimitive() call. */ virtual void endPrimitive() = 0; /** Add given vertex to current primitive After issuing a beginPrimitive(), each pushVertex() adds a vertex to the active primitive. */ virtual void pushVertex( const Vertex& vertex ) = 0; /** Query error status @returns true, if an error occured during primitive construction. */ virtual bool isError() = 0; }; typedef ::boost::shared_ptr< IRenderModule > IRenderModuleSharedPtr; /// Little RAII wrapper for guarding access to IRenderModule interface class RenderModuleGuard : private ::boost::noncopyable { public: explicit RenderModuleGuard( const IRenderModuleSharedPtr& rRenderModule ) : mpRenderModule( rRenderModule ) { mpRenderModule->lock(); } ~RenderModuleGuard() { mpRenderModule->unlock(); } private: const IRenderModuleSharedPtr mpRenderModule; }; } #endif /* INCLUDED_CANVAS_IRENDERMODULE_HXX */ <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <ctime> #include <cstdio> #include <boost/filesystem.hpp> #include "gflags/gflags.h" #include "jsoncons/json.hpp" #include "utils/protocol.h" #include "utils/connection.h" #include "bots/bot_interface.h" #include "bots/raw_bot.h" #include "bots/basic/bot.h" #include "bots/tomek/bot.h" #include "bots/piotr/bot.h" #include "bots/greedy/bot.h" #include "bots/stepping/bot.h" #include "bots/constant/bot.h" #include "bots/kamikaze/bot.h" #include "game/simulator.h" DECLARE_string(race_id); DECLARE_string(throttle_scheduler); DECLARE_string(switch_scheduler); DEFINE_string(track, "keimola", "The track to run simulator on."); DEFINE_int32(physics, 0, "The physics to use"); std::string random_race_id() { char buffer[80]; sprintf (buffer, "%d", rand()); return std::string(buffer); } int main(int argc, char** argv) { std::vector<std::pair<std::vector<double>, std::vector<double> > > physics; physics = { {{0.98, 0.2 }, {1.9, -0.9, -0.00125, 0.00125 * sqrt(180000), 0.3}}, {{0.98, 0.168896}, {1.9, -0.9, -0.00118604, 0.483757, 0.284649}}, {{0.98, 0.233986}, {1.9, -0.9, -0.00120513, 0.497467, 0.289232}}, {{0.98, 0.214027}, {1.9, -0.9, -0.00127153, 0.546417, 0.305167}}, {{0.98, 0.17629 }, {1.9, -0.9, -0.00130643, 0.572936, 0.313544}}, {{0.98, 0.198433}, {1.9, -0.9, -0.00129546, 0.56454 , 0.31091 }}, {{0.98, 0.210197}, {1.9, -0.9, -0.00121806, 0.506844, 0.292334}}, }; // FLAGS_throttle_scheduler = "BinaryThrottleScheduler"; // FLAGS_switch_scheduler = "NeverSwitchScheduler"; gflags::ParseCommandLineFlags(&argc, &argv, true); srand (time(NULL)); if (FLAGS_race_id.empty()) { FLAGS_race_id = random_race_id(); } boost::filesystem::create_directories("bin/" + FLAGS_race_id); game::Simulator::Result result; { std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::stepping::Bot())); std::unique_ptr<game::Simulator> simulator(new game::Simulator()); game::Simulator::Options options; options.physics_params = game::PhysicsParams::Load(); options.physics_params.velocity_model_params.model = physics[FLAGS_physics].first; options.physics_params.drift_model_params.model = physics[FLAGS_physics].second; options.track_name = FLAGS_track; result = simulator->Run(bot.get(), options); } std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl; std::cout << "TOTAL TICKS: " << result.total_ticks << std::endl; std::cout << "TOTAL DISTANCE: " << result.total_distance << std::endl; std::cout << "MAX TICK TIME: " << result.max_tick_time_ms << " ms" << std::endl; std::cout << "AVG TICK TIME: " << result.avg_tick_time_ms << " ms" << std::endl; if (result.crashed) { std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl; } return 0; } <commit_msg>Add 100 physics<commit_after>#include <iostream> #include <string> #include <ctime> #include <cstdio> #include <boost/filesystem.hpp> #include "gflags/gflags.h" #include "jsoncons/json.hpp" #include "utils/protocol.h" #include "utils/connection.h" #include "bots/bot_interface.h" #include "bots/raw_bot.h" #include "bots/basic/bot.h" #include "bots/tomek/bot.h" #include "bots/piotr/bot.h" #include "bots/greedy/bot.h" #include "bots/stepping/bot.h" #include "bots/constant/bot.h" #include "bots/kamikaze/bot.h" #include "game/simulator.h" DECLARE_string(race_id); DECLARE_string(throttle_scheduler); DECLARE_string(switch_scheduler); DEFINE_string(track, "keimola", "The track to run simulator on."); DEFINE_int32(physics, 0, "The physics to use"); std::string random_race_id() { char buffer[80]; sprintf (buffer, "%d", rand()); return std::string(buffer); } namespace { double range(double a, double b) { double r = double(rand() % 1000000) / 1000000.0; return a + r * (b-a); } } // anonymous namespace int main(int argc, char** argv) { std::vector<std::pair<std::vector<double>, std::vector<double> > > physics; physics = { {{0.98, 0.2 }, {1.9, -0.9, -0.00125, 0.00125 * sqrt(180000), 0.3}}, {{0.98, 0.168896}, {1.9, -0.9, -0.00118604, 0.483757, 0.284649}}, {{0.98, 0.233986}, {1.9, -0.9, -0.00120513, 0.497467, 0.289232}}, {{0.98, 0.214027}, {1.9, -0.9, -0.00127153, 0.546417, 0.305167}}, {{0.98, 0.17629 }, {1.9, -0.9, -0.00130643, 0.572936, 0.313544}}, {{0.98, 0.198433}, {1.9, -0.9, -0.00129546, 0.56454 , 0.31091 }}, {{0.98, 0.210197}, {1.9, -0.9, -0.00121806, 0.506844, 0.292334}}, }; srand(123456789); while (physics.size() < 100) { // speed_decay acceleration angle_decay angle_change_speed target_angle_fac target_angle_treshold physics.push_back({{range(0.9, 0.99), range(0.1, 0.5)}, {1.9, -0.9, range(-0.001, -0.002), range(0.3, 0.7), range(0.25, 0.35)}}); /*printf("{%lf %lf}{%lf %lf %lf %lf}\n", physics.back().first[0], physics.back().first[1], physics.back().second[0], physics.back().second[1], physics.back().second[2], physics.back().second[3] );*/ } // FLAGS_throttle_scheduler = "BinaryThrottleScheduler"; // FLAGS_switch_scheduler = "NeverSwitchScheduler"; gflags::ParseCommandLineFlags(&argc, &argv, true); srand (time(NULL)); if (FLAGS_race_id.empty()) { FLAGS_race_id = random_race_id(); } boost::filesystem::create_directories("bin/" + FLAGS_race_id); game::Simulator::Result result; { std::unique_ptr<bots::RawBot> bot(new bots::RawBot(new bots::stepping::Bot())); std::unique_ptr<game::Simulator> simulator(new game::Simulator()); game::Simulator::Options options; options.physics_params = game::PhysicsParams::Load(); options.physics_params.velocity_model_params.model = physics[FLAGS_physics].first; options.physics_params.drift_model_params.model = physics[FLAGS_physics].second; options.track_name = FLAGS_track; result = simulator->Run(bot.get(), options); } std::cout << "BEST LAP: " << result.best_lap_time_in_ticks << std::endl; std::cout << "TOTAL TICKS: " << result.total_ticks << std::endl; std::cout << "TOTAL DISTANCE: " << result.total_distance << std::endl; std::cout << "MAX TICK TIME: " << result.max_tick_time_ms << " ms" << std::endl; std::cout << "AVG TICK TIME: " << result.avg_tick_time_ms << " ms" << std::endl; if (result.crashed) { std::cout << "CRASHED !!!!!!!!!!!!!" << std::endl; } return 0; } <|endoftext|>
<commit_before>#include "xchainer/op_node.h" #include <algorithm> #include <cassert> #include <functional> #include <memory> #include <tuple> #include <utility> #include <vector> #include "xchainer/array_node.h" #include "xchainer/backward.h" #include "xchainer/graph.h" namespace xchainer { namespace internal { OpNodeBackwardEntry::OpNodeBackwardEntry( OpNode& op_node, std::vector<nonstd::optional<size_t>> next_array_node_indices, BackwardFunction backward_func) : op_node_{op_node}, next_array_node_indices_{std::move(next_array_node_indices)}, backward_func_{std::move(backward_func)} {} std::vector<std::shared_ptr<ArrayNode>> OpNodeBackwardEntry::GetNextArrayNodes() const { std::vector<std::shared_ptr<ArrayNode>> array_nodes; array_nodes.reserve(next_array_node_indices_.size()); for (nonstd::optional<size_t> index : next_array_node_indices_) { if (index.has_value()) { array_nodes.emplace_back(gsl::at(op_node_.next_array_nodes(), *index)); } else { array_nodes.emplace_back(nullptr); } } return array_nodes; } void OpNodeBackwardEntry::AddExoticNextArrayNode(std::tuple<GraphId, std::vector<std::shared_ptr<ArrayNode>>> next_array_nodes) { assert(std::get<0>(next_array_nodes) != op_node_.graph_id()); exotic_next_array_nodes_.emplace_back(std::move(next_array_nodes)); } } // namespace internal OpNode::OpNode( std::string name, GraphId graph_id, std::vector<std::weak_ptr<ArrayNode>> prev_array_nodes, std::vector<internal::ArrayProps> prev_array_props) : name_{std::move(name)}, graph_id_{graph_id}, prev_array_nodes_{std::move(prev_array_nodes)}, prev_array_props_{std::move(prev_array_props)} { assert(prev_array_props_.size() == prev_array_nodes_.size()); AssertConsistency(); } void OpNode::AssertConsistency() const { #ifndef NDEBUG // No pair of entries may have the same graph ID. assert(std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [this](const auto& tup1) { return std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [&tup1](const auto& tup2) { return &tup1 == &tup2 || std::get<0>(tup1) != std::get<0>(tup2); }); })); // Corresponding previous array nodes across graphs (corresponding to the same output array) should have the same array body, if it's // alive. for (size_t i_prev = 0; i_prev < prev_node_count(); ++i_prev) { nonstd::optional<internal::ArrayBody*> prev_array_body{}; for (const auto& tup : outer_graphs_prev_array_nodes_) { const std::vector<std::shared_ptr<ArrayNode>>& vec = std::get<1>(tup); const std::shared_ptr<ArrayNode>& prev_array_node = vec[i_prev]; std::shared_ptr<internal::ArrayBody> body = prev_array_node->GetBody(); if (!prev_array_body.has_value()) { prev_array_body = body.get(); } else { assert(*prev_array_body == body.get()); } } } #endif // NDEBUG } std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() { assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node != nullptr; })); assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node->graph_id() == graph_id_; })); return next_array_nodes_; } const std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() const { assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node != nullptr; })); assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node->graph_id() == graph_id_; })); return next_array_nodes_; } internal::OpNodeBackwardEntry& OpNode::RegisterBackwardFunction( std::vector<std::shared_ptr<ArrayNode>> next_array_nodes, BackwardFunction backward_func) { AssertConsistency(); assert(!next_array_nodes.empty()); assert(std::all_of(next_array_nodes.begin(), next_array_nodes.end(), [this](const std::shared_ptr<ArrayNode>& next_array_node) { // next_array_node could be nullptr, if the corresponding input array does not require grad. return next_array_node == nullptr || next_array_node->graph_id() == graph_id_; })); // Update the rank of op node for (const std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) { if (next_array_node != nullptr) { rank_ = std::max(rank_, next_array_node->rank() + 1); } } // Store next nodes and record indices of them std::vector<nonstd::optional<size_t>> next_array_node_indices; next_array_node_indices.reserve(next_array_nodes.size()); for (std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) { if (next_array_node != nullptr) { next_array_node_indices.emplace_back(next_array_nodes_.size()); next_array_nodes_.emplace_back(std::move(next_array_node)); } else { next_array_node_indices.emplace_back(nonstd::nullopt); } } // Add backward entry backward_entries_.emplace_back(*this, std::move(next_array_node_indices), std::move(backward_func)); AssertConsistency(); return backward_entries_.back(); } void OpNode::RegisterOuterGraphsPreviousArrayNodes( const GraphId& other_graph_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_prev_array_nodes) { AssertConsistency(); assert(other_graph_id != graph_id_); assert(outer_graphs_prev_array_nodes.size() == prev_array_props_.size()); outer_graphs_prev_array_nodes_.emplace_back(other_graph_id, std::move(outer_graphs_prev_array_nodes)); AssertConsistency(); } namespace internal { std::shared_ptr<ArrayNode> CreatePrevArrayNode(std::shared_ptr<OpNode> op_node, size_t prev_array_node_index) { assert(prev_array_node_index < op_node->prev_node_count()); assert(op_node->prev_array_nodes()[prev_array_node_index].expired()); const internal::ArrayProps& props = op_node->GetPrevArrayProps(prev_array_node_index); auto prev_array_node = std::make_shared<ArrayNode>(props.shape, props.dtype, props.device, op_node->graph_id()); prev_array_node->set_next_op_node(std::move(op_node)); op_node->prev_array_nodes()[prev_array_node_index] = prev_array_node; return prev_array_node; } } // namespace internal } // namespace xchainer <commit_msg>Fix for segfault<commit_after>#include "xchainer/op_node.h" #include <algorithm> #include <cassert> #include <functional> #include <memory> #include <tuple> #include <utility> #include <vector> #include "xchainer/array_node.h" #include "xchainer/backward.h" #include "xchainer/graph.h" namespace xchainer { namespace internal { OpNodeBackwardEntry::OpNodeBackwardEntry( OpNode& op_node, std::vector<nonstd::optional<size_t>> next_array_node_indices, BackwardFunction backward_func) : op_node_{op_node}, next_array_node_indices_{std::move(next_array_node_indices)}, backward_func_{std::move(backward_func)} {} std::vector<std::shared_ptr<ArrayNode>> OpNodeBackwardEntry::GetNextArrayNodes() const { std::vector<std::shared_ptr<ArrayNode>> array_nodes; array_nodes.reserve(next_array_node_indices_.size()); for (nonstd::optional<size_t> index : next_array_node_indices_) { if (index.has_value()) { array_nodes.emplace_back(gsl::at(op_node_.next_array_nodes(), *index)); } else { array_nodes.emplace_back(nullptr); } } return array_nodes; } void OpNodeBackwardEntry::AddExoticNextArrayNode(std::tuple<GraphId, std::vector<std::shared_ptr<ArrayNode>>> next_array_nodes) { assert(std::get<0>(next_array_nodes) != op_node_.graph_id()); exotic_next_array_nodes_.emplace_back(std::move(next_array_nodes)); } } // namespace internal OpNode::OpNode( std::string name, GraphId graph_id, std::vector<std::weak_ptr<ArrayNode>> prev_array_nodes, std::vector<internal::ArrayProps> prev_array_props) : name_{std::move(name)}, graph_id_{graph_id}, prev_array_nodes_{std::move(prev_array_nodes)}, prev_array_props_{std::move(prev_array_props)} { assert(prev_array_props_.size() == prev_array_nodes_.size()); AssertConsistency(); } void OpNode::AssertConsistency() const { #ifndef NDEBUG // No pair of entries may have the same graph ID. assert(std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [this](const auto& tup1) { return std::all_of(outer_graphs_prev_array_nodes_.begin(), outer_graphs_prev_array_nodes_.end(), [&tup1](const auto& tup2) { return &tup1 == &tup2 || std::get<0>(tup1) != std::get<0>(tup2); }); })); // Corresponding previous array nodes across graphs (corresponding to the same output array) should have the same array body, if it's // alive. for (size_t i_prev = 0; i_prev < prev_node_count(); ++i_prev) { nonstd::optional<internal::ArrayBody*> prev_array_body{}; for (const auto& tup : outer_graphs_prev_array_nodes_) { const std::vector<std::shared_ptr<ArrayNode>>& vec = std::get<1>(tup); const std::shared_ptr<ArrayNode>& prev_array_node = vec[i_prev]; std::shared_ptr<internal::ArrayBody> body = prev_array_node->GetBody(); if (!prev_array_body.has_value()) { prev_array_body = body.get(); } else { assert(*prev_array_body == body.get()); } } } #endif // NDEBUG } std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() { assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node != nullptr; })); assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node->graph_id() == graph_id_; })); return next_array_nodes_; } const std::vector<std::shared_ptr<ArrayNode>>& OpNode::next_array_nodes() const { assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node != nullptr; })); assert(std::all_of(next_array_nodes_.begin(), next_array_nodes_.end(), [this](const std::shared_ptr<ArrayNode>& arr_node) { return arr_node->graph_id() == graph_id_; })); return next_array_nodes_; } internal::OpNodeBackwardEntry& OpNode::RegisterBackwardFunction( std::vector<std::shared_ptr<ArrayNode>> next_array_nodes, BackwardFunction backward_func) { AssertConsistency(); assert(!next_array_nodes.empty()); assert(std::all_of(next_array_nodes.begin(), next_array_nodes.end(), [this](const std::shared_ptr<ArrayNode>& next_array_node) { // next_array_node could be nullptr, if the corresponding input array does not require grad. return next_array_node == nullptr || next_array_node->graph_id() == graph_id_; })); // Update the rank of op node for (const std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) { if (next_array_node != nullptr) { rank_ = std::max(rank_, next_array_node->rank() + 1); } } // Store next nodes and record indices of them std::vector<nonstd::optional<size_t>> next_array_node_indices; next_array_node_indices.reserve(next_array_nodes.size()); for (std::shared_ptr<ArrayNode>& next_array_node : next_array_nodes) { if (next_array_node != nullptr) { next_array_node_indices.emplace_back(next_array_nodes_.size()); next_array_nodes_.emplace_back(std::move(next_array_node)); } else { next_array_node_indices.emplace_back(nonstd::nullopt); } } // Add backward entry backward_entries_.emplace_back(*this, std::move(next_array_node_indices), std::move(backward_func)); AssertConsistency(); return backward_entries_.back(); } void OpNode::RegisterOuterGraphsPreviousArrayNodes( const GraphId& other_graph_id, std::vector<std::shared_ptr<ArrayNode>> outer_graphs_prev_array_nodes) { AssertConsistency(); assert(other_graph_id != graph_id_); assert(outer_graphs_prev_array_nodes.size() == prev_array_props_.size()); outer_graphs_prev_array_nodes_.emplace_back(other_graph_id, std::move(outer_graphs_prev_array_nodes)); AssertConsistency(); } namespace internal { std::shared_ptr<ArrayNode> CreatePrevArrayNode(std::shared_ptr<OpNode> op_node, size_t prev_array_node_index) { assert(prev_array_node_index < op_node->prev_node_count()); assert(op_node->prev_array_nodes()[prev_array_node_index].expired()); const internal::ArrayProps& props = op_node->GetPrevArrayProps(prev_array_node_index); auto prev_array_node = std::make_shared<ArrayNode>(props.shape, props.dtype, props.device, op_node->graph_id()); op_node->prev_array_nodes()[prev_array_node_index] = prev_array_node; prev_array_node->set_next_op_node(std::move(op_node)); return prev_array_node; } } // namespace internal } // namespace xchainer <|endoftext|>
<commit_before>// Copyright (c) 2012, Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp" #include "error.hpp" #include <fstream> #include <cassert> namespace sak { file_input_stream::file_input_stream() : m_filesize(0) { } file_input_stream::file_input_stream(const std::string& filename) : m_filesize(0) { open(filename); } void file_input_stream::open(const std::string& filename) { assert(!m_file.is_open()); boost::system::error_code ec; open(filename, ec); // If an error throw error::throw_error(ec); } void file_input_stream::open(const std::string& filename, boost::system::error_code& ec) { assert(!m_file.is_open()); m_file.open(filename.c_str(), std::ios::in | std::ios::binary); if (!m_file.is_open()) { ec = error::make_error_code(error::failed_open_file); return; } m_file.seekg(0, std::ios::end); assert(m_file); // We cannot use the read_position function here due to a // problem on the iOS platform described in the read_position // function. auto pos = m_file.tellg(); assert(pos >= 0); m_filesize = (uint32_t) pos; m_file.seekg(0, std::ios::beg); assert(m_file); } void file_input_stream::seek(uint32_t pos) { assert(m_file.is_open()); m_file.seekg(pos, std::ios::beg); assert(m_file); // if(m_file.fail()) // { // ec = error::make_error_code(error::failed_open_file); // return; // } } uint32_t file_input_stream::read_position() { assert(m_file.is_open()); // Work around for problem on iOS where tellg returned -1 when // reading the last byte. However the EOF flag was correctly // set. So here we check for EOF if true we set the // read_position = m_file_size if(m_file.eof()) { return m_file_size; } else { std::streamoff pos = m_file.tellg(); std::cout << "tellg = " << (int32_t) pos << std::endl; assert(pos >= 0); return static_cast<uint32_t>(pos); } } void file_input_stream::read(uint8_t* buffer, uint32_t bytes) { assert(m_file.is_open()); std::cout << "file_input_stream::read " << bytes << std::endl; m_file.read(reinterpret_cast<char*>(buffer), bytes); assert(bytes == static_cast<uint32_t>(m_file.gcount())); } uint32_t file_input_stream::bytes_available() { assert(m_file.is_open()); std::cout << "file_input_stream::bytes_available " << std::endl; uint32_t pos = read_position(); assert(pos <= m_filesize); return m_filesize - pos; } uint32_t file_input_stream::size() { assert(m_file.is_open()); return m_filesize; } } <commit_msg>Fix typo in variable name<commit_after>// Copyright (c) 2012, Steinwurf ApS // 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 Steinwurf ApS 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 Steinwurf ApS 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 "file_input_stream.hpp" #include "error.hpp" #include <fstream> #include <cassert> namespace sak { file_input_stream::file_input_stream() : m_filesize(0) { } file_input_stream::file_input_stream(const std::string& filename) : m_filesize(0) { open(filename); } void file_input_stream::open(const std::string& filename) { assert(!m_file.is_open()); boost::system::error_code ec; open(filename, ec); // If an error throw error::throw_error(ec); } void file_input_stream::open(const std::string& filename, boost::system::error_code& ec) { assert(!m_file.is_open()); m_file.open(filename.c_str(), std::ios::in | std::ios::binary); if (!m_file.is_open()) { ec = error::make_error_code(error::failed_open_file); return; } m_file.seekg(0, std::ios::end); assert(m_file); // We cannot use the read_position function here due to a // problem on the iOS platform described in the read_position // function. auto pos = m_file.tellg(); assert(pos >= 0); m_filesize = (uint32_t) pos; m_file.seekg(0, std::ios::beg); assert(m_file); } void file_input_stream::seek(uint32_t pos) { assert(m_file.is_open()); m_file.seekg(pos, std::ios::beg); assert(m_file); // if(m_file.fail()) // { // ec = error::make_error_code(error::failed_open_file); // return; // } } uint32_t file_input_stream::read_position() { assert(m_file.is_open()); // Work around for problem on iOS where tellg returned -1 when // reading the last byte. However the EOF flag was correctly // set. So here we check for EOF if true we set the // read_position = m_file_size if(m_file.eof()) { return m_filesize; } else { std::streamoff pos = m_file.tellg(); std::cout << "tellg = " << (int32_t) pos << std::endl; assert(pos >= 0); return static_cast<uint32_t>(pos); } } void file_input_stream::read(uint8_t* buffer, uint32_t bytes) { assert(m_file.is_open()); std::cout << "file_input_stream::read " << bytes << std::endl; m_file.read(reinterpret_cast<char*>(buffer), bytes); assert(bytes == static_cast<uint32_t>(m_file.gcount())); } uint32_t file_input_stream::bytes_available() { assert(m_file.is_open()); std::cout << "file_input_stream::bytes_available " << std::endl; uint32_t pos = read_position(); assert(pos <= m_filesize); return m_filesize - pos; } uint32_t file_input_stream::size() { assert(m_file.is_open()); return m_filesize; } } <|endoftext|>
<commit_before><commit_msg>Very confused...<commit_after><|endoftext|>
<commit_before>#include "defines.h" #include "DcxDWMModule.h" PFNDWMISCOMPOSITIONENABLED DcxDWMModule::DwmIsCompositionEnabledUx = nullptr; PFNDWMGETWINDOWATTRIBUTE DcxDWMModule::DwmGetWindowAttributeUx = nullptr; PFNDWMSETWINDOWATTRIBUTE DcxDWMModule::DwmSetWindowAttributeUx = nullptr; PFNDWMEXTENDFRAMEINTOCLIENTAREA DcxDWMModule::DwmExtendFrameIntoClientAreaUx = nullptr; PFNDWMENABLEBLURBEHINDWINDOW DcxDWMModule::DwmEnableBlurBehindWindowUx = nullptr; PFNDWMGETCOLORIZATIONCOLOR DcxDWMModule::DwmGetColorizationColorUx = nullptr; DcxDWMModule::DcxDWMModule(void) : m_bAero(false), m_bVista(false), m_bWin7(false), m_bWin8(false) { } DcxDWMModule::~DcxDWMModule(void) { if (isUseable()) unload(); } bool DcxDWMModule::load(void) { if (isUseable()) return false; DWORD winMajor = 0; if (!GetWindowVersion(&winMajor, nullptr)) return false; this->m_bVista = (winMajor >= 6); // OS is Vista+ this->m_bWin7 = (winMajor > 6); // OS is Windows7+ this->m_bWin8 = (winMajor > 7); // OS is Windows8+ this->m_bWin10 = (winMajor > 8); // OS is Windows10+ DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("Loading DWMAPI.DLL...")); m_hModule = LoadLibrary(TEXT("dwmapi.dll")); if (m_hModule != nullptr) { DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("DWMAPI.DLL Loaded, Vista+ OS Assumed")); DwmIsCompositionEnabledUx = (PFNDWMISCOMPOSITIONENABLED) GetProcAddress(m_hModule, "DwmIsCompositionEnabled"); // Vista ONLY! DwmGetWindowAttributeUx = (PFNDWMGETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmGetWindowAttribute"); // Vista ONLY! DwmSetWindowAttributeUx = (PFNDWMSETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmSetWindowAttribute"); // Vista ONLY! DwmExtendFrameIntoClientAreaUx = (PFNDWMEXTENDFRAMEINTOCLIENTAREA) GetProcAddress(m_hModule, "DwmExtendFrameIntoClientArea"); // Vista ONLY! DwmEnableBlurBehindWindowUx = (PFNDWMENABLEBLURBEHINDWINDOW) GetProcAddress(m_hModule, "DwmEnableBlurBehindWindow"); // Vista ONLY! DwmGetColorizationColorUx = (PFNDWMGETCOLORIZATIONCOLOR) GetProcAddress(m_hModule, "DwmGetColorizationColor"); // Vista ONLY! #if DCX_DEBUG_OUTPUT if (DwmIsCompositionEnabledUx != nullptr) mIRCLinker::debug(TEXT("LoadDLL"), TEXT("Found Vista DWM Functions")); #endif refreshComposite(); } return isUseable(); } bool DcxDWMModule::unload(void) { if (m_hModule != nullptr) { FreeLibrary(m_hModule); m_hModule = nullptr; DwmIsCompositionEnabledUx = nullptr; DwmGetWindowAttributeUx = nullptr; DwmSetWindowAttributeUx = nullptr; DwmExtendFrameIntoClientAreaUx = nullptr; DwmEnableBlurBehindWindowUx = nullptr; DwmGetColorizationColorUx = nullptr; } return isUseable(); } bool DcxDWMModule::refreshComposite() { BOOL bAero; if (FAILED(dcxDwmIsCompositionEnabled(&bAero))) bAero = FALSE; m_bAero = (bAero != FALSE); return m_bAero; } HRESULT DcxDWMModule::dcxDwmSetWindowAttribute(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute) { if (DwmSetWindowAttributeUx != nullptr) return DwmSetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmGetWindowAttribute(HWND hwnd, DWORD dwAttribute, PVOID pvAttribute, DWORD cbAttribute) { if (DwmGetWindowAttributeUx != nullptr) return DwmGetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmIsCompositionEnabled(BOOL *pfEnabled) { if (DwmIsCompositionEnabledUx != nullptr) return DwmIsCompositionEnabledUx(pfEnabled); *pfEnabled = FALSE; return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmExtendFrameIntoClientArea(HWND hwnd, const MARGINS *pMarInset) { if (DwmExtendFrameIntoClientAreaUx != nullptr) return DwmExtendFrameIntoClientAreaUx(hwnd, pMarInset); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmEnableBlurBehindWindow(HWND hwnd, __in const DWM_BLURBEHIND *pBlurBehind) { if (DwmEnableBlurBehindWindowUx != nullptr) return DwmEnableBlurBehindWindowUx(hwnd, pBlurBehind); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmGetColorizationColor( __out DWORD *pcrColorization, __out BOOL *pfOpaqueBlend) { if (DwmGetColorizationColorUx != nullptr) return DwmGetColorizationColorUx(pcrColorization, pfOpaqueBlend); return DWM_E_COMPOSITIONDISABLED; } <commit_msg>[modules] forgot to initialize bWin10<commit_after>#include "defines.h" #include "DcxDWMModule.h" PFNDWMISCOMPOSITIONENABLED DcxDWMModule::DwmIsCompositionEnabledUx = nullptr; PFNDWMGETWINDOWATTRIBUTE DcxDWMModule::DwmGetWindowAttributeUx = nullptr; PFNDWMSETWINDOWATTRIBUTE DcxDWMModule::DwmSetWindowAttributeUx = nullptr; PFNDWMEXTENDFRAMEINTOCLIENTAREA DcxDWMModule::DwmExtendFrameIntoClientAreaUx = nullptr; PFNDWMENABLEBLURBEHINDWINDOW DcxDWMModule::DwmEnableBlurBehindWindowUx = nullptr; PFNDWMGETCOLORIZATIONCOLOR DcxDWMModule::DwmGetColorizationColorUx = nullptr; DcxDWMModule::DcxDWMModule(void) : m_bAero(false), m_bVista(false), m_bWin7(false), m_bWin8(false), m_bWin10(false) { } DcxDWMModule::~DcxDWMModule(void) { if (isUseable()) unload(); } bool DcxDWMModule::load(void) { if (isUseable()) return false; DWORD winMajor = 0; if (!GetWindowVersion(&winMajor, nullptr)) return false; this->m_bVista = (winMajor >= 6); // OS is Vista+ this->m_bWin7 = (winMajor > 6); // OS is Windows7+ this->m_bWin8 = (winMajor > 7); // OS is Windows8+ this->m_bWin10 = (winMajor > 8); // OS is Windows10+ DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("Loading DWMAPI.DLL...")); m_hModule = LoadLibrary(TEXT("dwmapi.dll")); if (m_hModule != nullptr) { DCX_DEBUG(mIRCLinker::debug, TEXT("LoadDLL"), TEXT("DWMAPI.DLL Loaded, Vista+ OS Assumed")); DwmIsCompositionEnabledUx = (PFNDWMISCOMPOSITIONENABLED) GetProcAddress(m_hModule, "DwmIsCompositionEnabled"); // Vista ONLY! DwmGetWindowAttributeUx = (PFNDWMGETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmGetWindowAttribute"); // Vista ONLY! DwmSetWindowAttributeUx = (PFNDWMSETWINDOWATTRIBUTE) GetProcAddress(m_hModule, "DwmSetWindowAttribute"); // Vista ONLY! DwmExtendFrameIntoClientAreaUx = (PFNDWMEXTENDFRAMEINTOCLIENTAREA) GetProcAddress(m_hModule, "DwmExtendFrameIntoClientArea"); // Vista ONLY! DwmEnableBlurBehindWindowUx = (PFNDWMENABLEBLURBEHINDWINDOW) GetProcAddress(m_hModule, "DwmEnableBlurBehindWindow"); // Vista ONLY! DwmGetColorizationColorUx = (PFNDWMGETCOLORIZATIONCOLOR) GetProcAddress(m_hModule, "DwmGetColorizationColor"); // Vista ONLY! #if DCX_DEBUG_OUTPUT if (DwmIsCompositionEnabledUx != nullptr) mIRCLinker::debug(TEXT("LoadDLL"), TEXT("Found Vista DWM Functions")); #endif refreshComposite(); } return isUseable(); } bool DcxDWMModule::unload(void) { if (m_hModule != nullptr) { FreeLibrary(m_hModule); m_hModule = nullptr; DwmIsCompositionEnabledUx = nullptr; DwmGetWindowAttributeUx = nullptr; DwmSetWindowAttributeUx = nullptr; DwmExtendFrameIntoClientAreaUx = nullptr; DwmEnableBlurBehindWindowUx = nullptr; DwmGetColorizationColorUx = nullptr; } return isUseable(); } bool DcxDWMModule::refreshComposite() { BOOL bAero; if (FAILED(dcxDwmIsCompositionEnabled(&bAero))) bAero = FALSE; m_bAero = (bAero != FALSE); return m_bAero; } HRESULT DcxDWMModule::dcxDwmSetWindowAttribute(HWND hwnd, DWORD dwAttribute, LPCVOID pvAttribute, DWORD cbAttribute) { if (DwmSetWindowAttributeUx != nullptr) return DwmSetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmGetWindowAttribute(HWND hwnd, DWORD dwAttribute, PVOID pvAttribute, DWORD cbAttribute) { if (DwmGetWindowAttributeUx != nullptr) return DwmGetWindowAttributeUx(hwnd, dwAttribute, pvAttribute, cbAttribute); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmIsCompositionEnabled(BOOL *pfEnabled) { if (DwmIsCompositionEnabledUx != nullptr) return DwmIsCompositionEnabledUx(pfEnabled); *pfEnabled = FALSE; return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmExtendFrameIntoClientArea(HWND hwnd, const MARGINS *pMarInset) { if (DwmExtendFrameIntoClientAreaUx != nullptr) return DwmExtendFrameIntoClientAreaUx(hwnd, pMarInset); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmEnableBlurBehindWindow(HWND hwnd, __in const DWM_BLURBEHIND *pBlurBehind) { if (DwmEnableBlurBehindWindowUx != nullptr) return DwmEnableBlurBehindWindowUx(hwnd, pBlurBehind); return DWM_E_COMPOSITIONDISABLED; } HRESULT DcxDWMModule::dcxDwmGetColorizationColor( __out DWORD *pcrColorization, __out BOOL *pfOpaqueBlend) { if (DwmGetColorizationColorUx != nullptr) return DwmGetColorizationColorUx(pcrColorization, pfOpaqueBlend); return DWM_E_COMPOSITIONDISABLED; } <|endoftext|>
<commit_before>#include "FSRespSource.h" #include <type_traits> #include <stdexcept> #include <boost/locale.hpp> #include "CommonErrorRespSource.h" #include "detail/MimeDB.h" using namespace HTTP; using namespace HTTP::RespSource; FS::Response::Response(const boost::filesystem::path &FileName, const char *MimeType, time_t IfModifiedSince) : MyMimeType(MimeType) { time_t LastModTime=boost::filesystem::last_write_time(FileName); Header::FormatDateTime(LastModTime,LastModifiedStr); if ((!IfModifiedSince) || (LastModTime>IfModifiedSince)) { FileSize=boost::filesystem::file_size(FileName); FilePos=0; InS.open(FileName.string().data(),std::ios_base::binary); if (!InS.is_open()) throw std::runtime_error("Cannot open target file"); } else { FileSize=NotModifiedSize; FilePos=0; } } bool FS::Response::GetExtraHeader(unsigned int Index, const char **OutHeader, const char **OutHeaderEnd, const char **OutHeaderVal, const char **OutHeaderValEnd) { if (Index==0) { const std::string &HName=Header::GetHeaderName(HN_LAST_MODIFIED); *OutHeader=HName.data(); *OutHeaderEnd=HName.data() + HName.size(); *OutHeaderVal=LastModifiedStr; *OutHeaderValEnd=LastModifiedStr+sizeof(LastModifiedStr); return true; } else return false; } bool FS::Response::Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength, boost::asio::yield_context &Ctx) { if (FileSize!=NotModifiedSize) { unsigned long long RemLength=FileSize-FilePos; if (MaxLength>RemLength) MaxLength=(unsigned int)RemLength; InS.read((char *)TargetBuff,MaxLength); OutLength=MaxLength; FilePos+=MaxLength; return (FilePos==FileSize) || (InS.fail()); } else { OutLength=0; return true; } } FS::FS(const boost::filesystem::path &NewRoot) : Root(NewRoot) { } IResponse *FS::Create(METHOD Method, const std::string &Resource, const QueryParams &Query, const std::vector<Header> &HeaderA, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd, boost::asio::io_service &ParentIOS, void *ParentConn) { boost::filesystem::path Target; try { if (std::is_same<boost::filesystem::path::value_type,wchar_t>()) Target=boost::filesystem::canonical(Root / boost::locale::conv::utf_to_utf<wchar_t,char>(Resource)); else Target=boost::filesystem::canonical(Root / Resource); } catch (...) { return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); } if ( (std::distance(Root.begin(), Root.end())<=std::distance(Target.begin(), Target.end())) && (std::equal(Root.begin(), Root.end(), Target.begin())) && (boost::filesystem::exists(Target)) ) { time_t IfModSinceTime=0; try { for (const Header &CurrH : HeaderA) { if (CurrH.IntName==HN_IF_MOD_SINCE) { IfModSinceTime=CurrH.GetDateTime(); break; } } } catch (...) { } if (!boost::filesystem::is_directory(Target)) return new Response(Target,GetMimeType(Target),IfModSinceTime); else return new CommonError::Response(Resource,HeaderA,NULL,RC_FORBIDDEN); } else return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); } const char *FS::GetMimeType(const boost::filesystem::path &FileName) { return detail::MimeDB::GetMimeType(FileName.extension().string()); } <commit_msg>FSRespSource: indent fix<commit_after>#include "FSRespSource.h" #include <type_traits> #include <stdexcept> #include <boost/locale.hpp> #include "CommonErrorRespSource.h" #include "detail/MimeDB.h" using namespace HTTP; using namespace HTTP::RespSource; FS::Response::Response(const boost::filesystem::path &FileName, const char *MimeType, time_t IfModifiedSince) : MyMimeType(MimeType) { time_t LastModTime=boost::filesystem::last_write_time(FileName); Header::FormatDateTime(LastModTime,LastModifiedStr); if ((!IfModifiedSince) || (LastModTime>IfModifiedSince)) { FileSize=boost::filesystem::file_size(FileName); FilePos=0; InS.open(FileName.string().data(),std::ios_base::binary); if (!InS.is_open()) throw std::runtime_error("Cannot open target file"); } else { FileSize=NotModifiedSize; FilePos=0; } } bool FS::Response::GetExtraHeader(unsigned int Index, const char **OutHeader, const char **OutHeaderEnd, const char **OutHeaderVal, const char **OutHeaderValEnd) { if (Index==0) { const std::string &HName=Header::GetHeaderName(HN_LAST_MODIFIED); *OutHeader=HName.data(); *OutHeaderEnd=HName.data() + HName.size(); *OutHeaderVal=LastModifiedStr; *OutHeaderValEnd=LastModifiedStr+sizeof(LastModifiedStr); return true; } else return false; } bool FS::Response::Read(unsigned char *TargetBuff, unsigned int MaxLength, unsigned int &OutLength, boost::asio::yield_context &Ctx) { if (FileSize!=NotModifiedSize) { unsigned long long RemLength=FileSize-FilePos; if (MaxLength>RemLength) MaxLength=(unsigned int)RemLength; InS.read((char *)TargetBuff,MaxLength); OutLength=MaxLength; FilePos+=MaxLength; return (FilePos==FileSize) || (InS.fail()); } else { OutLength=0; return true; } } FS::FS(const boost::filesystem::path &NewRoot) : Root(NewRoot) { } IResponse *FS::Create(METHOD Method, const std::string &Resource, const QueryParams &Query, const std::vector<Header> &HeaderA, const unsigned char *ContentBuff, const unsigned char *ContentBuffEnd, boost::asio::io_service &ParentIOS, void *ParentConn) { boost::filesystem::path Target; try { if (std::is_same<boost::filesystem::path::value_type,wchar_t>()) Target=boost::filesystem::canonical(Root / boost::locale::conv::utf_to_utf<wchar_t,char>(Resource)); else Target=boost::filesystem::canonical(Root / Resource); } catch (...) { return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); } if ( (std::distance(Root.begin(), Root.end())<=std::distance(Target.begin(), Target.end())) && (std::equal(Root.begin(), Root.end(), Target.begin())) && (boost::filesystem::exists(Target)) ) { time_t IfModSinceTime=0; try { for (const Header &CurrH : HeaderA) { if (CurrH.IntName==HN_IF_MOD_SINCE) { IfModSinceTime=CurrH.GetDateTime(); break; } } } catch (...) { } if (!boost::filesystem::is_directory(Target)) return new Response(Target,GetMimeType(Target),IfModSinceTime); else return new CommonError::Response(Resource,HeaderA,NULL,RC_FORBIDDEN); } else return new CommonError::Response(Resource,HeaderA,NULL,RC_NOTFOUND); } const char *FS::GetMimeType(const boost::filesystem::path &FileName) { return detail::MimeDB::GetMimeType(FileName.extension().string()); } <|endoftext|>
<commit_before>#include "condor_common.h" #include <iostream.h> #include "condor_config.h" #include "condor_classad.h" #include "condor_debug.h" #include "condor_query.h" #include "condor_q.h" #include "condor_attributes.h" #include "match_prefix.h" #include "my_hostname.h" #include "files.h" extern "C" int SetSyscalls(int val){return val;} extern void short_print(int,int,const char*,int,int,int,int,int,const char *); static void processCommandLineArguments(int, char *[]); extern "C" void set_debug_flags( char * ); static char *_FileName_ = __FILE__; static void short_header (void); static void usage (char *); static void displayJobShort (ClassAd *); static void shorten (char *, int); static int verbose = 0, summarize = 1, global = 0; static int malformed, unexpanded, running, idle; static CondorQ Q; static QueryResult result; static CondorQuery scheddQuery(SCHEDD_AD); static CondorQuery submittorQuery(SUBMITTOR_AD); static ClassAdList scheddList; static bool querySchedds = false; static bool querySubmittors = false; static char constraint[4096]; extern "C" int Termlog; int main (int argc, char **argv) { ClassAd *job; ClassAd *ad; bool first = true; int cluster, proc; char scheddAddr[64]; char scheddName[64]; char scheddMachine[64]; // load up configuration file config( 0 ); #if !defined(WIN32) install_sig_handler(SIGPIPE, SIG_IGN ); #endif // process arguments processCommandLineArguments (argc, argv); // make sure we are querying schedd's or submittors if (!global && !querySchedds && !querySubmittors) { char *host = my_hostname(); querySchedds = true; result = scheddQuery.addConstraint (SCHEDD_NAME, host); if (result != Q_OK) { fprintf(stderr,"Error: Couldn't add constraint Name=\"%s\"\n",host); exit (1); } } // get the list of ads from the collector result = querySchedds ? scheddQuery.fetchAds(scheddList) : submittorQuery.fetchAds(scheddList); if (result != Q_OK) { fprintf (stderr, "Error %d: %s\n", result, getStrQueryResult(result)); exit(1); } // get queue from each ScheddIpAddr in ad scheddList.Open(); while ((ad = scheddList.Next())) { ClassAdList jobs; // get the address of the schedd if (!ad->LookupString(ATTR_SCHEDD_IP_ADDR, scheddAddr) || !ad->LookupString(ATTR_NAME, scheddName) || !ad->LookupString(ATTR_MACHINE, scheddMachine)) continue; // fetch queue from schedd if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK) continue; // sort jobs by (cluster.proc) jobs.Sort( (SortFunctionType)JobSort ); // display the jobs from this submittor if (jobs.MyLength() != 0) { // print header if (querySchedds) { printf ("\n\n-- Schedd: %s : %s\n", scheddName, scheddAddr); } else { printf ("\n\n-- Submittor: %s : %s : %s\n", scheddName, scheddAddr, scheddMachine); } // initialize counters malformed = 0; idle = 0; running = 0; unexpanded = 0; if (verbose) { jobs.fPrintAttrListList (stdout); } else { short_header (); jobs.Open (); while (job = jobs.Next()) { displayJobShort (job); } jobs.Close (); } if (summarize) { printf("\n%d jobs; " "%d unexpanded, %d idle, %d running, %d malformed\n", unexpanded+idle+running+malformed,unexpanded,idle,running, malformed); } } first = false; } // close list scheddList.Close(); if (first) { fprintf (stderr,"Error: Collector has no record of schedd/submittor\n"); exit(1); } return 0; } static void processCommandLineArguments (int argc, char *argv[]) { int i, cluster, proc; char *arg; for (i = 1; i < argc; i++) { // if the argument begins with a '-', use only the part following // the '-' for prefix matches if (*argv[i] == '-') arg = argv[i]+1; else arg = argv[i]; if (match_prefix (arg, "long")) { verbose = 1; summarize = 0; } else if (match_prefix (arg, "D")) { Termlog = 1; set_debug_flags( argv[++i] ); } else if (match_prefix (arg, "name")) { if (querySubmittors) { // cannot query both schedd's and submittors fprintf (stderr, "Cannot query both schedd's and submittors\n"); exit(1); } // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -name requires another parameter\n"); exit(1); } sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i+1]); result = scheddQuery.addConstraint (constraint); if (result != Q_OK) { fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i], getStrQueryResult(result)); exit (1); } i++; querySchedds = true; } else if (match_prefix (arg, "submittor")) { char *at; if (querySchedds) { // cannot query both schedd's and submittors fprintf (stderr, "Cannot query both schedd's and submittors\n"); exit(1); } // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -submittor requires another " "parameter\n"); exit(1); } i++; if ((at = strchr(argv[i],'@'))) { // is the name already qualified with a UID_DOMAIN? sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i]); *at = '\0'; } else { // no ... add UID_DOMAIN char *uid_domain = param("UID_DOMAIN"); if (uid_domain == NULL) { EXCEPT ("No 'UID_DOMAIN' found in config file"); } sprintf (constraint, "%s == \"%s@%s\"", ATTR_NAME, argv[i], uid_domain); free (uid_domain); } // insert the constraints result = submittorQuery.addConstraint (constraint); if (result != Q_OK) { fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i], getStrQueryResult(result)); exit (1); } if (Q.add (CQ_OWNER, argv[i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } querySubmittors = true; } else if (match_prefix (arg, "constraint")) { // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -constraint requires another " "parameter\n"); exit(1); } if (Q.add (argv[++i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } summarize = 0; } else if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2) { sprintf (constraint, "((%s == %d) && (%s == %d))", ATTR_CLUSTER_ID, cluster, ATTR_PROC_ID, proc); Q.add (constraint); summarize = 0; } else if (sscanf (argv[i], "%d", &cluster) == 1) { sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster); Q.add (constraint); summarize = 0; } else if (match_prefix (arg, "global")) { global = 1; } else if (match_prefix (arg, "help")) { usage(argv[0]); exit(0); } else { // assume name of owner of job if (Q.add (CQ_OWNER, argv[i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } } } } static void displayJobShort (ClassAd *ad) { int cluster, proc, date, status, prio, image_size; float utime; char owner[64], cmd[2048], args[2048]; if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) || !ad->EvalInteger (ATTR_PROC_ID, NULL, proc) || !ad->EvalInteger (ATTR_Q_DATE, NULL, date) || !ad->EvalFloat (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)|| !ad->EvalInteger (ATTR_JOB_STATUS, NULL, status) || !ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio) || !ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size) || !ad->EvalString (ATTR_OWNER, NULL, owner) || !ad->EvalString (ATTR_JOB_CMD, NULL, cmd) ) { printf (" --- ???? --- \n"); return; } shorten (owner, 14); if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args); shorten (cmd, 18); short_print (cluster, proc, owner, date, (int)utime, status, prio, image_size, cmd); switch (status) { case UNEXPANDED: unexpanded++; break; case IDLE: idle++; break; case RUNNING: running++; break; } } static void short_header (void) { printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n", "ID", "OWNER", "SUBMITTED", "CPU_USAGE", "ST", "PRI", "SIZE", "CMD" ); } static void shorten (char *buff, int len) { if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\0'; } static void usage (char *myName) { printf ("Usage: %s [options]\n\twhere [options] are\n" "\t\t-global\t\t\tGet global queue\n" "\t\t-submittor <submittor>\tGet queue of specific submittor\n" "\t\t-help\t\t\tThis screen\n" "\t\t-name <name>\t\tName of schedd\n" "\t\t-constraint <expr>\tAdd constraint on classads\n" "\t\t-long\t\t\tVerbose output\n" "\t\t<cluster>\t\tGet information about specific cluster\n" "\t\t<cluster>.<proc>\tGet information about specific job\n" "\t\t<owner>\t\t\tInformation about jobs owned by <owner>\n", myName); } <commit_msg>unused variables cluster and proc<commit_after>#include "condor_common.h" #include <iostream.h> #include "condor_config.h" #include "condor_classad.h" #include "condor_debug.h" #include "condor_query.h" #include "condor_q.h" #include "condor_attributes.h" #include "match_prefix.h" #include "my_hostname.h" #include "files.h" extern "C" int SetSyscalls(int val){return val;} extern void short_print(int,int,const char*,int,int,int,int,int,const char *); static void processCommandLineArguments(int, char *[]); extern "C" void set_debug_flags( char * ); static char *_FileName_ = __FILE__; static void short_header (void); static void usage (char *); static void displayJobShort (ClassAd *); static void shorten (char *, int); static int verbose = 0, summarize = 1, global = 0; static int malformed, unexpanded, running, idle; static CondorQ Q; static QueryResult result; static CondorQuery scheddQuery(SCHEDD_AD); static CondorQuery submittorQuery(SUBMITTOR_AD); static ClassAdList scheddList; static bool querySchedds = false; static bool querySubmittors = false; static char constraint[4096]; extern "C" int Termlog; int main (int argc, char **argv) { ClassAd *job; ClassAd *ad; bool first = true; char scheddAddr[64]; char scheddName[64]; char scheddMachine[64]; // load up configuration file config( 0 ); #if !defined(WIN32) install_sig_handler(SIGPIPE, SIG_IGN ); #endif // process arguments processCommandLineArguments (argc, argv); // make sure we are querying schedd's or submittors if (!global && !querySchedds && !querySubmittors) { char *host = my_hostname(); querySchedds = true; result = scheddQuery.addConstraint (SCHEDD_NAME, host); if (result != Q_OK) { fprintf(stderr,"Error: Couldn't add constraint Name=\"%s\"\n",host); exit (1); } } // get the list of ads from the collector result = querySchedds ? scheddQuery.fetchAds(scheddList) : submittorQuery.fetchAds(scheddList); if (result != Q_OK) { fprintf (stderr, "Error %d: %s\n", result, getStrQueryResult(result)); exit(1); } // get queue from each ScheddIpAddr in ad scheddList.Open(); while ((ad = scheddList.Next())) { ClassAdList jobs; // get the address of the schedd if (!ad->LookupString(ATTR_SCHEDD_IP_ADDR, scheddAddr) || !ad->LookupString(ATTR_NAME, scheddName) || !ad->LookupString(ATTR_MACHINE, scheddMachine)) continue; // fetch queue from schedd if (Q.fetchQueueFromHost (jobs, scheddAddr) != Q_OK) continue; // sort jobs by (cluster.proc) jobs.Sort( (SortFunctionType)JobSort ); // display the jobs from this submittor if (jobs.MyLength() != 0) { // print header if (querySchedds) { printf ("\n\n-- Schedd: %s : %s\n", scheddName, scheddAddr); } else { printf ("\n\n-- Submittor: %s : %s : %s\n", scheddName, scheddAddr, scheddMachine); } // initialize counters malformed = 0; idle = 0; running = 0; unexpanded = 0; if (verbose) { jobs.fPrintAttrListList (stdout); } else { short_header (); jobs.Open (); while (job = jobs.Next()) { displayJobShort (job); } jobs.Close (); } if (summarize) { printf("\n%d jobs; " "%d unexpanded, %d idle, %d running, %d malformed\n", unexpanded+idle+running+malformed,unexpanded,idle,running, malformed); } } first = false; } // close list scheddList.Close(); if (first) { fprintf (stderr,"Error: Collector has no record of schedd/submittor\n"); exit(1); } return 0; } static void processCommandLineArguments (int argc, char *argv[]) { int i, cluster, proc; char *arg; for (i = 1; i < argc; i++) { // if the argument begins with a '-', use only the part following // the '-' for prefix matches if (*argv[i] == '-') arg = argv[i]+1; else arg = argv[i]; if (match_prefix (arg, "long")) { verbose = 1; summarize = 0; } else if (match_prefix (arg, "D")) { Termlog = 1; set_debug_flags( argv[++i] ); } else if (match_prefix (arg, "name")) { if (querySubmittors) { // cannot query both schedd's and submittors fprintf (stderr, "Cannot query both schedd's and submittors\n"); exit(1); } // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -name requires another parameter\n"); exit(1); } sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i+1]); result = scheddQuery.addConstraint (constraint); if (result != Q_OK) { fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i], getStrQueryResult(result)); exit (1); } i++; querySchedds = true; } else if (match_prefix (arg, "submittor")) { char *at; if (querySchedds) { // cannot query both schedd's and submittors fprintf (stderr, "Cannot query both schedd's and submittors\n"); exit(1); } // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -submittor requires another " "parameter\n"); exit(1); } i++; if ((at = strchr(argv[i],'@'))) { // is the name already qualified with a UID_DOMAIN? sprintf (constraint, "%s == \"%s\"", ATTR_NAME, argv[i]); *at = '\0'; } else { // no ... add UID_DOMAIN char *uid_domain = param("UID_DOMAIN"); if (uid_domain == NULL) { EXCEPT ("No 'UID_DOMAIN' found in config file"); } sprintf (constraint, "%s == \"%s@%s\"", ATTR_NAME, argv[i], uid_domain); free (uid_domain); } // insert the constraints result = submittorQuery.addConstraint (constraint); if (result != Q_OK) { fprintf (stderr, "Argument %d (%s): Error %s\n", i, argv[i], getStrQueryResult(result)); exit (1); } if (Q.add (CQ_OWNER, argv[i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } querySubmittors = true; } else if (match_prefix (arg, "constraint")) { // make sure we have at least one more argument if (argc <= i+1) { fprintf( stderr, "Argument -constraint requires another " "parameter\n"); exit(1); } if (Q.add (argv[++i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } summarize = 0; } else if (sscanf (argv[i], "%d.%d", &cluster, &proc) == 2) { sprintf (constraint, "((%s == %d) && (%s == %d))", ATTR_CLUSTER_ID, cluster, ATTR_PROC_ID, proc); Q.add (constraint); summarize = 0; } else if (sscanf (argv[i], "%d", &cluster) == 1) { sprintf (constraint, "(%s == %d)", ATTR_CLUSTER_ID, cluster); Q.add (constraint); summarize = 0; } else if (match_prefix (arg, "global")) { global = 1; } else if (match_prefix (arg, "help")) { usage(argv[0]); exit(0); } else { // assume name of owner of job if (Q.add (CQ_OWNER, argv[i]) != Q_OK) { fprintf (stderr, "Error: Argument %d (%s)\n", i, argv[i]); exit (1); } } } } static void displayJobShort (ClassAd *ad) { int cluster, proc, date, status, prio, image_size; float utime; char owner[64], cmd[2048], args[2048]; if (!ad->EvalInteger (ATTR_CLUSTER_ID, NULL, cluster) || !ad->EvalInteger (ATTR_PROC_ID, NULL, proc) || !ad->EvalInteger (ATTR_Q_DATE, NULL, date) || !ad->EvalFloat (ATTR_JOB_REMOTE_USER_CPU, NULL, utime)|| !ad->EvalInteger (ATTR_JOB_STATUS, NULL, status) || !ad->EvalInteger (ATTR_JOB_PRIO, NULL, prio) || !ad->EvalInteger (ATTR_IMAGE_SIZE, NULL, image_size) || !ad->EvalString (ATTR_OWNER, NULL, owner) || !ad->EvalString (ATTR_JOB_CMD, NULL, cmd) ) { printf (" --- ???? --- \n"); return; } shorten (owner, 14); if (ad->EvalString ("Args", NULL, args)) strcat (cmd, args); shorten (cmd, 18); short_print (cluster, proc, owner, date, (int)utime, status, prio, image_size, cmd); switch (status) { case UNEXPANDED: unexpanded++; break; case IDLE: idle++; break; case RUNNING: running++; break; } } static void short_header (void) { printf( " %-7s %-14s %11s %12s %-2s %-3s %-4s %-18s\n", "ID", "OWNER", "SUBMITTED", "CPU_USAGE", "ST", "PRI", "SIZE", "CMD" ); } static void shorten (char *buff, int len) { if ((unsigned int)strlen (buff) > (unsigned int)len) buff[len] = '\0'; } static void usage (char *myName) { printf ("Usage: %s [options]\n\twhere [options] are\n" "\t\t-global\t\t\tGet global queue\n" "\t\t-submittor <submittor>\tGet queue of specific submittor\n" "\t\t-help\t\t\tThis screen\n" "\t\t-name <name>\t\tName of schedd\n" "\t\t-constraint <expr>\tAdd constraint on classads\n" "\t\t-long\t\t\tVerbose output\n" "\t\t<cluster>\t\tGet information about specific cluster\n" "\t\t<cluster>.<proc>\tGet information about specific job\n" "\t\t<owner>\t\t\tInformation about jobs owned by <owner>\n", myName); } <|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 "conversiontable.h" #include <iostream> ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" ) { editBoxValue=-1; items.setAutoDelete(true); widgets.setAutoDelete(true); connect(this,SIGNAL(signalSymmetric(int,int,double)),this,SLOT(makeSymmetric(int,int,double))); } ConversionTable::~ConversionTable() { } QTableItem* ConversionTable::item( int r, int c ) const { return items.find(indexOf(r,c)); } void ConversionTable::setItem(int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); i->setRow(r); // Otherwise the item i->setCol(c); //doesn't know where it is! } void ConversionTable::clearCell( int r, int c ) { items.remove(indexOf(r,c)); } void ConversionTable::takeItem(QTableItem *item) { items.setAutoDelete(false); items.remove(indexOf(item->row(),item->col())); items.setAutoDelete(true); } void ConversionTable::insertWidget(int r, int c, QWidget *w ) { widgets.replace(indexOf(r,c),w); } QWidget* ConversionTable::cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); } void ConversionTable::clearCellWidget( int r, int c ) { QWidget *w = widgets.take(indexOf(r,c)); if (w) w->deleteLater(); } ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et), eb( 0 ) { //wedonotwantthisitemtobereplaced setReplaceable( false ); } void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected ) { QColorGroup g(cg); // Draw in gray all those cells which are not editable if (row() == col()) g.setColor( QColorGroup::Base, gray ); QTableItem::paint( p, g, cr, selected ); } QWidget* ConversionTableItem::createEditor() const { ((ConversionTableItem*)this)->eb=new EditBox(table()->viewport()); eb->setValue(text().toDouble()); // Initialize the box with this value QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose())); return eb; } void ConversionTable::acceptValueAndClose() { QTable::endEdit(currentRow(),currentColumn(),true,false); } void ConversionTableItem::setContentFromEditor( QWidget *w ) { // theuser changed the value of the combobox, so synchronize the // value of the item (its text), with the value of the combobox if ( w->inherits( "EditBox" ) ) { if (eb->accepted) { setText(QString::number(eb->value())); // Only accept value if Ok was pressed before emit ratioChanged(row(),col(),eb->value()); // Signal to store if (row()!=col()) emit signalSymmetric(row(),col(),eb->value()); // Signal to make symmetric. just in case, check if row,col are different (it shouldn't be editable, anyway) } } else QTableItem::setContentFromEditor( w ); } void ConversionTableItem::setText( const QString &s ) { if (eb) { // initializetheeditboxfromthetext eb->setValue(s.toDouble()); } QTableItem::setText(s); } QString ConversionTable::text(int r, int c ) const // without this function, the usual (text(r,c)) won't work { return(item(r,c)->text()); //Note that item(r,c) was reimplemented here for large sparse tables... } void ConversionTable::initTable() { for (int r=0;r<numRows();r++) { this->createNewItem(r,r,1.0); item(r,r)->setEnabled(false); // Diagonal is not editable } } void ConversionTable::createNewItem(int r, int c, double amount) { ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent); setItem(r,c, ci ); ci->setText(QString::number(amount)); // connect signal (forward) to know when it's actually changed connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double))); connect(ci, SIGNAL(signalSymmetric(int,int,double)),this,SIGNAL(signalSymmetric(int,int,double))); connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int))); } void ConversionTable::setUnitIDs(const IDList &idList) { unitIDs=idList; } void ConversionTable::setRatio(int ingID1, int ingID2, double ratio) { int indexID1=unitIDs.find(&ingID1); int indexID2=unitIDs.find(&ingID2); createNewItem(indexID1,indexID2,ratio); } int ConversionTable::getUnitID(int rc) { return(*(unitIDs.at(rc))); return(1); } QWidget * ConversionTable::beginEdit ( int row, int col, bool replace ) { // If there's no item, create it first. if (!item(row,col)) { createNewItem(row,col,0); } if (!(item(col,row)) && (row!=col)) createNewItem(col,row,0); // Create the symmetric one.It shouldn't be necessary to do this if (row,col) exists, but just in case, it's checked. row==col is neither supposed to be editable, but check anyway // Then call normal beginEdit QTable::beginEdit(row,col,replace); } void ConversionTable::makeSymmetric(int r,int c,double amount) { QTableItem *it; it=item(c,r); if (amount) (( ConversionTableItem *) it)->setTextAndSave(QString::number(1.0/amount)); // Change value and store in database else (( ConversionTableItem *) it)->setTextAndSave(QString::number(0));// Change value and store in database } void ConversionTableItem::setTextAndSave(const QString &s) { setText(s); // Change text emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted emit ratioChanged(row(),col(),s.toDouble()); // Signal to store } void ConversionTable::repaintCell(int r,int c) { QTable::updateCell(r,c); } void ConversionTable::resize(int r,int c) { setNumRows(r); setNumCols(c); initTable(); } void ConversionTable::clear(void) { items.clear(); widgets.clear(); unitIDs.clear(); resize(0,0); }<commit_msg>Fix compiling for Qt 3.1.2<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 "conversiontable.h" #include <iostream> ConversionTable::ConversionTable(QWidget* parent,int maxrows,int maxcols):QTable( maxrows, maxcols, parent, "table" ) { editBoxValue=-1; items.setAutoDelete(true); widgets.setAutoDelete(true); connect(this,SIGNAL(signalSymmetric(int,int,double)),this,SLOT(makeSymmetric(int,int,double))); } ConversionTable::~ConversionTable() { } QTableItem* ConversionTable::item( int r, int c ) const { return items.find(indexOf(r,c)); } void ConversionTable::setItem(int r, int c, QTableItem *i ) { items.replace( indexOf( r, c ), i ); i->setRow(r); // Otherwise the item i->setCol(c); //doesn't know where it is! } void ConversionTable::clearCell( int r, int c ) { items.remove(indexOf(r,c)); } void ConversionTable::takeItem(QTableItem *item) { items.setAutoDelete(false); items.remove(indexOf(item->row(),item->col())); items.setAutoDelete(true); } void ConversionTable::insertWidget(int r, int c, QWidget *w ) { widgets.replace(indexOf(r,c),w); } QWidget* ConversionTable::cellWidget( int r, int c ) const { return widgets.find( indexOf( r, c ) ); } void ConversionTable::clearCellWidget( int r, int c ) { QWidget *w = widgets.take(indexOf(r,c)); if (w) w->deleteLater(); } ConversionTableItem::ConversionTableItem( QTable *t, EditType et ):QTableItem( t, et, QString::null), eb( 0 ) { //wedonotwantthisitemtobereplaced setReplaceable( false ); } void ConversionTableItem::paint( QPainter *p, const QColorGroup &cg, const QRect &cr, bool selected ) { QColorGroup g(cg); // Draw in gray all those cells which are not editable if (row() == col()) g.setColor( QColorGroup::Base, gray ); QTableItem::paint( p, g, cr, selected ); } QWidget* ConversionTableItem::createEditor() const { ((ConversionTableItem*)this)->eb=new EditBox(table()->viewport()); eb->setValue(text().toDouble()); // Initialize the box with this value QObject::connect(eb,SIGNAL(valueChanged(double)),table(),SLOT(acceptValueAndClose())); return eb; } void ConversionTable::acceptValueAndClose() { QTable::endEdit(currentRow(),currentColumn(),true,false); } void ConversionTableItem::setContentFromEditor( QWidget *w ) { // theuser changed the value of the combobox, so synchronize the // value of the item (its text), with the value of the combobox if ( w->inherits( "EditBox" ) ) { if (eb->accepted) { setText(QString::number(eb->value())); // Only accept value if Ok was pressed before emit ratioChanged(row(),col(),eb->value()); // Signal to store if (row()!=col()) emit signalSymmetric(row(),col(),eb->value()); // Signal to make symmetric. just in case, check if row,col are different (it shouldn't be editable, anyway) } } else QTableItem::setContentFromEditor( w ); } void ConversionTableItem::setText( const QString &s ) { if (eb) { // initializetheeditboxfromthetext eb->setValue(s.toDouble()); } QTableItem::setText(s); } QString ConversionTable::text(int r, int c ) const // without this function, the usual (text(r,c)) won't work { return(item(r,c)->text()); //Note that item(r,c) was reimplemented here for large sparse tables... } void ConversionTable::initTable() { for (int r=0;r<numRows();r++) { this->createNewItem(r,r,1.0); item(r,r)->setEnabled(false); // Diagonal is not editable } } void ConversionTable::createNewItem(int r, int c, double amount) { ConversionTableItem *ci= new ConversionTableItem(this,QTableItem::WhenCurrent); setItem(r,c, ci ); ci->setText(QString::number(amount)); // connect signal (forward) to know when it's actually changed connect(ci, SIGNAL(ratioChanged(int,int,double)),this,SIGNAL(ratioChanged(int,int,double))); connect(ci, SIGNAL(signalSymmetric(int,int,double)),this,SIGNAL(signalSymmetric(int,int,double))); connect(ci, SIGNAL(signalRepaintCell(int,int)),this,SLOT(repaintCell(int,int))); } void ConversionTable::setUnitIDs(const IDList &idList) { unitIDs=idList; } void ConversionTable::setRatio(int ingID1, int ingID2, double ratio) { int indexID1=unitIDs.find(&ingID1); int indexID2=unitIDs.find(&ingID2); createNewItem(indexID1,indexID2,ratio); } int ConversionTable::getUnitID(int rc) { return(*(unitIDs.at(rc))); return(1); } QWidget * ConversionTable::beginEdit ( int row, int col, bool replace ) { // If there's no item, create it first. if (!item(row,col)) { createNewItem(row,col,0); } if (!(item(col,row)) && (row!=col)) createNewItem(col,row,0); // Create the symmetric one.It shouldn't be necessary to do this if (row,col) exists, but just in case, it's checked. row==col is neither supposed to be editable, but check anyway // Then call normal beginEdit QTable::beginEdit(row,col,replace); } void ConversionTable::makeSymmetric(int r,int c,double amount) { QTableItem *it; it=item(c,r); if (amount) (( ConversionTableItem *) it)->setTextAndSave(QString::number(1.0/amount)); // Change value and store in database else (( ConversionTableItem *) it)->setTextAndSave(QString::number(0));// Change value and store in database } void ConversionTableItem::setTextAndSave(const QString &s) { setText(s); // Change text emit signalRepaintCell(row(),col()); // Indicate to update the cell to the table. Otherwise it's not repainted emit ratioChanged(row(),col(),s.toDouble()); // Signal to store } void ConversionTable::repaintCell(int r,int c) { QTable::updateCell(r,c); } void ConversionTable::resize(int r,int c) { setNumRows(r); setNumCols(c); initTable(); } void ConversionTable::clear(void) { items.clear(); widgets.clear(); unitIDs.clear(); resize(0,0); }<|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h" namespace { // TODO(phoglund): These tests are generally broken on mac. // http://code.google.com/p/webrtc/issues/detail?id=1268 class DISABLED_ON_MAC(ViEExtendedIntegrationTest) : public LegacyFixture { }; TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsBaseTestWithoutErrors) { tests_->ViEBaseExtendedTest(); } // TODO(phoglund): Crashes on the v4l2loopback camera. TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), DISABLED_RunsCaptureTestWithoutErrors) { tests_->ViECaptureExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsCodecTestWithoutErrors) { tests_->ViECodecExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsEncryptionTestWithoutErrors) { tests_->ViEEncryptionExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsFileTestWithoutErrors) { tests_->ViEFileExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsImageProcessTestWithoutErrors) { tests_->ViEImageProcessExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsRenderTestWithoutErrors) { tests_->ViERenderExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsRtpRtcpTestWithoutErrors) { tests_->ViERtpRtcpExtendedTest(); } } // namespace <commit_msg>Disable ViEExtendedIntegrationTest.RunsCodecTestWithoutErrors test.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/test/testsupport/gtest_disable.h" #include "webrtc/video_engine/test/auto_test/automated/legacy_fixture.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h" namespace { // TODO(phoglund): These tests are generally broken on mac. // http://code.google.com/p/webrtc/issues/detail?id=1268 class DISABLED_ON_MAC(ViEExtendedIntegrationTest) : public LegacyFixture { }; TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsBaseTestWithoutErrors) { tests_->ViEBaseExtendedTest(); } // TODO(phoglund): Crashes on the v4l2loopback camera. TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), DISABLED_RunsCaptureTestWithoutErrors) { tests_->ViECaptureExtendedTest(); } // Flaky on Windows: http://code.google.com/p/webrtc/issues/detail?id=1925 // (in addition to being disabled on Mac due to webrtc:1268). #if defined(WEBRTC_MAC) || defined(_WIN32) #define MAYBE_RunsCodecTestWithoutErrors DISABLED_RunsCodecTestWithoutErrors #else #define MAYBE_RunsCodecTestWithoutErrors RunsCodecTestWithoutErrors #endif TEST_F(ViEExtendedIntegrationTest, MAYBE_RunsCodecTestWithoutErrors) { tests_->ViECodecExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsEncryptionTestWithoutErrors) { tests_->ViEEncryptionExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsFileTestWithoutErrors) { tests_->ViEFileExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsImageProcessTestWithoutErrors) { tests_->ViEImageProcessExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsRenderTestWithoutErrors) { tests_->ViERenderExtendedTest(); } TEST_F(DISABLED_ON_MAC(ViEExtendedIntegrationTest), RunsRtpRtcpTestWithoutErrors) { tests_->ViERtpRtcpExtendedTest(); } } // namespace <|endoftext|>
<commit_before>#include "GUI.hpp" #include <string> #include <vector> #include <QMessageBox> #include <QAction> #include <QCloseEvent> #include <QFontDatabase> #include "Game.hpp" #include "NewGameDialog.hpp" #include "VirtualView.hpp" #include "AugmentedView.hpp" namespace Go_GUI { /** * @brief Checks for gui elements and fonts and connects signals and slots * @param QWidget/QMainWindow parent widget that creates this */ GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr) { ui_main.setupUi(this); QString texture_path = "res/textures/"; whitebasket_pixmap = QPixmap(texture_path + "white_basket.png"); blackbasket_pixmap = QPixmap(texture_path + "black_basket.png"); closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png"); gotable_pixmap = QPixmap(texture_path + "go_table.png"); if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull()) QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path)); // loading font QFontDatabase fontDatabase; QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF"; if (fontDatabase.addApplicationFont(font_path) == -1) QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path)); // connections connect(ui_main.open_action, &QAction::triggered, this, &GUI::slot_MenuOpen); connect(ui_main.save_action, &QAction::triggered, this, &GUI::slot_MenuSave); connect(ui_main.exit_action, &QAction::triggered, this, &QWidget::close); connect(ui_main.info_action, &QAction::triggered, this, &GUI::slot_MenuInfo); connect(ui_main.viewswitch_button, &QPushButton::clicked, this, &GUI::slot_ViewSwitch); connect(ui_main.newgame_button, &QPushButton::clicked, this, &GUI::slot_ButtonNewGame); connect(ui_main.pass_button, &QPushButton::clicked, this, &GUI::slot_ButtonPass); connect(ui_main.resign_button, &QPushButton::clicked, this, &GUI::slot_ButtonResign); // setting initial values this->init(); } /** * @brief Sets initial settings, texts and windows */ void GUI::init(){ this->setWindowTitle("Augmented Go"); this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); virtual_view = new VirtualView(this); augmented_view = new AugmentedView(this); // Attaching augmented view to big container augmented_view->setParent(ui_main.big_container); augmented_view->rescaleImage(ui_main.big_container->size()); ui_main.big_container->setToolTip("augmented view"); augmented_view->show(); // Attaching virtual view to small container virtual_view->setParent(ui_main.small_container); ui_main.small_container->setToolTip("virtual view"); virtual_view->show(); ui_main.white_basket->setPixmap(closedbasket_pixmap); ui_main.black_basket->setPixmap(closedbasket_pixmap); ui_main.go_table_label->setPixmap(gotable_pixmap); ui_main.capturedwhite_label->setText(QString()); ui_main.capturedblack_label->setText(QString()); } /** * @brief sets labels and variables for player names. * @param QString name of black player (default: "Black" * @param QString name of white player (default: "White" */ void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){ ui_main.blackplayer_label->setText(blackplayer_name); ui_main.whiteplayer_label->setText(whiteplayer_name); } ////////// //Public Slots ////////// /** * @brief SLOT "new image" * If a new image is sent to GUI, refresh and rescale picture. * @param QImage new image from scanner */ void GUI::slot_newImage(QImage image) { printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format()); augmented_view->setImage(image); augmented_view->rescaleImage(augmented_view->parentWidget()->size()); } /** * @brief SLOT "new game data" * If new game data is sent to GUI, refresh display of current player and captured stones. * @param game new game representation */ void GUI::slot_newGameData(const GoBackend::Game* game) { // update internal pointer if the board has been changed if (game != game) game = game; auto& board = game->getBoard(); auto current_player = board.ToPlay(); // Updating basket pictures switch (current_player) { case SG_WHITE: ui_main.white_basket->setPixmap(whitebasket_pixmap); ui_main.black_basket->setPixmap(closedbasket_pixmap); break; case SG_BLACK: ui_main.white_basket->setPixmap(closedbasket_pixmap); ui_main.black_basket->setPixmap(blackbasket_pixmap); break; default: assert(false); break; } // Updating Game-Settings ui_main.movenumber_label->setText(QString::number(board.MoveNumber())); ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat())); ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap())); ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE))); ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK))); // refresh virtual view if (ui_main.big_container->toolTip() == "virtual view") virtual_view->createAndSetScene(ui_main.big_container->size(), &board); else if (ui_main.big_container->toolTip() == "augmented view") virtual_view->createAndSetScene(ui_main.small_container->size(), &board); printf(">>> New Game data! <<<\n"); } /** * @brief SLOT "Show finished game results" * If a game ended, the BackendThread sends a signal with the results. * Here the results are shown to the user. */ void GUI::slot_showFinishedGameResults(QString result){ QMessageBox::information(this, "Game results", result); auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?"); if (answer == QMessageBox::Yes) this->slot_ButtonNewGame(); } /** * @brief SLOT "setup new game" * When a new game has been started, setup game name and player names on gui. * @param QString game name * @param QString black player name * @param QString white player name */ void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){ // emit to backend that gui wants to set up a new game! auto rules = GoRules(0, GoKomi(komi), true, true); emit signal_newGame(rules); // Setting up new names for players ui_main.gamename_label->setText(game_name); ui_main.blackplayer_label->setText(blackplayer_name); ui_main.whiteplayer_label->setText(whiteplayer_name); ui_main.kominumber_label->setText(QString::number(komi)); ui_main.handicapnumber_label->setText(QString::number(0)); } ////////// //Private Slots ////////// /** * @brief SLOT "NewGame/Reset" * Opens a Dialog that asks for game rules and names. */ void GUI::slot_ButtonNewGame(){ NewGameDialog* newgame = new NewGameDialog(this); newgame->exec(); } /** * @brief SLOT "Resign" * Opens a Dialog that asks for confirmation. * If answered yes, a signal is sent to backend that the current player surrenders. */ void GUI::slot_ButtonResign(){ if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes) emit signal_resign(); } /** * @brief SLOT "Pass" * Opens a Dialog that asks for confirmation. * If answered yes, a signal is sent to backend that the current player passes. */ void GUI::slot_ButtonPass(){ if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes) emit signal_pass(); } /** * @brief SLOT "ViewSwitch" * Switches big view with small view. * To assign a view to something a QWidget has to be created. */ void GUI::slot_ViewSwitch(){ if (ui_main.big_container->toolTip() == "virtual view"){ // switching augmented view to big container augmented_view->setParent(ui_main.big_container); augmented_view->rescaleImage(ui_main.big_container->size()); ui_main.big_container->setToolTip("augmented view"); augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !! // new style virtual_view->setParent(ui_main.small_container); virtual_view->createAndSetScene(ui_main.small_container->size(), &(go_game->getBoard())); ui_main.small_container->setToolTip("virtual view"); virtual_view->show(); } else if (ui_main.big_container->toolTip() == "augmented view"){ // switching augmented view to small container augmented_view->setParent(ui_main.small_container); augmented_view->rescaleImage(ui_main.small_container->size()); ui_main.small_container->setToolTip("augmented view"); augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !! virtual_view->setParent(ui_main.big_container); virtual_view->createAndSetScene(ui_main.big_container->size(), &(go_game->getBoard())); ui_main.big_container->setToolTip("virtual view"); virtual_view->show(); } } /** * @brief SLOT QAction "MenuOpen" * opens a filedialog that lets the user choose an sgf-file. * @todo loading sgf file */ void GUI::slot_MenuOpen(){ QString selfilter = tr("SGF (*.sgf)"); QString fileName = QFileDialog::getOpenFileName( this, "open sgf-file", NULL, tr("SGF (*.sgf)" ), &selfilter ); if (!fileName.isNull()){ // TODO ask if user wants to save the current game! emit signal_openGame(fileName); } } /** * @brief SLOT QAction "MenuSave" * opens a filedialog that lets the user choose an sgf-file. */ void GUI::slot_MenuSave(){ QString selfilter = tr("SGF (*.sgf)"); QString fileName = QFileDialog::getSaveFileName( this, "save sgf-file", NULL, tr("SGF (*.sgf)" ), &selfilter ); if (!fileName.isNull()) emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name); } /** * @brief SLOT QAction "MenuInfo" * opens a window with information about the application. */ void GUI::slot_MenuInfo(){ // Appliction Info std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n"; // Build date and time output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n"; // Copyright std::string year = __DATE__; year = year.substr(year.find_last_of(" ")); // deleting day and month output += "Copyright " + year + "\n"; // Licence output += "\nThis software is released under the \"MIT License\".\n" "See the file LICENSE for full license and copying terms.\n"; // Final InfoBox QMessageBox::about(this, "Info", output.c_str()); } /** * @brief overridden SLOT QCloseEvent "closeEvent" * When trying to close the application a window appears and asks if user is sure. * If answered "yes" the a signal to the backend thread is sent to stop it. * If answered "no" the close event is ignored. * @param QCloseEvent close event that shall or shall not be executed afterwards. */ void GUI::closeEvent(QCloseEvent *event){ // If at least one move was was done // TODO If game loaded -> move number greater than start number! if (ui_main.movenumber_label->text().toInt() > 0){ if (QMessageBox::question(this, "Save?", "Save current game?") == QMessageBox::Yes) this->slot_MenuSave(); } // Ask if the user wants to quit if (QMessageBox::question(this, "Quit?", "Do you really want to quit?") == QMessageBox::Yes){ emit stop_backend_thread(); event->accept(); } else event->ignore(); } } // namespace Go_GUI<commit_msg>refs #104 changed button texts<commit_after>#include "GUI.hpp" #include <string> #include <vector> #include <QMessageBox> #include <QAction> #include <QCloseEvent> #include <QFontDatabase> #include "Game.hpp" #include "NewGameDialog.hpp" #include "VirtualView.hpp" #include "AugmentedView.hpp" namespace Go_GUI { /** * @brief Checks for gui elements and fonts and connects signals and slots * @param QWidget/QMainWindow parent widget that creates this */ GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr) { ui_main.setupUi(this); QString texture_path = "res/textures/"; whitebasket_pixmap = QPixmap(texture_path + "white_basket.png"); blackbasket_pixmap = QPixmap(texture_path + "black_basket.png"); closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png"); gotable_pixmap = QPixmap(texture_path + "go_table.png"); if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull()) QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path)); // loading font QFontDatabase fontDatabase; QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF"; if (fontDatabase.addApplicationFont(font_path) == -1) QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path)); // connections connect(ui_main.open_action, &QAction::triggered, this, &GUI::slot_MenuOpen); connect(ui_main.save_action, &QAction::triggered, this, &GUI::slot_MenuSave); connect(ui_main.exit_action, &QAction::triggered, this, &QWidget::close); connect(ui_main.info_action, &QAction::triggered, this, &GUI::slot_MenuInfo); connect(ui_main.viewswitch_button, &QPushButton::clicked, this, &GUI::slot_ViewSwitch); connect(ui_main.newgame_button, &QPushButton::clicked, this, &GUI::slot_ButtonNewGame); connect(ui_main.pass_button, &QPushButton::clicked, this, &GUI::slot_ButtonPass); connect(ui_main.resign_button, &QPushButton::clicked, this, &GUI::slot_ButtonResign); // setting initial values this->init(); } /** * @brief Sets initial settings, texts and windows */ void GUI::init(){ this->setWindowTitle("Augmented Go"); this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); virtual_view = new VirtualView(this); augmented_view = new AugmentedView(this); // Attaching augmented view to big container augmented_view->setParent(ui_main.big_container); augmented_view->rescaleImage(ui_main.big_container->size()); ui_main.big_container->setToolTip("augmented view"); augmented_view->show(); // Attaching virtual view to small container virtual_view->setParent(ui_main.small_container); ui_main.small_container->setToolTip("virtual view"); virtual_view->show(); ui_main.white_basket->setPixmap(closedbasket_pixmap); ui_main.black_basket->setPixmap(closedbasket_pixmap); ui_main.go_table_label->setPixmap(gotable_pixmap); ui_main.capturedwhite_label->setText(QString()); ui_main.capturedblack_label->setText(QString()); } /** * @brief sets labels and variables for player names. * @param QString name of black player (default: "Black" * @param QString name of white player (default: "White" */ void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){ ui_main.blackplayer_label->setText(blackplayer_name); ui_main.whiteplayer_label->setText(whiteplayer_name); } ////////// //Public Slots ////////// /** * @brief SLOT "new image" * If a new image is sent to GUI, refresh and rescale picture. * @param QImage new image from scanner */ void GUI::slot_newImage(QImage image) { printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format()); augmented_view->setImage(image); augmented_view->rescaleImage(augmented_view->parentWidget()->size()); } /** * @brief SLOT "new game data" * If new game data is sent to GUI, refresh display of current player and captured stones. * @param game new game representation */ void GUI::slot_newGameData(const GoBackend::Game* game) { // update internal pointer if the board has been changed if (game != game) game = game; auto& board = game->getBoard(); auto current_player = board.ToPlay(); // Updating basket pictures switch (current_player) { case SG_WHITE: ui_main.white_basket->setPixmap(whitebasket_pixmap); ui_main.black_basket->setPixmap(closedbasket_pixmap); break; case SG_BLACK: ui_main.white_basket->setPixmap(closedbasket_pixmap); ui_main.black_basket->setPixmap(blackbasket_pixmap); break; default: assert(false); break; } // Updating Game-Settings ui_main.movenumber_label->setText(QString::number(board.MoveNumber())); ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat())); ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap())); ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE))); ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK))); // refresh virtual view if (ui_main.big_container->toolTip() == "virtual view") virtual_view->createAndSetScene(ui_main.big_container->size(), &board); else if (ui_main.big_container->toolTip() == "augmented view") virtual_view->createAndSetScene(ui_main.small_container->size(), &board); printf(">>> New Game data! <<<\n"); } /** * @brief SLOT "Show finished game results" * If a game ended, the BackendThread sends a signal with the results. * Here the results are shown to the user. */ void GUI::slot_showFinishedGameResults(QString result){ QMessageBox::information(this, "Game results", result); auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?"); if (answer == QMessageBox::Yes) this->slot_ButtonNewGame(); } /** * @brief SLOT "setup new game" * When a new game has been started, setup game name and player names on gui. * @param QString game name * @param QString black player name * @param QString white player name */ void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){ // emit to backend that gui wants to set up a new game! auto rules = GoRules(0, GoKomi(komi), true, true); emit signal_newGame(rules); // Setting up new names for players ui_main.gamename_label->setText(game_name); ui_main.blackplayer_label->setText(blackplayer_name); ui_main.whiteplayer_label->setText(whiteplayer_name); ui_main.kominumber_label->setText(QString::number(komi)); ui_main.handicapnumber_label->setText(QString::number(0)); } ////////// //Private Slots ////////// /** * @brief SLOT "NewGame/Reset" * Opens a Dialog that asks for game rules and names. */ void GUI::slot_ButtonNewGame(){ NewGameDialog* newgame = new NewGameDialog(this); newgame->exec(); } /** * @brief SLOT "Resign" * Opens a Dialog that asks for confirmation. * If answered yes, a signal is sent to backend that the current player surrenders. */ void GUI::slot_ButtonResign(){ if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes) emit signal_resign(); } /** * @brief SLOT "Pass" * Opens a Dialog that asks for confirmation. * If answered yes, a signal is sent to backend that the current player passes. */ void GUI::slot_ButtonPass(){ if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes) emit signal_pass(); } /** * @brief SLOT "ViewSwitch" * Switches big view with small view. * To assign a view to something a QWidget has to be created. */ void GUI::slot_ViewSwitch(){ if (ui_main.big_container->toolTip() == "virtual view"){ // switching augmented view to big container augmented_view->setParent(ui_main.big_container); augmented_view->rescaleImage(ui_main.big_container->size()); ui_main.big_container->setToolTip("augmented view"); augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !! // new style virtual_view->setParent(ui_main.small_container); virtual_view->createAndSetScene(ui_main.small_container->size(), &(go_game->getBoard())); ui_main.small_container->setToolTip("virtual view"); virtual_view->show(); } else if (ui_main.big_container->toolTip() == "augmented view"){ // switching augmented view to small container augmented_view->setParent(ui_main.small_container); augmented_view->rescaleImage(ui_main.small_container->size()); ui_main.small_container->setToolTip("augmented view"); augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !! virtual_view->setParent(ui_main.big_container); virtual_view->createAndSetScene(ui_main.big_container->size(), &(go_game->getBoard())); ui_main.big_container->setToolTip("virtual view"); virtual_view->show(); } } /** * @brief SLOT QAction "MenuOpen" * opens a filedialog that lets the user choose an sgf-file. * @todo loading sgf file */ void GUI::slot_MenuOpen(){ QString selfilter = tr("SGF (*.sgf)"); QString fileName = QFileDialog::getOpenFileName( this, "open sgf-file", NULL, tr("SGF (*.sgf)" ), &selfilter ); if (!fileName.isNull()){ // TODO ask if user wants to save the current game! emit signal_openGame(fileName); } } /** * @brief SLOT QAction "MenuSave" * opens a filedialog that lets the user choose an sgf-file. */ void GUI::slot_MenuSave(){ QString selfilter = tr("SGF (*.sgf)"); QString fileName = QFileDialog::getSaveFileName( this, "save sgf-file", NULL, tr("SGF (*.sgf)" ), &selfilter ); if (!fileName.isNull()) emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name); } /** * @brief SLOT QAction "MenuInfo" * opens a window with information about the application. */ void GUI::slot_MenuInfo(){ // Appliction Info std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n"; // Build date and time output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n"; // Copyright std::string year = __DATE__; year = year.substr(year.find_last_of(" ")); // deleting day and month output += "Copyright " + year + "\n"; // Licence output += "\nThis software is released under the \"MIT License\".\n" "See the file LICENSE for full license and copying terms.\n"; // Final InfoBox QMessageBox::about(this, "Info", output.c_str()); } /** * @brief overridden SLOT QCloseEvent "closeEvent" * When trying to close the application a window appears and asks if user is sure. * If answered "yes" the a signal to the backend thread is sent to stop it. * If answered "no" the close event is ignored. * @param QCloseEvent close event that shall or shall not be executed afterwards. */ void GUI::closeEvent(QCloseEvent *event){ // If at least one move was was done // TODO If game loaded -> move number greater than start number! int answer = 0; bool saveable = ui_main.movenumber_label->text().toInt() > 0; if (saveable) answer = QMessageBox::question(this, "Save?", "Do you want to save before quit?", "Save", "Don't Save", "Cancel"); else answer = QMessageBox::question(this, "Quit?", "Do you really want to quit?", "Quit", "Cancel"); if(answer == 0 && saveable){ this->slot_MenuSave(); emit stop_backend_thread(); event->accept(); } else if((answer == 1 && saveable) || (answer == 0 && !saveable)){ emit stop_backend_thread(); event->accept(); } else event->ignore(); } } // namespace Go_GUI<|endoftext|>
<commit_before>// Copyright 2013-2015 Stanford University // // 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 <cmath> #include <algorithm> #include <array> #include <limits> #include "src/cost/correctness.h" #include "src/ext/x64asm/include/x64asm.h" using namespace cpputil; using namespace std; using namespace x64asm; namespace stoke { CorrectnessCost& CorrectnessCost::set_target(const Cfg& target, bool stack_out, bool heap_out) { assert(sandbox_ != nullptr); live_out_ = target.live_outs(); stack_out_ = stack_out; heap_out_ = heap_out; reference_out_.clear(); recompute_target_defs(target.live_outs()); sandbox_->insert_function(target); sandbox_->set_entrypoint(target.get_code()[0].get_operand<x64asm::Label>(0)); sandbox_->run(); for (auto i = sandbox_->result_begin(), ie = sandbox_->result_end(); i != ie; ++i) { reference_out_.push_back(*i); } return *this; } void CorrectnessCost::recompute_target_defs(const RegSet& rs) { target_gp_out_.clear(); for (auto i = rs.gp_begin(), ie = rs.gp_end(); i != ie; ++i) { target_gp_out_.push_back(*i); } target_sse_out_.clear(); for (auto i = rs.any_sub_sse_begin(), ie = rs.any_sub_sse_end(); i != ie; ++i) { target_sse_out_.push_back(*i); } // TODO -- An x64asm iterator over these flags would be nice target_rf_out_.clear(); for (auto f: { eflags_cf, eflags_pf, eflags_af, eflags_zf, eflags_of, eflags_sf }) { if (rs.contains(f)) { target_rf_out_.push_back(f); } } } /** Evaluate a rewrite. This method may shortcircuit and return max as soon as its result would equal or exceed that value. */ CorrectnessCost::result_type CorrectnessCost::operator()(const Cfg& cfg, const Cost max) { run_sandbox(cfg); auto cost = evaluate_correctness(cfg, max); bool correct = cost == 0; return result_type(correct, cost); } Cost CorrectnessCost::evaluate_correctness(const Cfg& cfg, const Cost max) { switch (reduction_) { case Reduction::MAX: return max_correctness(cfg, max); case Reduction::SUM: return sum_correctness(cfg, max); default: assert(false); return 0; } } Cost CorrectnessCost::max_correctness(const Cfg& cfg, const Cost max) { Cost res = 0; counter_example_testcase_ = -1; size_t i = 0; for (size_t ie = sandbox_->size(); res < max && i < ie; ++i) { const auto err = evaluate_error(reference_out_[i], *(sandbox_->get_result(i)), cfg.def_outs()); assert(err <= max_testcase_cost); if (err != 0 && counter_example_testcase_ < 0) { counter_example_testcase_ = i; } res = std::max(res, err); } assert(res <= max_correctness_cost); return res; } Cost CorrectnessCost::sum_correctness(const Cfg& cfg, const Cost max) { Cost res = 0; counter_example_testcase_ = -1; size_t i = 0; for (size_t ie = sandbox_->size(); res < max && i < ie; ++i) { const auto err = evaluate_error(reference_out_[i], *(sandbox_->get_result(i)), cfg.def_outs()); assert(err <= max_testcase_cost); if (err != 0 && counter_example_testcase_ < 0) { counter_example_testcase_ = i; } res += err; } assert(res <= max_correctness_cost); return res; } Cost CorrectnessCost::evaluate_error(const CpuState& t, const CpuState& r, const RegSet& defs) const { // Only assess a signal penalty if target and rewrite disagree if (t.code != r.code) { return sig_penalty_; } // If this testcase has signalled, we can't guarantee register state -- // and technically we can do whatever we want with signalling code -- so // just return zero cost if (t.code != ErrorCode::NORMAL) { return 0; } // Otherwise, we can do the usual thing and check results register by register Cost cost = 0; cost += gp_error(t, r, defs); cost += sse_error(t.sse, r.sse, defs); cost += rflags_error(t.rf, r.rf, defs); if (stack_out_) { cost += mem_error(t.stack, r.stack); } if (heap_out_) { cost += block_heap_ ? block_mem_error(t.heap, r.heap, r.sse, defs) : mem_error(t.heap, r.heap); } return cost; } Cost CorrectnessCost::gp_error(const CpuState& t, const CpuState& r, const RegSet& defs) const { Cost cost = 0; for (const auto& r_t : target_gp_out_) { auto size = r_t.size(); auto bytes = size/8; auto delta = undef_default(bytes); const auto val_t = t[r_t]; auto is_t_rh = (r_t).type() == Type::RH; for (auto r_r = defs.gp_begin(), r_re = defs.gp_end(); r_r != r_re; ++r_r) { if (r_t != *r_r && !relax_reg_) { continue; } if ((*r_r).size() < size) { continue; } uint64_t val_r; bool is_same = false; auto is_r_rh = (*r_r).type() == Type::RH; if (!(is_t_rh && is_r_rh)) { // normal case, we are looking at two non-rh registers val_r = r.read_gp(*r_r, size, 0); is_same = ((uint64_t)r_t) == ((uint64_t)*r_r); } else if (is_t_rh && is_r_rh) { // we are comparing two rh registers, also simple val_r = r[*r_r]; is_same = r_t == *r_r; } else if (is_t_rh) { // t is an rh register, but r is not: // make sure that there is a corresponding rh register, and that it's defined if ((*r_r).size() < 16 || *r_r >= 4) { continue; } // get rh register that corresponds to r auto rh = Constants::rhs()[*r_r]; is_same = false; val_r = r[rh]; } else { // r is an rh register, but t is not, so no match assert(is_r_rh); continue; } const auto eval = evaluate_distance(val_t, val_r) + (is_same ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } return cost; } Cost CorrectnessCost::sse_error(const Regs& t, const Regs& r, const RegSet& defs) const { Cost cost = 0; for (size_t i = 0; i < sse_count_; ++i) { for (const auto& s_t : target_sse_out_) { auto delta = undef_default(sse_width_); uint64_t val_t = 0; switch (sse_width_) { case 1: val_t = t[s_t].get_fixed_byte(i); break; case 2: val_t = t[s_t].get_fixed_word(i); break; case 4: val_t = t[s_t].get_fixed_double(i); break; case 8: val_t = t[s_t].get_fixed_quad(i); break; default: assert(false); break; } for (auto s_r = defs.any_sub_sse_begin(), s_re = defs.any_sub_sse_end(); s_r != s_re; ++s_r) { if (s_t != *s_r && !relax_reg_) { continue; } uint64_t val_r = 0; switch (sse_width_) { case 1: val_r = r[*s_r].get_fixed_byte(i); break; case 2: val_r = r[*s_r].get_fixed_word(i); break; case 4: val_r = r[*s_r].get_fixed_double(i); break; case 8: val_r = r[*s_r].get_fixed_quad(i); break; default: assert(false); break; } const auto eval = evaluate_distance(val_t, val_r) + ((s_t == *s_r) ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } } return cost; } Cost CorrectnessCost::mem_error(const Memory& t, const Memory& r) const { Cost cost = 0; for (auto i = t.valid_begin(), ie = t.valid_end(); i != ie; ++i) { if (relax_mem_) { Cost delta = undef_default(1); for (auto j = r.valid_begin(), je = r.valid_end(); j != je; ++j) { const auto eval = evaluate_distance(t[*i], r[*j]) + (*i == *j ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } else { cost += evaluate_distance(t[*i], r[*i]); } } return cost; } Cost CorrectnessCost::block_mem_error(const Memory& t, const Memory& rmem, const Regs& rsse, const RegSet& defs) const { Cost cost = 0; for (size_t i = *t.valid_begin(), ie = t.upper_bound(); i < ie; i += 16) { // Skip invalid blocks if (!t.is_valid(i)) { assert(!t.is_valid_quad(i)); assert(!t.is_valid_quad(i+8)); continue; } // Make sure that this block is valid in the target and rewrite assert(t.is_valid_quad(i) && rmem.is_valid_quad(i)); assert(t.is_valid_quad(i+8) && rmem.is_valid_quad(i+8)); // Start off with vanilla memory to memory comparison Cost delta = evaluate_distance(t.get_quad(i), rmem.get_quad(i)) + evaluate_distance(t.get_quad(i+8), rmem.get_quad(i+8)); // If we've relaxed mem, we can also look in sse registers if (relax_mem_) { for (auto s_r = defs.any_sub_sse_begin(), s_re = defs.any_sub_sse_end(); s_r != s_re; ++s_r) { Cost eval = evaluate_distance(t.get_quad(i), rsse[*s_r].get_fixed_quad(0)) + evaluate_distance(t.get_quad(i+8), rsse[*s_r].get_fixed_quad(1)) + misalign_penalty_; delta = min(delta, eval); } } // Now accrue the lowest cost we were able to find cost += delta; } return cost; } Cost CorrectnessCost::rflags_error(const RFlags& t, const RFlags& r, const RegSet& defs) const { Cost cost = 0; for (auto f : target_rf_out_) { const auto i = f.index(); cost += defs.contains(f) ? (t.is_set(i) ^ r.is_set(i)) : 1; } return cost; } Cost CorrectnessCost::undef_default(size_t num_bytes) const { Cost res = 0; switch (distance_) { case Distance::HAMMING: res = 8*num_bytes; break; case Distance::DOUBLEWORD: res = (num_bytes + 3)/4; break; case Distance::ULP: res = max_error_cost; break; case Distance::EXTENSION: // Add user-defined implementation here ... res = 0; break; default: assert(false); res = 0; } // Invariant 1: Penalty should not exceed max_error_cost assert(res <= max_error_cost); return res; } Cost CorrectnessCost::evaluate_distance(uint64_t x, uint64_t y) const { switch (distance_) { case Distance::HAMMING: return hamming_distance(x, y); case Distance::ULP: return ulp_distance(x, y); case Distance::DOUBLEWORD: return doubleword_distance(x,y); default: assert(false); return 0; } } Cost CorrectnessCost::ulp_distance(uint64_t x, uint64_t y) const { auto t = *((int64_t*)&x); t = t < 0 ? numeric_limits<int64_t>::min() - t : t; auto r = *((int64_t*)&y); r = r < 0 ? numeric_limits<int64_t>::min() - r : r; uint64_t ulp = t >= r ? t - r : r - t; ulp = ulp < min_ulp_ ? 0 : ulp - min_ulp_; return ulp > max_error_cost ? max_error_cost : ulp; } } // namespace stoke <commit_msg>undo invalid fix<commit_after>// Copyright 2013-2015 Stanford University // // 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 <cmath> #include <algorithm> #include <array> #include <limits> #include "src/cost/correctness.h" #include "src/ext/x64asm/include/x64asm.h" using namespace cpputil; using namespace std; using namespace x64asm; namespace stoke { CorrectnessCost& CorrectnessCost::set_target(const Cfg& target, bool stack_out, bool heap_out) { assert(sandbox_ != nullptr); live_out_ = target.live_outs(); stack_out_ = stack_out; heap_out_ = heap_out; reference_out_.clear(); recompute_target_defs(target.live_outs()); sandbox_->insert_function(target); sandbox_->set_entrypoint(target.get_code()[0].get_operand<x64asm::Label>(0)); sandbox_->run(); for (auto i = sandbox_->result_begin(), ie = sandbox_->result_end(); i != ie; ++i) { reference_out_.push_back(*i); } return *this; } void CorrectnessCost::recompute_target_defs(const RegSet& rs) { target_gp_out_.clear(); for (auto i = rs.gp_begin(), ie = rs.gp_end(); i != ie; ++i) { target_gp_out_.push_back(*i); } target_sse_out_.clear(); for (auto i = rs.any_sub_sse_begin(), ie = rs.any_sub_sse_end(); i != ie; ++i) { target_sse_out_.push_back(*i); } // TODO -- An x64asm iterator over these flags would be nice target_rf_out_.clear(); for (auto f: { eflags_cf, eflags_pf, eflags_af, eflags_zf, eflags_of, eflags_sf }) { if (rs.contains(f)) { target_rf_out_.push_back(f); } } } /** Evaluate a rewrite. This method may shortcircuit and return max as soon as its result would equal or exceed that value. */ CorrectnessCost::result_type CorrectnessCost::operator()(const Cfg& cfg, const Cost max) { run_sandbox(cfg); auto cost = evaluate_correctness(cfg, max); bool correct = cost == 0; return result_type(correct, cost); } Cost CorrectnessCost::evaluate_correctness(const Cfg& cfg, const Cost max) { switch (reduction_) { case Reduction::MAX: return max_correctness(cfg, max); case Reduction::SUM: return sum_correctness(cfg, max); default: assert(false); return 0; } } Cost CorrectnessCost::max_correctness(const Cfg& cfg, const Cost max) { Cost res = 0; counter_example_testcase_ = -1; size_t i = 0; for (size_t ie = sandbox_->size(); res < max && i < ie; ++i) { const auto err = evaluate_error(reference_out_[i], *(sandbox_->get_result(i)), cfg.def_outs()); assert(err <= max_testcase_cost); if (err != 0 && counter_example_testcase_ < 0) { counter_example_testcase_ = i; } res = std::max(res, err); } assert(res <= max_correctness_cost); return res; } Cost CorrectnessCost::sum_correctness(const Cfg& cfg, const Cost max) { Cost res = 0; counter_example_testcase_ = -1; size_t i = 0; for (size_t ie = sandbox_->size(); res < max && i < ie; ++i) { const auto err = evaluate_error(reference_out_[i], *(sandbox_->get_result(i)), cfg.def_outs()); assert(err <= max_testcase_cost); if (err != 0 && counter_example_testcase_ < 0) { counter_example_testcase_ = i; } res += err; } assert(res <= max_correctness_cost); return res; } Cost CorrectnessCost::evaluate_error(const CpuState& t, const CpuState& r, const RegSet& defs) const { // Only assess a signal penalty if target and rewrite disagree if (t.code != r.code) { return sig_penalty_; } // If this testcase has signalled, we can't guarantee register state -- // and technically we can do whatever we want with signalling code -- so // just return zero cost if (t.code != ErrorCode::NORMAL) { return 0; } // Otherwise, we can do the usual thing and check results register by register Cost cost = 0; cost += gp_error(t, r, defs); cost += sse_error(t.sse, r.sse, defs); cost += rflags_error(t.rf, r.rf, defs); if (stack_out_) { cost += mem_error(t.stack, r.stack); } if (heap_out_) { cost += block_heap_ ? block_mem_error(t.heap, r.heap, r.sse, defs) : mem_error(t.heap, r.heap); } return cost; } Cost CorrectnessCost::gp_error(const CpuState& t, const CpuState& r, const RegSet& defs) const { Cost cost = 0; for (const auto& r_t : target_gp_out_) { auto size = r_t.size(); auto bytes = size/8; auto delta = undef_default(bytes); const auto val_t = t[r_t]; auto is_t_rh = (r_t).type() == Type::RH; for (auto r_r = defs.gp_begin(), r_re = defs.gp_end(); r_r != r_re; ++r_r) { if (r_t != *r_r && !relax_reg_) { continue; } if ((*r_r).size() < size) { continue; } uint64_t val_r; bool is_same = false; auto is_r_rh = (*r_r).type() == Type::RH; if (!(is_t_rh && is_r_rh)) { // normal case, we are looking at two non-rh registers val_r = r.read_gp(*r_r, size, 0); is_same = ((uint64_t)r_t) == ((uint64_t)*r_r); } else if (is_t_rh && is_r_rh) { // we are comparing two rh registers, also simple val_r = r[*r_r]; is_same = r_t == *r_r; } else if (is_t_rh) { // t is an rh register, but r is not: // make sure that there is a corresponding rh register, and that it's defined if ((*r_r).size() < 16 || *r_r >= 4) { continue; } // get rh register that corresponds to r auto rh = Constants::rhs()[*r_r]; is_same = rh == r_t; val_r = r[rh]; } else { // r is an rh register, but t is not, so no match assert(is_r_rh); continue; } const auto eval = evaluate_distance(val_t, val_r) + (is_same ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } return cost; } Cost CorrectnessCost::sse_error(const Regs& t, const Regs& r, const RegSet& defs) const { Cost cost = 0; for (size_t i = 0; i < sse_count_; ++i) { for (const auto& s_t : target_sse_out_) { auto delta = undef_default(sse_width_); uint64_t val_t = 0; switch (sse_width_) { case 1: val_t = t[s_t].get_fixed_byte(i); break; case 2: val_t = t[s_t].get_fixed_word(i); break; case 4: val_t = t[s_t].get_fixed_double(i); break; case 8: val_t = t[s_t].get_fixed_quad(i); break; default: assert(false); break; } for (auto s_r = defs.any_sub_sse_begin(), s_re = defs.any_sub_sse_end(); s_r != s_re; ++s_r) { if (s_t != *s_r && !relax_reg_) { continue; } uint64_t val_r = 0; switch (sse_width_) { case 1: val_r = r[*s_r].get_fixed_byte(i); break; case 2: val_r = r[*s_r].get_fixed_word(i); break; case 4: val_r = r[*s_r].get_fixed_double(i); break; case 8: val_r = r[*s_r].get_fixed_quad(i); break; default: assert(false); break; } const auto eval = evaluate_distance(val_t, val_r) + ((s_t == *s_r) ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } } return cost; } Cost CorrectnessCost::mem_error(const Memory& t, const Memory& r) const { Cost cost = 0; for (auto i = t.valid_begin(), ie = t.valid_end(); i != ie; ++i) { if (relax_mem_) { Cost delta = undef_default(1); for (auto j = r.valid_begin(), je = r.valid_end(); j != je; ++j) { const auto eval = evaluate_distance(t[*i], r[*j]) + (*i == *j ? 0 : misalign_penalty_); delta = min(delta, eval); } cost += delta; } else { cost += evaluate_distance(t[*i], r[*i]); } } return cost; } Cost CorrectnessCost::block_mem_error(const Memory& t, const Memory& rmem, const Regs& rsse, const RegSet& defs) const { Cost cost = 0; for (size_t i = *t.valid_begin(), ie = t.upper_bound(); i < ie; i += 16) { // Skip invalid blocks if (!t.is_valid(i)) { assert(!t.is_valid_quad(i)); assert(!t.is_valid_quad(i+8)); continue; } // Make sure that this block is valid in the target and rewrite assert(t.is_valid_quad(i) && rmem.is_valid_quad(i)); assert(t.is_valid_quad(i+8) && rmem.is_valid_quad(i+8)); // Start off with vanilla memory to memory comparison Cost delta = evaluate_distance(t.get_quad(i), rmem.get_quad(i)) + evaluate_distance(t.get_quad(i+8), rmem.get_quad(i+8)); // If we've relaxed mem, we can also look in sse registers if (relax_mem_) { for (auto s_r = defs.any_sub_sse_begin(), s_re = defs.any_sub_sse_end(); s_r != s_re; ++s_r) { Cost eval = evaluate_distance(t.get_quad(i), rsse[*s_r].get_fixed_quad(0)) + evaluate_distance(t.get_quad(i+8), rsse[*s_r].get_fixed_quad(1)) + misalign_penalty_; delta = min(delta, eval); } } // Now accrue the lowest cost we were able to find cost += delta; } return cost; } Cost CorrectnessCost::rflags_error(const RFlags& t, const RFlags& r, const RegSet& defs) const { Cost cost = 0; for (auto f : target_rf_out_) { const auto i = f.index(); cost += defs.contains(f) ? (t.is_set(i) ^ r.is_set(i)) : 1; } return cost; } Cost CorrectnessCost::undef_default(size_t num_bytes) const { Cost res = 0; switch (distance_) { case Distance::HAMMING: res = 8*num_bytes; break; case Distance::DOUBLEWORD: res = (num_bytes + 3)/4; break; case Distance::ULP: res = max_error_cost; break; case Distance::EXTENSION: // Add user-defined implementation here ... res = 0; break; default: assert(false); res = 0; } // Invariant 1: Penalty should not exceed max_error_cost assert(res <= max_error_cost); return res; } Cost CorrectnessCost::evaluate_distance(uint64_t x, uint64_t y) const { switch (distance_) { case Distance::HAMMING: return hamming_distance(x, y); case Distance::ULP: return ulp_distance(x, y); case Distance::DOUBLEWORD: return doubleword_distance(x,y); default: assert(false); return 0; } } Cost CorrectnessCost::ulp_distance(uint64_t x, uint64_t y) const { auto t = *((int64_t*)&x); t = t < 0 ? numeric_limits<int64_t>::min() - t : t; auto r = *((int64_t*)&y); r = r < 0 ? numeric_limits<int64_t>::min() - r : r; uint64_t ulp = t >= r ? t - r : r - t; ulp = ulp < min_ulp_ ? 0 : ulp - min_ulp_; return ulp > max_error_cost ? max_error_cost : ulp; } } // namespace stoke <|endoftext|>
<commit_before>// Copyright (c) 2016 Jack Grigg // Copyright (c) 2016 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Implementation of the Equihash Proof-of-Work algorithm. // // Reference // ========= // Alex Biryukov and Dmitry Khovratovich // Equihash: Asymmetric Proof-of-Work Based on the Generalized Birthday Problem // NDSS ’16, 21-24 February 2016, San Diego, CA, USA // https://www.internetsociety.org/sites/default/files/blogs-media/equihash-asymmetric-proof-of-work-based-generalized-birthday-problem.pdf #include "crypto/equihash.h" #include "util.h" #include <algorithm> #include <cmath> #include <iostream> #include <stdexcept> void validate_params(int n, int k) { if (k>=n) { std::cerr << "n must be larger than k\n"; throw invalid_params(); } if (n % 8 != 0) { std::cerr << "Parameters must satisfy n = 0 mod 8\n"; throw invalid_params(); } if ((n/(k+1)) % 8 != 0) { std::cerr << "Parameters must satisfy n/(k+1) = 0 mod 8\n"; throw invalid_params(); } } int Equihash::InitialiseState(eh_HashState& base_state) { unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES] = {}; memcpy(personalization, "ZcashPOW", 8); memcpy(personalization+8, &n, 4); memcpy(personalization+12, &k, 4); return crypto_generichash_blake2b_init_salt_personal(&base_state, NULL, 0, // No key. n/8, NULL, // No salt. personalization); } StepRow::StepRow(unsigned int n, const eh_HashState& base_state, eh_index i) : hash {new unsigned char[n/8]}, len {n/8}, indices {i} { eh_HashState state; state = base_state; crypto_generichash_blake2b_update(&state, (unsigned char*) &i, sizeof(eh_index)); crypto_generichash_blake2b_final(&state, hash, n/8); assert(indices.size() == 1); } StepRow::~StepRow() { delete[] hash; } StepRow::StepRow(const StepRow& a) : hash {new unsigned char[a.len]}, len {a.len}, indices(a.indices) { for (int i = 0; i < len; i++) hash[i] = a.hash[i]; } StepRow& StepRow::operator=(const StepRow& a) { unsigned char* p = new unsigned char[a.len]; for (int i = 0; i < a.len; i++) p[i] = a.hash[i]; delete[] hash; hash = p; len = a.len; indices = a.indices; return *this; } StepRow& StepRow::operator^=(const StepRow& a) { if (a.len != len) { throw std::invalid_argument("Hash length differs"); } if (a.indices.size() != indices.size()) { throw std::invalid_argument("Number of indices differs"); } unsigned char* p = new unsigned char[len]; for (int i = 0; i < len; i++) p[i] = hash[i] ^ a.hash[i]; delete[] hash; hash = p; indices.reserve(indices.size() + a.indices.size()); indices.insert(indices.end(), a.indices.begin(), a.indices.end()); return *this; } void StepRow::TrimHash(int l) { unsigned char* p = new unsigned char[len-l]; for (int i = 0; i < len-l; i++) p[i] = hash[i+l]; delete[] hash; hash = p; len -= l; } bool StepRow::IsZero() { char res = 0; for (int i = 0; i < len; i++) res |= hash[i]; return res == 0; } bool HasCollision(StepRow& a, StepRow& b, int l) { bool res = true; for (int j = 0; j < l; j++) res &= a.hash[j] == b.hash[j]; return res; } // Checks if the intersection of a.indices and b.indices is empty bool DistinctIndices(const StepRow& a, const StepRow& b) { std::vector<eh_index> aSrt(a.indices); std::vector<eh_index> bSrt(b.indices); std::sort(aSrt.begin(), aSrt.end()); std::sort(bSrt.begin(), bSrt.end()); unsigned int i = 0; for (unsigned int j = 0; j < bSrt.size(); j++) { while (aSrt[i] < bSrt[j]) { i++; if (i == aSrt.size()) { return true; } } assert(aSrt[i] >= bSrt[j]); if (aSrt[i] == bSrt[j]) { return false; } } return true; } Equihash::Equihash(unsigned int n, unsigned int k) : n(n), k(k) { validate_params(n, k); } std::set<std::vector<eh_index>> Equihash::BasicSolve(const eh_HashState& base_state) { assert(CollisionBitLength() + 1 < 8*sizeof(eh_index)); eh_index init_size { ((eh_index) 1) << (CollisionBitLength() + 1) }; // 1) Generate first list LogPrint("pow", "Generating first list\n"); std::vector<StepRow> X; X.reserve(init_size); for (eh_index i = 0; i < init_size; i++) { X.emplace_back(n, base_state, i); } // 3) Repeat step 2 until 2n/(k+1) bits remain for (int r = 1; r < k && X.size() > 0; r++) { LogPrint("pow", "Round %d:\n", r); // 2a) Sort the list LogPrint("pow", "- Sorting list\n"); std::sort(X.begin(), X.end()); LogPrint("pow", "- Finding collisions\n"); int i = 0; int posFree = 0; std::vector<StepRow> Xc; while (i < X.size() - 1) { // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits int j = 1; while (i+j < X.size() && HasCollision(X[i], X[i+j], CollisionByteLength())) { j++; } // 2c) Calculate tuples (X_i ^ X_j, (i, j)) for (int l = 0; l < j - 1; l++) { for (int m = l + 1; m < j; m++) { if (DistinctIndices(X[i+l], X[i+m])) { Xc.push_back(X[i+l] ^ X[i+m]); Xc.back().TrimHash(CollisionByteLength()); } } } // 2d) Store tuples on the table in-place if possible while (posFree < i+j && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } i += j; } // 2e) Handle edge case where final table entry has no collision while (posFree < X.size() && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } if (Xc.size() > 0) { // 2f) Add overflow to end of table X.insert(X.end(), Xc.begin(), Xc.end()); } else if (posFree < X.size()) { // 2g) Remove empty space at the end X.erase(X.begin()+posFree, X.end()); X.shrink_to_fit(); } } // k+1) Find a collision on last 2n(k+1) bits LogPrint("pow", "Final round:\n"); std::set<std::vector<eh_index>> solns; if (X.size() > 1) { LogPrint("pow", "- Sorting list\n"); std::sort(X.begin(), X.end()); LogPrint("pow", "- Finding collisions\n"); for (int i = 0; i < X.size() - 1; i++) { StepRow res = X[i] ^ X[i+1]; if (res.IsZero() && DistinctIndices(X[i], X[i+1])) { solns.insert(res.GetSolution()); } } } else LogPrint("pow", "- List is empty\n"); return solns; } bool Equihash::IsValidSolution(const eh_HashState& base_state, std::vector<eh_index> soln) { eh_index soln_size { pow(2, k) }; if (soln.size() != soln_size) { LogPrint("pow", "Invalid solution size: %d\n", soln.size()); return false; } std::vector<StepRow> X; X.reserve(soln_size); for (eh_index i : soln) { X.emplace_back(n, base_state, i); } while (X.size() > 1) { std::vector<StepRow> Xc; for (int i = 0; i < X.size(); i += 2) { if (!HasCollision(X[i], X[i+1], CollisionByteLength())) { LogPrint("pow", "Invalid solution: invalid collision length between StepRows\n"); LogPrint("pow", "X[i] = %s\n", X[i].GetHex()); LogPrint("pow", "X[i+1] = %s\n", X[i+1].GetHex()); return false; } if (X[i+1].IndicesBefore(X[i])) { return false; LogPrint("pow", "Invalid solution: Index tree incorrectly ordered\n"); } if (!DistinctIndices(X[i], X[i+1])) { LogPrint("pow", "Invalid solution: duplicate indices\n"); return false; } Xc.push_back(X[i] ^ X[i+1]); Xc.back().TrimHash(CollisionByteLength()); } X = Xc; } assert(X.size() == 1); return X[0].IsZero(); } <commit_msg>Use left shift instead of floating-point pow() in equihash.<commit_after>// Copyright (c) 2016 Jack Grigg // Copyright (c) 2016 The Zcash developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Implementation of the Equihash Proof-of-Work algorithm. // // Reference // ========= // Alex Biryukov and Dmitry Khovratovich // Equihash: Asymmetric Proof-of-Work Based on the Generalized Birthday Problem // NDSS ’16, 21-24 February 2016, San Diego, CA, USA // https://www.internetsociety.org/sites/default/files/blogs-media/equihash-asymmetric-proof-of-work-based-generalized-birthday-problem.pdf #include "crypto/equihash.h" #include "util.h" #include <algorithm> #include <iostream> #include <stdexcept> void validate_params(int n, int k) { if (k>=n) { std::cerr << "n must be larger than k\n"; throw invalid_params(); } if (n % 8 != 0) { std::cerr << "Parameters must satisfy n = 0 mod 8\n"; throw invalid_params(); } if ((n/(k+1)) % 8 != 0) { std::cerr << "Parameters must satisfy n/(k+1) = 0 mod 8\n"; throw invalid_params(); } } int Equihash::InitialiseState(eh_HashState& base_state) { unsigned char personalization[crypto_generichash_blake2b_PERSONALBYTES] = {}; memcpy(personalization, "ZcashPOW", 8); memcpy(personalization+8, &n, 4); memcpy(personalization+12, &k, 4); return crypto_generichash_blake2b_init_salt_personal(&base_state, NULL, 0, // No key. n/8, NULL, // No salt. personalization); } StepRow::StepRow(unsigned int n, const eh_HashState& base_state, eh_index i) : hash {new unsigned char[n/8]}, len {n/8}, indices {i} { eh_HashState state; state = base_state; crypto_generichash_blake2b_update(&state, (unsigned char*) &i, sizeof(eh_index)); crypto_generichash_blake2b_final(&state, hash, n/8); assert(indices.size() == 1); } StepRow::~StepRow() { delete[] hash; } StepRow::StepRow(const StepRow& a) : hash {new unsigned char[a.len]}, len {a.len}, indices(a.indices) { for (int i = 0; i < len; i++) hash[i] = a.hash[i]; } StepRow& StepRow::operator=(const StepRow& a) { unsigned char* p = new unsigned char[a.len]; for (int i = 0; i < a.len; i++) p[i] = a.hash[i]; delete[] hash; hash = p; len = a.len; indices = a.indices; return *this; } StepRow& StepRow::operator^=(const StepRow& a) { if (a.len != len) { throw std::invalid_argument("Hash length differs"); } if (a.indices.size() != indices.size()) { throw std::invalid_argument("Number of indices differs"); } unsigned char* p = new unsigned char[len]; for (int i = 0; i < len; i++) p[i] = hash[i] ^ a.hash[i]; delete[] hash; hash = p; indices.reserve(indices.size() + a.indices.size()); indices.insert(indices.end(), a.indices.begin(), a.indices.end()); return *this; } void StepRow::TrimHash(int l) { unsigned char* p = new unsigned char[len-l]; for (int i = 0; i < len-l; i++) p[i] = hash[i+l]; delete[] hash; hash = p; len -= l; } bool StepRow::IsZero() { char res = 0; for (int i = 0; i < len; i++) res |= hash[i]; return res == 0; } bool HasCollision(StepRow& a, StepRow& b, int l) { bool res = true; for (int j = 0; j < l; j++) res &= a.hash[j] == b.hash[j]; return res; } // Checks if the intersection of a.indices and b.indices is empty bool DistinctIndices(const StepRow& a, const StepRow& b) { std::vector<eh_index> aSrt(a.indices); std::vector<eh_index> bSrt(b.indices); std::sort(aSrt.begin(), aSrt.end()); std::sort(bSrt.begin(), bSrt.end()); unsigned int i = 0; for (unsigned int j = 0; j < bSrt.size(); j++) { while (aSrt[i] < bSrt[j]) { i++; if (i == aSrt.size()) { return true; } } assert(aSrt[i] >= bSrt[j]); if (aSrt[i] == bSrt[j]) { return false; } } return true; } Equihash::Equihash(unsigned int n, unsigned int k) : n(n), k(k) { validate_params(n, k); } std::set<std::vector<eh_index>> Equihash::BasicSolve(const eh_HashState& base_state) { assert(CollisionBitLength() + 1 < 8*sizeof(eh_index)); eh_index init_size { ((eh_index) 1) << (CollisionBitLength() + 1) }; // 1) Generate first list LogPrint("pow", "Generating first list\n"); std::vector<StepRow> X; X.reserve(init_size); for (eh_index i = 0; i < init_size; i++) { X.emplace_back(n, base_state, i); } // 3) Repeat step 2 until 2n/(k+1) bits remain for (int r = 1; r < k && X.size() > 0; r++) { LogPrint("pow", "Round %d:\n", r); // 2a) Sort the list LogPrint("pow", "- Sorting list\n"); std::sort(X.begin(), X.end()); LogPrint("pow", "- Finding collisions\n"); int i = 0; int posFree = 0; std::vector<StepRow> Xc; while (i < X.size() - 1) { // 2b) Find next set of unordered pairs with collisions on the next n/(k+1) bits int j = 1; while (i+j < X.size() && HasCollision(X[i], X[i+j], CollisionByteLength())) { j++; } // 2c) Calculate tuples (X_i ^ X_j, (i, j)) for (int l = 0; l < j - 1; l++) { for (int m = l + 1; m < j; m++) { if (DistinctIndices(X[i+l], X[i+m])) { Xc.push_back(X[i+l] ^ X[i+m]); Xc.back().TrimHash(CollisionByteLength()); } } } // 2d) Store tuples on the table in-place if possible while (posFree < i+j && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } i += j; } // 2e) Handle edge case where final table entry has no collision while (posFree < X.size() && Xc.size() > 0) { X[posFree++] = Xc.back(); Xc.pop_back(); } if (Xc.size() > 0) { // 2f) Add overflow to end of table X.insert(X.end(), Xc.begin(), Xc.end()); } else if (posFree < X.size()) { // 2g) Remove empty space at the end X.erase(X.begin()+posFree, X.end()); X.shrink_to_fit(); } } // k+1) Find a collision on last 2n(k+1) bits LogPrint("pow", "Final round:\n"); std::set<std::vector<eh_index>> solns; if (X.size() > 1) { LogPrint("pow", "- Sorting list\n"); std::sort(X.begin(), X.end()); LogPrint("pow", "- Finding collisions\n"); for (int i = 0; i < X.size() - 1; i++) { StepRow res = X[i] ^ X[i+1]; if (res.IsZero() && DistinctIndices(X[i], X[i+1])) { solns.insert(res.GetSolution()); } } } else LogPrint("pow", "- List is empty\n"); return solns; } bool Equihash::IsValidSolution(const eh_HashState& base_state, std::vector<eh_index> soln) { eh_index soln_size { 1u << k }; if (soln.size() != soln_size) { LogPrint("pow", "Invalid solution size: %d\n", soln.size()); return false; } std::vector<StepRow> X; X.reserve(soln_size); for (eh_index i : soln) { X.emplace_back(n, base_state, i); } while (X.size() > 1) { std::vector<StepRow> Xc; for (int i = 0; i < X.size(); i += 2) { if (!HasCollision(X[i], X[i+1], CollisionByteLength())) { LogPrint("pow", "Invalid solution: invalid collision length between StepRows\n"); LogPrint("pow", "X[i] = %s\n", X[i].GetHex()); LogPrint("pow", "X[i+1] = %s\n", X[i+1].GetHex()); return false; } if (X[i+1].IndicesBefore(X[i])) { return false; LogPrint("pow", "Invalid solution: Index tree incorrectly ordered\n"); } if (!DistinctIndices(X[i], X[i+1])) { LogPrint("pow", "Invalid solution: duplicate indices\n"); return false; } Xc.push_back(X[i] ^ X[i+1]); Xc.back().TrimHash(CollisionByteLength()); } X = Xc; } assert(X.size() == 1); return X[0].IsZero(); } <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <vector> #include <sstream> #include <string> #include <hdf5.h> #include <hdf5_hl.h> #include "tppmatrix.h" #include "omxmatrix.h" #include "stdutil.h" #include "define.h" int convertMat2h5(char *); int convertH5toMat(char *); string get_h5_name(char *filename); string get_tpp_name(char *filename); int copy_data(TPPMatrix*, OMXMatrix*, int, int, vector<string>&); int copy_data(OMXMatrix*, TPPMatrix*, int, int); hid_t _memspace = -1; hid_t _dataspace = -1; int main(int argc, char* argv[]) { // Get cmdline parameters // for each input .mat file cout << "\nCube MAT/OMX Converter (built " << __DATE__ << ")\n"; int errors = 0; for (int i=1; i<argc; i++) { char *tpfilename = argv[i]; printf("\n\nConverting %s to ",tpfilename); // Figure out which way we're converting: string str(tpfilename); int v; if (((size_t)str.find(".omx")==string::npos) && ((size_t)str.find(".OMX")==string::npos)) { v = convertMat2h5(tpfilename); } else { v = convertH5toMat(tpfilename); } if (v!=0) { printf(">> Failed to convert %s.",tpfilename); errors += v; } } printf("\nDone; %d errors and %d of %d completed.\n",errors,argc-errors-1,argc-1); } int convertMat2h5(char *filename) { int rows, cols, tables, rtn; TPPMatrix *matrix; OMXMatrix *omx; vector<string> matNames; try { // try to open file matrix = new TPPMatrix(); matrix->openFile(filename); // get tp+ parameters such as zones, tables, names. rows = cols = matrix->getZones(); tables = matrix->getTables(); for (int t=1; t<=tables; t++) { string name(matrix->getTableName(t)); matNames.push_back(name); } // Create OMX file string h5_name = get_h5_name(filename); omx = new OMXMatrix(); omx->createFile(tables, rows, cols, matNames, h5_name); // Copy data rtn = copy_data(matrix, omx, rows, tables, matNames); // All done matrix->closeFile(); omx->closeFile(); } catch (TPPMatrix::FileOpenException&) { printf("Can't open %s.",filename); return 1; } return 0; } int convertH5toMat(char *filename) { int zones, tables, rtn; TPPMatrix *tpp; OMXMatrix *omx; const char* tnames[MAX_TABLES]; try { // Open h5 file and get dimensions, table names omx = new OMXMatrix(); omx->openFile(filename); tables = omx->getTables(); zones = omx->getRows(); for (int t=1; t<=tables; t++) { tnames[t-1]=omx->getTableName(t).c_str(); } // create TPP file string tppname = get_tpp_name(filename); tpp = new TPPMatrix(); tpp->createFile(tables, zones, tnames, tppname.c_str()); // Copy data rtn = copy_data(omx, tpp, zones, tables); /* Close the files. */ tpp->closeFile(); omx->closeFile(); } catch (TPPMatrix::FileOpenException&) { printf("Can't open %s.",filename); return 1; } return 0; } // Copy from HDF5 to TPP: int copy_data(OMXMatrix *omx, TPPMatrix *matrix, int zones, int tables) { // Set up some scratch space for reading row data double *rowdata = matrix->allocateRowBuffer(); int row; printf("\n"); string tableNames[MAX_TABLES+1]; for (int t = 1; t <=tables; t++) { tableNames[t] = omx->getTableName(t); } // Loop on all rows for (row=1;row<=zones;row++) { if (row % 127 ==0) printf("Zone: %d\r",row); // Loop for each table for (int t=1;t<=tables;t++) { // Grab a row of data omx->getRow(tableNames[t], row, rowdata); // And write it to h5 matrix->writeRow(t, row, rowdata); } } printf("Zone: %d\n",row-1); free(rowdata); return 0; } // Copy from TPP to HDF5: int copy_data(TPPMatrix *matrix, OMXMatrix *omx, int zones, int tables, vector<string> &matNames) { double* rowdata; // Set up some scratch space for reading row data rowdata = matrix->allocateRowBuffer(); // Loop for each row int col; for (col=1;col<=zones;col++) { if (col %47 == 1) printf("\r%d tables: zone %d ",tables, col); for (int t=1; t<=tables; t++) { // Grab a row of data try { matrix->getRow(t, col, rowdata); } catch (TPPMatrix::MatrixReadException&) { fprintf(stderr, "ERROR: Can't read table row %d in table %d!\n", col, t); exit(2); } // And write it to h5 omx->writeRow(matNames[t-1], col, rowdata); } } // Clean up printf("\r%d tables: zone %d \n",tables, col-1); free(rowdata); return 0; } // Replace .mat with .h5 in filename string get_h5_name(char *filename) { string str(filename); size_t dot = str.rfind('.'); str.erase(dot,4); str.insert(dot,".omx"); printf("%s\n",str.c_str()); return str; } // Replace .mat with .h5 in filename string get_tpp_name(char *filename) { string str(filename); size_t dot = str.rfind('.'); str.erase(dot,4); str.insert(dot,".mat"); printf("%s\n",str.c_str()); return str; } <commit_msg>Add usage msg<commit_after>#include <cstdlib> #include <iostream> #include <vector> #include <sstream> #include <string> #include <hdf5.h> #include <hdf5_hl.h> #include "tppmatrix.h" #include "omxmatrix.h" #include "stdutil.h" #include "define.h" int convertMat2h5(char *); int convertH5toMat(char *); string get_h5_name(char *filename); string get_tpp_name(char *filename); int copy_data(TPPMatrix*, OMXMatrix*, int, int, vector<string>&); int copy_data(OMXMatrix*, TPPMatrix*, int, int); hid_t _memspace = -1; hid_t _dataspace = -1; int main(int argc, char* argv[]) { // Get cmdline parameters // for each input .mat file cout << "\nCube MAT/OMX Converter (built " << __DATE__ << ")\n"; int errors = 0; if (argc==1) { cout << "\nUsage: cube2omx.exe [filename1] [filename2] ...\n"; cout << " - Files ending in .omx or .OMX will be converted from OMX to Cube\n"; cout << " - Files ending in anything else will be converted from Cube to OMX\n\n"; exit(0); } for (int i=1; i<argc; i++) { char *tpfilename = argv[i]; printf("\n\nConverting %s to ",tpfilename); // Figure out which way we're converting: string str(tpfilename); int v; if (((size_t)str.find(".omx")==string::npos) && ((size_t)str.find(".OMX")==string::npos)) { v = convertMat2h5(tpfilename); } else { v = convertH5toMat(tpfilename); } if (v!=0) { printf(">> Failed to convert %s.",tpfilename); errors += v; } } printf("\nDone; %d errors and %d of %d completed.\n",errors,argc-errors-1,argc-1); } int convertMat2h5(char *filename) { int rows, cols, tables, rtn; TPPMatrix *matrix; OMXMatrix *omx; vector<string> matNames; try { // try to open file matrix = new TPPMatrix(); matrix->openFile(filename); // get tp+ parameters such as zones, tables, names. rows = cols = matrix->getZones(); tables = matrix->getTables(); for (int t=1; t<=tables; t++) { string name(matrix->getTableName(t)); matNames.push_back(name); } // Create OMX file string h5_name = get_h5_name(filename); omx = new OMXMatrix(); omx->createFile(tables, rows, cols, matNames, h5_name); // Copy data rtn = copy_data(matrix, omx, rows, tables, matNames); // All done matrix->closeFile(); omx->closeFile(); } catch (TPPMatrix::FileOpenException&) { printf("Can't open %s.",filename); return 1; } return 0; } int convertH5toMat(char *filename) { int zones, tables, rtn; TPPMatrix *tpp; OMXMatrix *omx; const char* tnames[MAX_TABLES]; try { // Open h5 file and get dimensions, table names omx = new OMXMatrix(); omx->openFile(filename); tables = omx->getTables(); zones = omx->getRows(); for (int t=1; t<=tables; t++) { tnames[t-1]=omx->getTableName(t).c_str(); } // create TPP file string tppname = get_tpp_name(filename); tpp = new TPPMatrix(); tpp->createFile(tables, zones, tnames, tppname.c_str()); // Copy data rtn = copy_data(omx, tpp, zones, tables); /* Close the files. */ tpp->closeFile(); omx->closeFile(); } catch (TPPMatrix::FileOpenException&) { printf("Can't open %s.",filename); return 1; } return 0; } // Copy from HDF5 to TPP: int copy_data(OMXMatrix *omx, TPPMatrix *matrix, int zones, int tables) { // Set up some scratch space for reading row data double *rowdata = matrix->allocateRowBuffer(); int row; printf("\n"); string tableNames[MAX_TABLES+1]; for (int t = 1; t <=tables; t++) { tableNames[t] = omx->getTableName(t); } // Loop on all rows for (row=1;row<=zones;row++) { if (row % 127 ==0) printf("Zone: %d\r",row); // Loop for each table for (int t=1;t<=tables;t++) { // Grab a row of data omx->getRow(tableNames[t], row, rowdata); // And write it to h5 matrix->writeRow(t, row, rowdata); } } printf("Zone: %d\n",row-1); free(rowdata); return 0; } // Copy from TPP to HDF5: int copy_data(TPPMatrix *matrix, OMXMatrix *omx, int zones, int tables, vector<string> &matNames) { double* rowdata; // Set up some scratch space for reading row data rowdata = matrix->allocateRowBuffer(); // Loop for each row int col; for (col=1;col<=zones;col++) { if (col %47 == 1) printf("\r%d tables: zone %d ",tables, col); for (int t=1; t<=tables; t++) { // Grab a row of data try { matrix->getRow(t, col, rowdata); } catch (TPPMatrix::MatrixReadException&) { fprintf(stderr, "ERROR: Can't read table row %d in table %d!\n", col, t); exit(2); } // And write it to h5 omx->writeRow(matNames[t-1], col, rowdata); } } // Clean up printf("\r%d tables: zone %d \n",tables, col-1); free(rowdata); return 0; } // Replace .mat with .h5 in filename string get_h5_name(char *filename) { string str(filename); size_t dot = str.rfind('.'); str.erase(dot,4); str.insert(dot,".omx"); printf("%s\n",str.c_str()); return str; } // Replace .mat with .h5 in filename string get_tpp_name(char *filename) { string str(filename); size_t dot = str.rfind('.'); str.erase(dot,4); str.insert(dot,".mat"); printf("%s\n",str.c_str()); return str; } <|endoftext|>
<commit_before>// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- // Small example how write text. // // This code is public domain // (but note, that the led-matrix library this depends on is GPL v2) #include "led-matrix.h" #include "graphics.h" #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> using namespace rgb_matrix; static int usage(const char *progname) { fprintf(stderr, "usage: %s [options]\n", progname); fprintf(stderr, "Reads text from stdin and displays it. " "Empty string: clear screen\n"); fprintf(stderr, "Options:\n" "\t-f <font-file>: Use given font.\n" "\t-r <rows> : Display rows. 16 for 16x32, 32 for 32x32. " "Default: 32\n" "\t-c <chained> : Daisy-chained boards. Default: 1.\n" "\t-x <x-origin> : X-Origin of displaying text (Default: 0)\n" "\t-y <y-origin> : Y-Origin of displaying text (Default: 0)\n" "\t-C <r,g,b> : Color. Default 255,255,0\n"); return 1; } static bool parseColor(Color *c, const char *str) { return sscanf(str, "%hhu,%hhu,%hhu", &c->r, &c->g, &c->b) == 3; } int main(int argc, char *argv[]) { const char *line = NULL; Color color(255, 0, 0); const char *bdf_font_file = "/root/rpi-rgb-led-matrix/fonts/7x14.bdf"; int rows = 16; int chain = 3; int x_orig = 1; int y_orig = 1; int microseconds = 2000000; int opt; while ((opt = getopt(argc, argv, "r:c:x:y:f:t:m:C:")) != -1) { switch (opt) { case 'r': rows = atoi(optarg); break; case 'c': chain = atoi(optarg); break; case 'x': x_orig = atoi(optarg); break; case 'y': y_orig = atoi(optarg); break; case 'm': microseconds = atoi(optarg); break; case 'f': bdf_font_file = strdup(optarg); break; case 't': line = strdup(optarg); break; case 'C': if (!parseColor(&color, optarg)) { fprintf(stderr, "Invalid color spec.\n"); return usage(argv[0]); } break; } } if (bdf_font_file == NULL) { fprintf(stderr, "Need to specify BDF font-file with -f\n"); return usage(argv[0]); } /* * Load font. This needs to be a filename with a bdf bitmap font. */ rgb_matrix::Font font; if (!font.LoadFont(bdf_font_file)) { fprintf(stderr, "Couldn't load font '%s'\n", bdf_font_file); return usage(argv[0]); } /* * Set up GPIO pins. This fails when not running as root. */ GPIO io; if (!io.Init()) return 1; /* * Set up the RGBMatrix. It implements a 'Canvas' interface. */ RGBMatrix *canvas = new RGBMatrix(&io, rows, chain); bool all_extreme_colors = true; all_extreme_colors &= color.r == 0 || color.r == 255; all_extreme_colors &= color.g == 0 || color.g == 255; all_extreme_colors &= color.b == 0 || color.b == 255; if (all_extreme_colors) canvas->SetPWMBits(1); const int x = x_orig; int y = y_orig; bool line_empty = strlen(line) == 0; if ((y + font.height() > canvas->height()) || line_empty) { canvas->Clear(); y = y_orig; } if (line_empty) return -1; rgb_matrix::DrawText(canvas, font, x, y + font.baseline(), color, line); y += font.height(); usleep(microseconds); // Finished. Shut down the RGB matrix. canvas->Clear(); delete canvas; return 0; } <commit_msg>Relative font path, micro to seconds<commit_after>// -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*- // Small example how write text. // // This code is public domain // (but note, that the led-matrix library this depends on is GPL v2) #include "led-matrix.h" #include "graphics.h" #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> using namespace rgb_matrix; static int usage(const char *progname) { fprintf(stderr, "usage: %s [options]\n", progname); fprintf(stderr, "Reads text from stdin and displays it. " "Empty string: clear screen\n"); fprintf(stderr, "Options:\n" "\t-t <text>: Text to be displayed (<= 13 chars).\n" "\t-s <seconds>: seconds to sleep.\n" "\t-f <font-file>: Use given font.\n" "\t-r <rows> : Display rows. 16 for 16x32, 32 for 32x32. " "Default: 32\n" "\t-c <chained> : Daisy-chained boards. Default: 1.\n" "\t-x <x-origin> : X-Origin of displaying text (Default: 0)\n" "\t-y <y-origin> : Y-Origin of displaying text (Default: 0)\n" "\t-C <r,g,b> : Color. Default 255,255,0\n"); return 1; } static bool parseColor(Color *c, const char *str) { return sscanf(str, "%hhu,%hhu,%hhu", &c->r, &c->g, &c->b) == 3; } int main(int argc, char *argv[]) { Color color(0, 105, 166); const char *line = NULL; const char *bdf_font_file = "./fonts/7x14.bdf"; unsigned int rows = 16; unsigned int chain = 3; unsigned int x_orig = 1; unsigned int y_orig = 1; unsigned int seconds = 2; int opt; while ((opt = getopt(argc, argv, "r:c:x:y:s:f:t:C:")) != -1) { switch (opt) { case 'r': rows = atoi(optarg); break; case 'c': chain = atoi(optarg); break; case 'x': x_orig = atoi(optarg); break; case 'y': y_orig = atoi(optarg); break; case 's': seconds = atoi(optarg); break; case 'f': bdf_font_file = strdup(optarg); break; case 't': line = strdup(optarg); break; case 'C': if (!parseColor(&color, optarg)) { fprintf(stderr, "Invalid color spec.\n"); return usage(argv[0]); } break; } } if (bdf_font_file == NULL) { fprintf(stderr, "Need to specify BDF font-file with -f\n"); return usage(argv[0]); } /* * Load font. This needs to be a filename with a bdf bitmap font. */ rgb_matrix::Font font; if (!font.LoadFont(bdf_font_file)) { fprintf(stderr, "Couldn't load font '%s'\n", bdf_font_file); return usage(argv[0]); } /* * Set up GPIO pins. This fails when not running as root. */ GPIO io; if (!io.Init()) return 1; /* * Set up the RGBMatrix. It implements a 'Canvas' interface. */ RGBMatrix *canvas = new RGBMatrix(&io, rows, chain); bool all_extreme_colors = true; all_extreme_colors &= color.r == 0 || color.r == 255; all_extreme_colors &= color.g == 0 || color.g == 255; all_extreme_colors &= color.b == 0 || color.b == 255; if (all_extreme_colors) canvas->SetPWMBits(1); const int x = x_orig; int y = y_orig; bool line_empty = strlen(line) == 0; if ((y + font.height() > canvas->height()) || line_empty) { canvas->Clear(); y = y_orig; } if (line_empty) return -1; rgb_matrix::DrawText(canvas, font, x, y + font.baseline(), color, line); y += font.height(); usleep(seconds*1000000); // Finished. Shut down the RGB matrix. canvas->Clear(); delete canvas; return 0; } <|endoftext|>
<commit_before>#ifndef ITER_CYCLE_H_ #define ITER_CYCLE_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Cycle and cycle template <typename Container> class Cycle; template <typename Container> Cycle<Container> cycle(Container&&); template <typename T> Cycle<std::initializer_list<T>> cycle(std::initializer_list<T>); template <typename Container> class Cycle { private: // The cycle function is the only thing allowed to create a Cycle friend Cycle cycle<Container>(Container&&); template <typename T> friend Cycle<std::initializer_list<T>> cycle( std::initializer_list<T>); Container container; // Value constructor for use only in the cycle function Cycle(Container container) : container(std::forward<Container>(container)) { } public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: using iter_type = iterator_type<Container>; iterator_type<Container> sub_iter; const iterator_type<Container> begin; const iterator_type<Container> end; public: Iterator (iterator_type<Container> iter, iterator_type<Container> end) : sub_iter{iter}, begin{iter}, end{end} { } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; // reset to beginning upon reaching the end if (!(this->sub_iter != this->end)) { // explicit destruction with placement new in order // to support iterators with no operator= this->sub_iter.~iter_type(); new(&this->sub_iter) iterator_type<Container>( this->begin); } return *this; } constexpr bool operator!=(const Iterator&) const { return true; } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; // Helper function to instantiate a Cycle template <typename Container> Cycle<Container> cycle(Container&& container) { return {std::forward<Container>(container)}; } template <typename T> Cycle<std::initializer_list<T>> cycle(std::initializer_list<T> il) { return {std::move(il)}; } } #endif <commit_msg>adds cycle iter ==<commit_after>#ifndef ITER_CYCLE_H_ #define ITER_CYCLE_H_ #include "iterbase.hpp" #include <utility> #include <iterator> #include <initializer_list> namespace iter { //Forward declarations of Cycle and cycle template <typename Container> class Cycle; template <typename Container> Cycle<Container> cycle(Container&&); template <typename T> Cycle<std::initializer_list<T>> cycle(std::initializer_list<T>); template <typename Container> class Cycle { private: // The cycle function is the only thing allowed to create a Cycle friend Cycle cycle<Container>(Container&&); template <typename T> friend Cycle<std::initializer_list<T>> cycle( std::initializer_list<T>); Container container; // Value constructor for use only in the cycle function Cycle(Container container) : container(std::forward<Container>(container)) { } public: class Iterator : public std::iterator<std::input_iterator_tag, iterator_traits_deref<Container>> { private: using iter_type = iterator_type<Container>; iterator_type<Container> sub_iter; const iterator_type<Container> begin; const iterator_type<Container> end; public: Iterator (iterator_type<Container> iter, iterator_type<Container> end) : sub_iter{iter}, begin{iter}, end{end} { } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { ++this->sub_iter; // reset to beginning upon reaching the end if (!(this->sub_iter != this->end)) { // explicit destruction with placement new in order // to support iterators with no operator= this->sub_iter.~iter_type(); new(&this->sub_iter) iterator_type<Container>( this->begin); } return *this; } constexpr bool operator!=(const Iterator&) const { return true; } bool operator==(const Iterator& other) const { return !(*this != other); } }; Iterator begin() { return {std::begin(this->container), std::end(this->container)}; } Iterator end() { return {std::end(this->container), std::end(this->container)}; } }; // Helper function to instantiate a Cycle template <typename Container> Cycle<Container> cycle(Container&& container) { return {std::forward<Container>(container)}; } template <typename T> Cycle<std::initializer_list<T>> cycle(std::initializer_list<T> il) { return {std::move(il)}; } } #endif <|endoftext|>
<commit_before>#pragma once /** * Central place to store Solver config options */ #include <cstdio> #include <vector> #include <cmath> struct SolverOptions { double residual; int max_iters, restart; unsigned max_p, p_min; bool variable_p; enum relaxation_type { SIMONCINI, BOURAS }; relaxation_type relax_type; SolverOptions(double r, int m_iters, unsigned p) : residual(r), max_iters(m_iters), restart(50), max_p(p), variable_p(false), relax_type(BOURAS) {}; SolverOptions() : residual(1e-5), max_iters(500), restart(500), max_p(16), p_min(5), variable_p(true), relax_type(BOURAS) {}; unsigned predict_p(double eps) const { // if no relaxation, return default p if (!this->variable_p) return max_p; // relaxation from Bouras & Fraysse if (this->relax_type == BOURAS) { double alpha = 1. / std::min(eps, 1.); double nu = std::min(alpha*this->residual,1.); // predict p for Spherical Laplace kernel -- abstract out return std::min((unsigned)ceil(-log(nu)),max_p); } else if (this->relax_type == SIMONCINI) { return std::min((unsigned)ceil(-log(eps)),max_p); } return max_p; } }; <commit_msg>change log to log2 in predict_p function<commit_after>#pragma once /** * Central place to store Solver config options */ #include <cstdio> #include <vector> #include <cmath> struct SolverOptions { double residual; int max_iters, restart; unsigned max_p, p_min; bool variable_p; enum relaxation_type { SIMONCINI, BOURAS }; relaxation_type relax_type; SolverOptions(double r, int m_iters, unsigned p) : residual(r), max_iters(m_iters), restart(50), max_p(p), variable_p(false), relax_type(BOURAS) {}; SolverOptions() : residual(1e-5), max_iters(500), restart(500), max_p(16), p_min(5), variable_p(true), relax_type(BOURAS) {}; unsigned predict_p(double eps) const { // if no relaxation, return default p if (!this->variable_p) return max_p; // relaxation from Bouras & Fraysse if (this->relax_type == BOURAS) { double alpha = 1. / std::min(eps, 1.); double nu = std::min(alpha*this->residual,1.); // predict p for Spherical Laplace kernel -- abstract out return std::min((unsigned)ceil(-log2(nu)),max_p); } else if (this->relax_type == SIMONCINI) { return std::min((unsigned)ceil(-log2(eps)),max_p); } return max_p; } }; <|endoftext|>
<commit_before>// Copyright (c) 2012-2017 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 "util.h" #include "utiltime.h" #include "validation.h" #include "test/test_bitcoin.h" #include "checkqueue.h" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> #include <memory> #include "random.h" // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { ++n_calls; return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory += b; }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory += b; }; ~MemoryCheck(){ fake_allocated_memory -= b; }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen = 1; cv.notify_one(); cv.wait(l, []{ return nFrozen == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (auto i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r || end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::unique_ptr<Unique_Queue>(new Unique_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::unique_ptr<Memory_Queue>(new Memory_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::unique_ptr<FrozenCleanup_Queue>(new FrozenCleanup_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); control.Wait(); // Hangs here }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } // Unfreeze FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::unique_ptr<Standard_Queue>(new Standard_Queue{QUEUE_BATCH_SIZE}); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; { bool has_lock {false}; bool has_tried {false}; bool done {false}; bool done_ack {false}; std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Expose more parallelism with relaxed atomics (suggested in #9938). Fix a test to check the exclusive or of two properties rather than just or.<commit_after>// Copyright (c) 2012-2017 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 "util.h" #include "utiltime.h" #include "validation.h" #include "test/test_bitcoin.h" #include "checkqueue.h" #include <boost/test/unit_test.hpp> #include <boost/thread.hpp> #include <atomic> #include <thread> #include <vector> #include <mutex> #include <condition_variable> #include <unordered_set> #include <memory> #include "random.h" // BasicTestingSetup not sufficient because nScriptCheckThreads is not set // otherwise. BOOST_FIXTURE_TEST_SUITE(checkqueue_tests, TestingSetup) static const int QUEUE_BATCH_SIZE = 128; struct FakeCheck { bool operator()() { return true; } void swap(FakeCheck& x){}; }; struct FakeCheckCheckCompletion { static std::atomic<size_t> n_calls; bool operator()() { n_calls.fetch_add(1, std::memory_order_relaxed); return true; } void swap(FakeCheckCheckCompletion& x){}; }; struct FailingCheck { bool fails; FailingCheck(bool _fails) : fails(_fails){}; FailingCheck() : fails(true){}; bool operator()() { return !fails; } void swap(FailingCheck& x) { std::swap(fails, x.fails); }; }; struct UniqueCheck { static std::mutex m; static std::unordered_multiset<size_t> results; size_t check_id; UniqueCheck(size_t check_id_in) : check_id(check_id_in){}; UniqueCheck() : check_id(0){}; bool operator()() { std::lock_guard<std::mutex> l(m); results.insert(check_id); return true; } void swap(UniqueCheck& x) { std::swap(x.check_id, check_id); }; }; struct MemoryCheck { static std::atomic<size_t> fake_allocated_memory; bool b {false}; bool operator()() { return true; } MemoryCheck(){}; MemoryCheck(const MemoryCheck& x) { // We have to do this to make sure that destructor calls are paired // // Really, copy constructor should be deletable, but CCheckQueue breaks // if it is deleted because of internal push_back. fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; MemoryCheck(bool b_) : b(b_) { fake_allocated_memory.fetch_add(b, std::memory_order_relaxed); }; ~MemoryCheck() { fake_allocated_memory.fetch_sub(b, std::memory_order_relaxed); }; void swap(MemoryCheck& x) { std::swap(b, x.b); }; }; struct FrozenCleanupCheck { static std::atomic<uint64_t> nFrozen; static std::condition_variable cv; static std::mutex m; // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks. bool should_freeze {false}; bool operator()() { return true; } FrozenCleanupCheck() {} ~FrozenCleanupCheck() { if (should_freeze) { std::unique_lock<std::mutex> l(m); nFrozen.store(1, std::memory_order_relaxed); cv.notify_one(); cv.wait(l, []{ return nFrozen.load(std::memory_order_relaxed) == 0;}); } } void swap(FrozenCleanupCheck& x){std::swap(should_freeze, x.should_freeze);}; }; // Static Allocations std::mutex FrozenCleanupCheck::m{}; std::atomic<uint64_t> FrozenCleanupCheck::nFrozen{0}; std::condition_variable FrozenCleanupCheck::cv{}; std::mutex UniqueCheck::m; std::unordered_multiset<size_t> UniqueCheck::results; std::atomic<size_t> FakeCheckCheckCompletion::n_calls{0}; std::atomic<size_t> MemoryCheck::fake_allocated_memory{0}; // Queue Typedefs typedef CCheckQueue<FakeCheckCheckCompletion> Correct_Queue; typedef CCheckQueue<FakeCheck> Standard_Queue; typedef CCheckQueue<FailingCheck> Failing_Queue; typedef CCheckQueue<UniqueCheck> Unique_Queue; typedef CCheckQueue<MemoryCheck> Memory_Queue; typedef CCheckQueue<FrozenCleanupCheck> FrozenCleanup_Queue; /** This test case checks that the CCheckQueue works properly * with each specified size_t Checks pushed. */ void Correct_Queue_range(std::vector<size_t> range) { auto small_queue = std::unique_ptr<Correct_Queue>(new Correct_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{small_queue->Thread();}); } // Make vChecks here to save on malloc (this test can be slow...) std::vector<FakeCheckCheckCompletion> vChecks; for (auto i : range) { size_t total = i; FakeCheckCheckCompletion::n_calls = 0; CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get()); while (total) { vChecks.resize(std::min(total, (size_t) InsecureRandRange(10))); total -= vChecks.size(); control.Add(vChecks); } BOOST_REQUIRE(control.Wait()); if (FakeCheckCheckCompletion::n_calls != i) { BOOST_REQUIRE_EQUAL(FakeCheckCheckCompletion::n_calls, i); BOOST_TEST_MESSAGE("Failure on trial " << i << " expected, got " << FakeCheckCheckCompletion::n_calls); } } tg.interrupt_all(); tg.join_all(); } /** Test that 0 checks is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Zero) { std::vector<size_t> range; range.push_back((size_t)0); Correct_Queue_range(range); } /** Test that 1 check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_One) { std::vector<size_t> range; range.push_back((size_t)1); Correct_Queue_range(range); } /** Test that MAX check is correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Max) { std::vector<size_t> range; range.push_back(100000); Correct_Queue_range(range); } /** Test that random numbers of checks are correct */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Correct_Random) { std::vector<size_t> range; range.reserve(100000/1000); for (size_t i = 2; i < 100000; i += std::max((size_t)1, (size_t)InsecureRandRange(std::min((size_t)1000, ((size_t)100000) - i)))) range.push_back(i); Correct_Queue_range(range); } /** Test that failing checks are caught */ BOOST_AUTO_TEST_CASE(test_CheckQueue_Catches_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (size_t i = 0; i < 1001; ++i) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); size_t remaining = i; while (remaining) { size_t r = InsecureRandRange(10); std::vector<FailingCheck> vChecks; vChecks.reserve(r); for (size_t k = 0; k < r && remaining; k++, remaining--) vChecks.emplace_back(remaining == 1); control.Add(vChecks); } bool success = control.Wait(); if (i > 0) { BOOST_REQUIRE(!success); } else if (i == 0) { BOOST_REQUIRE(success); } } tg.interrupt_all(); tg.join_all(); } // Test that a block validation which fails does not interfere with // future blocks, ie, the bad state is cleared. BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure) { auto fail_queue = std::unique_ptr<Failing_Queue>(new Failing_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{fail_queue->Thread();}); } for (auto times = 0; times < 10; ++times) { for (bool end_fails : {true, false}) { CCheckQueueControl<FailingCheck> control(fail_queue.get()); { std::vector<FailingCheck> vChecks; vChecks.resize(100, false); vChecks[99] = end_fails; control.Add(vChecks); } bool r =control.Wait(); BOOST_REQUIRE(r != end_fails); } } tg.interrupt_all(); tg.join_all(); } // Test that unique checks are actually all called individually, rather than // just one check being called repeatedly. Test that checks are not called // more than once as well BOOST_AUTO_TEST_CASE(test_CheckQueue_UniqueCheck) { auto queue = std::unique_ptr<Unique_Queue>(new Unique_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } size_t COUNT = 100000; size_t total = COUNT; { CCheckQueueControl<UniqueCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<UniqueCheck> vChecks; for (size_t k = 0; k < r && total; k++) vChecks.emplace_back(--total); control.Add(vChecks); } } bool r = true; BOOST_REQUIRE_EQUAL(UniqueCheck::results.size(), COUNT); for (size_t i = 0; i < COUNT; ++i) r = r && UniqueCheck::results.count(i) == 1; BOOST_REQUIRE(r); tg.interrupt_all(); tg.join_all(); } // Test that blocks which might allocate lots of memory free their memory aggressively. // // This test attempts to catch a pathological case where by lazily freeing // checks might mean leaving a check un-swapped out, and decreasing by 1 each // time could leave the data hanging across a sequence of blocks. BOOST_AUTO_TEST_CASE(test_CheckQueue_Memory) { auto queue = std::unique_ptr<Memory_Queue>(new Memory_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } for (size_t i = 0; i < 1000; ++i) { size_t total = i; { CCheckQueueControl<MemoryCheck> control(queue.get()); while (total) { size_t r = InsecureRandRange(10); std::vector<MemoryCheck> vChecks; for (size_t k = 0; k < r && total; k++) { total--; // Each iteration leaves data at the front, back, and middle // to catch any sort of deallocation failure vChecks.emplace_back(total == 0 || total == i || total == i/2); } control.Add(vChecks); } } BOOST_REQUIRE_EQUAL(MemoryCheck::fake_allocated_memory, 0); } tg.interrupt_all(); tg.join_all(); } // Test that a new verification cannot occur until all checks // have been destructed BOOST_AUTO_TEST_CASE(test_CheckQueue_FrozenCleanup) { auto queue = std::unique_ptr<FrozenCleanup_Queue>(new FrozenCleanup_Queue {QUEUE_BATCH_SIZE}); boost::thread_group tg; bool fails = false; for (auto x = 0; x < nScriptCheckThreads; ++x) { tg.create_thread([&]{queue->Thread();}); } std::thread t0([&]() { CCheckQueueControl<FrozenCleanupCheck> control(queue.get()); std::vector<FrozenCleanupCheck> vChecks(1); // Freezing can't be the default initialized behavior given how the queue // swaps in default initialized Checks (otherwise freezing destructor // would get called twice). vChecks[0].should_freeze = true; control.Add(vChecks); control.Wait(); // Hangs here }); { std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); // Wait until the queue has finished all jobs and frozen FrozenCleanupCheck::cv.wait(l, [](){return FrozenCleanupCheck::nFrozen == 1;}); } // Try to get control of the queue a bunch of times for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } { // Unfreeze (we need lock n case of spurious wakeup) std::unique_lock<std::mutex> l(FrozenCleanupCheck::m); FrozenCleanupCheck::nFrozen = 0; } // Awaken frozen destructor FrozenCleanupCheck::cv.notify_one(); // Wait for control to finish t0.join(); tg.interrupt_all(); tg.join_all(); BOOST_REQUIRE(!fails); } /** Test that CCheckQueueControl is threadsafe */ BOOST_AUTO_TEST_CASE(test_CheckQueueControl_Locks) { auto queue = std::unique_ptr<Standard_Queue>(new Standard_Queue{QUEUE_BATCH_SIZE}); { boost::thread_group tg; std::atomic<int> nThreads {0}; std::atomic<int> fails {0}; for (size_t i = 0; i < 3; ++i) { tg.create_thread( [&]{ CCheckQueueControl<FakeCheck> control(queue.get()); // While sleeping, no other thread should execute to this point auto observed = ++nThreads; MilliSleep(10); fails += observed != nThreads; }); } tg.join_all(); BOOST_REQUIRE_EQUAL(fails, 0); } { boost::thread_group tg; std::mutex m; std::condition_variable cv; { bool has_lock {false}; bool has_tried {false}; bool done {false}; bool done_ack {false}; std::unique_lock<std::mutex> l(m); tg.create_thread([&]{ CCheckQueueControl<FakeCheck> control(queue.get()); std::unique_lock<std::mutex> ll(m); has_lock = true; cv.notify_one(); cv.wait(ll, [&]{return has_tried;}); done = true; cv.notify_one(); // Wait until the done is acknowledged // cv.wait(ll, [&]{return done_ack;}); }); // Wait for thread to get the lock cv.wait(l, [&](){return has_lock;}); bool fails = false; for (auto x = 0; x < 100 && !fails; ++x) { fails = queue->ControlMutex.try_lock(); } has_tried = true; cv.notify_one(); cv.wait(l, [&](){return done;}); // Acknowledge the done done_ack = true; cv.notify_one(); BOOST_REQUIRE(!fails); } tg.join_all(); } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/// \file ROOT/RCluster.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2020-03-11 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RCluster #define ROOT7_RCluster #include <ROOT/RNTupleUtil.hxx> #include <unordered_map> #include <unordered_set> #include <vector> namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROnDiskPage \ingroup NTuple \brief A page as being stored on disk, that is packed and compressed Used by the cluster pool to cache pages from the physical storage. Such pages generally need to be uncompressed and unpacked before they can be used by RNTuple upper layers. */ // clang-format on class ROnDiskPage { private: /// The memory location of the bytes const void *fAddress = nullptr; /// The compressed and packed size of the page std::size_t fSize = 0; public: /// On-disk pages within a page source are identified by the column and page number. The key is used for /// associative collections of on-disk pages. struct Key { DescriptorId_t fColumnId; NTupleSize_t fPageNo; Key(DescriptorId_t columnId, NTupleSize_t pageNo) : fColumnId(columnId), fPageNo(pageNo) {} friend bool operator ==(const Key &lhs, const Key &rhs) { return lhs.fColumnId == rhs.fColumnId && lhs.fPageNo == rhs.fPageNo; } }; ROnDiskPage() = default; ROnDiskPage(void *address, std::size_t size) : fAddress(address), fSize(size) {} const void *GetAddress() const { return fAddress; } std::size_t GetSize() const { return fSize; } bool IsNull() const { return fAddress == nullptr; } }; } // namespace Detail } // namespace Experimental } // namespace ROOT // For hash maps ROnDiskPage::Key --> ROnDiskPage namespace std { template <> struct hash<ROOT::Experimental::Detail::ROnDiskPage::Key> { // TODO(jblomer): quick and dirty hash, likely very sub-optimal, to be revised later. size_t operator()(const ROOT::Experimental::Detail::ROnDiskPage::Key &key) const { return ((std::hash<ROOT::Experimental::DescriptorId_t>()(key.fColumnId) ^ (hash<ROOT::Experimental::NTupleSize_t>()(key.fPageNo) << 1)) >> 1); } }; } namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROOT::Experimental::Detail::ROnDiskPageMap \ingroup NTuple \brief A memory region that contains packed and compressed pages Derived classes implement how the on-disk pages are stored in memory, e.g. mmap'd or in a special area. */ // clang-format on class ROnDiskPageMap { friend class RCluster; protected: /// The memory region containing the on-disk pages. Ownership of the memory region is passed to the page map. /// Therefore, the region needs to be allocated in a way that fits the derived class and its destructor. void *fMemory; std::unordered_map<ROnDiskPage::Key, ROnDiskPage> fOnDiskPages; public: explicit ROnDiskPageMap(void *memory) : fMemory(memory) {} ROnDiskPageMap(const ROnDiskPageMap &other) = delete; ROnDiskPageMap(ROnDiskPageMap &&other); ROnDiskPageMap &operator =(const ROnDiskPageMap &other) = delete; ROnDiskPageMap &operator =(ROnDiskPageMap &&other); virtual ~ROnDiskPageMap(); /// Inserts information about a page stored in fMemory. Therefore, the address referenced by onDiskPage /// needs to be owned by the fMemory block. If a page map contains a page of a given column, it is expected /// that _all_ the pages of that column in that cluster are part of the page map. void Register(const ROnDiskPage::Key &key, const ROnDiskPage &onDiskPage) { fOnDiskPages.emplace(key, onDiskPage); } }; // clang-format off /** \class ROOT::Experimental::Detail::ROnDiskPageMapHeap \ingroup NTuple \brief An ROnDiskPageMap that is used for an fMemory allocated as an array of unsigned char. */ // clang-format on class ROnDiskPageMapHeap : public ROnDiskPageMap { public: explicit ROnDiskPageMapHeap(void *memory) : ROnDiskPageMap(memory) {} ~ROnDiskPageMapHeap(); }; // clang-format off /** \class ROOT::Experimental::Detail::RCluster \ingroup NTuple \brief An in-memory subset of the packed and compressed pages of a cluster Binds together several page maps that represent all the pages of certain columns of a cluster */ // clang-format on class RCluster { protected: /// References the cluster identifier in the page source that created the cluster DescriptorId_t fClusterId; /// Multiple page maps can be combined in a single RCluster std::vector<ROnDiskPageMap> fPageMaps; /// Set of the (complete) columns represented by the RCluster std::unordered_set<DescriptorId_t> fAvailColumns; /// Lookup table for the on-disk pages std::unordered_map<ROnDiskPage::Key, ROnDiskPage> fOnDiskPages; public: explicit RCluster(DescriptorId_t clusterId) : fClusterId(clusterId) {} RCluster(const RCluster &other) = delete; RCluster(RCluster &&other) = default; RCluster &operator =(const RCluster &other) = delete; RCluster &operator =(RCluster &&other) = default; ~RCluster() = default; /// Move the given page map into this cluster; on-disk pages that are present in both the cluster at hand and /// pageMap are gracefully handled such that a following lookup will return the page from either of the /// memory regions void Adopt(ROnDiskPageMap &&pageMap); /// Move the contents of other into this cluster; on-disk pages that are present in both the cluster at hand and /// the "other" cluster are gracefully handled such that a following lookup will return the page from /// either of the clusters void Adopt(RCluster &&other); /// Marks the column as complete; must be done for all columns, even empty ones without associated pages, /// before the cluster is given from the page storage to the cluster pool. Marking the available columns is /// typically the last step of RPageSouce::LoadCluster(). void SetColumnAvailable(DescriptorId_t columnId); const ROnDiskPage *GetOnDiskPage(const ROnDiskPage::Key &key) const; DescriptorId_t GetId() const { return fClusterId; } const std::unordered_set<DescriptorId_t> &GetAvailColumns() const { return fAvailColumns; } bool ContainsColumn(DescriptorId_t columnId) const { return fAvailColumns.count(columnId) > 0; } size_t GetNOnDiskPages() const { return fOnDiskPages.size(); } }; } // namespace Detail } // namespace Experimental } // namespace ROOT #endif <commit_msg>[ntuple] add clarifying comments<commit_after>/// \file ROOT/RCluster.hxx /// \ingroup NTuple ROOT7 /// \author Jakob Blomer <jblomer@cern.ch> /// \date 2020-03-11 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2020, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_RCluster #define ROOT7_RCluster #include <ROOT/RNTupleUtil.hxx> #include <unordered_map> #include <unordered_set> #include <vector> namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROnDiskPage \ingroup NTuple \brief A page as being stored on disk, that is packed and compressed Used by the cluster pool to cache pages from the physical storage. Such pages generally need to be uncompressed and unpacked before they can be used by RNTuple upper layers. */ // clang-format on class ROnDiskPage { private: /// The memory location of the bytes const void *fAddress = nullptr; /// The compressed and packed size of the page std::size_t fSize = 0; public: /// On-disk pages within a page source are identified by the column and page number. The key is used for /// associative collections of on-disk pages. struct Key { DescriptorId_t fColumnId; NTupleSize_t fPageNo; Key(DescriptorId_t columnId, NTupleSize_t pageNo) : fColumnId(columnId), fPageNo(pageNo) {} friend bool operator ==(const Key &lhs, const Key &rhs) { return lhs.fColumnId == rhs.fColumnId && lhs.fPageNo == rhs.fPageNo; } }; ROnDiskPage() = default; ROnDiskPage(void *address, std::size_t size) : fAddress(address), fSize(size) {} const void *GetAddress() const { return fAddress; } std::size_t GetSize() const { return fSize; } bool IsNull() const { return fAddress == nullptr; } }; } // namespace Detail } // namespace Experimental } // namespace ROOT // For hash maps ROnDiskPage::Key --> ROnDiskPage namespace std { template <> struct hash<ROOT::Experimental::Detail::ROnDiskPage::Key> { // TODO(jblomer): quick and dirty hash, likely very sub-optimal, to be revised later. size_t operator()(const ROOT::Experimental::Detail::ROnDiskPage::Key &key) const { return ((std::hash<ROOT::Experimental::DescriptorId_t>()(key.fColumnId) ^ (hash<ROOT::Experimental::NTupleSize_t>()(key.fPageNo) << 1)) >> 1); } }; } namespace ROOT { namespace Experimental { namespace Detail { // clang-format off /** \class ROOT::Experimental::Detail::ROnDiskPageMap \ingroup NTuple \brief A memory region that contains packed and compressed pages Derived classes implement how the on-disk pages are stored in memory, e.g. mmap'd or in a special area. */ // clang-format on class ROnDiskPageMap { friend class RCluster; protected: /// The memory region containing the on-disk pages. Ownership of the memory region is passed to the page map. /// Therefore, the region needs to be allocated in a way that fits the derived class and its destructor. void *fMemory; std::unordered_map<ROnDiskPage::Key, ROnDiskPage> fOnDiskPages; public: explicit ROnDiskPageMap(void *memory) : fMemory(memory) {} ROnDiskPageMap(const ROnDiskPageMap &other) = delete; /// The default move constructor does not reset fMemory ROnDiskPageMap(ROnDiskPageMap &&other); ROnDiskPageMap &operator =(const ROnDiskPageMap &other) = delete; /// The default move assignment does not reset fMemory ROnDiskPageMap &operator =(ROnDiskPageMap &&other); virtual ~ROnDiskPageMap(); /// Inserts information about a page stored in fMemory. Therefore, the address referenced by onDiskPage /// needs to be owned by the fMemory block. If a page map contains a page of a given column, it is expected /// that _all_ the pages of that column in that cluster are part of the page map. void Register(const ROnDiskPage::Key &key, const ROnDiskPage &onDiskPage) { fOnDiskPages.emplace(key, onDiskPage); } }; // clang-format off /** \class ROOT::Experimental::Detail::ROnDiskPageMapHeap \ingroup NTuple \brief An ROnDiskPageMap that is used for an fMemory allocated as an array of unsigned char. */ // clang-format on class ROnDiskPageMapHeap : public ROnDiskPageMap { public: explicit ROnDiskPageMapHeap(void *memory) : ROnDiskPageMap(memory) {} ~ROnDiskPageMapHeap(); }; // clang-format off /** \class ROOT::Experimental::Detail::RCluster \ingroup NTuple \brief An in-memory subset of the packed and compressed pages of a cluster Binds together several page maps that represent all the pages of certain columns of a cluster */ // clang-format on class RCluster { protected: /// References the cluster identifier in the page source that created the cluster DescriptorId_t fClusterId; /// Multiple page maps can be combined in a single RCluster std::vector<ROnDiskPageMap> fPageMaps; /// Set of the (complete) columns represented by the RCluster std::unordered_set<DescriptorId_t> fAvailColumns; /// Lookup table for the on-disk pages std::unordered_map<ROnDiskPage::Key, ROnDiskPage> fOnDiskPages; public: explicit RCluster(DescriptorId_t clusterId) : fClusterId(clusterId) {} RCluster(const RCluster &other) = delete; RCluster(RCluster &&other) = default; RCluster &operator =(const RCluster &other) = delete; RCluster &operator =(RCluster &&other) = default; ~RCluster() = default; /// Move the given page map into this cluster; on-disk pages that are present in both the cluster at hand and /// pageMap are gracefully handled such that a following lookup will return the page from either of the /// memory regions void Adopt(ROnDiskPageMap &&pageMap); /// Move the contents of other into this cluster; on-disk pages that are present in both the cluster at hand and /// the "other" cluster are gracefully handled such that a following lookup will return the page from /// either of the clusters void Adopt(RCluster &&other); /// Marks the column as complete; must be done for all columns, even empty ones without associated pages, /// before the cluster is given from the page storage to the cluster pool. Marking the available columns is /// typically the last step of RPageSouce::LoadCluster(). void SetColumnAvailable(DescriptorId_t columnId); const ROnDiskPage *GetOnDiskPage(const ROnDiskPage::Key &key) const; DescriptorId_t GetId() const { return fClusterId; } const std::unordered_set<DescriptorId_t> &GetAvailColumns() const { return fAvailColumns; } bool ContainsColumn(DescriptorId_t columnId) const { return fAvailColumns.count(columnId) > 0; } size_t GetNOnDiskPages() const { return fOnDiskPages.size(); } }; } // namespace Detail } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before>/* * opencog/atoms/execution/DLScheme.cc * * Copyright (C) 2019 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <dlfcn.h> #include "DLScheme.h" using namespace opencog; SchemeEval* opencog::get_evaluator_for_scheme(AtomSpace* as) { static void* library = dlopen("libsmob.so", RTLD_LAZY); static void* getev = dlsym(library, "get_scheme_evaluator"); typedef SchemeEval* (*SEGetter)(AtomSpace*); // static SEGetter getter = std::reinterpret_cast<SEGetter>(getev); static SEGetter getter = (SEGetter) getev; return getter(as); } <commit_msg>Add just a bit fo error checking<commit_after>/* * opencog/atoms/execution/DLScheme.cc * * Copyright (C) 2019 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <dlfcn.h> #include <opencog/util/exceptions.h> #include "DLScheme.h" using namespace opencog; static void* library = nullptr; SchemeEval* opencog::get_evaluator_for_scheme(AtomSpace* as) { if (nullptr == library) library = dlopen("libsmob.so", RTLD_LAZY); if (nullptr == library) throw RuntimeException(TRACE_INFO, "Unable to dynamically load libsmob.so: %s", dlerror()); static void* getev = dlsym(library, "get_scheme_evaluator"); if (nullptr == getev) throw RuntimeException(TRACE_INFO, "Unable to dynamically load scheme evaluator: %s", dlerror()); typedef SchemeEval* (*SEGetter)(AtomSpace*); // static SEGetter getter = std::reinterpret_cast<SEGetter>(getev); static SEGetter getter = (SEGetter) getev; return getter(as); } static __attribute__ ((destructor)) void fini(void) { if (library) dlclose(library); } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include "mailbox.h" Mailbox::Mailbox (){ //Attempt to create a new memory segment. controlID = shmget(controlKey, controlSize, S_IRUSR | S_IWUSR | IPC_CREAT); if (controlID == -1) { //Fatal error. Unknown error with shmget. exit(-1); } //Attach to the memory segment. controlPointer = (char*)shmat(controlID, NULL, 0); } Mailbox::~Mailbox (){ shmdt(controlPointer); shmdctl(controlID, IPC_RMID); } void Mailbox::CheckForNewUsers(){ //Search for an empty comm slot. //Note, I use a simple locking mechanism here that will greatly reduce R/W collisions, but is not actually //completely thread-safe. That's because between checking a zero bit and setting the bit to one, this process //can be made to sleep or another process on another CPU can intervene. It's much better than nothing and is //simple enough for now. int NumberofBoxes = controlSize / boxSize; for (int i = 1; i < NumberofBoxes; i++){ tSlot = i * 32768; //The first byte in a segment indicates ownership. Byte = One if claimed and Zero if unclaimed. if (controlPointer[tSlot] == 0x0){ //Claim the slot. controlPointer[tSlot] = 0x1; //Register the slot location. Wait until the byte-lock is off. while (!Done){ if (controlPointer[0] == 0x0){ controlPointer[0] = 0x1; Slot = i; Done = true; unsigned char Pos = (unsigned char)controlPointer[1]; controlPointer[Pos + 2] = (unsigned char)Slot; Pos++; controlPointer[1] = Pos; controlPointer[0] = 0x0; i = 256; } else { // Sleep for 3 microseconds and then check again. nanosleep (&req, &rem); } } } } } void Mailbox::CloseUserBox(){ } void Mailbox::CheckMessages(){ } string Mailbox::GetNextMessage(){ } //Wait for a response from the game service. //Response will incluse a session ID, confirmed slot number for message exchange, starting position, //full character stats, map, nearby enemies... //Mailbox format: Byte 0 = Taken/Free flag; Byte 1 = Message for server flag; Byte 2 = Message for client flag. //Byte 3 + 4 = size of message. Byte 5+ = message. //No thread issues since only one server-client per segment and always only read or write not both. RetVal += "&Slot=" + to_string(Slot); while (controlPointer[Slot * 32768 + 2] == 0x0){ // Sleep for 3 microseconds and then check again. nanosleep (&req, &rem); } size_t messageLen = (int)((unsigned char)controlPointer[3]) * 256 + (int)((unsigned char)controlPointer[4]); string Temp(reinterpret_cast<const char *>(controlPointer[5]), messageLen); RetVal += Temp; return RetVal; <commit_msg>Update mailbox.cpp<commit_after>#include <string> #include <vector> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/stat.h> #include <string.h> #include <atomic> #include "mailbox.h" using namespace std; Mailbox::Mailbox (){ //Attempt to create a new memory segment. controlID = shmget(controlKey, controlSize, S_IRUSR | S_IWUSR | IPC_CREAT); if (controlID == -1) { //Fatal error. Unknown error with shmget. exit(-1); } //Attach to the memory segment. controlPointer = (char*)shmat(controlID, NULL, 0); } Mailbox::~Mailbox (){ shmdt(controlPointer); shmctl(controlID, IPC_RMID, NULL); } void Mailbox::OpenUserBox(int Box){ OpenBoxes.push_back(Box); } void Mailbox::CloseUserBox(int Box){ for (int i = 0; i < OpenBoxes.size(); i++){ if (OpenBoxes[i] == Box){ OpenBoxes.erase(OpenBoxes.begin() + i); for (int j = 0; j < slotCount; j++){ ClearSlot(Box, j); } } } } bool Mailbox::SetupSuccessful(){ return (controlPointer != NULL); } void Mailbox::CheckMessages(){ if (LockInbox()){ for (int i = 1; i < inboxCount;i++){ if (CheckSlot(0,i)){ Inbox.push_back(GetMessage(0,i)); ClearSlot(0,i); } else { break; } } UnlockInbox(); } } bool Mailbox::LockInbox(){ //Attempt to lock Inbox. Success = Inbox was not locked. bool* LockLocation = controlPointer + InboxLock; return (!std::atomic_fetch_or(LockLocation, true)); } void Mailbox::UnlockInbox(){ bool* LockLocation = controlPointer + InboxLock; *LockLocation = 0x0; } string Mailbox::GetNextMessage(){ string RetVal = ""; CheckMessages(); if (Inbox.size() > 0){ RetVal = Inbox[0]; Inbox.erase(Inbox.begin()); } return RetVal; } void Mailbox::BroadcastMessage(string Message){ for (int i = 0; i < OpenBoxes.size(); i++){ SendMessageToBox(Message, i); } } void Mailbox::SendMessageToBox(std::string Message, int Box){ //Note: a full box results in a dropped message. for (int i = 1; i < slotCount; i++){ if (CheckSlot(Box, i)){ SetMessage(Box, i, Message); break; } } } bool Mailbox::CheckSlot(int Box, int Slot){ // For future reference - this is not server-side thread-safe, modify if expanding use to other programs. //To be thread safe, atomically reserve while checking (as we do with locking the Inbox.) char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } return (MemLoc[MessageSetFlag] == 0x0); } string Mailbox::GetMessage(int Box, int Slot){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memcpy (&Buffer, MemLoc + FlagSetSize, slotSize - FlagSetSize); return (string(Buffer)); } void Mailbox::SetMessage(int Box, int Slot, string Message){ char Buffer[slotSize]; char* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } *(MemLoc + MessageSetFlag) = 0x1; int MemSize = Message.size(); if (MemSize > slotSize - FlagSetSize) { MemSize = slotSize - FlagSetSize;} memcpy ( MemLoc + FlagSetSize, Message.c_str(), MemSize); } void Mailbox::ClearSlot (int Box, int Slot){ void* MemLoc; if (Box == 0 ){ MemLoc = controlPointer + (Slot * slotSize); } else { MemLoc = controlPointer + inboxSize + (Box * boxSize) + (Slot * slotSize); } memset (MemLoc,'\0',slotSize); } int Mailbox::FindSlot(int Box){ for (int i = 1; i < boxSize; i++){ char* MemLoc = controlPointer + inboxSize + (Box * boxSize) + (i * slotSize); if (*(MemLoc + MessageSetFlag) == 0x0){ *(MemLoc + MessageSetFlag) = 0x1; return i; } } return 0; } <|endoftext|>
<commit_before>// Example macro describing how to use te mathmore integration // it calculates the numerically cumulative integral of a distribution (like in this case the BreitWigner) // to execute the macro type it (you need to compile with AClic) // // root[0]: .x mathmoreIntegration.C+ // // This tutorials require having libMathMore built with ROOT. // // To build mathmore you need to have a version of GSL >= 1.8 installed in your system // The ROOT configure will automatically find GSL if the script gsl-config (from GSL) is in your PATH,. // otherwise you need to configure root with the options --gsl-incdir and --gsl-libdir. // // // Authors: M. Slawinska and L. Moneta #include "TMath.h" #include "TH1.h" #include "TCanvas.h" #include "TLegend.h" //#include "TLabel.h" #include "Math/Integrator.h" #include "Math/Functor.h" #include "Math/WrappedFunction.h" #include "Math/IFunction.h" #include "Math/Integrator.h" #include <iostream> #include "TStopwatch.h" #include "TF1.h" //!calculates exact integral of Breit Wigner distribution //!and compares with existing methods int nc = 0; double exactIntegral( double a, double b) { return (TMath::ATan(2*b)- TMath::ATan(2*a))/ TMath::Pi(); } double func( double x){ nc++; return TMath::BreitWigner(x); } // TF1 requires the function to have the ( )( double *, double *) signature double func2(const double *x, const double * = 0){ nc++; return TMath::BreitWigner(x[0]); } void testIntegPerf(double x1, double x2, int n = 100000){ std::cout << "\n\n***************************************************************\n"; std::cout << "Test integration performances in interval [ " << x1 << " , " << x2 << " ]\n\n"; TStopwatch timer; double dx = (x2-x1)/double(n); //ROOT::Math::Functor1D<ROOT::Math::IGenFunction> f1(& TMath::BreitWigner); ROOT::Math::WrappedFunction<> f1(func); timer.Start(); ROOT::Math::Integrator ig(f1 ); double s1 = 0.0; nc = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ig.Integral(x1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Integrator (default):\t" << timer.RealTime() << std::endl; std::cout << "Number of function calls = " << nc/n << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); timer.Start(); s1 = 0; nc = 0; ROOT::Math::Integrator ig2(f1, ROOT::Math::Integration::ADAPTIVE, ROOT::Math::Integration::GAUSS61,1.E-12,1.E-12); for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ig2.Integral(x1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Integrator(GAUSS61):\t" << timer.RealTime() << std::endl; std::cout << "Number of function calls = " << nc/n << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); //TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x)",x1, x2); // this is faster but cannot measure number of function calls TF1 *fBW = new TF1("fBW",func2,x1, x2,0); timer.Start(); nc = 0; double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= fBW->Integral(x1,x ); } timer.Stop(); std::cout << "Time using TF1::Integral :\t\t\t" << timer.RealTime() << std::endl; std::cout << "Number of function calls = " << nc/n << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } void DrawCumulative(double x1, double x2, int n = 100){ std::cout << "\n\n***************************************************************\n"; std::cout << "Drawing cumulatives of BreitWigner in interval [ " << x1 << " , " << x2 << " ]\n\n"; double dx = (x2-x1)/double(n); TH1D *cum0 = new TH1D("cum0", "", n, x1, x2); //exact cumulative for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum0->SetBinContent(i, exactIntegral(x1, x)); } // alternative method using ROOT::Math::Functor class ROOT::Math::Functor1D<ROOT::Math::IGenFunction> f1(& TMath::BreitWigner); ROOT::Math::Integrator ig(f1, ROOT::Math::Integration::ADAPTIVE, ROOT::Math::Integration::GAUSS61,1.E-12,1.E-12); TH1D *cum1 = new TH1D("cum1", "", n, x1, x2); for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum1->SetBinContent(i, ig.Integral(x1,x)); } TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x, 0, 1)",x1, x2); TH1D *cum2 = new TH1D("cum2", "", n, x1, x2); for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum2->SetBinContent(i, fBW->Integral(x1,x)); } TH1D *cum10 = new TH1D("cum10", "", n, x1, x2); //difference between 1 and exact TH1D *cum20 = new TH1D("cum23", "", n, x1, x2); //difference between 2 and excact for (int i = 1; i <= n; ++i) { double delta = cum1->GetBinContent(i) - cum0->GetBinContent(i); double delta2 = cum2->GetBinContent(i) - cum0->GetBinContent(i); //std::cout << " diff for " << x << " is " << delta << " " << cum1->GetBinContent(i) << std::endl; cum10->SetBinContent(i, delta ); cum10->SetBinError(i, std::numeric_limits<double>::epsilon() * cum1->GetBinContent(i) ); cum20->SetBinContent(i, delta2 ); } TCanvas *c1 = new TCanvas("c1","Integration example",20,10,800,500); c1->Divide(2,1); c1->Draw(); cum0->SetLineColor(kBlack); cum0->SetTitle("BreitWigner - the cumulative"); cum0->SetStats(0); cum1->SetLineStyle(2); cum2->SetLineStyle(3); cum1->SetLineColor(kBlue); cum2->SetLineColor(kRed); c1->cd(1); cum0->DrawCopy("h"); cum1->DrawCopy("same"); //cum2->DrawCopy("same"); cum2->DrawCopy("same"); c1->cd(2); cum10->SetTitle("Difference"); cum10->SetStats(0); cum10->SetLineColor(kBlue); cum10->Draw("e0"); cum20->SetLineColor(kRed); cum20->Draw("hsame"); TLegend * l = new TLegend(0.11, 0.8, 0.7 ,0.89); l->AddEntry(cum10, "GSL integration - analytical "); l->AddEntry(cum20, "TF1::Integral - analytical "); l->Draw(); c1->Update(); std::cout << "\n***************************************************************\n"; } void mathmoreIntegration(double a = -2, double b = 2) { DrawCumulative(a, b); testIntegPerf(a, b); } <commit_msg>From Lorenzo: Fix for broken tutorial.<commit_after>// Example macro describing how to use te mathmore integration // it calculates the numerically cumulative integral of a distribution (like in this case the BreitWigner) // to execute the macro type it (you need to compile with AClic) // // root[0]: .x mathmoreIntegration.C+ // // This tutorials require having libMathMore built with ROOT. // // To build mathmore you need to have a version of GSL >= 1.8 installed in your system // The ROOT configure will automatically find GSL if the script gsl-config (from GSL) is in your PATH,. // otherwise you need to configure root with the options --gsl-incdir and --gsl-libdir. // // // Authors: M. Slawinska and L. Moneta #include "TMath.h" #include "TH1.h" #include "TCanvas.h" #include "TLegend.h" //#include "TLabel.h" #include "Math/Functor.h" #include "Math/WrappedFunction.h" #include "Math/IFunction.h" #include "Math/Integrator.h" #include <iostream> #include "TStopwatch.h" #include "TF1.h" //!calculates exact integral of Breit Wigner distribution //!and compares with existing methods int nc = 0; double exactIntegral( double a, double b) { return (TMath::ATan(2*b)- TMath::ATan(2*a))/ TMath::Pi(); } double func( double x){ nc++; return TMath::BreitWigner(x); } // TF1 requires the function to have the ( )( double *, double *) signature double func2(const double *x, const double * = 0){ nc++; return TMath::BreitWigner(x[0]); } void testIntegPerf(double x1, double x2, int n = 100000){ std::cout << "\n\n***************************************************************\n"; std::cout << "Test integration performances in interval [ " << x1 << " , " << x2 << " ]\n\n"; TStopwatch timer; double dx = (x2-x1)/double(n); //ROOT::Math::Functor1D<ROOT::Math::IGenFunction> f1(& TMath::BreitWigner); ROOT::Math::WrappedFunction<> f1(func); timer.Start(); ROOT::Math::Integrator ig(f1 ); double s1 = 0.0; nc = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s1+= ig.Integral(x1,x); } timer.Stop(); std::cout << "Time using ROOT::Math::Integrator :\t" << timer.RealTime() << std::endl; std::cout << "Number of function calls = " << nc/n << std::endl; int pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); //TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x)",x1, x2); // this is faster but cannot measure number of function calls TF1 *fBW = new TF1("fBW",func2,x1, x2,0); timer.Start(); nc = 0; double s2 = 0; for (int i = 0; i < n; ++i) { double x = x1 + dx*i; s2+= fBW->Integral(x1,x ); } timer.Stop(); std::cout << "Time using TF1::Integral :\t\t\t" << timer.RealTime() << std::endl; std::cout << "Number of function calls = " << nc/n << std::endl; pr = std::cout.precision(18); std::cout << s1 << std::endl; std::cout.precision(pr); } void DrawCumulative(double x1, double x2, int n = 100){ std::cout << "\n\n***************************************************************\n"; std::cout << "Drawing cumulatives of BreitWigner in interval [ " << x1 << " , " << x2 << " ]\n\n"; double dx = (x2-x1)/double(n); TH1D *cum0 = new TH1D("cum0", "", n, x1, x2); //exact cumulative for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum0->SetBinContent(i, exactIntegral(x1, x)); } // alternative method using ROOT::Math::Functor class ROOT::Math::Functor1D<ROOT::Math::IGenFunction> f1(& TMath::BreitWigner); ROOT::Math::Integrator ig(f1, ROOT::Math::IntegrationOneDim::ADAPTIVE,1.E-12,1.E-12); TH1D *cum1 = new TH1D("cum1", "", n, x1, x2); for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum1->SetBinContent(i, ig.Integral(x1,x)); } TF1 *fBW = new TF1("fBW","TMath::BreitWigner(x, 0, 1)",x1, x2); TH1D *cum2 = new TH1D("cum2", "", n, x1, x2); for (int i = 1; i <= n; ++i) { double x = x1 + dx*i; cum2->SetBinContent(i, fBW->Integral(x1,x)); } TH1D *cum10 = new TH1D("cum10", "", n, x1, x2); //difference between 1 and exact TH1D *cum20 = new TH1D("cum23", "", n, x1, x2); //difference between 2 and excact for (int i = 1; i <= n; ++i) { double delta = cum1->GetBinContent(i) - cum0->GetBinContent(i); double delta2 = cum2->GetBinContent(i) - cum0->GetBinContent(i); //std::cout << " diff for " << x << " is " << delta << " " << cum1->GetBinContent(i) << std::endl; cum10->SetBinContent(i, delta ); cum10->SetBinError(i, std::numeric_limits<double>::epsilon() * cum1->GetBinContent(i) ); cum20->SetBinContent(i, delta2 ); } TCanvas *c1 = new TCanvas("c1","Integration example",20,10,800,500); c1->Divide(2,1); c1->Draw(); cum0->SetLineColor(kBlack); cum0->SetTitle("BreitWigner - the cumulative"); cum0->SetStats(0); cum1->SetLineStyle(2); cum2->SetLineStyle(3); cum1->SetLineColor(kBlue); cum2->SetLineColor(kRed); c1->cd(1); cum0->DrawCopy("h"); cum1->DrawCopy("same"); //cum2->DrawCopy("same"); cum2->DrawCopy("same"); c1->cd(2); cum10->SetTitle("Difference"); cum10->SetStats(0); cum10->SetLineColor(kBlue); cum10->Draw("e0"); cum20->SetLineColor(kRed); cum20->Draw("hsame"); TLegend * l = new TLegend(0.11, 0.8, 0.7 ,0.89); l->AddEntry(cum10, "GSL integration - analytical "); l->AddEntry(cum20, "TF1::Integral - analytical "); l->Draw(); c1->Update(); std::cout << "\n***************************************************************\n"; } void mathmoreIntegration(double a = -2, double b = 2) { DrawCumulative(a, b); testIntegPerf(a, b); } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include "kangaru.hpp" struct CarsContainer; struct Fuel { virtual ~Fuel(); virtual auto getPrice() const noexcept -> double = 0; }; Fuel::~Fuel() = default; struct Car { auto refuel(size_t litres) const noexcept -> double { return litres * fuel_->getPrice(); } auto setFuel(std::shared_ptr<Fuel> fuel) -> void { fuel_ = std::move(fuel); } protected: explicit Car(std::shared_ptr<Fuel> fuel) : fuel_{std::move(fuel)} {} private: std::shared_ptr<Fuel> fuel_; }; struct Petrol : Fuel { virtual auto getPrice() const noexcept -> double override { return 130.70; } }; struct PremiumPetrol : Petrol { virtual auto getPrice() const noexcept -> double override final { return 144.30; } }; struct Diesel : Fuel { virtual auto getPrice() const noexcept -> double override final { return 135.30; } }; struct OpelAstra : Car { explicit OpelAstra(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct NissanQuashqai : Car { explicit NissanQuashqai(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct HondaHRV : Car { explicit HondaHRV(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct HondaHRVDiesel : HondaHRV { explicit HondaHRVDiesel(std::shared_ptr<Fuel> fuel) : HondaHRV{std::move(fuel)} {} }; struct CarsContainer : kgr::Container { CarsContainer() = default; protected: virtual auto init() -> void override final; }; auto CarsContainer::init() -> void {} namespace kgr { template<> struct Service<Fuel> : NoDependencies, Single {}; template<> struct Service<Petrol> : NoDependencies, Overrides<Fuel> {}; template<> struct Service<PremiumPetrol> : NoDependencies, Single {}; template<> struct Service<Diesel> : NoDependencies, Single {}; template<> struct Service<OpelAstra> : Dependency<Petrol> {}; template<> struct Service<NissanQuashqai> : Dependency<Petrol> {}; template<> struct Service<HondaHRV> : Dependency<PremiumPetrol> {}; template<> struct Service<HondaHRVDiesel> : Dependency<Diesel> {}; } // namespace kgr int main() { auto garage = kgr::make_container<CarsContainer>(); auto astra1 = garage->service<OpelAstra>(); auto astra2 = garage->service<OpelAstra>(); auto quashqai = garage->service<NissanQuashqai>(); auto hrv = garage->service<HondaHRV>(); auto hrv_diesel = garage->service<HondaHRVDiesel>(); auto premium = garage->service<PremiumPetrol>(); astra2->setFuel(premium); std::cout << std::boolalpha << std::fixed << std::setprecision(2); std::cout << "`astra1` and `astra2` is the same auto: " << (astra1 == astra2) << "\n`hrv` and `hrv_diesel` is the same auto: " << (hrv == hrv_diesel) << "\npremium petrol is single: " << (premium == garage->service<PremiumPetrol>()) << "\n\nRefuel costs:" "\n\tOpel Astra(1), 50 litres: " << astra1->refuel(50) << "\n\tOpel Astra(2), 50 litres: " << astra2->refuel(50) << "\n\tNissan Quashqai, 30 litres: " << quashqai->refuel(30) << "\n\tHonda" "\n\t HR-V, 30 litres: " << hrv->refuel(30) << "\n\t HR-V Diesel, 30 litres: " << hrv_diesel->refuel(30) << '\n'; } <commit_msg>Car-example: Flexible fuel prices<commit_after>#include <iostream> #include <iomanip> #include <stdexcept> #include "kangaru.hpp" struct CarsContainer; struct Fuel { auto getPrice() const noexcept -> double { return price_; } auto setPrice(double price) -> void { if (price < 0.0) throw std::runtime_error{"Price cannot be negative"}; price_ = price; } protected: Fuel() = default; private: double price_; }; struct Car { auto refuel(size_t litres) const noexcept -> double { return litres * fuel_->getPrice(); } auto setFuel(std::shared_ptr<Fuel> fuel) -> void { fuel_ = std::move(fuel); } protected: explicit Car(std::shared_ptr<Fuel> fuel) : fuel_{std::move(fuel)} {} private: std::shared_ptr<Fuel> fuel_; }; struct Petrol : Fuel { Petrol() = default; }; struct PremiumPetrol : Petrol { PremiumPetrol() = default; }; struct Diesel : Fuel { Diesel() = default; }; struct OpelAstra : Car { explicit OpelAstra(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct NissanQuashqai : Car { explicit NissanQuashqai(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct HondaHRV : Car { explicit HondaHRV(std::shared_ptr<Fuel> fuel) : Car{std::move(fuel)} {} }; struct HondaHRVDiesel : HondaHRV { explicit HondaHRVDiesel(std::shared_ptr<Fuel> fuel) : HondaHRV{std::move(fuel)} {} }; struct CarsContainer : kgr::Container { CarsContainer() = default; protected: virtual auto init() -> void override final; }; auto CarsContainer::init() -> void { service<Petrol>()->setPrice(130.70); service<PremiumPetrol>()->setPrice(144.50); service<Diesel>()->setPrice(135.30); } namespace kgr { template<> struct Service<Fuel> : NoDependencies, Single {}; template<> struct Service<Petrol> : NoDependencies, Overrides<Fuel> {}; template<> struct Service<PremiumPetrol> : NoDependencies, Single {}; template<> struct Service<Diesel> : NoDependencies, Single {}; template<> struct Service<OpelAstra> : Dependency<Petrol> {}; template<> struct Service<NissanQuashqai> : Dependency<Petrol> {}; template<> struct Service<HondaHRV> : Dependency<PremiumPetrol> {}; template<> struct Service<HondaHRVDiesel> : Dependency<Diesel> {}; } // namespace kgr int main() { auto garage = kgr::make_container<CarsContainer>(); auto astra1 = garage->service<OpelAstra>(); auto astra2 = garage->service<OpelAstra>(); auto quashqai = garage->service<NissanQuashqai>(); auto hrv = garage->service<HondaHRV>(); auto hrv_diesel = garage->service<HondaHRVDiesel>(); auto premium = garage->service<PremiumPetrol>(); astra2->setFuel(premium); std::cout << std::boolalpha << std::fixed << std::setprecision(2); std::cout << "`astra1` and `astra2` is the same auto: " << (astra1 == astra2) << "\n`hrv` and `hrv_diesel` is the same auto: " << (hrv == hrv_diesel) << "\npremium petrol is single: " << (premium == garage->service<PremiumPetrol>()) << "\nPremium petrol costs " << premium->getPrice() << " per litre" "\n\nRefuel costs:" "\n\tOpel Astra(1), 50 litres: " << astra1->refuel(50) << "\n\tOpel Astra(2), 50 litres: " << astra2->refuel(50) << "\n\tNissan Quashqai, 30 litres: " << quashqai->refuel(30) << "\n\tHonda" "\n\t HR-V, 30 litres: " << hrv->refuel(30) << "\n\t HR-V Diesel, 30 litres: " << hrv_diesel->refuel(30) << '\n'; premium->setPrice(147.20); std::cout << "Update premium petrol price to " << premium->getPrice() << "\nNow refuel of Honda HR-V (30 litres) costs " << hrv->refuel(30) << '\n'; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2020 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 <addrdb.h> #include <addrman.h> #include <blockencodings.h> #include <blockfilter.h> #include <chain.h> #include <coins.h> #include <compressor.h> #include <consensus/merkle.h> #include <key.h> #include <merkleblock.h> #include <net.h> #include <node/utxo_snapshot.h> #include <primitives/block.h> #include <protocol.h> #include <psbt.h> #include <pubkey.h> #include <script/keyorigin.h> #include <streams.h> #include <undo.h> #include <version.h> #include <exception> #include <stdexcept> #include <stdint.h> #include <unistd.h> #include <vector> #include <test/fuzz/fuzz.h> void initialize() { // Fuzzers using pubkey must hold an ECCVerifyHandle. static const ECCVerifyHandle verify_handle; } namespace { struct invalid_fuzzing_input_exception : public std::exception { }; template <typename T> CDataStream Serialize(const T& obj) { CDataStream ds(SER_NETWORK, INIT_PROTO_VERSION); ds << obj; return ds; } template <typename T> T Deserialize(CDataStream ds) { T obj; ds >> obj; return obj; } template <typename T> void DeserializeFromFuzzingInput(const std::vector<uint8_t>& buffer, T& obj) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); try { int version; ds >> version; ds.SetVersion(version); } catch (const std::ios_base::failure&) { throw invalid_fuzzing_input_exception(); } try { ds >> obj; } catch (const std::ios_base::failure&) { throw invalid_fuzzing_input_exception(); } assert(buffer.empty() || !Serialize(obj).empty()); } template <typename T> void AssertEqualAfterSerializeDeserialize(const T& obj) { assert(Deserialize<T>(Serialize(obj)) == obj); } } // namespace void test_one_input(const std::vector<uint8_t>& buffer) { try { #if BLOCK_FILTER_DESERIALIZE BlockFilter block_filter; DeserializeFromFuzzingInput(buffer, block_filter); #elif ADDR_INFO_DESERIALIZE CAddrInfo addr_info; DeserializeFromFuzzingInput(buffer, addr_info); #elif BLOCK_FILE_INFO_DESERIALIZE CBlockFileInfo block_file_info; DeserializeFromFuzzingInput(buffer, block_file_info); #elif BLOCK_HEADER_AND_SHORT_TXIDS_DESERIALIZE CBlockHeaderAndShortTxIDs block_header_and_short_txids; DeserializeFromFuzzingInput(buffer, block_header_and_short_txids); #elif FEE_RATE_DESERIALIZE CFeeRate fee_rate; DeserializeFromFuzzingInput(buffer, fee_rate); AssertEqualAfterSerializeDeserialize(fee_rate); #elif MERKLE_BLOCK_DESERIALIZE CMerkleBlock merkle_block; DeserializeFromFuzzingInput(buffer, merkle_block); #elif OUT_POINT_DESERIALIZE COutPoint out_point; DeserializeFromFuzzingInput(buffer, out_point); AssertEqualAfterSerializeDeserialize(out_point); #elif PARTIAL_MERKLE_TREE_DESERIALIZE CPartialMerkleTree partial_merkle_tree; DeserializeFromFuzzingInput(buffer, partial_merkle_tree); #elif PUB_KEY_DESERIALIZE CPubKey pub_key; DeserializeFromFuzzingInput(buffer, pub_key); // TODO: The following equivalence should hold for CPubKey? Fix. // AssertEqualAfterSerializeDeserialize(pub_key); #elif SCRIPT_DESERIALIZE CScript script; DeserializeFromFuzzingInput(buffer, script); #elif SUB_NET_DESERIALIZE CSubNet sub_net; DeserializeFromFuzzingInput(buffer, sub_net); AssertEqualAfterSerializeDeserialize(sub_net); #elif TX_IN_DESERIALIZE CTxIn tx_in; DeserializeFromFuzzingInput(buffer, tx_in); AssertEqualAfterSerializeDeserialize(tx_in); #elif FLAT_FILE_POS_DESERIALIZE FlatFilePos flat_file_pos; DeserializeFromFuzzingInput(buffer, flat_file_pos); AssertEqualAfterSerializeDeserialize(flat_file_pos); #elif KEY_ORIGIN_INFO_DESERIALIZE KeyOriginInfo key_origin_info; DeserializeFromFuzzingInput(buffer, key_origin_info); AssertEqualAfterSerializeDeserialize(key_origin_info); #elif PARTIALLY_SIGNED_TRANSACTION_DESERIALIZE PartiallySignedTransaction partially_signed_transaction; DeserializeFromFuzzingInput(buffer, partially_signed_transaction); #elif PREFILLED_TRANSACTION_DESERIALIZE PrefilledTransaction prefilled_transaction; DeserializeFromFuzzingInput(buffer, prefilled_transaction); #elif PSBT_INPUT_DESERIALIZE PSBTInput psbt_input; DeserializeFromFuzzingInput(buffer, psbt_input); #elif PSBT_OUTPUT_DESERIALIZE PSBTOutput psbt_output; DeserializeFromFuzzingInput(buffer, psbt_output); #elif BLOCK_DESERIALIZE CBlock block; DeserializeFromFuzzingInput(buffer, block); #elif BLOCKLOCATOR_DESERIALIZE CBlockLocator bl; DeserializeFromFuzzingInput(buffer, bl); #elif BLOCKMERKLEROOT CBlock block; DeserializeFromFuzzingInput(buffer, block); bool mutated; BlockMerkleRoot(block, &mutated); #elif ADDRMAN_DESERIALIZE CAddrMan am; DeserializeFromFuzzingInput(buffer, am); #elif BLOCKHEADER_DESERIALIZE CBlockHeader bh; DeserializeFromFuzzingInput(buffer, bh); #elif BANENTRY_DESERIALIZE CBanEntry be; DeserializeFromFuzzingInput(buffer, be); #elif TXUNDO_DESERIALIZE CTxUndo tu; DeserializeFromFuzzingInput(buffer, tu); #elif BLOCKUNDO_DESERIALIZE CBlockUndo bu; DeserializeFromFuzzingInput(buffer, bu); #elif COINS_DESERIALIZE Coin coin; DeserializeFromFuzzingInput(buffer, coin); #elif NETADDR_DESERIALIZE CNetAddr na; DeserializeFromFuzzingInput(buffer, na); AssertEqualAfterSerializeDeserialize(na); #elif SERVICE_DESERIALIZE CService s; DeserializeFromFuzzingInput(buffer, s); AssertEqualAfterSerializeDeserialize(s); #elif MESSAGEHEADER_DESERIALIZE CMessageHeader mh; DeserializeFromFuzzingInput(buffer, mh); (void)mh.IsCommandValid(); #elif ADDRESS_DESERIALIZE CAddress a; DeserializeFromFuzzingInput(buffer, a); #elif INV_DESERIALIZE CInv i; DeserializeFromFuzzingInput(buffer, i); #elif BLOOMFILTER_DESERIALIZE CBloomFilter bf; DeserializeFromFuzzingInput(buffer, bf); #elif DISKBLOCKINDEX_DESERIALIZE CDiskBlockIndex dbi; DeserializeFromFuzzingInput(buffer, dbi); #elif TXOUTCOMPRESSOR_DESERIALIZE CTxOut to; auto toc = Using<TxOutCompression>(to); DeserializeFromFuzzingInput(buffer, toc); #elif BLOCKTRANSACTIONS_DESERIALIZE BlockTransactions bt; DeserializeFromFuzzingInput(buffer, bt); #elif BLOCKTRANSACTIONSREQUEST_DESERIALIZE BlockTransactionsRequest btr; DeserializeFromFuzzingInput(buffer, btr); #elif SNAPSHOTMETADATA_DESERIALIZE SnapshotMetadata snapshot_metadata; DeserializeFromFuzzingInput(buffer, snapshot_metadata); #elif UINT160_DESERIALIZE uint160 u160; DeserializeFromFuzzingInput(buffer, u160); AssertEqualAfterSerializeDeserialize(u160); #elif UINT256_DESERIALIZE uint256 u256; DeserializeFromFuzzingInput(buffer, u256); AssertEqualAfterSerializeDeserialize(u256); #else #error Need at least one fuzz target to compile #endif // Classes intentionally not covered in this file since their deserialization code is // fuzzed elsewhere: // * Deserialization of CTxOut is fuzzed in test/fuzz/tx_out.cpp // * Deserialization of CMutableTransaction is fuzzed in src/test/fuzz/transaction.cpp } catch (const invalid_fuzzing_input_exception&) { } } <commit_msg>fuzz: Check for addrv1 compatibility before using addrv1 serializer<commit_after>// Copyright (c) 2009-2020 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 <addrdb.h> #include <addrman.h> #include <blockencodings.h> #include <blockfilter.h> #include <chain.h> #include <coins.h> #include <compressor.h> #include <consensus/merkle.h> #include <key.h> #include <merkleblock.h> #include <net.h> #include <netbase.h> #include <node/utxo_snapshot.h> #include <primitives/block.h> #include <protocol.h> #include <psbt.h> #include <pubkey.h> #include <script/keyorigin.h> #include <streams.h> #include <undo.h> #include <version.h> #include <exception> #include <stdexcept> #include <stdint.h> #include <unistd.h> #include <vector> #include <test/fuzz/fuzz.h> void initialize() { // Fuzzers using pubkey must hold an ECCVerifyHandle. static const ECCVerifyHandle verify_handle; } namespace { struct invalid_fuzzing_input_exception : public std::exception { }; template <typename T> CDataStream Serialize(const T& obj, const int version = INIT_PROTO_VERSION) { CDataStream ds(SER_NETWORK, version); ds << obj; return ds; } template <typename T> T Deserialize(CDataStream ds) { T obj; ds >> obj; return obj; } template <typename T> void DeserializeFromFuzzingInput(const std::vector<uint8_t>& buffer, T& obj) { CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION); try { int version; ds >> version; ds.SetVersion(version); } catch (const std::ios_base::failure&) { throw invalid_fuzzing_input_exception(); } try { ds >> obj; } catch (const std::ios_base::failure&) { throw invalid_fuzzing_input_exception(); } assert(buffer.empty() || !Serialize(obj).empty()); } template <typename T> void AssertEqualAfterSerializeDeserialize(const T& obj, const int version = INIT_PROTO_VERSION) { assert(Deserialize<T>(Serialize(obj, version)) == obj); } } // namespace void test_one_input(const std::vector<uint8_t>& buffer) { try { #if BLOCK_FILTER_DESERIALIZE BlockFilter block_filter; DeserializeFromFuzzingInput(buffer, block_filter); #elif ADDR_INFO_DESERIALIZE CAddrInfo addr_info; DeserializeFromFuzzingInput(buffer, addr_info); #elif BLOCK_FILE_INFO_DESERIALIZE CBlockFileInfo block_file_info; DeserializeFromFuzzingInput(buffer, block_file_info); #elif BLOCK_HEADER_AND_SHORT_TXIDS_DESERIALIZE CBlockHeaderAndShortTxIDs block_header_and_short_txids; DeserializeFromFuzzingInput(buffer, block_header_and_short_txids); #elif FEE_RATE_DESERIALIZE CFeeRate fee_rate; DeserializeFromFuzzingInput(buffer, fee_rate); AssertEqualAfterSerializeDeserialize(fee_rate); #elif MERKLE_BLOCK_DESERIALIZE CMerkleBlock merkle_block; DeserializeFromFuzzingInput(buffer, merkle_block); #elif OUT_POINT_DESERIALIZE COutPoint out_point; DeserializeFromFuzzingInput(buffer, out_point); AssertEqualAfterSerializeDeserialize(out_point); #elif PARTIAL_MERKLE_TREE_DESERIALIZE CPartialMerkleTree partial_merkle_tree; DeserializeFromFuzzingInput(buffer, partial_merkle_tree); #elif PUB_KEY_DESERIALIZE CPubKey pub_key; DeserializeFromFuzzingInput(buffer, pub_key); // TODO: The following equivalence should hold for CPubKey? Fix. // AssertEqualAfterSerializeDeserialize(pub_key); #elif SCRIPT_DESERIALIZE CScript script; DeserializeFromFuzzingInput(buffer, script); #elif SUB_NET_DESERIALIZE CSubNet sub_net; DeserializeFromFuzzingInput(buffer, sub_net); AssertEqualAfterSerializeDeserialize(sub_net); #elif TX_IN_DESERIALIZE CTxIn tx_in; DeserializeFromFuzzingInput(buffer, tx_in); AssertEqualAfterSerializeDeserialize(tx_in); #elif FLAT_FILE_POS_DESERIALIZE FlatFilePos flat_file_pos; DeserializeFromFuzzingInput(buffer, flat_file_pos); AssertEqualAfterSerializeDeserialize(flat_file_pos); #elif KEY_ORIGIN_INFO_DESERIALIZE KeyOriginInfo key_origin_info; DeserializeFromFuzzingInput(buffer, key_origin_info); AssertEqualAfterSerializeDeserialize(key_origin_info); #elif PARTIALLY_SIGNED_TRANSACTION_DESERIALIZE PartiallySignedTransaction partially_signed_transaction; DeserializeFromFuzzingInput(buffer, partially_signed_transaction); #elif PREFILLED_TRANSACTION_DESERIALIZE PrefilledTransaction prefilled_transaction; DeserializeFromFuzzingInput(buffer, prefilled_transaction); #elif PSBT_INPUT_DESERIALIZE PSBTInput psbt_input; DeserializeFromFuzzingInput(buffer, psbt_input); #elif PSBT_OUTPUT_DESERIALIZE PSBTOutput psbt_output; DeserializeFromFuzzingInput(buffer, psbt_output); #elif BLOCK_DESERIALIZE CBlock block; DeserializeFromFuzzingInput(buffer, block); #elif BLOCKLOCATOR_DESERIALIZE CBlockLocator bl; DeserializeFromFuzzingInput(buffer, bl); #elif BLOCKMERKLEROOT CBlock block; DeserializeFromFuzzingInput(buffer, block); bool mutated; BlockMerkleRoot(block, &mutated); #elif ADDRMAN_DESERIALIZE CAddrMan am; DeserializeFromFuzzingInput(buffer, am); #elif BLOCKHEADER_DESERIALIZE CBlockHeader bh; DeserializeFromFuzzingInput(buffer, bh); #elif BANENTRY_DESERIALIZE CBanEntry be; DeserializeFromFuzzingInput(buffer, be); #elif TXUNDO_DESERIALIZE CTxUndo tu; DeserializeFromFuzzingInput(buffer, tu); #elif BLOCKUNDO_DESERIALIZE CBlockUndo bu; DeserializeFromFuzzingInput(buffer, bu); #elif COINS_DESERIALIZE Coin coin; DeserializeFromFuzzingInput(buffer, coin); #elif NETADDR_DESERIALIZE CNetAddr na; DeserializeFromFuzzingInput(buffer, na); if (na.IsAddrV1Compatible()) { AssertEqualAfterSerializeDeserialize(na); } AssertEqualAfterSerializeDeserialize(na, INIT_PROTO_VERSION | ADDRV2_FORMAT); #elif SERVICE_DESERIALIZE CService s; DeserializeFromFuzzingInput(buffer, s); AssertEqualAfterSerializeDeserialize(s); #elif MESSAGEHEADER_DESERIALIZE CMessageHeader mh; DeserializeFromFuzzingInput(buffer, mh); (void)mh.IsCommandValid(); #elif ADDRESS_DESERIALIZE CAddress a; DeserializeFromFuzzingInput(buffer, a); #elif INV_DESERIALIZE CInv i; DeserializeFromFuzzingInput(buffer, i); #elif BLOOMFILTER_DESERIALIZE CBloomFilter bf; DeserializeFromFuzzingInput(buffer, bf); #elif DISKBLOCKINDEX_DESERIALIZE CDiskBlockIndex dbi; DeserializeFromFuzzingInput(buffer, dbi); #elif TXOUTCOMPRESSOR_DESERIALIZE CTxOut to; auto toc = Using<TxOutCompression>(to); DeserializeFromFuzzingInput(buffer, toc); #elif BLOCKTRANSACTIONS_DESERIALIZE BlockTransactions bt; DeserializeFromFuzzingInput(buffer, bt); #elif BLOCKTRANSACTIONSREQUEST_DESERIALIZE BlockTransactionsRequest btr; DeserializeFromFuzzingInput(buffer, btr); #elif SNAPSHOTMETADATA_DESERIALIZE SnapshotMetadata snapshot_metadata; DeserializeFromFuzzingInput(buffer, snapshot_metadata); #elif UINT160_DESERIALIZE uint160 u160; DeserializeFromFuzzingInput(buffer, u160); AssertEqualAfterSerializeDeserialize(u160); #elif UINT256_DESERIALIZE uint256 u256; DeserializeFromFuzzingInput(buffer, u256); AssertEqualAfterSerializeDeserialize(u256); #else #error Need at least one fuzz target to compile #endif // Classes intentionally not covered in this file since their deserialization code is // fuzzed elsewhere: // * Deserialization of CTxOut is fuzzed in test/fuzz/tx_out.cpp // * Deserialization of CMutableTransaction is fuzzed in src/test/fuzz/transaction.cpp } catch (const invalid_fuzzing_input_exception&) { } } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { // default, to allow for specialization template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Spe10Model1 { public: Spe10Model1() = delete; }; // class FunctionSpe10Model1 /** * \note For dimRange 1 we only read the Kx values from the file. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, RangeFieldType(0)); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] = (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > /** * We read only the Kx values from file and scale the unit matrix. Thus we should be the same as the scalar variant. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".spe10.model1"; } private: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeFieldType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) RangeType unit_matrix(0.0); for (size_t dd = 0; dd < dimDomain; ++dd) unit_matrix[dd][dd] = 1.0; std::vector< RangeType > data(entriesPerDim, unit_matrix); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] *= (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::maxValue = 998.915; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <commit_msg>[functions.spe10] minor updates<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { // default, to allow for specialization template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1 > class Spe10Model1 { public: Spe10Model1() = delete; }; // class FunctionSpe10Model1 /** * \note For dimRange 1 we only read the Kx values from the file. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return LocalizableFunctionInterface < EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >::static_id() + ".spe10.model1"; } // ... static_id(...) public: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; private: static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, RangeFieldType(0)); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] = (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > /** * We read only the Kx values from file and scale the unit matrix. Thus we should be the same as the scalar variant. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp > class Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > BaseType; typedef Spe10Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, 2, 2 > ThisType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const int dimRange = BaseType::dimRange; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return LocalizableFunctionInterface < EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >::static_id() + ".spe10.model1"; } // ... static_id(...) public: static const size_t numXelements; static const size_t numYelements; static const size_t numZelements; static const RangeFieldType minValue; static const RangeFieldType maxValue; private: static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (maxValue - minValue); const RangeFieldType shift = min - scale*minValue; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = numXelements*numYelements*numZelements; // create storage (there should be exactly 6000 values in the file, but we only read the first 2000) RangeType unit_matrix(0.0); for (size_t dd = 0; dd < dimDomain; ++dd) unit_matrix[dd][dd] = 1.0; std::vector< RangeType > data(entriesPerDim, unit_matrix); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) { data[counter] *= (tmp * scale) + shift; ++counter; } datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = "perm_case1.dat"; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[762.0 15.24]"; config["min_value"] = "0.001"; config["max_value"] = "998.915"; config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(), const std::string sub_name = static_id()) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< ThisType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< std::vector< DomainFieldType > >("lower_left"), dimDomain), cfg.get("upper_right", default_cfg.get< std::vector< DomainFieldType > >("upper_right"), dimDomain), cfg.get("min_val", minValue), cfg.get("max_val", maxValue), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Spe10Model1(const std::string& filename, const std::vector< DomainFieldType >& lowerLeft, const std::vector< DomainFieldType >& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} Spe10Model1(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min = minValue, const RangeFieldType max = maxValue, const std::string nm = static_id()) : BaseType(lowerLeft, upperRight, {numXelements, numZelements}, read_values_from_file(filename, min, max), nm) {} virtual std::string type() const DS_OVERRIDE { return BaseType::static_id() + ".spe10.model1"; } virtual ThisType* copy() const DS_OVERRIDE { return new ThisType(*this); } }; // class Spe10Model1< ..., 2, ..., 1, 1 > template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 1, 1 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 1, 1 >::RangeFieldType Spe10Model1< E, D, 2, R, 1, 1 >::maxValue = 998.915; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numXelements = 100; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numYelements = 1; template< class E, class D, class R > const size_t Spe10Model1< E, D, 2, R, 2, 2 >::numZelements = 20; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::minValue = 0.001; template< class E, class D, class R > const typename Spe10Model1< E, D, 2, R, 2, 2 >::RangeFieldType Spe10Model1< E, D, 2, R, 2, 2 >::maxValue = 998.915; } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <|endoftext|>
<commit_before>#include <ESPWebConfig.h> #include <ESP8266WiFi.h> char* ESPWebConfig::_helpText = NULL; ParamStore ESPWebConfig::_paramStore; const String* ESPWebConfig::_paramNames = NULL; int ESPWebConfig::_paramNamesLength = 0; boolean ESPWebConfig::_configurationDone = false; // TODO: Only create server when web config starts. ESP8266WebServer* ewc_server; // EEprom defines #define STRING_END 0 #define SSID_ID 1 #define PASS_ID 2 #define NO_OF_INTERNAL_PARAMS 2 #define USER_PARAM_ID 3 #define UNUSED(expr) do { (void)(expr); } while (0) ESPWebConfig::ESPWebConfig(const char* configPassword, String* paramNames, int paramNamesLength, char* helpText) { _configPassword = configPassword; _paramNames = paramNames; _paramNamesLength = paramNamesLength; _helpText = helpText; } bool ESPWebConfig::setup() { bool cfgRead = false; ESPWC_PRINTLN("Setup"); cfgRead = _paramStore.ReadConfig(); if (cfgRead) { ESPWC_PRINTLN("Start wifi"); if (this->_startWifi()) { ESPWC_PRINTLN("Wifi started"); return true; } } else { ESPWC_PRINTLN("Not Configured"); } // Configure device this->_startWebConfiguration(); // One more try to read config and start wifi. if (_paramStore.ReadConfig() && this->_startWifi()) { return true; } return false; } char* ESPWebConfig::getParameter(const char *name) { ESPWC_PRINT("getParameter "); ESPWC_PRINTLN(name); byte id = this->_nameToId(name); return _paramStore.GetParameterById(id); } byte ESPWebConfig::getRaw(unsigned int address) { return _paramStore._eepromData[address]; } void ESPWebConfig::setRaw(unsigned int address, byte val) { _paramStore._eepromData[address] = val; EEPROM.write(address, val); EEPROM.commit(); } void ESPWebConfig::startConfig(unsigned long timeoutMs) { ESPWC_PRINTLN("Start config."); this->_startWebConfiguration(timeoutMs); } void ESPWebConfig::clearConfig() { if (_configCleard) return; ESPWC_PRINTLN("Clear config."); EEPROM.write(0, CONFIG_ERASED); EEPROM.commit(); _configCleard = true; } ///////// Private functions /////////////////// /* Find id of variablename. 1, 2, ..., return 0 on failure. */ byte ESPWebConfig::_nameToId(const char* name) { if (!name || !_paramNames) { ESPWC_PRINTLN("_nameToId invalid"); return 0; } for (int i = 0; i<_paramNamesLength; i++) { ESPWC_PRINT("Compare parameter "); ESPWC_PRINTLN(_paramNames[i]); if (strcmp(_paramNames[i].c_str(), name) == 0) { return i+USER_PARAM_ID; } } ESPWC_PRINT("No parameter with name "); ESPWC_PRINTLN(name); return 0; } bool ESPWebConfig::_startWifi() { WiFi.mode(WIFI_STA); char* ssid = _paramStore.GetParameterById(SSID_ID); char* pass = _paramStore.GetParameterById(PASS_ID); ESPWC_PRINT("_startWifi: "); ESPWC_PRINT(ssid?ssid:"NULL"); ESPWC_PRINT(" "); ESPWC_PRINTLN(pass?pass:"NULL"); WiFi.begin(ssid, pass); if(WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println("WiFi Connect Failed! ..."); return false; } ESPWC_PRINTLN("_startWifi: OK!!!!"); return true; } void ESPWebConfig::_handleSave() { int address = 0; const char* c; EEPROM.write(address, CONFIG_VALID); address++; for (int i = 1; i <= (_paramNamesLength + NO_OF_INTERNAL_PARAMS); i++) { String val = ewc_server->arg(String(i)); c = val.c_str(); EEPROM.write(address, i); address++; while(*c) { EEPROM.write(address, *c); address++; c++; } EEPROM.write(address, 0); address++; } EEPROM.commit(); ewc_server->send(200, "text/html", F("<html><body><h1>Configuration done.</h1></body></html>")); ewc_server->close(); delay(1000); _configurationDone = true; } void ESPWebConfig::_handleServe() { char inp[128]; // Get chipId uint32_t chipid = ESP.getChipId(); char chipStr[32] ={0}; sprintf(chipStr, "<p>ChipId: %0X</p>", chipid); Serial.println("Handle config page"); ewc_server->setContentLength(CONTENT_LENGTH_UNKNOWN); ewc_server->send(200, "text/html", ""); ewc_server->sendContent("<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" "<style type=text/css>" "body { margin:5%; font-family: Arial;} form p label {display:block;float:left;width:100px;}" "</style></head>" "<body><h1>Configure device</h1><form action=\"/\" method=\"post\">" "<h3>Wifi configuration</h3>"); ESPWebConfig::_generateInputField("SSID*", SSID_ID, inp, 128); ewc_server->sendContent(inp); ESPWebConfig::_generateInputField("password|Password", PASS_ID, inp, 128); ewc_server->sendContent(inp); if (_paramNamesLength) { sprintf(inp, "<h3>Parameters</h3><p>%s</p>", _helpText?_helpText:""); ewc_server->sendContent(inp); for (int i = 0; i < _paramNamesLength; i++) { ESPWebConfig::_generateInputField(_paramNames[i].c_str(), i + USER_PARAM_ID, inp, 128); ewc_server->sendContent(inp); } } ewc_server->sendContent("<p><input type=\"submit\" value=\"Save\"/></p></form><br>"); // Print chipId, Could be useful in config. ewc_server->sendContent(chipStr); ewc_server->sendContent("</body></html>"); ewc_server->sendContent(""); ewc_server->client().stop(); } void ESPWebConfig::_generateInputField(const char *legend, int id, char *html, int len) { char *p = html; unsigned int left = len-1;// zero term int l = 0; char *val = NULL; if (_paramStore.Restore()) { val = _paramStore.GetParameterById(id); } const char *type = NULL; // Check for inpit type char *tmp = strchr(legend, '|'); if (tmp) { type = legend; legend = tmp+1; *tmp = '\0';// Convert | to end of string } char *req = strchr(legend, '*'); l = sprintf(p, "<p><label>%s</label><input name=%d", legend, id); p += l; left -= l; if (type && strlen(type) + 8 + 17 < left) { l = sprintf(p, " type=\"%s\"", type); left -= l; p += l; } if (val && strlen(val) + 9 + 17 < left) { l = sprintf(p, " value=\"%s\"", val); left -= l; p += l; } // End input tag if (req) { sprintf(p, " \"required\"/></p>"); } else { sprintf(p, " /></p>"); } } bool ESPWebConfig::_startWebConfiguration(unsigned long timeoutMs) { if (WiFi.isConnected()) WiFi.disconnect(); ewc_server = new ESP8266WebServer(80); // ESP8266WebServer server(80); WiFi.mode(WIFI_AP); char ap_name[32]; IPAddress myIP = WiFi.softAPIP(); String ipstr; if (myIP) { ipstr = myIP.toString(); } else{ ipstr = "unknown_ip"; } sprintf(ap_name, "ESP_%s", ipstr.c_str()); if (_configPassword) { WiFi.softAP(ap_name, _configPassword); } else { WiFi.softAP(ap_name); } ESPWC_PRINTLN("Add handler /old "); ewc_server->on("/", HTTP_GET, this->_handleServe); ewc_server->on("/", HTTP_POST, this->_handleSave); ewc_server->begin(); ESPWC_PRINTLN("Enter config mode."); // Serve the config page at "/" until config done. unsigned long startTime = millis(); while(!_configurationDone) { // ESPWC_PRINTLN("HANDLE config mode."); ewc_server->handleClient(); if (timeoutMs && (millis() - startTime) > timeoutMs) { ESPWC_PRINTLN("Config timeout, restart"); delay(100); ESP.restart(); } } return true; } <commit_msg>Bugfix: WifiConnect failed<commit_after>#include <ESPWebConfig.h> #include <ESP8266WiFi.h> char* ESPWebConfig::_helpText = NULL; ParamStore ESPWebConfig::_paramStore; const String* ESPWebConfig::_paramNames = NULL; int ESPWebConfig::_paramNamesLength = 0; boolean ESPWebConfig::_configurationDone = false; // TODO: Only create server when web config starts. ESP8266WebServer* ewc_server; // EEprom defines #define STRING_END 0 #define SSID_ID 1 #define PASS_ID 2 #define NO_OF_INTERNAL_PARAMS 2 #define USER_PARAM_ID 3 #define UNUSED(expr) do { (void)(expr); } while (0) ESPWebConfig::ESPWebConfig(const char* configPassword, String* paramNames, int paramNamesLength, char* helpText) { _configPassword = configPassword; _paramNames = paramNames; _paramNamesLength = paramNamesLength; _helpText = helpText; } bool ESPWebConfig::setup() { bool cfgRead = false; ESPWC_PRINTLN("Setup"); cfgRead = _paramStore.ReadConfig(); if (cfgRead) { if (this->_startWifi()) { return true; } return false; } else { ESPWC_PRINTLN("Not Configured"); } // Configure device this->_startWebConfiguration(); // One more try to read config and start wifi. if (_paramStore.ReadConfig() && this->_startWifi()) { return true; } return false; } char* ESPWebConfig::getParameter(const char *name) { ESPWC_PRINT("getParameter "); ESPWC_PRINTLN(name); byte id = this->_nameToId(name); return _paramStore.GetParameterById(id); } byte ESPWebConfig::getRaw(unsigned int address) { return _paramStore._eepromData[address]; } void ESPWebConfig::setRaw(unsigned int address, byte val) { _paramStore._eepromData[address] = val; EEPROM.write(address, val); EEPROM.commit(); } void ESPWebConfig::startConfig(unsigned long timeoutMs) { ESPWC_PRINTLN("Start config."); this->_startWebConfiguration(timeoutMs); } void ESPWebConfig::clearConfig() { if (_configCleard) return; ESPWC_PRINTLN("Clear config."); EEPROM.write(0, CONFIG_ERASED); EEPROM.commit(); _configCleard = true; } ///////// Private functions /////////////////// /* Find id of variablename. 1, 2, ..., return 0 on failure. */ byte ESPWebConfig::_nameToId(const char* name) { if (!name || !_paramNames) { ESPWC_PRINTLN("_nameToId invalid"); return 0; } for (int i = 0; i<_paramNamesLength; i++) { ESPWC_PRINT("Compare parameter "); ESPWC_PRINTLN(_paramNames[i]); if (strcmp(_paramNames[i].c_str(), name) == 0) { return i+USER_PARAM_ID; } } ESPWC_PRINT("No parameter with name "); ESPWC_PRINTLN(name); return 0; } bool ESPWebConfig::_startWifi() { WiFi.mode(WIFI_STA); char* ssid = _paramStore.GetParameterById(SSID_ID); char* pass = _paramStore.GetParameterById(PASS_ID); ESPWC_PRINT("_startWifi: "); ESPWC_PRINT(ssid?ssid:"NULL"); ESPWC_PRINT(" "); ESPWC_PRINTLN(pass?pass:"NULL"); WiFi.begin(ssid, pass); if(WiFi.waitForConnectResult() != WL_CONNECTED) { ESPWC_PRINTLN("WiFi Connect Failed! ..."); return false; } ESPWC_PRINTLN("_startWifi: OK!!!!"); return true; } void ESPWebConfig::_handleSave() { int address = 0; const char* c; EEPROM.write(address, CONFIG_VALID); address++; for (int i = 1; i <= (_paramNamesLength + NO_OF_INTERNAL_PARAMS); i++) { String val = ewc_server->arg(String(i)); c = val.c_str(); EEPROM.write(address, i); address++; while(*c) { EEPROM.write(address, *c); address++; c++; } EEPROM.write(address, 0); address++; } EEPROM.commit(); ewc_server->send(200, "text/html", F("<html><body><h1>Configuration done.</h1></body></html>")); ewc_server->close(); delay(1000); _configurationDone = true; } void ESPWebConfig::_handleServe() { char inp[128]; // Get chipId uint32_t chipid = ESP.getChipId(); char chipStr[32] ={0}; sprintf(chipStr, "<p>ChipId: %0X</p>", chipid); Serial.println("Handle config page"); ewc_server->setContentLength(CONTENT_LENGTH_UNKNOWN); ewc_server->send(200, "text/html", ""); ewc_server->sendContent("<!DOCTYPE html><html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" "<style type=text/css>" "body { margin:5%; font-family: Arial;} form p label {display:block;float:left;width:100px;}" "</style></head>" "<body><h1>Configure device</h1><form action=\"/\" method=\"post\">" "<h3>Wifi configuration</h3>"); ESPWebConfig::_generateInputField("SSID*", SSID_ID, inp, 128); ewc_server->sendContent(inp); ESPWebConfig::_generateInputField("password|Password", PASS_ID, inp, 128); ewc_server->sendContent(inp); if (_paramNamesLength) { sprintf(inp, "<h3>Parameters</h3><p>%s</p>", _helpText?_helpText:""); ewc_server->sendContent(inp); for (int i = 0; i < _paramNamesLength; i++) { ESPWebConfig::_generateInputField(_paramNames[i].c_str(), i + USER_PARAM_ID, inp, 128); ewc_server->sendContent(inp); } } ewc_server->sendContent("<p><input type=\"submit\" value=\"Save\"/></p></form><br>"); // Print chipId, Could be useful in config. ewc_server->sendContent(chipStr); ewc_server->sendContent("</body></html>"); ewc_server->sendContent(""); ewc_server->client().stop(); } void ESPWebConfig::_generateInputField(const char *legend, int id, char *html, int len) { char *p = html; unsigned int left = len-1;// zero term int l = 0; char *val = NULL; if (_paramStore.Restore()) { val = _paramStore.GetParameterById(id); } const char *type = NULL; // Check for inpit type char *tmp = strchr(legend, '|'); if (tmp) { type = legend; legend = tmp+1; *tmp = '\0';// Convert | to end of string } char *req = strchr(legend, '*'); l = sprintf(p, "<p><label>%s</label><input name=%d", legend, id); p += l; left -= l; if (type && strlen(type) + 8 + 17 < left) { l = sprintf(p, " type=\"%s\"", type); left -= l; p += l; } if (val && strlen(val) + 9 + 17 < left) { l = sprintf(p, " value=\"%s\"", val); left -= l; p += l; } // End input tag if (req) { sprintf(p, " \"required\"/></p>"); } else { sprintf(p, " /></p>"); } } bool ESPWebConfig::_startWebConfiguration(unsigned long timeoutMs) { if (WiFi.isConnected()) WiFi.disconnect(); ewc_server = new ESP8266WebServer(80); // ESP8266WebServer server(80); WiFi.mode(WIFI_AP); char ap_name[32]; IPAddress myIP = WiFi.softAPIP(); String ipstr; if (myIP) { ipstr = myIP.toString(); } else{ ipstr = "unknown_ip"; } sprintf(ap_name, "ESP_%s", ipstr.c_str()); if (_configPassword) { WiFi.softAP(ap_name, _configPassword); } else { WiFi.softAP(ap_name); } ESPWC_PRINTLN("Add handler /old "); ewc_server->on("/", HTTP_GET, this->_handleServe); ewc_server->on("/", HTTP_POST, this->_handleSave); ewc_server->begin(); ESPWC_PRINTLN("Enter config mode."); // Serve the config page at "/" until config done. unsigned long startTime = millis(); while(!_configurationDone) { // ESPWC_PRINTLN("HANDLE config mode."); ewc_server->handleClient(); if (timeoutMs && (millis() - startTime) > timeoutMs) { ESPWC_PRINTLN("Config timeout, restart"); delay(100); ESP.restart(); } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // Copyright (c) 2021 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #if !defined(_WIN32) #include "test.hpp" #include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp" #include "iceoryx_utils/cxx/string.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::cxx; using namespace iox::config; namespace iox { namespace test { class CmdLineParserConfigFileOption_test : public Test { public: void SetUp(){}; void TearDown() { // Reset optind to be able to parse again optind = 0; }; }; TEST_F(CmdLineParserConfigFileOption_test, NoConfigPathOptionLeadsToEmptyPath) { constexpr uint8_t NUMBER_OF_ARGS{1U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; args[0] = &appName[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq("")); } TEST_F(CmdLineParserConfigFileOption_test, ConfigPathShortOptionIsCorrectlyRead) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "-c"; char path[] = "/foo/bar.toml"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq(path)); } TEST_F(CmdLineParserConfigFileOption_test, ConfigPathLongOptionIsCorrectlyRead) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "--config-file"; char path[] = "/foo/bar/baz.toml"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq(path)); } TEST_F(CmdLineParserConfigFileOption_test, HelpLongOptionLeadsProgrammNotRunning) { constexpr uint8_t NUMBER_OF_ARGS{2U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "--help"; args[0] = &appName[0]; args[1] = &option[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_FALSE(result.value().run); } TEST_F(CmdLineParserConfigFileOption_test, WrongOptionLeadsUnkownOptionResult) { constexpr uint8_t NUMBER_OF_ARGS{2U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char unknownOption[] = "--unknown"; args[0] = &appName[0]; args[1] = &unknownOption[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_TRUE(result.has_error()); EXPECT_EQ(result.get_error(), CmdLineParserResult::UNKNOWN_OPTION_USED); } TEST_F(CmdLineParserConfigFileOption_test, UniqueIdOptionLeadsCallingCmdLineParserParseReturningNoError) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "-u"; char value[] = "4242"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &value[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); } TEST_F(CmdLineParserConfigFileOption_test, CmdLineParsingModeEqualToOneHandleOnlyTheFirstOption) { constexpr uint8_t NUMBER_OF_ARGS{5U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char uniqueIdOption[] = "-u"; char value[] = "4242"; char customOption[] = "-c"; char path[] = "/foo/bar.toml"; args[0] = &appName[0]; args[1] = &uniqueIdOption[0]; args[2] = &value[0]; args[3] = &customOption[0]; args[4] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args, CmdLineParser::CmdLineArgumentParsingMode::ONE); ASSERT_FALSE(result.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq("")); optind = 0; auto res = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(res.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); EXPECT_THAT(res.value().configFilePath.c_str(), StrEq(path)); } } // namespace test } // namespace iox #endif <commit_msg>iox-#454 Fix name<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // Copyright (c) 2021 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #if !defined(_WIN32) #include "test.hpp" #include "iceoryx_posh/roudi/roudi_cmd_line_parser_config_file_option.hpp" #include "iceoryx_utils/cxx/string.hpp" #include <memory> using namespace ::testing; using ::testing::Return; using namespace iox::cxx; using namespace iox::config; namespace iox { namespace test { class CmdLineParserConfigFileOption_test : public Test { public: void SetUp(){}; void TearDown() { // Reset optind to be able to parse again optind = 0; }; }; TEST_F(CmdLineParserConfigFileOption_test, NoConfigPathOptionLeadsToEmptyPath) { constexpr uint8_t NUMBER_OF_ARGS{1U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; args[0] = &appName[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq("")); } TEST_F(CmdLineParserConfigFileOption_test, ConfigPathShortOptionIsCorrectlyRead) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "-c"; char path[] = "/foo/bar.toml"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq(path)); } TEST_F(CmdLineParserConfigFileOption_test, ConfigPathLongOptionIsCorrectlyRead) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "--config-file"; char path[] = "/foo/bar/baz.toml"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq(path)); } TEST_F(CmdLineParserConfigFileOption_test, HelpLongOptionLeadsProgrammNotRunning) { constexpr uint8_t NUMBER_OF_ARGS{2U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "--help"; args[0] = &appName[0]; args[1] = &option[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); EXPECT_FALSE(result.value().run); } TEST_F(CmdLineParserConfigFileOption_test, WrongOptionLeadsUnkownOptionResult) { constexpr uint8_t NUMBER_OF_ARGS{2U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char unknownOption[] = "--unknown"; args[0] = &appName[0]; args[1] = &unknownOption[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_TRUE(result.has_error()); EXPECT_EQ(result.get_error(), CmdLineParserResult::UNKNOWN_OPTION_USED); } TEST_F(CmdLineParserConfigFileOption_test, UniqueIdOptionLeadsCallingCmdLineParserParseReturningNoError) { constexpr uint8_t NUMBER_OF_ARGS{3U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char option[] = "-u"; char value[] = "4242"; args[0] = &appName[0]; args[1] = &option[0]; args[2] = &value[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(result.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); } TEST_F(CmdLineParserConfigFileOption_test, CmdLineParsingModeEqualToOneHandleOnlyTheFirstOptionReturningNoError) { constexpr uint8_t NUMBER_OF_ARGS{5U}; char* args[NUMBER_OF_ARGS]; char appName[] = "./foo"; char uniqueIdOption[] = "-u"; char value[] = "4242"; char customOption[] = "-c"; char path[] = "/foo/bar.toml"; args[0] = &appName[0]; args[1] = &uniqueIdOption[0]; args[2] = &value[0]; args[3] = &customOption[0]; args[4] = &path[0]; CmdLineParserConfigFileOption sut; auto result = sut.parse(NUMBER_OF_ARGS, args, CmdLineParser::CmdLineArgumentParsingMode::ONE); ASSERT_FALSE(result.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); EXPECT_THAT(result.value().configFilePath.c_str(), StrEq("")); optind = 0; auto res = sut.parse(NUMBER_OF_ARGS, args); ASSERT_FALSE(res.has_error()); ASSERT_TRUE(result.value().uniqueRouDiId.has_value()); EXPECT_EQ(result.value().uniqueRouDiId.value(), 4242); EXPECT_THAT(res.value().configFilePath.c_str(), StrEq(path)); } } // namespace test } // namespace iox #endif <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/fvector.hh> #include <dune/stuff/common/type_utils.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { namespace Spe10 { namespace internal { static const std::string model1_filename = "perm_case1.dat"; static const size_t model1_x_elements = 100; static const size_t model1_y_elements = 1; static const size_t model1_z_elements = 20; static const double model_1_length_x = 762.0; static const double model_1_length_y = 7.62; static const double model_1_length_z = 15.24; static const double model1_min_value = 0.001; static const double model1_max_value = 998.915; template< class EntityImp, class DomainFieldImp, class RangeFieldImp, size_t r, size_t rC > class Model1Base : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, rC > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, rC > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; static const bool available = true; static std::string static_id() { return LocalizableFunctionInterface < EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >::static_id() + ".spe10.model1"; } // ... static_id(...) private: static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max, const RangeType& unit_range) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (internal::model1_max_value - internal::model1_min_value); const RangeFieldType shift = min - scale*internal::model1_min_value; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = model1_x_elements*model1_y_elements*model1_z_elements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, unit_range); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) data[counter++] *= (tmp*scale) + shift; datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = internal::model1_filename; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[" + Common::toString(internal::model_1_length_x) + " " + Common::toString(internal::model_1_length_z) + "]"; config.set("min_value", internal::model1_min_value); config.set("max_value", internal::model1_max_value); config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) template< class DerivedType > static std::unique_ptr< DerivedType > create_derived(const Common::Configuration config, const std::string sub_name) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< DerivedType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< DomainType >("lower_left")), cfg.get("upper_right", default_cfg.get< DomainType >("upper_right")), cfg.get("min_value", default_cfg.get< RangeFieldType >("min_value")), cfg.get("max_value", default_cfg.get< RangeFieldType >("max_value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Model1Base(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min, const RangeFieldType max, const std::string nm, const RangeType& unit_range) : BaseType(lowerLeft, upperRight, {model1_x_elements, model1_z_elements}, read_values_from_file(filename, min, max, unit_range), nm) {} virtual std::string type() const override { return BaseType::static_id() + ".spe10.model1"; } }; // class Model1Base } // namespace internal // default, to allow for specialization template< class E, class D, size_t d, class R, size_t r, size_t rC = 1 > class Model1 : public LocalizableFunctionInterface< E, D, d, R, r, rC > { Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); } }; /** * We read only the Kx values from file and scale the unit matrix atm. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp, size_t r > class Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, r > : public internal::Model1Base< EntityImp, DomainFieldImp, RangeFieldImp, r, r > { typedef internal::Model1Base< EntityImp, DomainFieldImp, RangeFieldImp, r, r > BaseType; typedef Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, r > ThisType; public: using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::RangeFieldType; using typename BaseType::RangeType; static std::unique_ptr< ThisType > create(const Common::Configuration config = BaseType::default_config(), const std::string sub_name = BaseType::static_id()) { return BaseType::template create_derived< ThisType >(config, sub_name); } // ... create(...) Model1(const std::string& filename, const Common::FieldVector< DomainFieldType, dimDomain >& lower_left, const Common::FieldVector< DomainFieldType, dimDomain >& upper_right, const RangeFieldType min = internal::model1_min_value, const RangeFieldType max = internal::model1_max_value, const std::string nm = BaseType::static_id()) : BaseType(filename, lower_left, upper_right, min, max, nm, unit_matrix()) {} private: template< size_t d, bool anything = true > struct Call { static RangeType unit_matrix() { RangeType ret(0.0); for (size_t rr = 0; rr < r; ++rr) ret[rr][rr] = 1.0; return ret; } }; template< bool anything > struct Call< 1, anything > { static RangeType unit_matrix() { return RangeType(1); } }; static RangeType unit_matrix() { return Call< r >::unit_matrix(); } }; // class Model1< ..., 2, ..., r, r > template <class EntityImp, class DomainFieldImp, size_t dim_domain, class RangeFieldImp, size_t r, size_t rC> class Model2 : public Stuff::GlobalFunctionInterface<EntityImp, DomainFieldImp, dim_domain, RangeFieldImp, r, rC> { static_assert(r==rC,""); static_assert(dim_domain==rC,""); static_assert(dim_domain==3,""); typedef Stuff::GlobalFunctionInterface<EntityImp, DomainFieldImp, dim_domain, RangeFieldImp, r, rC> BaseType; public: Model2(std::string data_filename = "perm_case2a.dat") : deltas_{{6.096, 3.048, 0.6096}} , permeability_(nullptr) , permMatrix_(0.0) , filename_(data_filename) { readPermeability(); } virtual ~Model2() { delete permeability_; permeability_ = nullptr; } //! currently used in gdt assembler virtual void evaluate(const typename BaseType::DomainType& x, typename BaseType::RangeType& diffusion) const final override { if (!permeability_) { DSC_LOG_ERROR_0 << "The SPE10-permeability data file could not be opened. This file does\n" << "not come with the dune-multiscale repository due to file size. To download it\n" << "execute\n" << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n" << "unzip the file and move the file 'spe_perm.dat' to\n" << "dune-multiscale/dune/multiscale/problems/spe10_permeability.dat!\n"; DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!"); } // 3 is the maximum space dimension for (size_t dim = 0; dim < dim_domain; ++dim) permIntervalls_[dim] = std::floor(x[dim] / deltas_[dim]); const int offset = permIntervalls_[0] + permIntervalls_[1] * 60 + permIntervalls_[2] * 220 * 60; for (size_t dim = 0; dim < dim_domain; ++dim) diffusion[dim][dim] = permeability_[offset + dim * 1122000]; } virtual size_t order() const { return 0u; } private: void readPermeability() { std::ifstream file(filename_); double val; if (!file) { // file couldn't be opened return; } file >> val; int counter = 0; permeability_ = new double[3366000]; while (!file.eof()) { // keep reading until end-of-file permeability_[counter++] = val; file >> val; // sets EOF flag if no value found } file.close(); } std::array<double, dim_domain> deltas_; double* permeability_; //! TODO automatic memory mutable typename BaseType::DomainType permIntervalls_; mutable Dune::FieldMatrix<double, BaseType::DomainType::dimension, BaseType::DomainType::dimension> permMatrix_; const std::string filename_; }; } // namespace Spe10 } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <commit_msg>[functions.spe10] note grid dimensions<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_FUNCTIONS_SPE10_HH #define DUNE_STUFF_FUNCTIONS_SPE10_HH #include <iostream> #include <memory> #include <dune/stuff/common/exceptions.hh> #include <dune/stuff/common/configuration.hh> #include <dune/stuff/common/color.hh> #include <dune/stuff/common/string.hh> #include <dune/stuff/common/fvector.hh> #include <dune/stuff/common/type_utils.hh> #include "checkerboard.hh" namespace Dune { namespace Stuff { namespace Exceptions { class spe10_data_file_missing : public Dune::IOError {}; } // namespace Exceptions namespace Functions { namespace Spe10 { namespace internal { static const std::string model1_filename = "perm_case1.dat"; static const size_t model1_x_elements = 100; static const size_t model1_y_elements = 1; static const size_t model1_z_elements = 20; static const double model_1_length_x = 762.0; static const double model_1_length_y = 7.62; static const double model_1_length_z = 15.24; static const double model1_min_value = 0.001; static const double model1_max_value = 998.915; template< class EntityImp, class DomainFieldImp, class RangeFieldImp, size_t r, size_t rC > class Model1Base : public Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, rC > { typedef Checkerboard< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, rC > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; typedef typename BaseType::RangeType RangeType; static const bool available = true; static std::string static_id() { return LocalizableFunctionInterface < EntityImp, DomainFieldImp, 2, RangeFieldImp, 1, 1 >::static_id() + ".spe10.model1"; } // ... static_id(...) private: static std::vector< RangeType > read_values_from_file(const std::string& filename, const RangeFieldType& min, const RangeFieldType& max, const RangeType& unit_range) { if (!(max > min)) DUNE_THROW(Dune::RangeError, "max (is " << max << ") has to be larger than min (is " << min << ")!"); const RangeFieldType scale = (max - min) / (internal::model1_max_value - internal::model1_min_value); const RangeFieldType shift = min - scale*internal::model1_min_value; // read all the data from the file std::ifstream datafile(filename); if (datafile.is_open()) { static const size_t entriesPerDim = model1_x_elements*model1_y_elements*model1_z_elements; // create storage (there should be exactly 6000 values in the file, but we onyl read the first 2000) std::vector< RangeType > data(entriesPerDim, unit_range); double tmp = 0; size_t counter = 0; while (datafile >> tmp && counter < entriesPerDim) data[counter++] *= (tmp*scale) + shift; datafile.close(); if (counter != entriesPerDim) DUNE_THROW(Dune::IOError, "wrong number of entries in '" << filename << "' (are " << counter << ", should be " << entriesPerDim << ")!"); return data; } else DUNE_THROW(Exceptions::spe10_data_file_missing, "could not open '" << filename << "'!"); } // ... read_values_from_file(...) public: static Common::Configuration default_config(const std::string sub_name = "") { Common::Configuration config; config["filename"] = internal::model1_filename; config["lower_left"] = "[0.0 0.0]"; config["upper_right"] = "[" + Common::toString(internal::model_1_length_x) + " " + Common::toString(internal::model_1_length_z) + "]"; config.set("min_value", internal::model1_min_value); config.set("max_value", internal::model1_max_value); config["name"] = static_id(); if (sub_name.empty()) return config; else { Common::Configuration tmp; tmp.add(config, sub_name); return tmp; } } // ... default_config(...) template< class DerivedType > static std::unique_ptr< DerivedType > create_derived(const Common::Configuration config, const std::string sub_name) { // get correct config const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config; const Common::Configuration default_cfg = default_config(); // create return Common::make_unique< DerivedType >( cfg.get("filename", default_cfg.get< std::string >("filename")), cfg.get("lower_left", default_cfg.get< DomainType >("lower_left")), cfg.get("upper_right", default_cfg.get< DomainType >("upper_right")), cfg.get("min_value", default_cfg.get< RangeFieldType >("min_value")), cfg.get("max_value", default_cfg.get< RangeFieldType >("max_value")), cfg.get("name", default_cfg.get< std::string >("name"))); } // ... create(...) Model1Base(const std::string& filename, const DomainType& lowerLeft, const DomainType& upperRight, const RangeFieldType min, const RangeFieldType max, const std::string nm, const RangeType& unit_range) : BaseType(lowerLeft, upperRight, {model1_x_elements, model1_z_elements}, read_values_from_file(filename, min, max, unit_range), nm) {} virtual std::string type() const override { return BaseType::static_id() + ".spe10.model1"; } }; // class Model1Base } // namespace internal // default, to allow for specialization template< class E, class D, size_t d, class R, size_t r, size_t rC = 1 > class Model1 : public LocalizableFunctionInterface< E, D, d, R, r, rC > { Model1() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); } }; /** * We read only the Kx values from file and scale the unit matrix atm. */ template< class EntityImp, class DomainFieldImp, class RangeFieldImp, size_t r > class Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, r > : public internal::Model1Base< EntityImp, DomainFieldImp, RangeFieldImp, r, r > { typedef internal::Model1Base< EntityImp, DomainFieldImp, RangeFieldImp, r, r > BaseType; typedef Model1< EntityImp, DomainFieldImp, 2, RangeFieldImp, r, r > ThisType; public: using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::RangeFieldType; using typename BaseType::RangeType; static std::unique_ptr< ThisType > create(const Common::Configuration config = BaseType::default_config(), const std::string sub_name = BaseType::static_id()) { return BaseType::template create_derived< ThisType >(config, sub_name); } // ... create(...) Model1(const std::string& filename, const Common::FieldVector< DomainFieldType, dimDomain >& lower_left, const Common::FieldVector< DomainFieldType, dimDomain >& upper_right, const RangeFieldType min = internal::model1_min_value, const RangeFieldType max = internal::model1_max_value, const std::string nm = BaseType::static_id()) : BaseType(filename, lower_left, upper_right, min, max, nm, unit_matrix()) {} private: template< size_t d, bool anything = true > struct Call { static RangeType unit_matrix() { RangeType ret(0.0); for (size_t rr = 0; rr < r; ++rr) ret[rr][rr] = 1.0; return ret; } }; template< bool anything > struct Call< 1, anything > { static RangeType unit_matrix() { return RangeType(1); } }; static RangeType unit_matrix() { return Call< r >::unit_matrix(); } }; // class Model1< ..., 2, ..., r, r > /** * Grid is currently mandated to have LL (0,0,0) to UR (365.76, 670.56, 51.816) corners */ template <class EntityImp, class DomainFieldImp, size_t dim_domain, class RangeFieldImp, size_t r, size_t rC> class Model2 : public Stuff::GlobalFunctionInterface<EntityImp, DomainFieldImp, dim_domain, RangeFieldImp, r, rC> { static_assert(r==rC,""); static_assert(dim_domain==rC,""); static_assert(dim_domain==3,""); typedef Stuff::GlobalFunctionInterface<EntityImp, DomainFieldImp, dim_domain, RangeFieldImp, r, rC> BaseType; public: Model2(std::string data_filename = "perm_case2a.dat") : deltas_{{6.096, 3.048, 0.6096}} , permeability_(nullptr) , permMatrix_(0.0) , filename_(data_filename) { readPermeability(); } virtual ~Model2() { delete permeability_; permeability_ = nullptr; } //! currently used in gdt assembler virtual void evaluate(const typename BaseType::DomainType& x, typename BaseType::RangeType& diffusion) const final override { if (!permeability_) { DSC_LOG_ERROR_0 << "The SPE10-permeability data file could not be opened. This file does\n" << "not come with the dune-multiscale repository due to file size. To download it\n" << "execute\n" << "wget http://www.spe.org/web/csp/datasets/por_perm_case2a.zip\n" << "unzip the file and move the file 'spe_perm.dat' to\n" << "dune-multiscale/dune/multiscale/problems/spe10_permeability.dat!\n"; DUNE_THROW(IOError, "Data file for Groundwaterflow permeability could not be opened!"); } // 3 is the maximum space dimension for (size_t dim = 0; dim < dim_domain; ++dim) permIntervalls_[dim] = std::floor(x[dim] / deltas_[dim]); const int offset = permIntervalls_[0] + permIntervalls_[1] * 60 + permIntervalls_[2] * 220 * 60; for (size_t dim = 0; dim < dim_domain; ++dim) diffusion[dim][dim] = permeability_[offset + dim * 1122000]; } virtual size_t order() const { return 0u; } private: void readPermeability() { std::ifstream file(filename_); double val; if (!file) { // file couldn't be opened return; } file >> val; int counter = 0; permeability_ = new double[3366000]; while (!file.eof()) { // keep reading until end-of-file permeability_[counter++] = val; file >> val; // sets EOF flag if no value found } file.close(); } std::array<double, dim_domain> deltas_; double* permeability_; //! TODO automatic memory mutable typename BaseType::DomainType permIntervalls_; mutable Dune::FieldMatrix<double, BaseType::DomainType::dimension, BaseType::DomainType::dimension> permMatrix_; const std::string filename_; }; } // namespace Spe10 } // namespace Functions } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_FUNCTIONS_SPE10_HH <|endoftext|>
<commit_before>#include <QtGui> #include "MainWindow.h" MainWindow::MainWindow() { QScrollArea *scrollArea = new QScrollArea; renderWidget = new Renderer; renderWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); scrollArea->setAlignment(Qt::AlignCenter); QWidget *widget = new QWidget; setCentralWidget(widget); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(5); scrollArea->setWidget(renderWidget); layout->addWidget(scrollArea); widget->setLayout(layout); signalMapper = new QSignalMapper(this); createActions(); createMenus(); this->setWindowTitle("IGP 3.0"); this->setWindowIcon(QIcon("./Resources/IGP.png")); } void MainWindow::newFile() { ResizeDialog resizeDialog(1, 1, 1, 1, 2000, 2000, QString("New Image Size")); if (resizeDialog.exec() == QDialog::Accepted) { renderWidget->newImage(resizeDialog.getWidth(),resizeDialog.getHeight()); renderWidget->resize(renderWidget->getMinSize());; } } void MainWindow::openFile() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->loadImage(fileName); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::openFileImport() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) { renderWidget->loadImage(fileName); resizeImage(); } renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::resizeImage() { QSize currentSize = renderWidget->getImageSize(); ResizeDialog resizeDialog(currentSize.width(), currentSize.height(), 1, 1, 2000, 2000); if (resizeDialog.exec() == QDialog::Accepted) { renderWidget->resizeImage(resizeDialog.getWidth(),resizeDialog.getHeight()); renderWidget->resize(renderWidget->getMinSize());; } } void MainWindow::saveFile() { QString fileName = QFileDialog::getOpenFileName(this, tr("Save Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->saveImage(fileName); } void MainWindow::setBrushColor() { QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Brush Color")); if (color.isValid()) renderWidget->setBrushColor(color); } void MainWindow::setBackgroundColor() { QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Background Color")); if (color.isValid()) renderWidget->setBackgroundColor(color); } void MainWindow::setOutlineColor() { QColor color = QColorDialog::getColor(Qt::black, this, tr("Select Background Color")); if (color.isValid()) renderWidget->setOutlineColor(color); } void MainWindow::setColorPalette() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Palette"), "./Palettes/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->changePalette(fileName); } void MainWindow::openPattern(QString dir) { renderWidget->setPattern(QDir(dir)); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateTranspose() { renderWidget->rotateTranspose(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateClockwise() { renderWidget->rotateClockwise(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateCounterClockwise() { renderWidget->rotateCounterClockwise(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotate180() { renderWidget->rotate180(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateFlipX() { renderWidget->rotateFlipX(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateFlipY() { renderWidget->rotateFlipY(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomIn() { renderWidget->zoomIn(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomOut() { renderWidget->zoomOut(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomNormal() { renderWidget->zoomNormal(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::about() { QMessageBox::about(this, tr("About IGP 3.0"), tr("The <b>Irregular Grid Painter</b> [IGP] allows the user to paint patterned tiles. This program's first version originated within the chainmaille community at M.A.I.L. by user Zlosk. The second version, written by user aganim, ended up being a HTML5 port. This final version is written by user TrenchCoatGuy [Brian Geuther] using the QT framework.")); } void MainWindow::createActions() { // File Actions newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new image grid")); connect(newAct, SIGNAL(triggered()), this, SLOT(newFile())); openAct = new QAction(tr("&Open"), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing image")); connect(openAct, SIGNAL(triggered()), this, SLOT(openFile())); openImportAct = new QAction(tr("&Import"), this); openImportAct->setStatusTip(tr("Open an existing image and scale it")); connect(openImportAct, SIGNAL(triggered()), this, SLOT(openFileImport())); resizeImageAct = new QAction(tr("&Resize"), this); resizeImageAct->setStatusTip(tr("Resize current image")); connect(resizeImageAct, SIGNAL(triggered()), this, SLOT(resizeImage())); saveAct = new QAction(tr("&Save"), this); saveAct->setShortcuts(QKeySequence::Save); saveAct->setStatusTip(tr("Save the opened image")); connect(saveAct, SIGNAL(triggered()), this, SLOT(saveFile())); // Rotate Image Actions rotateTransposeAct = new QAction(tr("Transpose Image"), this); rotateTransposeAct->setStatusTip(tr("Transposes the source image file")); connect(rotateTransposeAct, SIGNAL(triggered()), this, SLOT(rotateTranspose())); rotateClockwiseAct = new QAction(tr("Rotate Clockwise"), this); rotateClockwiseAct->setStatusTip(tr("Rotates the source image file by 90 degrees clockwise")); connect(rotateClockwiseAct, SIGNAL(triggered()), this, SLOT(rotateClockwise())); rotateCounterClockwiseAct = new QAction(tr("Rotate Counter-Clockwise"), this); rotateCounterClockwiseAct->setStatusTip(tr("Rotates the source image file by 90 degrees counter-clockwise")); connect(rotateCounterClockwiseAct, SIGNAL(triggered()), this, SLOT(rotateCounterClockwise())); rotate180Act = new QAction(tr("Rotate 180"), this); rotate180Act->setStatusTip(tr("Rotates the source image file by 180 degrees")); connect(rotate180Act, SIGNAL(triggered()), this, SLOT(rotate180())); rotateFlipXAct = new QAction(tr("Reflect X axis"), this); rotateFlipXAct->setStatusTip(tr("Reflects the source image files X axis")); connect(rotateFlipXAct, SIGNAL(triggered()), this, SLOT(rotateFlipX())); rotateFlipYAct = new QAction(tr("Reflect Y axis"), this); rotateFlipYAct->setStatusTip(tr("Reflects the source image files Y axis")); connect(rotateFlipYAct, SIGNAL(triggered()), this, SLOT(rotateFlipY())); // Zoom Actions zoomInAct = new QAction(tr("Zoom In"), this); zoomInAct->setShortcuts(QKeySequence::ZoomIn); zoomInAct->setStatusTip(tr("Increases size of image by 10%")); connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn())); zoomOutAct = new QAction(tr("Zoom Out"), this); zoomOutAct->setShortcuts(QKeySequence::ZoomOut); zoomOutAct->setStatusTip(tr("Decreases size of image by 10%")); connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut())); zoomNormalAct = new QAction(tr("Zoom Reset"), this); zoomNormalAct->setStatusTip(tr("Resets the zoom to 100%")); connect(zoomNormalAct, SIGNAL(triggered()), this, SLOT(zoomNormal())); // Color Actions setBrushColorAct = new QAction(tr("&Brush"), this); setBrushColorAct->setStatusTip(tr("Select a new brush color")); connect(setBrushColorAct, SIGNAL(triggered()), this, SLOT(setBrushColor())); setBackgroundColorAct = new QAction(tr("Back&ground"), this); setBackgroundColorAct->setStatusTip(tr("Select a new background color")); connect(setBackgroundColorAct, SIGNAL(triggered()), this, SLOT(setBackgroundColor())); setOutlineColorAct = new QAction(tr("&Outline"), this); setOutlineColorAct->setStatusTip(tr("Select a new outline color")); connect(setOutlineColorAct, SIGNAL(triggered()), this, SLOT(setOutlineColor())); setColorPaletteAct = new QAction(tr("&Palette Change"), this); setColorPaletteAct->setStatusTip(tr("Limit colors to the current image")); connect(setColorPaletteAct, SIGNAL(triggered()), this, SLOT(setColorPalette())); // About Action aboutAct = new QAction(tr("&About"), this); aboutAct->setShortcuts(QKeySequence::HelpContents); aboutAct->setStatusTip(tr("Description of this program")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); fileMenu->addAction(openImportAct); fileMenu->addAction(resizeImageAct); fileMenu->addAction(saveAct); editMenu = menuBar()->addMenu(tr("&Edit")); transformSubMenu = editMenu->addMenu(tr("&Transforms")); transformSubMenu->addAction(rotateTransposeAct); transformSubMenu->addAction(rotateClockwiseAct); transformSubMenu->addAction(rotateCounterClockwiseAct); transformSubMenu->addAction(rotate180Act); transformSubMenu->addAction(rotateFlipXAct); transformSubMenu->addAction(rotateFlipYAct); zoomSubMenu = editMenu->addMenu(tr("&Zoom")); zoomSubMenu->addAction(zoomInAct); zoomSubMenu->addAction(zoomOutAct); zoomSubMenu->addAction(zoomNormalAct); colorMenu = menuBar()->addMenu(tr("&Color")); colorMenu->addAction(setBrushColorAct); colorMenu->addAction(setBackgroundColorAct); colorMenu->addAction(setOutlineColorAct); colorMenu->addAction(setColorPaletteAct); patternMenu = menuBar()->addMenu(tr("&Patterns")); connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(openPattern(QString))); findPatterns(patternMenu); menuBar()->addSeparator(); aboutMenu = menuBar()->addMenu(tr("About")); aboutMenu->addAction(aboutAct); } void MainWindow::findPatterns(QMenu *menu, QDir dir) { // Filter for subfolders QStringList filters; filters << "*"; dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QStringList subDirs = dir.entryList(filters); while (subDirs.length()) { QString folder = subDirs.takeFirst(); QDir newDir(dir.path()); newDir.cd(folder); // Check subfolder for ini file if (newDir.exists(folder+QString(".ini"))) { QAction *newAct = new QAction(folder, this); signalMapper->setMapping(newAct, newDir.path()); connect(newAct, SIGNAL(triggered()), signalMapper, SLOT(map())); menu->addAction(newAct); //std::cout << "Pattern Found: " << folder.toStdString() << "\n"; } // Recursively repeat else { QMenu *subMenu; subMenu = menu->addMenu(folder); findPatterns(subMenu, newDir); } } } <commit_msg>Updating about message<commit_after>#include <QtGui> #include "MainWindow.h" MainWindow::MainWindow() { QScrollArea *scrollArea = new QScrollArea; renderWidget = new Renderer; renderWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); scrollArea->setAlignment(Qt::AlignCenter); QWidget *widget = new QWidget; setCentralWidget(widget); QVBoxLayout *layout = new QVBoxLayout; layout->setMargin(5); scrollArea->setWidget(renderWidget); layout->addWidget(scrollArea); widget->setLayout(layout); signalMapper = new QSignalMapper(this); createActions(); createMenus(); this->setWindowTitle("IGP 3.0"); this->setWindowIcon(QIcon("./Resources/IGP.png")); } void MainWindow::newFile() { ResizeDialog resizeDialog(1, 1, 1, 1, 2000, 2000, QString("New Image Size")); if (resizeDialog.exec() == QDialog::Accepted) { renderWidget->newImage(resizeDialog.getWidth(),resizeDialog.getHeight()); renderWidget->resize(renderWidget->getMinSize());; } } void MainWindow::openFile() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->loadImage(fileName); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::openFileImport() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) { renderWidget->loadImage(fileName); resizeImage(); } renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::resizeImage() { QSize currentSize = renderWidget->getImageSize(); ResizeDialog resizeDialog(currentSize.width(), currentSize.height(), 1, 1, 2000, 2000); if (resizeDialog.exec() == QDialog::Accepted) { renderWidget->resizeImage(resizeDialog.getWidth(),resizeDialog.getHeight()); renderWidget->resize(renderWidget->getMinSize());; } } void MainWindow::saveFile() { QString fileName = QFileDialog::getOpenFileName(this, tr("Save Image"), "./Img/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->saveImage(fileName); } void MainWindow::setBrushColor() { QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Brush Color")); if (color.isValid()) renderWidget->setBrushColor(color); } void MainWindow::setBackgroundColor() { QColor color = QColorDialog::getColor(Qt::white, this, tr("Select Background Color")); if (color.isValid()) renderWidget->setBackgroundColor(color); } void MainWindow::setOutlineColor() { QColor color = QColorDialog::getColor(Qt::black, this, tr("Select Background Color")); if (color.isValid()) renderWidget->setOutlineColor(color); } void MainWindow::setColorPalette() { QString fileName = QFileDialog::getOpenFileName(this, tr("Open Palette"), "./Palettes/", tr("Image Files (*.png *.jpg *.bmp)")); if (!fileName.isEmpty()) renderWidget->changePalette(fileName); } void MainWindow::openPattern(QString dir) { renderWidget->setPattern(QDir(dir)); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateTranspose() { renderWidget->rotateTranspose(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateClockwise() { renderWidget->rotateClockwise(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateCounterClockwise() { renderWidget->rotateCounterClockwise(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotate180() { renderWidget->rotate180(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateFlipX() { renderWidget->rotateFlipX(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::rotateFlipY() { renderWidget->rotateFlipY(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomIn() { renderWidget->zoomIn(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomOut() { renderWidget->zoomOut(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::zoomNormal() { renderWidget->zoomNormal(); renderWidget->resize(renderWidget->getMinSize()); } void MainWindow::about() { QMessageBox::about(this, tr("About IGP 3.0"), tr("The <b>Irregular Grid Painter</b> [IGP] allows the user to paint patterned tiles. This program's first version originated within the chainmaille community at M.A.I.L. by user Zlosk using the .Net framework. The second version, written by user aganim, used javascript and HTML5. This version is written by user TrenchCoatGuy [Brian Geuther] using the QT framework.")); } void MainWindow::createActions() { // File Actions newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new image grid")); connect(newAct, SIGNAL(triggered()), this, SLOT(newFile())); openAct = new QAction(tr("&Open"), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing image")); connect(openAct, SIGNAL(triggered()), this, SLOT(openFile())); openImportAct = new QAction(tr("&Import"), this); openImportAct->setStatusTip(tr("Open an existing image and scale it")); connect(openImportAct, SIGNAL(triggered()), this, SLOT(openFileImport())); resizeImageAct = new QAction(tr("&Resize"), this); resizeImageAct->setStatusTip(tr("Resize current image")); connect(resizeImageAct, SIGNAL(triggered()), this, SLOT(resizeImage())); saveAct = new QAction(tr("&Save"), this); saveAct->setShortcuts(QKeySequence::Save); saveAct->setStatusTip(tr("Save the opened image")); connect(saveAct, SIGNAL(triggered()), this, SLOT(saveFile())); // Rotate Image Actions rotateTransposeAct = new QAction(tr("Transpose Image"), this); rotateTransposeAct->setStatusTip(tr("Transposes the source image file")); connect(rotateTransposeAct, SIGNAL(triggered()), this, SLOT(rotateTranspose())); rotateClockwiseAct = new QAction(tr("Rotate Clockwise"), this); rotateClockwiseAct->setStatusTip(tr("Rotates the source image file by 90 degrees clockwise")); connect(rotateClockwiseAct, SIGNAL(triggered()), this, SLOT(rotateClockwise())); rotateCounterClockwiseAct = new QAction(tr("Rotate Counter-Clockwise"), this); rotateCounterClockwiseAct->setStatusTip(tr("Rotates the source image file by 90 degrees counter-clockwise")); connect(rotateCounterClockwiseAct, SIGNAL(triggered()), this, SLOT(rotateCounterClockwise())); rotate180Act = new QAction(tr("Rotate 180"), this); rotate180Act->setStatusTip(tr("Rotates the source image file by 180 degrees")); connect(rotate180Act, SIGNAL(triggered()), this, SLOT(rotate180())); rotateFlipXAct = new QAction(tr("Reflect X axis"), this); rotateFlipXAct->setStatusTip(tr("Reflects the source image files X axis")); connect(rotateFlipXAct, SIGNAL(triggered()), this, SLOT(rotateFlipX())); rotateFlipYAct = new QAction(tr("Reflect Y axis"), this); rotateFlipYAct->setStatusTip(tr("Reflects the source image files Y axis")); connect(rotateFlipYAct, SIGNAL(triggered()), this, SLOT(rotateFlipY())); // Zoom Actions zoomInAct = new QAction(tr("Zoom In"), this); zoomInAct->setShortcuts(QKeySequence::ZoomIn); zoomInAct->setStatusTip(tr("Increases size of image by 10%")); connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn())); zoomOutAct = new QAction(tr("Zoom Out"), this); zoomOutAct->setShortcuts(QKeySequence::ZoomOut); zoomOutAct->setStatusTip(tr("Decreases size of image by 10%")); connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut())); zoomNormalAct = new QAction(tr("Zoom Reset"), this); zoomNormalAct->setStatusTip(tr("Resets the zoom to 100%")); connect(zoomNormalAct, SIGNAL(triggered()), this, SLOT(zoomNormal())); // Color Actions setBrushColorAct = new QAction(tr("&Brush"), this); setBrushColorAct->setStatusTip(tr("Select a new brush color")); connect(setBrushColorAct, SIGNAL(triggered()), this, SLOT(setBrushColor())); setBackgroundColorAct = new QAction(tr("Back&ground"), this); setBackgroundColorAct->setStatusTip(tr("Select a new background color")); connect(setBackgroundColorAct, SIGNAL(triggered()), this, SLOT(setBackgroundColor())); setOutlineColorAct = new QAction(tr("&Outline"), this); setOutlineColorAct->setStatusTip(tr("Select a new outline color")); connect(setOutlineColorAct, SIGNAL(triggered()), this, SLOT(setOutlineColor())); setColorPaletteAct = new QAction(tr("&Palette Change"), this); setColorPaletteAct->setStatusTip(tr("Limit colors to the current image")); connect(setColorPaletteAct, SIGNAL(triggered()), this, SLOT(setColorPalette())); // About Action aboutAct = new QAction(tr("&About"), this); aboutAct->setShortcuts(QKeySequence::HelpContents); aboutAct->setStatusTip(tr("Description of this program")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); fileMenu->addAction(openImportAct); fileMenu->addAction(resizeImageAct); fileMenu->addAction(saveAct); editMenu = menuBar()->addMenu(tr("&Edit")); transformSubMenu = editMenu->addMenu(tr("&Transforms")); transformSubMenu->addAction(rotateTransposeAct); transformSubMenu->addAction(rotateClockwiseAct); transformSubMenu->addAction(rotateCounterClockwiseAct); transformSubMenu->addAction(rotate180Act); transformSubMenu->addAction(rotateFlipXAct); transformSubMenu->addAction(rotateFlipYAct); zoomSubMenu = editMenu->addMenu(tr("&Zoom")); zoomSubMenu->addAction(zoomInAct); zoomSubMenu->addAction(zoomOutAct); zoomSubMenu->addAction(zoomNormalAct); colorMenu = menuBar()->addMenu(tr("&Color")); colorMenu->addAction(setBrushColorAct); colorMenu->addAction(setBackgroundColorAct); colorMenu->addAction(setOutlineColorAct); colorMenu->addAction(setColorPaletteAct); patternMenu = menuBar()->addMenu(tr("&Patterns")); connect(signalMapper, SIGNAL(mapped(QString)), this, SLOT(openPattern(QString))); findPatterns(patternMenu); menuBar()->addSeparator(); aboutMenu = menuBar()->addMenu(tr("About")); aboutMenu->addAction(aboutAct); } void MainWindow::findPatterns(QMenu *menu, QDir dir) { // Filter for subfolders QStringList filters; filters << "*"; dir.setFilter(QDir::Dirs | QDir::NoDotAndDotDot); QStringList subDirs = dir.entryList(filters); while (subDirs.length()) { QString folder = subDirs.takeFirst(); QDir newDir(dir.path()); newDir.cd(folder); // Check subfolder for ini file if (newDir.exists(folder+QString(".ini"))) { QAction *newAct = new QAction(folder, this); signalMapper->setMapping(newAct, newDir.path()); connect(newAct, SIGNAL(triggered()), signalMapper, SLOT(map())); menu->addAction(newAct); //std::cout << "Pattern Found: " << folder.toStdString() << "\n"; } // Recursively repeat else { QMenu *subMenu; subMenu = menu->addMenu(folder); findPatterns(subMenu, newDir); } } } <|endoftext|>
<commit_before>#include <QtGui> #include <iostream> #include "GLCamera.h" #include "MainWindow.h" #include "GLModelWidget.h" #include <QFileDialog> #include <QColorDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // Windows m_glModelWidget = new GLModelWidget; setCentralWidget(m_glModelWidget); // The docking palette m_paletteDocker = new QDockWidget(tr("Palette"), this); m_paletteDocker->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); m_paletteWidget = new PaletteWidget(this); m_paletteDocker->setWidget(m_paletteWidget); addDockWidget(Qt::RightDockWidgetArea, m_paletteDocker); // Connect some window signals together QObject::connect(m_paletteWidget, SIGNAL(activeColorChanged(Imath::Color4f)), m_glModelWidget, SLOT(setActiveColor(Imath::Color4f))); QObject::connect(m_glModelWidget, SIGNAL(colorSampled(Imath::Color4f)), m_paletteWidget, SLOT(setActiveColor(Imath::Color4f))); // Toolbar m_toolbar = new QToolBar("Tools", this); m_toolbar->setOrientation(Qt::Vertical); addToolBar(Qt::LeftToolBarArea, m_toolbar); // Actions & Menus menuBar()->show(); m_menuFile = menuBar()->addMenu("Fi&le"); m_actFileNew = new QAction("&New", this); m_actFileNew->setShortcut(Qt::CTRL + Qt::Key_N); m_menuFile->addAction(m_actFileNew); connect(m_actFileNew, SIGNAL(triggered()), this, SLOT(newGrid())); m_menuFile->addSeparator(); m_actFileOpen = new QAction("&Open", this); m_actFileOpen->setShortcut(Qt::CTRL + Qt::Key_O); m_menuFile->addAction(m_actFileOpen); connect(m_actFileOpen, SIGNAL(triggered()), this, SLOT(openFile())); m_actFileSave = new QAction("&Save", this); m_actFileSave->setShortcut(Qt::CTRL + Qt::Key_S); m_menuFile->addAction(m_actFileSave); connect(m_actFileSave, SIGNAL(triggered()), this, SLOT(saveFile())); m_menuFile->addSeparator(); m_actQuit = new QAction("&Quit", this); m_actQuit->setShortcut(Qt::CTRL + Qt::Key_Q); m_menuFile->addAction(m_actQuit); connect(m_actQuit, SIGNAL(triggered()), qApp, SLOT(quit())); // ------ edit menu m_menuEdit = menuBar()->addMenu("&Edit"); m_actUndo = new QAction("Undo", this); m_actUndo->setShortcut(Qt::CTRL + Qt::Key_Z); m_menuEdit->addAction(m_actUndo); connect(m_actUndo, SIGNAL(triggered()), m_glModelWidget, SLOT(undo())); m_actRedo = new QAction("Redo", this); m_actRedo->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Z); m_menuEdit->addAction(m_actRedo); connect(m_actRedo, SIGNAL(triggered()), m_glModelWidget, SLOT(redo())); m_menuEdit->addSeparator(); m_actShiftUp = new QAction("Shift up", this); m_actShiftUp->setShortcut(Qt::CTRL + Qt::Key_BracketRight); m_menuEdit->addAction(m_actShiftUp); connect(m_actShiftUp, SIGNAL(triggered()), this, SLOT(shiftUp())); m_actShiftDown = new QAction("Shift down", this); m_actShiftDown->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); m_menuEdit->addAction(m_actShiftDown); connect(m_actShiftDown, SIGNAL(triggered()), this, SLOT(shiftDown())); m_actShiftWrap = new QAction("Wrap shift ops", this); m_actShiftWrap->setCheckable(true); m_actShiftWrap->setChecked(m_glModelWidget->shiftWrap()); m_menuEdit->addAction(m_actShiftWrap); connect(m_actShiftWrap, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setShiftWrap(bool))); m_menuEdit->addSeparator(); m_actUpRes = new QAction("Double grid resolution", this); m_actUpRes->setShortcut(Qt::CTRL + Qt::Key_Plus); m_menuEdit->addAction(m_actUpRes); connect(m_actUpRes, SIGNAL(triggered()), this, SLOT(upRes())); m_actDownRes = new QAction("Half grid resolution", this); m_actDownRes->setShortcut(Qt::CTRL + Qt::Key_Minus); m_menuEdit->addAction(m_actDownRes); connect(m_actDownRes, SIGNAL(triggered()), this, SLOT(downRes())); // ------ view menu m_menuView = menuBar()->addMenu("&View"); m_actViewGrid = new QAction("View Grid", this); m_actViewGrid->setShortcut(Qt::CTRL + Qt::Key_G); m_actViewGrid->setCheckable(true); m_actViewGrid->setChecked(m_glModelWidget->drawGrid()); m_menuView->addAction(m_actViewGrid); connect(m_actViewGrid, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawGrid(bool))); m_actViewVoxgrid = new QAction("Voxel Grid", this); m_actViewVoxgrid->setShortcut(Qt::Key_G); m_actViewVoxgrid->setCheckable(true); m_actViewVoxgrid->setChecked(m_glModelWidget->drawVoxelGrid()); m_menuView->addAction(m_actViewVoxgrid); connect(m_actViewVoxgrid, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawVoxelGrid(bool))); m_actViewBBox = new QAction("Bounding Box", this); m_actViewBBox->setShortcut(Qt::CTRL + Qt::Key_B); m_actViewBBox->setCheckable(true); m_actViewBBox->setChecked(m_glModelWidget->drawBoundingBox()); m_menuView->addAction(m_actViewBBox); connect(m_actViewBBox, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawBoundingBox(bool))); // ------ window menu m_menuWindow = menuBar()->addMenu("&Window"); m_menuWindow->addAction(m_toolbar->toggleViewAction()); m_menuWindow->addAction(m_paletteDocker->toggleViewAction()); // ------ toolbar hookups m_toolbarActionGroup = new QActionGroup(this); m_actToolSplat = new QAction("Splat", m_toolbarActionGroup); m_actToolSplat->setIcon(QIcon(QPixmap(":/icons/splat.png"))); m_actToolSplat->setCheckable(true); connect(m_actToolSplat, SIGNAL(toggled(bool)), this, SLOT(setToolSplat(bool))); m_actToolReplace = new QAction("Replace", m_toolbarActionGroup); m_actToolReplace->setIcon(QIcon(QPixmap(":/icons/pencil.png"))); m_actToolReplace->setCheckable(true); connect(m_actToolReplace, SIGNAL(toggled(bool)), this, SLOT(setToolReplace(bool))); m_actToolFlood = new QAction("Flood", m_toolbarActionGroup); m_actToolFlood->setIcon(QIcon(QPixmap(":/icons/paintBucket.png"))); m_actToolFlood->setCheckable(true); connect(m_actToolFlood, SIGNAL(toggled(bool)), this, SLOT(setToolFlood(bool))); m_actToolDropper = new QAction("Dropper", m_toolbarActionGroup); m_actToolDropper->setIcon(QIcon(QPixmap(":/icons/eyeDropper.png"))); m_actToolDropper->setCheckable(true); connect(m_actToolDropper, SIGNAL(toggled(bool)), this, SLOT(setToolDropper(bool))); m_actToolEraser = new QAction("Eraser", m_toolbarActionGroup); m_actToolEraser->setIcon(QIcon(QPixmap(":/icons/eraser.png"))); m_actToolEraser->setCheckable(true); connect(m_actToolEraser, SIGNAL(toggled(bool)), this, SLOT(setToolEraser(bool))); m_actToolSlab = new QAction("Slab", m_toolbarActionGroup); m_actToolSlab->setIcon(QIcon(QPixmap(":/icons/slab.png"))); m_actToolSlab->setCheckable(true); connect(m_actToolSlab, SIGNAL(toggled(bool)), this, SLOT(setToolSlab(bool))); //m_actToolRay = new QAction("Ray", this); m_actToolSplat->setChecked(true); m_toolbar->addActions(m_toolbarActionGroup->actions()); // Remaining verbosity setWindowTitle(tr("Sproxel " SPROXEL_VERSION)); statusBar()->showMessage(tr("Ready")); } void MainWindow::keyPressEvent(QKeyEvent* event) { const bool altDown = event->modifiers() & Qt::AltModifier; const bool ctrlDown = event->modifiers() & Qt::ControlModifier; //const bool shiftDown = event->modifiers() & Qt::ShiftModifier; if (altDown && event->key() == Qt::Key_X) { m_glModelWidget->setCurrentAxis(GLModelWidget::X_AXIS); } else if (altDown && event->key() == Qt::Key_Y) { m_glModelWidget->setCurrentAxis(GLModelWidget::Y_AXIS); } else if (altDown && event->key() == Qt::Key_Z) { m_glModelWidget->setCurrentAxis(GLModelWidget::Z_AXIS); } else if (ctrlDown && event->key() == Qt::Key_C) { QColor color = QColorDialog::getColor(Qt::white, this); m_paletteWidget->setActiveColor(Imath::Color4f((float)color.red()/255.0f, (float)color.green()/255.0f, (float)color.blue()/255.0f, (float)color.alpha()/255.0f)); } else if (ctrlDown && event->key() == Qt::Key_F) { // Frame the full extents no matter what m_glModelWidget->frame(true); } else if (event->key() == Qt::Key_F) { // Frame the data if it exists m_glModelWidget->frame(false); } else if (event->key() == Qt::Key_X) { m_paletteWidget->swapColors(); } //else if (event->key() == Qt::Key_D) //{ // m_paletteWidget->setDefaultColors(); //} else if (event->key() == Qt::Key_Q) m_actToolSplat->setChecked(true); else if (event->key() == Qt::Key_W) m_actToolReplace->setChecked(true); else if (event->key() == Qt::Key_E) m_actToolFlood->setChecked(true); else if (event->key() == Qt::Key_R) m_actToolDropper->setChecked(true); else if (event->key() == Qt::Key_T) m_actToolEraser->setChecked(true); else if (event->key() == Qt::Key_Y) m_actToolSlab->setChecked(true); else if (event->key() >= Qt::Key_Left && event->key() <= Qt::Key_PageDown) { m_glModelWidget->handleArrows(event); } else if (event->key() == Qt::Key_Space) { // It's okay to call setVoxelColor once on the model widget, but any more requires an internal wrapper m_glModelWidget->setVoxelColor(m_glModelWidget->activeVoxel(), m_glModelWidget->activeColor()); m_glModelWidget->updateGL(); } else if (event->key() == Qt::Key_Delete) { // It's okay to call setVoxelColor once on the model widget, but any more requires an internal wrapper m_glModelWidget->setVoxelColor(m_glModelWidget->activeVoxel(), Imath::Color4f(0.0f, 0.0f, 0.0f, 0.0f)); m_glModelWidget->updateGL(); } } void MainWindow::newGrid() { NewGridDialog dlg(this); dlg.setModal(true); if (dlg.exec()) { m_glModelWidget->resizeVoxelGrid(dlg.getVoxelSize()); } } void MainWindow::saveFile() { QString filename = QFileDialog::getSaveFileName(this, tr("Save voxels (CSV format) file as..."), QString(""), tr("CSV Files (*.csv)")); if (!filename.isEmpty()) { m_glModelWidget->saveGridCSV(filename.toStdString()); } } void MainWindow::openFile() { QString filename = QFileDialog::getOpenFileName(this, tr("Select CSV file to Open..."), QString(), tr("CSV Files (*.csv)")); if (!filename.isEmpty()) { m_glModelWidget->loadGridCSV(filename.toStdString()); } } // Trampoline functions because QSignalMapper can't do complex args // Search for QBoundMethod for a custom approach, but I'm too lazy to include it for now. void MainWindow::shiftUp() { m_glModelWidget->shiftVoxels(m_glModelWidget->currentAxis(), true, m_glModelWidget->shiftWrap()); } void MainWindow::shiftDown() { m_glModelWidget->shiftVoxels(m_glModelWidget->currentAxis(), false, m_glModelWidget->shiftWrap()); } void MainWindow::upRes() { m_glModelWidget->reresVoxelGrid(2.0f); } void MainWindow::downRes() { m_glModelWidget->reresVoxelGrid(0.5f); } void MainWindow::setToolSplat(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_SPLAT); } void MainWindow::setToolFlood(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_FLOOD); } void MainWindow::setToolRay(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_RAY); } void MainWindow::setToolDropper(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_DROPPER); } void MainWindow::setToolEraser(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_ERASER); } void MainWindow::setToolReplace(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_REPLACE); } void MainWindow::setToolSlab(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_SLAB); } // // Steal keypresses from your children! // bool MainWindow::eventFilter(QObject* qo, QEvent* ev) // { // if (ev->type() != QEvent::KeyPress) return false; // keyPressEvent(dynamic_cast<QKeyEvent*>(ev)); // return true; // } <commit_msg>References where the icons came from.<commit_after>#include <QtGui> #include <iostream> #include "GLCamera.h" #include "MainWindow.h" #include "GLModelWidget.h" #include <QFileDialog> #include <QColorDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { // Windows m_glModelWidget = new GLModelWidget; setCentralWidget(m_glModelWidget); // The docking palette m_paletteDocker = new QDockWidget(tr("Palette"), this); m_paletteDocker->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea); m_paletteWidget = new PaletteWidget(this); m_paletteDocker->setWidget(m_paletteWidget); addDockWidget(Qt::RightDockWidgetArea, m_paletteDocker); // Connect some window signals together QObject::connect(m_paletteWidget, SIGNAL(activeColorChanged(Imath::Color4f)), m_glModelWidget, SLOT(setActiveColor(Imath::Color4f))); QObject::connect(m_glModelWidget, SIGNAL(colorSampled(Imath::Color4f)), m_paletteWidget, SLOT(setActiveColor(Imath::Color4f))); // Toolbar m_toolbar = new QToolBar("Tools", this); m_toolbar->setOrientation(Qt::Vertical); addToolBar(Qt::LeftToolBarArea, m_toolbar); // Actions & Menus menuBar()->show(); m_menuFile = menuBar()->addMenu("Fi&le"); m_actFileNew = new QAction("&New", this); m_actFileNew->setShortcut(Qt::CTRL + Qt::Key_N); m_menuFile->addAction(m_actFileNew); connect(m_actFileNew, SIGNAL(triggered()), this, SLOT(newGrid())); m_menuFile->addSeparator(); m_actFileOpen = new QAction("&Open", this); m_actFileOpen->setShortcut(Qt::CTRL + Qt::Key_O); m_menuFile->addAction(m_actFileOpen); connect(m_actFileOpen, SIGNAL(triggered()), this, SLOT(openFile())); m_actFileSave = new QAction("&Save", this); m_actFileSave->setShortcut(Qt::CTRL + Qt::Key_S); m_menuFile->addAction(m_actFileSave); connect(m_actFileSave, SIGNAL(triggered()), this, SLOT(saveFile())); m_menuFile->addSeparator(); m_actQuit = new QAction("&Quit", this); m_actQuit->setShortcut(Qt::CTRL + Qt::Key_Q); m_menuFile->addAction(m_actQuit); connect(m_actQuit, SIGNAL(triggered()), qApp, SLOT(quit())); // ------ edit menu m_menuEdit = menuBar()->addMenu("&Edit"); m_actUndo = new QAction("Undo", this); m_actUndo->setShortcut(Qt::CTRL + Qt::Key_Z); m_menuEdit->addAction(m_actUndo); connect(m_actUndo, SIGNAL(triggered()), m_glModelWidget, SLOT(undo())); m_actRedo = new QAction("Redo", this); m_actRedo->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Z); m_menuEdit->addAction(m_actRedo); connect(m_actRedo, SIGNAL(triggered()), m_glModelWidget, SLOT(redo())); m_menuEdit->addSeparator(); m_actShiftUp = new QAction("Shift up", this); m_actShiftUp->setShortcut(Qt::CTRL + Qt::Key_BracketRight); m_menuEdit->addAction(m_actShiftUp); connect(m_actShiftUp, SIGNAL(triggered()), this, SLOT(shiftUp())); m_actShiftDown = new QAction("Shift down", this); m_actShiftDown->setShortcut(Qt::CTRL + Qt::Key_BracketLeft); m_menuEdit->addAction(m_actShiftDown); connect(m_actShiftDown, SIGNAL(triggered()), this, SLOT(shiftDown())); m_actShiftWrap = new QAction("Wrap shift ops", this); m_actShiftWrap->setCheckable(true); m_actShiftWrap->setChecked(m_glModelWidget->shiftWrap()); m_menuEdit->addAction(m_actShiftWrap); connect(m_actShiftWrap, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setShiftWrap(bool))); m_menuEdit->addSeparator(); m_actUpRes = new QAction("Double grid resolution", this); m_actUpRes->setShortcut(Qt::CTRL + Qt::Key_Plus); m_menuEdit->addAction(m_actUpRes); connect(m_actUpRes, SIGNAL(triggered()), this, SLOT(upRes())); m_actDownRes = new QAction("Half grid resolution", this); m_actDownRes->setShortcut(Qt::CTRL + Qt::Key_Minus); m_menuEdit->addAction(m_actDownRes); connect(m_actDownRes, SIGNAL(triggered()), this, SLOT(downRes())); // ------ view menu m_menuView = menuBar()->addMenu("&View"); m_actViewGrid = new QAction("View Grid", this); m_actViewGrid->setShortcut(Qt::CTRL + Qt::Key_G); m_actViewGrid->setCheckable(true); m_actViewGrid->setChecked(m_glModelWidget->drawGrid()); m_menuView->addAction(m_actViewGrid); connect(m_actViewGrid, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawGrid(bool))); m_actViewVoxgrid = new QAction("Voxel Grid", this); m_actViewVoxgrid->setShortcut(Qt::Key_G); m_actViewVoxgrid->setCheckable(true); m_actViewVoxgrid->setChecked(m_glModelWidget->drawVoxelGrid()); m_menuView->addAction(m_actViewVoxgrid); connect(m_actViewVoxgrid, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawVoxelGrid(bool))); m_actViewBBox = new QAction("Bounding Box", this); m_actViewBBox->setShortcut(Qt::CTRL + Qt::Key_B); m_actViewBBox->setCheckable(true); m_actViewBBox->setChecked(m_glModelWidget->drawBoundingBox()); m_menuView->addAction(m_actViewBBox); connect(m_actViewBBox, SIGNAL(toggled(bool)), m_glModelWidget, SLOT(setDrawBoundingBox(bool))); // ------ window menu m_menuWindow = menuBar()->addMenu("&Window"); m_menuWindow->addAction(m_toolbar->toggleViewAction()); m_menuWindow->addAction(m_paletteDocker->toggleViewAction()); // ------ toolbar hookups // Icons from the brilliant icon pack located at : http://pen-art.ru/ m_toolbarActionGroup = new QActionGroup(this); m_actToolSplat = new QAction("Splat", m_toolbarActionGroup); m_actToolSplat->setIcon(QIcon(QPixmap(":/icons/splat.png"))); m_actToolSplat->setCheckable(true); connect(m_actToolSplat, SIGNAL(toggled(bool)), this, SLOT(setToolSplat(bool))); m_actToolReplace = new QAction("Replace", m_toolbarActionGroup); m_actToolReplace->setIcon(QIcon(QPixmap(":/icons/pencil.png"))); m_actToolReplace->setCheckable(true); connect(m_actToolReplace, SIGNAL(toggled(bool)), this, SLOT(setToolReplace(bool))); m_actToolFlood = new QAction("Flood", m_toolbarActionGroup); m_actToolFlood->setIcon(QIcon(QPixmap(":/icons/paintBucket.png"))); m_actToolFlood->setCheckable(true); connect(m_actToolFlood, SIGNAL(toggled(bool)), this, SLOT(setToolFlood(bool))); m_actToolDropper = new QAction("Dropper", m_toolbarActionGroup); m_actToolDropper->setIcon(QIcon(QPixmap(":/icons/eyeDropper.png"))); m_actToolDropper->setCheckable(true); connect(m_actToolDropper, SIGNAL(toggled(bool)), this, SLOT(setToolDropper(bool))); m_actToolEraser = new QAction("Eraser", m_toolbarActionGroup); m_actToolEraser->setIcon(QIcon(QPixmap(":/icons/eraser.png"))); m_actToolEraser->setCheckable(true); connect(m_actToolEraser, SIGNAL(toggled(bool)), this, SLOT(setToolEraser(bool))); m_actToolSlab = new QAction("Slab", m_toolbarActionGroup); m_actToolSlab->setIcon(QIcon(QPixmap(":/icons/slab.png"))); m_actToolSlab->setCheckable(true); connect(m_actToolSlab, SIGNAL(toggled(bool)), this, SLOT(setToolSlab(bool))); //m_actToolRay = new QAction("Ray", this); m_actToolSplat->setChecked(true); m_toolbar->addActions(m_toolbarActionGroup->actions()); // Remaining verbosity setWindowTitle(tr("Sproxel " SPROXEL_VERSION)); statusBar()->showMessage(tr("Ready")); } void MainWindow::keyPressEvent(QKeyEvent* event) { const bool altDown = event->modifiers() & Qt::AltModifier; const bool ctrlDown = event->modifiers() & Qt::ControlModifier; //const bool shiftDown = event->modifiers() & Qt::ShiftModifier; if (altDown && event->key() == Qt::Key_X) { m_glModelWidget->setCurrentAxis(GLModelWidget::X_AXIS); } else if (altDown && event->key() == Qt::Key_Y) { m_glModelWidget->setCurrentAxis(GLModelWidget::Y_AXIS); } else if (altDown && event->key() == Qt::Key_Z) { m_glModelWidget->setCurrentAxis(GLModelWidget::Z_AXIS); } else if (ctrlDown && event->key() == Qt::Key_C) { QColor color = QColorDialog::getColor(Qt::white, this); m_paletteWidget->setActiveColor(Imath::Color4f((float)color.red()/255.0f, (float)color.green()/255.0f, (float)color.blue()/255.0f, (float)color.alpha()/255.0f)); } else if (ctrlDown && event->key() == Qt::Key_F) { // Frame the full extents no matter what m_glModelWidget->frame(true); } else if (event->key() == Qt::Key_F) { // Frame the data if it exists m_glModelWidget->frame(false); } else if (event->key() == Qt::Key_X) { m_paletteWidget->swapColors(); } //else if (event->key() == Qt::Key_D) //{ // m_paletteWidget->setDefaultColors(); //} else if (event->key() == Qt::Key_Q) m_actToolSplat->setChecked(true); else if (event->key() == Qt::Key_W) m_actToolReplace->setChecked(true); else if (event->key() == Qt::Key_E) m_actToolFlood->setChecked(true); else if (event->key() == Qt::Key_R) m_actToolDropper->setChecked(true); else if (event->key() == Qt::Key_T) m_actToolEraser->setChecked(true); else if (event->key() == Qt::Key_Y) m_actToolSlab->setChecked(true); else if (event->key() >= Qt::Key_Left && event->key() <= Qt::Key_PageDown) { m_glModelWidget->handleArrows(event); } else if (event->key() == Qt::Key_Space) { // It's okay to call setVoxelColor once on the model widget, but any more requires an internal wrapper m_glModelWidget->setVoxelColor(m_glModelWidget->activeVoxel(), m_glModelWidget->activeColor()); m_glModelWidget->updateGL(); } else if (event->key() == Qt::Key_Delete) { // It's okay to call setVoxelColor once on the model widget, but any more requires an internal wrapper m_glModelWidget->setVoxelColor(m_glModelWidget->activeVoxel(), Imath::Color4f(0.0f, 0.0f, 0.0f, 0.0f)); m_glModelWidget->updateGL(); } } void MainWindow::newGrid() { NewGridDialog dlg(this); dlg.setModal(true); if (dlg.exec()) { m_glModelWidget->resizeVoxelGrid(dlg.getVoxelSize()); } } void MainWindow::saveFile() { QString filename = QFileDialog::getSaveFileName(this, tr("Save voxels (CSV format) file as..."), QString(""), tr("CSV Files (*.csv)")); if (!filename.isEmpty()) { m_glModelWidget->saveGridCSV(filename.toStdString()); } } void MainWindow::openFile() { QString filename = QFileDialog::getOpenFileName(this, tr("Select CSV file to Open..."), QString(), tr("CSV Files (*.csv)")); if (!filename.isEmpty()) { m_glModelWidget->loadGridCSV(filename.toStdString()); } } // Trampoline functions because QSignalMapper can't do complex args // Search for QBoundMethod for a custom approach, but I'm too lazy to include it for now. void MainWindow::shiftUp() { m_glModelWidget->shiftVoxels(m_glModelWidget->currentAxis(), true, m_glModelWidget->shiftWrap()); } void MainWindow::shiftDown() { m_glModelWidget->shiftVoxels(m_glModelWidget->currentAxis(), false, m_glModelWidget->shiftWrap()); } void MainWindow::upRes() { m_glModelWidget->reresVoxelGrid(2.0f); } void MainWindow::downRes() { m_glModelWidget->reresVoxelGrid(0.5f); } void MainWindow::setToolSplat(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_SPLAT); } void MainWindow::setToolFlood(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_FLOOD); } void MainWindow::setToolRay(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_RAY); } void MainWindow::setToolDropper(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_DROPPER); } void MainWindow::setToolEraser(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_ERASER); } void MainWindow::setToolReplace(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_REPLACE); } void MainWindow::setToolSlab(bool stat) { if (stat) m_glModelWidget->setActiveTool(GLModelWidget::TOOL_SLAB); } // // Steal keypresses from your children! // bool MainWindow::eventFilter(QObject* qo, QEvent* ev) // { // if (ev->type() != QEvent::KeyPress) return false; // keyPressEvent(dynamic_cast<QKeyEvent*>(ev)); // return true; // } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions 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. ** ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QMainWindow> #include <QDeclarativeView> #include <QDeclarativeContext> #include "buzzer.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow mw; QDeclarativeView *view = new QDeclarativeView(&mw); view->setResizeMode(QDeclarativeView::SizeRootObjectToView); view->rootContext()->setContextProperty("hapticplayer", new Buzzer); view->setSource(QUrl::fromLocalFile(":/hapticsquare.qml")); mw.setCentralWidget(view); mw.showMaximized(); return app.exec(); } <commit_msg>fix hapticsquare qml resource loading bug.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Solutions 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. ** ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** Please note Third Party Software included with Qt Solutions may impose ** additional restrictions and it is the user's responsibility to ensure ** that they have met the licensing requirements of the GPL, LGPL, or Qt ** Solutions Commercial license and the relevant license of the Third ** Party Software they are using. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QApplication> #include <QMainWindow> #include <QDeclarativeView> #include <QDeclarativeContext> #include "buzzer.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); QMainWindow mw; QDeclarativeView *view = new QDeclarativeView(&mw); view->setResizeMode(QDeclarativeView::SizeRootObjectToView); view->rootContext()->setContextProperty("hapticplayer", new Buzzer); view->setSource(QUrl("qrc:hapticsquare.qml")); mw.setCentralWidget(view); mw.showMaximized(); return app.exec(); } <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "curlfetch.h" #include <string> #include <curl/curl.h> using std::string; // CURLOPT_WRITEFUNCTION: // size*nmemb bytes of data are at ptr, stream is user data // return must be size*nmemb or curl itself will fail. static size_t FetchToString(void* ptr, size_t size, size_t nmemb, void* user) { // static function, only user is DoCurlToString which uses CURLOPT_WRITEDATA // to set the "user" arg which is the C++ string (buffer) to write to. assert(user); size_t nbytes = size * nmemb; string *output_buffer = reinterpret_cast<string*>(user); output_buffer->append(reinterpret_cast<char*>(ptr), nbytes); return nbytes; } // Separate worker function to simplify bool return logic. static bool DoCurlToString(CURL* curl, const char* url, string* data) { CURLcode result; #define CURLOK(f) (f == CURLE_OK) if (CURLOK(curl_easy_setopt(curl, CURLOPT_URL, url)) && CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchToString)) && CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(data))) && CURLOK(curl_easy_perform(curl))) { return true; } return false; } // Wrapper to manage curl handle. Very simple stateless implementation. Less // simplistic would be to reuse the CURL* handle between invocations. bool CurlToString(const char* url, string* data) { CURL* curl = curl_easy_init(); bool ret = DoCurlToString(curl, url, data); curl_easy_cleanup(curl); return ret; } <commit_msg>Remove the assert() from curlfetch.cc<commit_after>// Copyright 2008, Google Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 3. Neither the name of Google Inc. nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO // EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "curlfetch.h" #include <string> #include <curl/curl.h> using std::string; // CURLOPT_WRITEFUNCTION: // size*nmemb bytes of data are at ptr, stream is user data // return must be size*nmemb or curl itself will fail. static size_t FetchToString(void* ptr, size_t size, size_t nmemb, void* user) { // static function, only user is DoCurlToString which uses CURLOPT_WRITEDATA // to set the "user" arg which is the C++ string (buffer) to write to. size_t nbytes = size * nmemb; string *output_buffer = reinterpret_cast<string*>(user); output_buffer->append(reinterpret_cast<char*>(ptr), nbytes); return nbytes; } // Separate worker function to simplify bool return logic. static bool DoCurlToString(CURL* curl, const char* url, string* data) { CURLcode result; #define CURLOK(f) (f == CURLE_OK) if (CURLOK(curl_easy_setopt(curl, CURLOPT_URL, url)) && CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, FetchToString)) && CURLOK(curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(data))) && CURLOK(curl_easy_perform(curl))) { return true; } return false; } // Wrapper to manage curl handle. Very simple stateless implementation. Less // simplistic would be to reuse the CURL* handle between invocations. bool CurlToString(const char* url, string* data) { CURL* curl = curl_easy_init(); bool ret = DoCurlToString(curl, url, data); curl_easy_cleanup(curl); return ret; } <|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 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "OpenRouteServiceRunner.h" #include "MarbleDebug.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "TinyWebBrowser.h" #include "GeoDataData.h" #include "GeoDataExtendedData.h" #include "routing/RouteRequest.h" #include <QString> #include <QVector> #include <QUrl> #include <QTime> #include <QTimer> #include <QNetworkReply> #include <QDomDocument> namespace Marble { OpenRouteServiceRunner::OpenRouteServiceRunner( QObject *parent ) : RoutingRunner( parent ), m_networkAccessManager() { connect( &m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(retrieveData(QNetworkReply*))); } OpenRouteServiceRunner::~OpenRouteServiceRunner() { // nothing to do } void OpenRouteServiceRunner::retrieveRoute( const RouteRequest *route ) { if ( route->size() < 2 ) { return; } GeoDataCoordinates source = route->source(); GeoDataCoordinates destination = route->destination(); QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["openrouteservice"]; QString request = xmlHeader(); QString unit = "KM"; QString preference = "Fastest"; if ( settings.contains( "preference" ) ) { preference = settings["preference"].toString(); } if ( preference == "Pedestrian" ) { unit = 'M'; } request += requestHeader( unit, preference ); request += requestPoint( StartPoint, source ); if ( route->size() > 2 ) { for ( int i = 1; i < route->size() - 1; ++i ) { request += requestPoint( ViaPoint, route->at( i ) ); } } request += requestPoint( EndPoint, destination ); request += requestFooter( settings ); request += xmlFooter(); //mDebug() << "POST: " << request; // Please refrain from making this URI public. To use it outside the scope // of marble you need permission from the openrouteservice.org team. QUrl url = QUrl( "http://openls.geog.uni-heidelberg.de/osm/eu/routing" ); m_request = QNetworkRequest( url ); m_request.setHeader( QNetworkRequest::ContentTypeHeader, "application/xml" ); m_requestData = request.toLatin1(); QEventLoop eventLoop; QTimer timer; timer.setSingleShot( true ); timer.setInterval( 15000 ); connect( &timer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); connect( this, SIGNAL(routeCalculated(GeoDataDocument*)), &eventLoop, SLOT(quit())); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT(get())); timer.start(); eventLoop.exec(); } void OpenRouteServiceRunner::get() { QNetworkReply *reply = m_networkAccessManager.post( m_request, m_requestData ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)), Qt::DirectConnection); } void OpenRouteServiceRunner::retrieveData( QNetworkReply *reply ) { if ( reply->isFinished() ) { QByteArray data = reply->readAll(); reply->deleteLater(); //mDebug() << "Download completed: " << data; GeoDataDocument* document = parse( data ); if ( !document ) { mDebug() << "Failed to parse the downloaded route data" << data; } emit routeCalculated( document ); } } void OpenRouteServiceRunner::handleError( QNetworkReply::NetworkError error ) { mDebug() << " Error when retrieving openrouteservice.org route: " << error; } QString OpenRouteServiceRunner::xmlHeader() { QString result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; result += "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" "; result += "xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" "; result += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; result += "xsi:schemaLocation=\"http://www.opengis.net/xls "; result += "http://schemas.opengis.net/ols/1.1.0/RouteService.xsd\" version=\"1.1\" xls:lang=\"en\">\n"; result += "<xls:RequestHeader/>\n"; return result; } QString OpenRouteServiceRunner::requestHeader( const QString &unit, const QString &routePreference ) { QString result = "<xls:Request methodName=\"RouteRequest\" requestID=\"123456789\" version=\"1.1\">\n"; result += "<xls:DetermineRouteRequest distanceUnit=\"%1\">\n"; result += "<xls:RoutePlan>\n"; result += "<xls:RoutePreference>%2</xls:RoutePreference>\n"; result += "<xls:WayPointList>\n"; return result.arg( unit ).arg( routePreference ); } QString OpenRouteServiceRunner::requestPoint( PointType pointType, const GeoDataCoordinates &coordinates ) { QString result = "<xls:%1>\n"; result += "<xls:Position>\n"; result += "<gml:Point srsName=\"EPSG:4326\">\n"; result += "<gml:pos>%2 %3</gml:pos>\n"; result += "</gml:Point>\n"; result += "</xls:Position>\n"; result += "</xls:%1>\n"; result = result.arg( pointType == StartPoint ? "StartPoint" : ( pointType == ViaPoint ? "ViaPoint" : "EndPoint" ) ); result = result.arg( coordinates.longitude( GeoDataCoordinates::Degree ), 0, 'f', 14 ); result = result.arg( coordinates.latitude( GeoDataCoordinates::Degree ), 0, 'f', 14 ); return result; } QString OpenRouteServiceRunner::requestFooter( const QHash<QString, QVariant>& settings ) { QString result = "</xls:WayPointList>\n"; if (settings["noMotorways"].toInt() || settings["noTollways"].toInt() ) { result += "<xls:AvoidList>\n"; if ( settings["noTollways"].toInt() ) { result += "<xls:AvoidFeature>Tollway</xls:AvoidFeature>"; } if ( settings["noMotorways"].toInt() ) { result += "<xls:AvoidFeature>Highway</xls:AvoidFeature>"; } result += "</xls:AvoidList>\n"; } result += "</xls:RoutePlan>\n"; result += "<xls:RouteInstructionsRequest provideGeometry=\"true\" />\n"; result += "<xls:RouteGeometryRequest/>\n"; result += "</xls:DetermineRouteRequest>\n"; result += "</xls:Request>\n"; return result; } QString OpenRouteServiceRunner::xmlFooter() { return "</xls:XLS>\n"; } GeoDataDocument* OpenRouteServiceRunner::parse( const QByteArray &content ) const { QDomDocument xml; if ( !xml.setContent( content ) ) { mDebug() << "Cannot parse xml file with routing instructions."; return 0; } QDomElement root = xml.documentElement(); GeoDataDocument* result = new GeoDataDocument(); result->setName( "OpenRouteService" ); QDomNodeList errors = root.elementsByTagName( "xls:Error" ); if ( errors.size() > 0 ) { return 0; // Returning early because fallback routing providers are used now // The code below can be used to parse OpenGis errors reported by ORS // and may be useful in the future #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < errors.length(); ++i ) { QDomNode node = errors.item( i ); QString errorMessage = node.attributes().namedItem( "message" ).nodeValue(); QRegExp regexp = QRegExp( "^(.*) Please Check your Position: (-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+) !" ); if ( regexp.indexIn( errorMessage ) == 0 ) { if ( regexp.capturedTexts().size() == 4 ) { GeoDataPlacemark* placemark = new GeoDataPlacemark; placemark->setName( regexp.capturedTexts().at( 1 ) ); GeoDataCoordinates position; position.setLongitude( regexp.capturedTexts().at( 2 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( regexp.capturedTexts().at( 3 ).toDouble(), GeoDataCoordinates::Degree ); placemark->setCoordinate( position ); result->append( placemark ); } } else { mDebug() << "Error message " << errorMessage << " not parsable."; /** @todo: How to handle this now with plugins? */ // QString message = tr( "Sorry, a problem occurred when calculating the route. Try adjusting start and destination points." ); // QPointer<QMessageBox> messageBox = new QMessageBox( QMessageBox::Warning, "Route Error", message ); // messageBox->setDetailedText( errorMessage ); // messageBox->exec(); // delete messageBox; } } } GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); QTime time; QDomNodeList summary = root.elementsByTagName( "xls:RouteSummary" ); if ( summary.size() > 0 ) { QDomNodeList timeNodeList = summary.item( 0 ).toElement().elementsByTagName( "xls:TotalTime" ); if ( timeNodeList.size() == 1 ) { QRegExp regexp = QRegExp( "^P(?:(\\d+)D)?T(?:(\\d+)H)?(?:(\\d+)M)?(\\d+)S" ); if ( regexp.indexIn( timeNodeList.item( 0 ).toElement().text() ) == 0 ) { QStringList matches = regexp.capturedTexts(); unsigned int hours( 0 ), minutes( 0 ), seconds( 0 ); switch ( matches.size() ) { case 5: // days = regexp.cap( matches.size() - 4 ).toInt(); // Intentionally no break case 4: hours = regexp.cap( matches.size() - 3 ).toInt(); // Intentionally no break case 3: minutes = regexp.cap( matches.size() - 2 ).toInt(); // Intentionally no break case 2: seconds = regexp.cap( matches.size() - 1 ).toInt(); break; default: mDebug() << "Unable to parse time string " << timeNodeList.item( 0 ).toElement().text(); } time = QTime( hours, minutes, seconds, 0 ); } } } GeoDataLineString* routeWaypoints = new GeoDataLineString; QDomNodeList geometry = root.elementsByTagName( "xls:RouteGeometry" ); if ( geometry.size() > 0 ) { QDomNodeList waypoints = geometry.item( 0 ).toElement().elementsByTagName( "gml:pos" ); #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < waypoints.length(); ++i ) { QDomNode node = waypoints.item( i ); QStringList content = node.toElement().text().split( ' ' ); if ( content.length() == 2 ) { GeoDataCoordinates position; position.setLongitude( content.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( content.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); routeWaypoints->append( position ); } } } routePlacemark->setGeometry( routeWaypoints ); qreal length = routeWaypoints->length( EARTH_RADIUS ); const QString name = nameString( "ORS", length, time ); const GeoDataExtendedData data = routeData( length, time ); routePlacemark->setExtendedData( data ); result->setName( name ); result->append( routePlacemark ); QDomNodeList instructionList = root.elementsByTagName( "xls:RouteInstructionsList" ); if ( instructionList.size() > 0 ) { QDomNodeList instructions = instructionList.item( 0 ).toElement().elementsByTagName( "xls:RouteInstruction" ); #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < instructions.length(); ++i ) { QDomElement node = instructions.item( i ).toElement(); QDomNodeList textNodes = node.elementsByTagName( "xls:Instruction" ); QDomNodeList positions = node.elementsByTagName( "gml:pos" ); if ( textNodes.size() > 0 && positions.size() > 0 ) { QStringList content = positions.at( 0 ).toElement().text().split( ' ' ); if ( content.length() == 2 ) { GeoDataLineString *lineString = new GeoDataLineString; for( int i = 0; i < positions.count(); ++i ) { QStringList pointList = positions.at( i ).toElement().text().split( ' ' ); GeoDataCoordinates position; position.setLongitude( pointList.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( pointList.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); lineString->append( position ); } GeoDataPlacemark* instruction = new GeoDataPlacemark; QString const text = textNodes.item( 0 ).toElement().text(); GeoDataExtendedData extendedData; GeoDataData turnTypeData; turnTypeData.setName( "turnType" ); QString road; RoutingInstruction::TurnType turnType = parseTurnType( text, &road ); turnTypeData.setValue( turnType ); extendedData.addValue( turnTypeData ); if ( !road.isEmpty() ) { GeoDataData roadName; roadName.setName( "roadName" ); roadName.setValue( road ); extendedData.addValue( roadName ); } QString const instructionText = turnType == RoutingInstruction::Unknown ? text : RoutingInstruction::generateRoadInstruction( turnType, road ); instruction->setName( instructionText ); instruction->setExtendedData( extendedData ); instruction->setGeometry( lineString ); result->append( instruction ); } } } } return result; } RoutingInstruction::TurnType OpenRouteServiceRunner::parseTurnType( const QString &text, QString *road ) { QRegExp syntax( "^(Go|Drive) (half left|left|sharp left|straight forward|half right|right|sharp right)( on )?(.*)?$", Qt::CaseSensitive, QRegExp::RegExp2 ); QString instruction; if ( syntax.indexIn( text ) == 0 ) { if ( syntax.captureCount() > 1 ) { instruction = syntax.cap( 2 ); if ( syntax.captureCount() == 4 ) { *road = syntax.cap( 4 ).remove(QLatin1String( " - Arrived at destination!")); } } } if ( instruction == "Continue" ) { return RoutingInstruction::Straight; } else if ( instruction == "half right" ) { return RoutingInstruction::SlightRight; } else if ( instruction == "right" ) { return RoutingInstruction::Right; } else if ( instruction == "sharp right" ) { return RoutingInstruction::SharpRight; } else if ( instruction == "straight forward" ) { return RoutingInstruction::Straight; } else if ( instruction == "turn" ) { return RoutingInstruction::TurnAround; } else if ( instruction == "sharp left" ) { return RoutingInstruction::SharpLeft; } else if ( instruction == "left" ) { return RoutingInstruction::Left; } else if ( instruction == "half left" ) { return RoutingInstruction::SlightLeft; } return RoutingInstruction::Unknown; } } // namespace Marble #include "OpenRouteServiceRunner.moc" <commit_msg>openrouteservice.org has changed their API URL, follow up.<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 2010 Dennis Nienhüser <earthwings@gentoo.org> // #include "OpenRouteServiceRunner.h" #include "MarbleDebug.h" #include "GeoDataDocument.h" #include "GeoDataPlacemark.h" #include "TinyWebBrowser.h" #include "GeoDataData.h" #include "GeoDataExtendedData.h" #include "routing/RouteRequest.h" #include <QString> #include <QVector> #include <QUrl> #include <QTime> #include <QTimer> #include <QNetworkReply> #include <QDomDocument> namespace Marble { OpenRouteServiceRunner::OpenRouteServiceRunner( QObject *parent ) : RoutingRunner( parent ), m_networkAccessManager() { connect( &m_networkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(retrieveData(QNetworkReply*))); } OpenRouteServiceRunner::~OpenRouteServiceRunner() { // nothing to do } void OpenRouteServiceRunner::retrieveRoute( const RouteRequest *route ) { if ( route->size() < 2 ) { return; } GeoDataCoordinates source = route->source(); GeoDataCoordinates destination = route->destination(); QHash<QString, QVariant> settings = route->routingProfile().pluginSettings()["openrouteservice"]; QString request = xmlHeader(); QString unit = "KM"; QString preference = "Fastest"; if ( settings.contains( "preference" ) ) { preference = settings["preference"].toString(); } if ( preference == "Pedestrian" ) { unit = 'M'; } request += requestHeader( unit, preference ); request += requestPoint( StartPoint, source ); if ( route->size() > 2 ) { for ( int i = 1; i < route->size() - 1; ++i ) { request += requestPoint( ViaPoint, route->at( i ) ); } } request += requestPoint( EndPoint, destination ); request += requestFooter( settings ); request += xmlFooter(); //mDebug() << "POST: " << request; // Please refrain from making this URI public. To use it outside the scope // of marble you need permission from the openrouteservice.org team. QUrl url = QUrl( "http://openls.geog.uni-heidelberg.de/osm/routing" ); m_request = QNetworkRequest( url ); m_request.setHeader( QNetworkRequest::ContentTypeHeader, "application/xml" ); m_requestData = request.toLatin1(); QEventLoop eventLoop; QTimer timer; timer.setSingleShot( true ); timer.setInterval( 15000 ); connect( &timer, SIGNAL(timeout()), &eventLoop, SLOT(quit())); connect( this, SIGNAL(routeCalculated(GeoDataDocument*)), &eventLoop, SLOT(quit())); // @todo FIXME Must currently be done in the main thread, see bug 257376 QTimer::singleShot( 0, this, SLOT(get())); timer.start(); eventLoop.exec(); } void OpenRouteServiceRunner::get() { QNetworkReply *reply = m_networkAccessManager.post( m_request, m_requestData ); connect( reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(handleError(QNetworkReply::NetworkError)), Qt::DirectConnection); } void OpenRouteServiceRunner::retrieveData( QNetworkReply *reply ) { if ( reply->isFinished() ) { QByteArray data = reply->readAll(); reply->deleteLater(); //mDebug() << "Download completed: " << data; GeoDataDocument* document = parse( data ); if ( !document ) { mDebug() << "Failed to parse the downloaded route data" << data; } emit routeCalculated( document ); } } void OpenRouteServiceRunner::handleError( QNetworkReply::NetworkError error ) { mDebug() << " Error when retrieving openrouteservice.org route: " << error; } QString OpenRouteServiceRunner::xmlHeader() { QString result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; result += "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" "; result += "xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" "; result += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "; result += "xsi:schemaLocation=\"http://www.opengis.net/xls "; result += "http://schemas.opengis.net/ols/1.1.0/RouteService.xsd\" version=\"1.1\" xls:lang=\"en\">\n"; result += "<xls:RequestHeader/>\n"; return result; } QString OpenRouteServiceRunner::requestHeader( const QString &unit, const QString &routePreference ) { QString result = "<xls:Request methodName=\"RouteRequest\" requestID=\"123456789\" version=\"1.1\">\n"; result += "<xls:DetermineRouteRequest distanceUnit=\"%1\">\n"; result += "<xls:RoutePlan>\n"; result += "<xls:RoutePreference>%2</xls:RoutePreference>\n"; result += "<xls:WayPointList>\n"; return result.arg( unit ).arg( routePreference ); } QString OpenRouteServiceRunner::requestPoint( PointType pointType, const GeoDataCoordinates &coordinates ) { QString result = "<xls:%1>\n"; result += "<xls:Position>\n"; result += "<gml:Point srsName=\"EPSG:4326\">\n"; result += "<gml:pos>%2 %3</gml:pos>\n"; result += "</gml:Point>\n"; result += "</xls:Position>\n"; result += "</xls:%1>\n"; result = result.arg( pointType == StartPoint ? "StartPoint" : ( pointType == ViaPoint ? "ViaPoint" : "EndPoint" ) ); result = result.arg( coordinates.longitude( GeoDataCoordinates::Degree ), 0, 'f', 14 ); result = result.arg( coordinates.latitude( GeoDataCoordinates::Degree ), 0, 'f', 14 ); return result; } QString OpenRouteServiceRunner::requestFooter( const QHash<QString, QVariant>& settings ) { QString result = "</xls:WayPointList>\n"; if (settings["noMotorways"].toInt() || settings["noTollways"].toInt() ) { result += "<xls:AvoidList>\n"; if ( settings["noTollways"].toInt() ) { result += "<xls:AvoidFeature>Tollway</xls:AvoidFeature>"; } if ( settings["noMotorways"].toInt() ) { result += "<xls:AvoidFeature>Highway</xls:AvoidFeature>"; } result += "</xls:AvoidList>\n"; } result += "</xls:RoutePlan>\n"; result += "<xls:RouteInstructionsRequest provideGeometry=\"true\" />\n"; result += "<xls:RouteGeometryRequest/>\n"; result += "</xls:DetermineRouteRequest>\n"; result += "</xls:Request>\n"; return result; } QString OpenRouteServiceRunner::xmlFooter() { return "</xls:XLS>\n"; } GeoDataDocument* OpenRouteServiceRunner::parse( const QByteArray &content ) const { QDomDocument xml; if ( !xml.setContent( content ) ) { mDebug() << "Cannot parse xml file with routing instructions."; return 0; } QDomElement root = xml.documentElement(); GeoDataDocument* result = new GeoDataDocument(); result->setName( "OpenRouteService" ); QDomNodeList errors = root.elementsByTagName( "xls:Error" ); if ( errors.size() > 0 ) { return 0; // Returning early because fallback routing providers are used now // The code below can be used to parse OpenGis errors reported by ORS // and may be useful in the future #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < errors.length(); ++i ) { QDomNode node = errors.item( i ); QString errorMessage = node.attributes().namedItem( "message" ).nodeValue(); QRegExp regexp = QRegExp( "^(.*) Please Check your Position: (-?[0-9]+.[0-9]+) (-?[0-9]+.[0-9]+) !" ); if ( regexp.indexIn( errorMessage ) == 0 ) { if ( regexp.capturedTexts().size() == 4 ) { GeoDataPlacemark* placemark = new GeoDataPlacemark; placemark->setName( regexp.capturedTexts().at( 1 ) ); GeoDataCoordinates position; position.setLongitude( regexp.capturedTexts().at( 2 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( regexp.capturedTexts().at( 3 ).toDouble(), GeoDataCoordinates::Degree ); placemark->setCoordinate( position ); result->append( placemark ); } } else { mDebug() << "Error message " << errorMessage << " not parsable."; /** @todo: How to handle this now with plugins? */ // QString message = tr( "Sorry, a problem occurred when calculating the route. Try adjusting start and destination points." ); // QPointer<QMessageBox> messageBox = new QMessageBox( QMessageBox::Warning, "Route Error", message ); // messageBox->setDetailedText( errorMessage ); // messageBox->exec(); // delete messageBox; } } } GeoDataPlacemark* routePlacemark = new GeoDataPlacemark; routePlacemark->setName( "Route" ); QTime time; QDomNodeList summary = root.elementsByTagName( "xls:RouteSummary" ); if ( summary.size() > 0 ) { QDomNodeList timeNodeList = summary.item( 0 ).toElement().elementsByTagName( "xls:TotalTime" ); if ( timeNodeList.size() == 1 ) { QRegExp regexp = QRegExp( "^P(?:(\\d+)D)?T(?:(\\d+)H)?(?:(\\d+)M)?(\\d+)S" ); if ( regexp.indexIn( timeNodeList.item( 0 ).toElement().text() ) == 0 ) { QStringList matches = regexp.capturedTexts(); unsigned int hours( 0 ), minutes( 0 ), seconds( 0 ); switch ( matches.size() ) { case 5: // days = regexp.cap( matches.size() - 4 ).toInt(); // Intentionally no break case 4: hours = regexp.cap( matches.size() - 3 ).toInt(); // Intentionally no break case 3: minutes = regexp.cap( matches.size() - 2 ).toInt(); // Intentionally no break case 2: seconds = regexp.cap( matches.size() - 1 ).toInt(); break; default: mDebug() << "Unable to parse time string " << timeNodeList.item( 0 ).toElement().text(); } time = QTime( hours, minutes, seconds, 0 ); } } } GeoDataLineString* routeWaypoints = new GeoDataLineString; QDomNodeList geometry = root.elementsByTagName( "xls:RouteGeometry" ); if ( geometry.size() > 0 ) { QDomNodeList waypoints = geometry.item( 0 ).toElement().elementsByTagName( "gml:pos" ); #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < waypoints.length(); ++i ) { QDomNode node = waypoints.item( i ); QStringList content = node.toElement().text().split( ' ' ); if ( content.length() == 2 ) { GeoDataCoordinates position; position.setLongitude( content.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( content.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); routeWaypoints->append( position ); } } } routePlacemark->setGeometry( routeWaypoints ); qreal length = routeWaypoints->length( EARTH_RADIUS ); const QString name = nameString( "ORS", length, time ); const GeoDataExtendedData data = routeData( length, time ); routePlacemark->setExtendedData( data ); result->setName( name ); result->append( routePlacemark ); QDomNodeList instructionList = root.elementsByTagName( "xls:RouteInstructionsList" ); if ( instructionList.size() > 0 ) { QDomNodeList instructions = instructionList.item( 0 ).toElement().elementsByTagName( "xls:RouteInstruction" ); #if QT_VERSION < 0x050000 unsigned int i=0; #else int i=0; #endif for ( ; i < instructions.length(); ++i ) { QDomElement node = instructions.item( i ).toElement(); QDomNodeList textNodes = node.elementsByTagName( "xls:Instruction" ); QDomNodeList positions = node.elementsByTagName( "gml:pos" ); if ( textNodes.size() > 0 && positions.size() > 0 ) { QStringList content = positions.at( 0 ).toElement().text().split( ' ' ); if ( content.length() == 2 ) { GeoDataLineString *lineString = new GeoDataLineString; for( int i = 0; i < positions.count(); ++i ) { QStringList pointList = positions.at( i ).toElement().text().split( ' ' ); GeoDataCoordinates position; position.setLongitude( pointList.at( 0 ).toDouble(), GeoDataCoordinates::Degree ); position.setLatitude( pointList.at( 1 ).toDouble(), GeoDataCoordinates::Degree ); lineString->append( position ); } GeoDataPlacemark* instruction = new GeoDataPlacemark; QString const text = textNodes.item( 0 ).toElement().text(); GeoDataExtendedData extendedData; GeoDataData turnTypeData; turnTypeData.setName( "turnType" ); QString road; RoutingInstruction::TurnType turnType = parseTurnType( text, &road ); turnTypeData.setValue( turnType ); extendedData.addValue( turnTypeData ); if ( !road.isEmpty() ) { GeoDataData roadName; roadName.setName( "roadName" ); roadName.setValue( road ); extendedData.addValue( roadName ); } QString const instructionText = turnType == RoutingInstruction::Unknown ? text : RoutingInstruction::generateRoadInstruction( turnType, road ); instruction->setName( instructionText ); instruction->setExtendedData( extendedData ); instruction->setGeometry( lineString ); result->append( instruction ); } } } } return result; } RoutingInstruction::TurnType OpenRouteServiceRunner::parseTurnType( const QString &text, QString *road ) { QRegExp syntax( "^(Go|Drive|Turn) (half left|left|sharp left|straight forward|half right|right|sharp right)( on )?(.*)?$", Qt::CaseSensitive, QRegExp::RegExp2 ); QString instruction; if ( syntax.indexIn( text ) == 0 ) { if ( syntax.captureCount() > 1 ) { instruction = syntax.cap( 2 ); if ( syntax.captureCount() == 4 ) { *road = syntax.cap( 4 ).remove(QLatin1String( " - Arrived at destination!")); } } } if ( instruction == "Continue" ) { return RoutingInstruction::Straight; } else if ( instruction == "half right" ) { return RoutingInstruction::SlightRight; } else if ( instruction == "right" ) { return RoutingInstruction::Right; } else if ( instruction == "sharp right" ) { return RoutingInstruction::SharpRight; } else if ( instruction == "straight forward" ) { return RoutingInstruction::Straight; } else if ( instruction == "turn" ) { return RoutingInstruction::TurnAround; } else if ( instruction == "sharp left" ) { return RoutingInstruction::SharpLeft; } else if ( instruction == "left" ) { return RoutingInstruction::Left; } else if ( instruction == "half left" ) { return RoutingInstruction::SlightLeft; } return RoutingInstruction::Unknown; } } // namespace Marble #include "OpenRouteServiceRunner.moc" <|endoftext|>