text
stringlengths
54
60.6k
<commit_before>/* Implementation of the Compiler class. */ #include <cctype> //character comparison functions #include <stdexcept> #include "compiler.hh" namespace ds_compiler { const size_t Compiler::NUM_REGISTERS = 8; const char Compiler::ERR_CHAR = '\0'; const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'}); const std::unordered_set<char> Compiler::MULT_OPS; //constructors Compiler::Compiler () : m_is (&std::cin), m_os (&std::cout) { } Compiler::Compiler (std::istream *new_is, std::ostream *new_os) : m_is (new_is), m_os (new_os) { } void Compiler::compile_intermediate () const { try { expression(); } catch (std::exception &ex) { std::cerr << ex.what() << '\n'; } } void Compiler::compile_full () const { compile_start(); compile_intermediate(); compile_end(); } void Compiler::compile_start () const { //emit lines for necessary includes emit_line("#include <stack>"); emit_line("#include <vector>"); emit_line("#include <iostream>"); emit_line("#include <string>"); //create a stack and vector for registers std::string stack_init = "static std::stack<int> cpu_stack;"; std::string registers_init = "static std::vector<int> cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0);"; emit_line(stack_init); emit_line(registers_init); //emit definition of a function for easier stack handling emit_line("int cpu_pop() {"); emit_line("int val = cpu_stack.top();"); emit_line("cpu_stack.pop();"); emit_line("return val; }"); //emit lines for int main() { emit_line("int main () {"); } void Compiler::compile_end () const { //dump register contents emit_line("std::cout << \"Register contents\\n\";"); emit_line( std::string("for (int i = 0; i < ") + std::to_string(NUM_REGISTERS) + "; ++i)" ); emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';"); //emit lines for closing main emit_line("return 0;"); emit_line("}"); } //cradle methods void Compiler::report_error(const std::string err) const { os() << '\n'; os() << "Error: " << err << '\n'; } void Compiler::abort(const std::string err) const { report_error(err); throw std::runtime_error("Compilation failed.\n"); } void Compiler::expected(const std::string expect) const { abort(expect + " expected.\n"); } //overload to handle single characters; //prevents having to construct a string whenever calling expected() void Compiler::expected(const char c) const { expected(std::string(1, c)); } //checks if next character matches; if so, consume that character void Compiler::match(const char c) const { if (is().peek() == c) { is().get(); } else { expected(c); } } void Compiler::expression () const { term(); while (is_in(ADD_OPS, is().peek())) { emit_line("cpu_stack.at(1) = cpu_stack.at(0);"); switch (is().peek()) { case '+': add(); break; case '-': subtract(); break; default: expected("Addop"); } } } void Compiler::term () const { char expr = get_num(); if (expr != ERR_CHAR) { emit_line( std::string("cpu_registers.at(0) = ") + expr + ";" ); } } // gets a valid identifier from input stream char Compiler::get_name () const { if (!std::isalpha(is().peek())) { expected("Name"); return ERR_CHAR; } else { return std::toupper(is().get()); } } //gets a number char Compiler::get_num () const { if (!std::isdigit(is().peek())) { expected("Integer"); return ERR_CHAR; } else { return is().get(); } } //output a string void Compiler::emit (std::string s) const { os() << s; } //output a string with newline void Compiler::emit_line (std::string s) const { emit(s); emit("\n"); } //helper members to allow using stream syntax with *is, *os void Compiler::add () const { match('+'); term(); emit_line( std::string("cpu_registers.at(0) = cpu_registers.at(1) + cpu_registers.at(0);") ); } void Compiler::subtract () const { match('-'); term(); emit_line( std::string("cpu_registers.at(0) = cpu_registers.at(1) - cpu_registers.at(0);") ); } bool Compiler::is_in(const std::unordered_set<char> us, const char elem) { return us.find(elem) != us.end(); } void Compiler::set_is (std::istream *new_is) { m_is = new_is; } void Compiler::set_os (std::ostream *new_os) { m_os = new_os; } std::istream& Compiler::is() const { return *m_is; } std::ostream& Compiler::os() const { return *m_os; } } //end namespace<commit_msg>Included instructions in compile_end() to dump register contents.<commit_after>/* Implementation of the Compiler class. */ #include <cctype> //character comparison functions #include <stdexcept> #include "compiler.hh" namespace ds_compiler { const size_t Compiler::NUM_REGISTERS = 8; const char Compiler::ERR_CHAR = '\0'; const std::unordered_set<char> Compiler::ADD_OPS({'+', '-'}); const std::unordered_set<char> Compiler::MULT_OPS; //constructors Compiler::Compiler () : m_is (&std::cin), m_os (&std::cout) { } Compiler::Compiler (std::istream *new_is, std::ostream *new_os) : m_is (new_is), m_os (new_os) { } void Compiler::compile_intermediate () const { try { expression(); } catch (std::exception &ex) { std::cerr << ex.what() << '\n'; } } void Compiler::compile_full () const { compile_start(); compile_intermediate(); compile_end(); } void Compiler::compile_start () const { //emit lines for necessary includes emit_line("#include <stack>"); emit_line("#include <vector>"); emit_line("#include <iostream>"); emit_line("#include <string>"); //create a stack and vector for registers std::string stack_init = "static std::stack<int> cpu_stack;"; std::string registers_init = "static std::vector<int> cpu_registers(" + std::to_string(NUM_REGISTERS) + ", 0);"; emit_line(stack_init); emit_line(registers_init); //emit definition of a function for easier stack handling emit_line("int cpu_pop() {"); emit_line("int val = cpu_stack.top();"); emit_line("cpu_stack.pop();"); emit_line("return val; }"); //emit lines for int main() { emit_line("int main () {"); } void Compiler::compile_end () const { //dump register contents emit_line("std::cout << \"Register contents\\n\";"); emit_line( std::string("for (int i = 0; i < ") + std::to_string(NUM_REGISTERS) + "; ++i)" ); emit_line("std::cout << std::string(\"Register \") << i << \": \" << cpu_registers.at(i) << '\\n';"); //emit lines for closing main emit_line("return 0;"); emit_line("}"); } //cradle methods void Compiler::report_error(const std::string err) const { os() << '\n'; os() << "Error: " << err << '\n'; } void Compiler::abort(const std::string err) const { report_error(err); throw std::runtime_error("Compilation failed.\n"); } void Compiler::expected(const std::string expect) const { abort(expect + " expected.\n"); } //overload to handle single characters; //prevents having to construct a string whenever calling expected() void Compiler::expected(const char c) const { expected(std::string(1, c)); } //checks if next character matches; if so, consume that character void Compiler::match(const char c) const { if (is().peek() == c) { is().get(); } else { expected(c); } } void Compiler::expression () const { term(); while (is_in(ADD_OPS, is().peek())) { emit_line("cpu_registers.at(1) = cpu_registers.at(0);"); switch (is().peek()) { case '+': add(); break; case '-': subtract(); break; default: expected("Addop"); } } } void Compiler::term () const { char expr = get_num(); if (expr != ERR_CHAR) { emit_line( std::string("cpu_registers.at(0) = ") + expr + ";" ); } } // gets a valid identifier from input stream char Compiler::get_name () const { if (!std::isalpha(is().peek())) { expected("Name"); return ERR_CHAR; } else { return std::toupper(is().get()); } } //gets a number char Compiler::get_num () const { if (!std::isdigit(is().peek())) { expected("Integer"); return ERR_CHAR; } else { return is().get(); } } //output a string void Compiler::emit (std::string s) const { os() << s; } //output a string with newline void Compiler::emit_line (std::string s) const { emit(s); emit("\n"); } //helper members to allow using stream syntax with *is, *os void Compiler::add () const { match('+'); term(); emit_line( std::string("cpu_registers.at(0) = cpu_registers.at(1) + cpu_registers.at(0);") ); } void Compiler::subtract () const { match('-'); term(); emit_line( std::string("cpu_registers.at(0) = cpu_registers.at(1) - cpu_registers.at(0);") ); } bool Compiler::is_in(const std::unordered_set<char> us, const char elem) { return us.find(elem) != us.end(); } void Compiler::set_is (std::istream *new_is) { m_is = new_is; } void Compiler::set_os (std::ostream *new_os) { m_os = new_os; } std::istream& Compiler::is() const { return *m_is; } std::ostream& Compiler::os() const { return *m_os; } } //end namespace<|endoftext|>
<commit_before>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "NativeControlObject.h" #include "TiObject.h" #include <stdlib.h> #include <string.h> #include <vector> #include <bb/cascades/Color> #include <qtgui/QColor> #define PROP_SETTING_FUNCTION(NAME) prop_##NAME #define PROP_SETTER(NAME) static int prop_##NAME(NativeControlObject* object, TiObject* obj) \ {\ return object->NAME(obj);\ } typedef int (*NATIVE_PROPSET_CALLBACK)(NativeControlObject*, TiObject*); // Prototypes static void initPropertyMap(); // Statics static vector<NATIVE_PROPSET_CALLBACK> s_functionMap; NativeControlObject::NativeControlObject() { control_ = NULL; initPropertyMap(); } NativeControlObject::~NativeControlObject() { } bb::cascades::Control* NativeControlObject::getControl() const { return control_; } void NativeControlObject::setControl(bb::cascades::Control* control) { control_ = control; } // PROP_SETTER_xxx creates a static version of functions which // calls the non-static on method on the NativeControlObject // class. PROP_SETTER(setBackgroundColor) int NativeControlObject::setBackgroundColor(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setColor) int NativeControlObject::setColor(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setLabel) int NativeControlObject::setLabel(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setMax) int NativeControlObject::setMax(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setMin) int NativeControlObject::setMin(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setText) int NativeControlObject::setText(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTextAlign) int NativeControlObject::setTextAlign(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTitle) int NativeControlObject::setTitle(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTop) int NativeControlObject::setTop(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setValue) int NativeControlObject::setValue(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setVisible) int NativeControlObject::setVisible(TiObject* obj) { bool visible; int error = getBoolean(obj, &visible); if (error != NATIVE_ERROR_OK) { return error; } ((bb::cascades::Control*)getNativeHandle())->setVisible(visible); return NATIVE_ERROR_OK; } // PROP_SETTING_FUNCTION resolves the static name of the function, e.g., // PROP_SETTING_FUNCTION(setBackgroundColor) resolves to "prop_setBackgroundColor" static void initPropertyMap() { static bool initialized = false; if (initialized == false) { initialized = true; s_functionMap.resize(N_PROP_LAST); s_functionMap[N_PROP_UNDEFINED] = NULL; s_functionMap[N_PROP_ANCHOR_POINT] = NULL; s_functionMap[N_PROP_ANIMATED_CENTER_POINT] = NULL; s_functionMap[N_PROP_AUTO_LINK] = NULL; s_functionMap[N_PROP_BACKGROUND_COLOR] = PROP_SETTING_FUNCTION(setBackgroundColor); s_functionMap[N_PROP_BACKGROUND_DISABLED_COLOR] = NULL; s_functionMap[N_PROP_BACKGROUND_DISABLED_IMAGE] = NULL; s_functionMap[N_PROP_BACKGROUND_FOCUSED_COLOR] = NULL; s_functionMap[N_PROP_BACKGROUND_FOCUSED_IMAGE] = NULL; s_functionMap[N_PROP_BACKGROUND_GRADIANT] = NULL; s_functionMap[N_PROP_BACKGROUND_IMAGE] = NULL; s_functionMap[N_PROP_BACKGROUND_LEFT_CAP] = NULL; s_functionMap[N_PROP_BACKGROUND_PADDING_BOTTOM] = NULL; s_functionMap[N_PROP_BACKGROUND_PADDING_LEFT] = NULL; s_functionMap[N_PROP_BACKGROUND_PADDING_RIGHT] = NULL; s_functionMap[N_PROP_BACKGROUND_PADDING_TOP] = NULL; s_functionMap[N_PROP_BACKGROUND_REPEAT] = NULL; s_functionMap[N_PROP_BACKGROUND_SELECTED_COLOR] = NULL; s_functionMap[N_PROP_BACKGROUND_SELECTED_IMAGE] = NULL; s_functionMap[N_PROP_BACKGROUND_TOP_CAP] = NULL; s_functionMap[N_PROP_BORDER_COLOR] = NULL; s_functionMap[N_PROP_BORDER_RADIUS] = NULL; s_functionMap[N_PROP_BORDER_WIDTH] = NULL; s_functionMap[N_PROP_BOTTOM] = NULL; s_functionMap[N_PROP_CENTER] = NULL; s_functionMap[N_PROP_CHILDREN] = NULL; s_functionMap[N_PROP_COLOR] = PROP_SETTING_FUNCTION(setColor); s_functionMap[N_PROP_ELLIPSIZE] = NULL; s_functionMap[N_PROP_FOCUSABLE] = NULL; s_functionMap[N_PROP_FONT] = NULL; s_functionMap[N_PROP_HEIGHT] = NULL; s_functionMap[N_PROP_HIGHLIGHTED_COLOR] = NULL; s_functionMap[N_PROP_HINT_TEXT] = NULL; s_functionMap[N_PROP_HTML] = NULL; s_functionMap[N_PROP_IMAGE] = NULL; s_functionMap[N_PROP_KEEP_SCREEN_ON] = NULL; s_functionMap[N_PROP_LABEL] = PROP_SETTING_FUNCTION(setLabel); s_functionMap[N_PROP_LAYOUT] = NULL; s_functionMap[N_PROP_LEFT] = NULL; s_functionMap[N_PROP_MAX] = PROP_SETTING_FUNCTION(setMax); s_functionMap[N_PROP_MIN] = PROP_SETTING_FUNCTION(setMin); s_functionMap[N_PROP_MINIMUM_FONT_SIZE] = NULL; s_functionMap[N_PROP_OPACITY] = NULL; s_functionMap[N_PROP_RIGHT] = NULL; s_functionMap[N_PROP_SHADOW_COLOR] = NULL; s_functionMap[N_PROP_SHADOW_OFFSET] = NULL; s_functionMap[N_PROP_SIZE] = NULL; s_functionMap[N_PROP_SOFT_KEYBOARD_ON_FOCUS] = NULL; s_functionMap[N_PROP_TEXT] = PROP_SETTING_FUNCTION(setText); s_functionMap[N_PROP_TEXT_ALIGN] = PROP_SETTING_FUNCTION(setTextAlign); s_functionMap[N_PROP_TEXT_ID] = NULL; s_functionMap[N_PROP_TITLE] = PROP_SETTING_FUNCTION(setTitle); s_functionMap[N_PROP_TOP] = PROP_SETTING_FUNCTION(setTop); s_functionMap[N_PROP_TOUCH_ENABLED] = NULL; s_functionMap[N_PROP_TRANSFORM] = NULL; s_functionMap[N_PROP_VALUE] = PROP_SETTING_FUNCTION(setValue); s_functionMap[N_PROP_VISIBLE] = PROP_SETTING_FUNCTION(setVisible); s_functionMap[N_PROP_WIDTH] = NULL; s_functionMap[N_PROP_WORD_WRAP] = NULL; s_functionMap[N_PROP_ZINDEX] = NULL; } } int NativeControlObject::setPropertyValue(size_t propertyNumber, TiObject* obj) { if ((propertyNumber < 0) || (propertyNumber >= s_functionMap.size()) || (s_functionMap[propertyNumber] == NULL)) { return NATIVE_ERROR_NOTSUPPORTED; } return (s_functionMap[propertyNumber])(this, obj); } int NativeControlObject::getColorComponents(TiObject* obj, float* r, float* g, float* b, float* a) { Handle<Value> value = obj->getValue(); if ((value.IsEmpty()) || (!value->IsString())) { return NATIVE_ERROR_INVALID_ARG; } Handle<String> v8color = Handle<String>::Cast(value); String::Utf8Value v8colorString(v8color); if (!QColor::isValidColor(*v8colorString)) { return NATIVE_ERROR_INVALID_ARG; } QColor qcolor(*v8colorString); qreal qr, qg, qb, qa; qcolor.getRgbF(&qr, &qg, &qb, &qa); *r = qr; *g = qg; *b = qb; *a = qa; return NATIVE_ERROR_OK; } int NativeControlObject::getBoolean(TiObject* obj, bool* value) { Handle<Value> v8value = obj->getValue(); if ((v8value.IsEmpty()) || ((!v8value->IsBoolean()) && (!v8value->IsBooleanObject()))) { return NATIVE_ERROR_INVALID_ARG; } Handle<Boolean> b = v8value->ToBoolean(); *value = b->Value(); return NATIVE_ERROR_OK; } int NativeControlObject::getString(TiObject* obj, QString& str) { Handle<Value> value = obj->getValue(); if ((value.IsEmpty()) || (!value->IsString())) { return NATIVE_ERROR_INVALID_ARG; } Handle<String> v8string = Handle<String>::Cast(value); String::Utf8Value v8UtfString(v8string); const char* cStr = *v8UtfString; str = cStr; return NATIVE_ERROR_OK; } int NativeControlObject::getFloat(TiObject* obj, float* value) { Handle<Value> v8value = obj->getValue(); if ((v8value.IsEmpty()) || ((!v8value->IsNumber()) && (!v8value->IsNumberObject()))) { return NATIVE_ERROR_INVALID_ARG; } Handle<Number> num = Handle<Number>::Cast(v8value); *value = (float)num->Value(); return NATIVE_ERROR_OK; } <commit_msg>Make the functionMap const by initializing it statically, renamed the init function to initFunctionMap<commit_after>/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "NativeControlObject.h" #include "TiObject.h" #include <stdlib.h> #include <string.h> #include <vector> #include <bb/cascades/Color> #include <qtgui/QColor> #define PROP_SETTING_FUNCTION(NAME) prop_##NAME #define PROP_SETTER(NAME) static int prop_##NAME(NativeControlObject* object, TiObject* obj) \ {\ return object->NAME(obj);\ } typedef int (*NATIVE_PROPSET_CALLBACK)(NativeControlObject*, TiObject*); // Prototypes static vector<NATIVE_PROPSET_CALLBACK> initFunctionMap(); // Statics static const vector<NATIVE_PROPSET_CALLBACK> s_functionMap = initFunctionMap(); NativeControlObject::NativeControlObject() { control_ = NULL; } NativeControlObject::~NativeControlObject() { } bb::cascades::Control* NativeControlObject::getControl() const { return control_; } void NativeControlObject::setControl(bb::cascades::Control* control) { control_ = control; } // PROP_SETTER_xxx creates a static version of functions which // calls the non-static on method on the NativeControlObject // class. PROP_SETTER(setBackgroundColor) int NativeControlObject::setBackgroundColor(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setColor) int NativeControlObject::setColor(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setLabel) int NativeControlObject::setLabel(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setMax) int NativeControlObject::setMax(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setMin) int NativeControlObject::setMin(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setText) int NativeControlObject::setText(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTextAlign) int NativeControlObject::setTextAlign(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTitle) int NativeControlObject::setTitle(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setTop) int NativeControlObject::setTop(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setValue) int NativeControlObject::setValue(TiObject* obj) { return NATIVE_ERROR_NOTSUPPORTED; } PROP_SETTER(setVisible) int NativeControlObject::setVisible(TiObject* obj) { bool visible; int error = getBoolean(obj, &visible); if (error != NATIVE_ERROR_OK) { return error; } ((bb::cascades::Control*)getNativeHandle())->setVisible(visible); return NATIVE_ERROR_OK; } // PROP_SETTING_FUNCTION resolves the static name of the function, e.g., // PROP_SETTING_FUNCTION(setBackgroundColor) resolves to "prop_setBackgroundColor" static vector<NATIVE_PROPSET_CALLBACK> initFunctionMap() { vector<NATIVE_PROPSET_CALLBACK> vect; vect.resize(N_PROP_LAST); vect[N_PROP_UNDEFINED] = NULL; vect[N_PROP_ANCHOR_POINT] = NULL; vect[N_PROP_ANIMATED_CENTER_POINT] = NULL; vect[N_PROP_AUTO_LINK] = NULL; vect[N_PROP_BACKGROUND_COLOR] = PROP_SETTING_FUNCTION(setBackgroundColor); vect[N_PROP_BACKGROUND_DISABLED_COLOR] = NULL; vect[N_PROP_BACKGROUND_DISABLED_IMAGE] = NULL; vect[N_PROP_BACKGROUND_FOCUSED_COLOR] = NULL; vect[N_PROP_BACKGROUND_FOCUSED_IMAGE] = NULL; vect[N_PROP_BACKGROUND_GRADIANT] = NULL; vect[N_PROP_BACKGROUND_IMAGE] = NULL; vect[N_PROP_BACKGROUND_LEFT_CAP] = NULL; vect[N_PROP_BACKGROUND_PADDING_BOTTOM] = NULL; vect[N_PROP_BACKGROUND_PADDING_LEFT] = NULL; vect[N_PROP_BACKGROUND_PADDING_RIGHT] = NULL; vect[N_PROP_BACKGROUND_PADDING_TOP] = NULL; vect[N_PROP_BACKGROUND_REPEAT] = NULL; vect[N_PROP_BACKGROUND_SELECTED_COLOR] = NULL; vect[N_PROP_BACKGROUND_SELECTED_IMAGE] = NULL; vect[N_PROP_BACKGROUND_TOP_CAP] = NULL; vect[N_PROP_BORDER_COLOR] = NULL; vect[N_PROP_BORDER_RADIUS] = NULL; vect[N_PROP_BORDER_WIDTH] = NULL; vect[N_PROP_BOTTOM] = NULL; vect[N_PROP_CENTER] = NULL; vect[N_PROP_CHILDREN] = NULL; vect[N_PROP_COLOR] = PROP_SETTING_FUNCTION(setColor); vect[N_PROP_ELLIPSIZE] = NULL; vect[N_PROP_FOCUSABLE] = NULL; vect[N_PROP_FONT] = NULL; vect[N_PROP_HEIGHT] = NULL; vect[N_PROP_HIGHLIGHTED_COLOR] = NULL; vect[N_PROP_HINT_TEXT] = NULL; vect[N_PROP_HTML] = NULL; vect[N_PROP_IMAGE] = NULL; vect[N_PROP_KEEP_SCREEN_ON] = NULL; vect[N_PROP_LABEL] = PROP_SETTING_FUNCTION(setLabel); vect[N_PROP_LAYOUT] = NULL; vect[N_PROP_LEFT] = NULL; vect[N_PROP_MAX] = PROP_SETTING_FUNCTION(setMax); vect[N_PROP_MIN] = PROP_SETTING_FUNCTION(setMin); vect[N_PROP_MINIMUM_FONT_SIZE] = NULL; vect[N_PROP_OPACITY] = NULL; vect[N_PROP_RIGHT] = NULL; vect[N_PROP_SHADOW_COLOR] = NULL; vect[N_PROP_SHADOW_OFFSET] = NULL; vect[N_PROP_SIZE] = NULL; vect[N_PROP_SOFT_KEYBOARD_ON_FOCUS] = NULL; vect[N_PROP_TEXT] = PROP_SETTING_FUNCTION(setText); vect[N_PROP_TEXT_ALIGN] = PROP_SETTING_FUNCTION(setTextAlign); vect[N_PROP_TEXT_ID] = NULL; vect[N_PROP_TITLE] = PROP_SETTING_FUNCTION(setTitle); vect[N_PROP_TOP] = PROP_SETTING_FUNCTION(setTop); vect[N_PROP_TOUCH_ENABLED] = NULL; vect[N_PROP_TRANSFORM] = NULL; vect[N_PROP_VALUE] = PROP_SETTING_FUNCTION(setValue); vect[N_PROP_VISIBLE] = PROP_SETTING_FUNCTION(setVisible); vect[N_PROP_WIDTH] = NULL; vect[N_PROP_WORD_WRAP] = NULL; vect[N_PROP_ZINDEX] = NULL; return vect; } int NativeControlObject::setPropertyValue(size_t propertyNumber, TiObject* obj) { if ((propertyNumber < 0) || (propertyNumber >= s_functionMap.size()) || (s_functionMap[propertyNumber] == NULL)) { return NATIVE_ERROR_NOTSUPPORTED; } return (s_functionMap[propertyNumber])(this, obj); } int NativeControlObject::getColorComponents(TiObject* obj, float* r, float* g, float* b, float* a) { Handle<Value> value = obj->getValue(); if ((value.IsEmpty()) || (!value->IsString())) { return NATIVE_ERROR_INVALID_ARG; } Handle<String> v8color = Handle<String>::Cast(value); String::Utf8Value v8colorString(v8color); if (!QColor::isValidColor(*v8colorString)) { return NATIVE_ERROR_INVALID_ARG; } QColor qcolor(*v8colorString); qreal qr, qg, qb, qa; qcolor.getRgbF(&qr, &qg, &qb, &qa); *r = qr; *g = qg; *b = qb; *a = qa; return NATIVE_ERROR_OK; } int NativeControlObject::getBoolean(TiObject* obj, bool* value) { Handle<Value> v8value = obj->getValue(); if ((v8value.IsEmpty()) || ((!v8value->IsBoolean()) && (!v8value->IsBooleanObject()))) { return NATIVE_ERROR_INVALID_ARG; } Handle<Boolean> b = v8value->ToBoolean(); *value = b->Value(); return NATIVE_ERROR_OK; } int NativeControlObject::getString(TiObject* obj, QString& str) { Handle<Value> value = obj->getValue(); if ((value.IsEmpty()) || (!value->IsString())) { return NATIVE_ERROR_INVALID_ARG; } Handle<String> v8string = Handle<String>::Cast(value); String::Utf8Value v8UtfString(v8string); const char* cStr = *v8UtfString; str = cStr; return NATIVE_ERROR_OK; } int NativeControlObject::getFloat(TiObject* obj, float* value) { Handle<Value> v8value = obj->getValue(); if ((v8value.IsEmpty()) || ((!v8value->IsNumber()) && (!v8value->IsNumberObject()))) { return NATIVE_ERROR_INVALID_ARG; } Handle<Number> num = Handle<Number>::Cast(v8value); *value = (float)num->Value(); return NATIVE_ERROR_OK; } <|endoftext|>
<commit_before>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2010, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== // Tests for the sequence_journaled module. // ========================================================================== #include <seqan/basic.h> #include <seqan/file.h> #include "test_sequence_journaled.h" #include "test_sequence_journaled_iterator.h" SEQAN_BEGIN_TESTSUITE(test_sequence_journaled) { // Call tests of the sequence journal with unbalanced tree journal. SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_set); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_host); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_clear); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_erase_position); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_erase_begin_end); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_insert); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_insert_value); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign_value); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_subscript_operator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign_infix); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_length); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_virtual_to_host_position); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_copy_constructor); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_begin_end_iterator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_begin_end_const_iterator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_subscript_operator_randomized); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_fuzzying); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_segments_read_only); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_segments_read_write); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_sum); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_difference); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_relations); // Call tests of the sequence journal with sorted array journals. SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_set); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_host); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_clear); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_erase_position); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_erase_begin_end); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_insert); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_insert_value); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign_value); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_subscript_operator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign_infix); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_length); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_virtual_to_host_position); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_copy_constructor); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_begin_end_iterator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_begin_end_const_iterator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_subscript_operator_randomized); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_fuzzying); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_segments_read_only); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_segments_read_write); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_sum); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_difference); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_relations); // Verify checkpoints. SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entry.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree_iterator.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree_node.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_sorted_array.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/sequence_journaled.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/sequence_journaled_iterator.h"); } SEQAN_END_TESTSUITE <commit_msg>removed redundant tests<commit_after>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2010, Knut Reinert, FU Berlin // 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. // // ========================================================================== // Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de> // ========================================================================== // Tests for the sequence_journaled module. // ========================================================================== #include <seqan/basic.h> #include <seqan/file.h> #include "test_sequence_journaled.h" #include "test_sequence_journaled_iterator.h" SEQAN_BEGIN_TESTSUITE(test_sequence_journaled) { // Call tests of the sequence journal with unbalanced tree journal. SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_set); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_host); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_clear); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_erase_position); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_erase_begin_end); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_insert); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_insert_value); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign_value); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_subscript_operator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_assign_infix); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_length); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_virtual_to_host_position); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_copy_constructor); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_begin_end_iterator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_begin_end_const_iterator); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_subscript_operator_randomized); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_fuzzying); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_segments_read_only); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_segments_read_write); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_sum); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_difference); SEQAN_CALL_TEST(test_sequence_journaled_unbalanced_tree_iterator_relations); // Call tests of the sequence journal with sorted array journals. SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_set); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_host); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_clear); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_erase_position); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_erase_begin_end); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_insert); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_insert_value); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign_value); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_subscript_operator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_assign_infix); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_length); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_virtual_to_host_position); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_copy_constructor); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_begin_end_iterator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_begin_end_const_iterator); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_subscript_operator_randomized); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_fuzzying); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_segments_read_only); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_segments_read_write); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_sum); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_difference); SEQAN_CALL_TEST(test_sequence_journaled_sorted_array_iterator_relations); // Verify checkpoints. SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entry.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree_iterator.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_unbalanced_tree_node.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/journal_entries_sorted_array.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/sequence_journaled.h"); SEQAN_VERIFY_CHECKPOINTS("projects/library/seqan/sequence_journaled/sequence_journaled_iterator.h"); } SEQAN_END_TESTSUITE <|endoftext|>
<commit_before>//===--- Registry.cpp - Matcher registry -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===------------------------------------------------------------===// /// /// \file /// \brief Registry map populated at static initialization time. /// //===------------------------------------------------------------===// #include "clang/ASTMatchers/Dynamic/Registry.h" #include <utility> #include "Marshallers.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ManagedStatic.h" namespace clang { namespace ast_matchers { namespace dynamic { namespace { using internal::MatcherDescriptor; typedef llvm::StringMap<const MatcherDescriptor *> ConstructorMap; class RegistryMaps { public: RegistryMaps(); ~RegistryMaps(); const ConstructorMap &constructors() const { return Constructors; } private: void registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback); ConstructorMap Constructors; }; void RegistryMaps::registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback) { assert(Constructors.find(MatcherName) == Constructors.end()); Constructors[MatcherName] = Callback; } #define REGISTER_MATCHER(name) \ registerMatcher(#name, internal::makeMatcherAutoMarshall( \ ::clang::ast_matchers::name, #name)); #define SPECIFIC_MATCHER_OVERLOAD(name, Id) \ static_cast< ::clang::ast_matchers::name##_Type##Id>( \ ::clang::ast_matchers::name) #define REGISTER_OVERLOADED_2(name) \ do { \ MatcherDescriptor *Callbacks[] = { \ internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 0), \ #name), \ internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 1), \ #name) \ }; \ registerMatcher(#name, \ new internal::OverloadedMatcherDescriptor(Callbacks)); \ } while (0) /// \brief Generate a registry map with all the known matchers. RegistryMaps::RegistryMaps() { // TODO: Here is the list of the missing matchers, grouped by reason. // // Need Variant/Parser fixes: // ofKind // // Polymorphic + argument overload: // findAll // // Other: // loc // equals // equalsNode REGISTER_OVERLOADED_2(callee); REGISTER_OVERLOADED_2(hasPrefix); REGISTER_OVERLOADED_2(hasType); REGISTER_OVERLOADED_2(isDerivedFrom); REGISTER_OVERLOADED_2(isSameOrDerivedFrom); REGISTER_OVERLOADED_2(pointsTo); REGISTER_OVERLOADED_2(references); REGISTER_OVERLOADED_2(thisPointerType); REGISTER_MATCHER(accessSpecDecl); REGISTER_MATCHER(alignOfExpr); REGISTER_MATCHER(allOf); REGISTER_MATCHER(anyOf); REGISTER_MATCHER(anything); REGISTER_MATCHER(argumentCountIs); REGISTER_MATCHER(arraySubscriptExpr); REGISTER_MATCHER(arrayType); REGISTER_MATCHER(asString); REGISTER_MATCHER(asmStmt); REGISTER_MATCHER(atomicType); REGISTER_MATCHER(autoType); REGISTER_MATCHER(binaryOperator); REGISTER_MATCHER(bindTemporaryExpr); REGISTER_MATCHER(blockPointerType); REGISTER_MATCHER(boolLiteral); REGISTER_MATCHER(breakStmt); REGISTER_MATCHER(builtinType); REGISTER_MATCHER(cStyleCastExpr); REGISTER_MATCHER(callExpr); REGISTER_MATCHER(castExpr); REGISTER_MATCHER(catchStmt); REGISTER_MATCHER(characterLiteral); REGISTER_MATCHER(classTemplateDecl); REGISTER_MATCHER(classTemplateSpecializationDecl); REGISTER_MATCHER(complexType); REGISTER_MATCHER(compoundLiteralExpr); REGISTER_MATCHER(compoundStmt); REGISTER_MATCHER(conditionalOperator); REGISTER_MATCHER(constCastExpr); REGISTER_MATCHER(constantArrayType); REGISTER_MATCHER(constructExpr); REGISTER_MATCHER(constructorDecl); REGISTER_MATCHER(containsDeclaration); REGISTER_MATCHER(continueStmt); REGISTER_MATCHER(ctorInitializer); REGISTER_MATCHER(decl); REGISTER_MATCHER(declCountIs); REGISTER_MATCHER(declRefExpr); REGISTER_MATCHER(declStmt); REGISTER_MATCHER(defaultArgExpr); REGISTER_MATCHER(deleteExpr); REGISTER_MATCHER(dependentSizedArrayType); REGISTER_MATCHER(destructorDecl); REGISTER_MATCHER(doStmt); REGISTER_MATCHER(dynamicCastExpr); REGISTER_MATCHER(eachOf); REGISTER_MATCHER(elaboratedType); REGISTER_MATCHER(enumConstantDecl); REGISTER_MATCHER(enumDecl); REGISTER_MATCHER(explicitCastExpr); REGISTER_MATCHER(expr); REGISTER_MATCHER(fieldDecl); REGISTER_MATCHER(floatLiteral); REGISTER_MATCHER(forEach); REGISTER_MATCHER(forEachDescendant); REGISTER_MATCHER(forField); REGISTER_MATCHER(forRangeStmt); REGISTER_MATCHER(forStmt); REGISTER_MATCHER(functionDecl); REGISTER_MATCHER(functionTemplateDecl); REGISTER_MATCHER(functionType); REGISTER_MATCHER(functionalCastExpr); REGISTER_MATCHER(gotoStmt); REGISTER_MATCHER(has); REGISTER_MATCHER(hasAncestor); REGISTER_MATCHER(hasAnyArgument); REGISTER_MATCHER(hasAnyConstructorInitializer); REGISTER_MATCHER(hasAnyParameter); REGISTER_MATCHER(hasAnySubstatement); REGISTER_MATCHER(hasAnyTemplateArgument); REGISTER_MATCHER(hasAnyUsingShadowDecl); REGISTER_MATCHER(hasArgument); REGISTER_MATCHER(hasArgumentOfType); REGISTER_MATCHER(hasBase); REGISTER_MATCHER(hasBody); REGISTER_MATCHER(hasCanonicalType); REGISTER_MATCHER(hasCondition); REGISTER_MATCHER(hasConditionVariableStatement); REGISTER_MATCHER(hasDeclContext); REGISTER_MATCHER(hasDeclaration); REGISTER_MATCHER(hasDeducedType); REGISTER_MATCHER(hasDescendant); REGISTER_MATCHER(hasDestinationType); REGISTER_MATCHER(hasEitherOperand); REGISTER_MATCHER(hasElementType); REGISTER_MATCHER(hasFalseExpression); REGISTER_MATCHER(hasImplicitDestinationType); REGISTER_MATCHER(hasIncrement); REGISTER_MATCHER(hasIndex); REGISTER_MATCHER(hasInitializer); REGISTER_MATCHER(hasLHS); REGISTER_MATCHER(hasLocalQualifiers); REGISTER_MATCHER(hasLoopInit); REGISTER_MATCHER(hasMethod); REGISTER_MATCHER(hasName); REGISTER_MATCHER(hasObjectExpression); REGISTER_MATCHER(hasOperatorName); REGISTER_MATCHER(hasOverloadedOperatorName); REGISTER_MATCHER(hasParameter); REGISTER_MATCHER(hasParent); REGISTER_MATCHER(hasQualifier); REGISTER_MATCHER(hasRHS); REGISTER_MATCHER(hasSingleDecl); REGISTER_MATCHER(hasSize); REGISTER_MATCHER(hasSizeExpr); REGISTER_MATCHER(hasSourceExpression); REGISTER_MATCHER(hasTargetDecl); REGISTER_MATCHER(hasTemplateArgument); REGISTER_MATCHER(hasTrueExpression); REGISTER_MATCHER(hasUnaryOperand); REGISTER_MATCHER(hasValueType); REGISTER_MATCHER(ifStmt); REGISTER_MATCHER(ignoringImpCasts); REGISTER_MATCHER(ignoringParenCasts); REGISTER_MATCHER(ignoringParenImpCasts); REGISTER_MATCHER(implicitCastExpr); REGISTER_MATCHER(incompleteArrayType); REGISTER_MATCHER(initListExpr); REGISTER_MATCHER(innerType); REGISTER_MATCHER(integerLiteral); REGISTER_MATCHER(isArrow); REGISTER_MATCHER(isConstQualified); REGISTER_MATCHER(isDefinition); REGISTER_MATCHER(isExplicitTemplateSpecialization); REGISTER_MATCHER(isExternC); REGISTER_MATCHER(isImplicit); REGISTER_MATCHER(isInteger); REGISTER_MATCHER(isOverride); REGISTER_MATCHER(isPrivate); REGISTER_MATCHER(isProtected); REGISTER_MATCHER(isPublic); REGISTER_MATCHER(isTemplateInstantiation); REGISTER_MATCHER(isVirtual); REGISTER_MATCHER(isWritten); REGISTER_MATCHER(lValueReferenceType); REGISTER_MATCHER(labelStmt); REGISTER_MATCHER(lambdaExpr); REGISTER_MATCHER(matchesName); REGISTER_MATCHER(materializeTemporaryExpr); REGISTER_MATCHER(member); REGISTER_MATCHER(memberCallExpr); REGISTER_MATCHER(memberExpr); REGISTER_MATCHER(memberPointerType); REGISTER_MATCHER(methodDecl); REGISTER_MATCHER(namedDecl); REGISTER_MATCHER(namesType); REGISTER_MATCHER(namespaceDecl); REGISTER_MATCHER(nestedNameSpecifier); REGISTER_MATCHER(nestedNameSpecifierLoc); REGISTER_MATCHER(newExpr); REGISTER_MATCHER(nullPtrLiteralExpr); REGISTER_MATCHER(nullStmt); REGISTER_MATCHER(ofClass); REGISTER_MATCHER(on); REGISTER_MATCHER(onImplicitObjectArgument); REGISTER_MATCHER(operatorCallExpr); REGISTER_MATCHER(parameterCountIs); REGISTER_MATCHER(parenType); REGISTER_MATCHER(pointee); REGISTER_MATCHER(pointerType); REGISTER_MATCHER(qualType); REGISTER_MATCHER(rValueReferenceType); REGISTER_MATCHER(recordDecl); REGISTER_MATCHER(recordType); REGISTER_MATCHER(referenceType); REGISTER_MATCHER(refersToDeclaration); REGISTER_MATCHER(refersToType); REGISTER_MATCHER(reinterpretCastExpr); REGISTER_MATCHER(returnStmt); REGISTER_MATCHER(returns); REGISTER_MATCHER(sizeOfExpr); REGISTER_MATCHER(specifiesNamespace); REGISTER_MATCHER(specifiesType); REGISTER_MATCHER(specifiesTypeLoc); REGISTER_MATCHER(statementCountIs); REGISTER_MATCHER(staticCastExpr); REGISTER_MATCHER(stmt); REGISTER_MATCHER(stringLiteral); REGISTER_MATCHER(switchCase); REGISTER_MATCHER(switchStmt); REGISTER_MATCHER(templateSpecializationType); REGISTER_MATCHER(thisExpr); REGISTER_MATCHER(throughUsingDecl); REGISTER_MATCHER(throwExpr); REGISTER_MATCHER(to); REGISTER_MATCHER(tryStmt); REGISTER_MATCHER(type); REGISTER_MATCHER(typeLoc); REGISTER_MATCHER(typedefType); REGISTER_MATCHER(unaryExprOrTypeTraitExpr); REGISTER_MATCHER(unaryOperator); REGISTER_MATCHER(unless); REGISTER_MATCHER(userDefinedLiteral); REGISTER_MATCHER(usingDecl); REGISTER_MATCHER(varDecl); REGISTER_MATCHER(variableArrayType); REGISTER_MATCHER(whileStmt); REGISTER_MATCHER(withInitializer); } RegistryMaps::~RegistryMaps() { for (ConstructorMap::iterator it = Constructors.begin(), end = Constructors.end(); it != end; ++it) { delete it->second; } } static llvm::ManagedStatic<RegistryMaps> RegistryData; } // anonymous namespace // static llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName, const SourceRange &NameRange, Diagnostics *Error) { ConstructorMap::const_iterator it = RegistryData->constructors().find(MatcherName); if (it == RegistryData->constructors().end()) { Error->addError(NameRange, Error->ET_RegistryNotFound) << MatcherName; return llvm::Optional<MatcherCtor>(); } return it->second; } // static VariantMatcher Registry::constructMatcher(MatcherCtor Ctor, const SourceRange &NameRange, ArrayRef<ParserValue> Args, Diagnostics *Error) { return Ctor->create(NameRange, Args, Error); } // static VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID, ArrayRef<ParserValue> Args, Diagnostics *Error) { VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error); if (Out.isNull()) return Out; llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher(); if (Result.hasValue()) { llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); if (Bound.hasValue()) { return VariantMatcher::SingleMatcher(*Bound); } } Error->addError(NameRange, Error->ET_RegistryNotBindable); return VariantMatcher(); } } // namespace dynamic } // namespace ast_matchers } // namespace clang <commit_msg>Another pass at adding missing matchers into the registry.<commit_after>//===--- Registry.cpp - Matcher registry -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===------------------------------------------------------------===// /// /// \file /// \brief Registry map populated at static initialization time. /// //===------------------------------------------------------------===// #include "clang/ASTMatchers/Dynamic/Registry.h" #include <utility> #include "Marshallers.h" #include "clang/ASTMatchers/ASTMatchers.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ManagedStatic.h" namespace clang { namespace ast_matchers { namespace dynamic { namespace { using internal::MatcherDescriptor; typedef llvm::StringMap<const MatcherDescriptor *> ConstructorMap; class RegistryMaps { public: RegistryMaps(); ~RegistryMaps(); const ConstructorMap &constructors() const { return Constructors; } private: void registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback); ConstructorMap Constructors; }; void RegistryMaps::registerMatcher(StringRef MatcherName, MatcherDescriptor *Callback) { assert(Constructors.find(MatcherName) == Constructors.end()); Constructors[MatcherName] = Callback; } #define REGISTER_MATCHER(name) \ registerMatcher(#name, internal::makeMatcherAutoMarshall( \ ::clang::ast_matchers::name, #name)); #define SPECIFIC_MATCHER_OVERLOAD(name, Id) \ static_cast< ::clang::ast_matchers::name##_Type##Id>( \ ::clang::ast_matchers::name) #define REGISTER_OVERLOADED_2(name) \ do { \ MatcherDescriptor *Callbacks[] = { \ internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 0), \ #name), \ internal::makeMatcherAutoMarshall(SPECIFIC_MATCHER_OVERLOAD(name, 1), \ #name) \ }; \ registerMatcher(#name, \ new internal::OverloadedMatcherDescriptor(Callbacks)); \ } while (0) /// \brief Generate a registry map with all the known matchers. RegistryMaps::RegistryMaps() { // TODO: Here is the list of the missing matchers, grouped by reason. // // Need Variant/Parser fixes: // ofKind // // Polymorphic + argument overload: // findAll // // Other: // loc // equals // equalsNode REGISTER_OVERLOADED_2(callee); REGISTER_OVERLOADED_2(hasPrefix); REGISTER_OVERLOADED_2(hasType); REGISTER_OVERLOADED_2(isDerivedFrom); REGISTER_OVERLOADED_2(isSameOrDerivedFrom); REGISTER_OVERLOADED_2(pointsTo); REGISTER_OVERLOADED_2(references); REGISTER_OVERLOADED_2(thisPointerType); REGISTER_MATCHER(accessSpecDecl); REGISTER_MATCHER(alignOfExpr); REGISTER_MATCHER(allOf); REGISTER_MATCHER(anyOf); REGISTER_MATCHER(anything); REGISTER_MATCHER(argumentCountIs); REGISTER_MATCHER(arraySubscriptExpr); REGISTER_MATCHER(arrayType); REGISTER_MATCHER(asString); REGISTER_MATCHER(asmStmt); REGISTER_MATCHER(atomicType); REGISTER_MATCHER(autoType); REGISTER_MATCHER(binaryOperator); REGISTER_MATCHER(bindTemporaryExpr); REGISTER_MATCHER(blockPointerType); REGISTER_MATCHER(boolLiteral); REGISTER_MATCHER(breakStmt); REGISTER_MATCHER(builtinType); REGISTER_MATCHER(cStyleCastExpr); REGISTER_MATCHER(callExpr); REGISTER_MATCHER(caseStmt); REGISTER_MATCHER(castExpr); REGISTER_MATCHER(catchStmt); REGISTER_MATCHER(characterLiteral); REGISTER_MATCHER(classTemplateDecl); REGISTER_MATCHER(classTemplateSpecializationDecl); REGISTER_MATCHER(complexType); REGISTER_MATCHER(compoundLiteralExpr); REGISTER_MATCHER(compoundStmt); REGISTER_MATCHER(conditionalOperator); REGISTER_MATCHER(constCastExpr); REGISTER_MATCHER(constantArrayType); REGISTER_MATCHER(constructExpr); REGISTER_MATCHER(constructorDecl); REGISTER_MATCHER(containsDeclaration); REGISTER_MATCHER(continueStmt); REGISTER_MATCHER(ctorInitializer); REGISTER_MATCHER(decl); REGISTER_MATCHER(declCountIs); REGISTER_MATCHER(declRefExpr); REGISTER_MATCHER(declStmt); REGISTER_MATCHER(declaratorDecl); REGISTER_MATCHER(defaultArgExpr); REGISTER_MATCHER(defaultStmt); REGISTER_MATCHER(deleteExpr); REGISTER_MATCHER(dependentSizedArrayType); REGISTER_MATCHER(destructorDecl); REGISTER_MATCHER(doStmt); REGISTER_MATCHER(dynamicCastExpr); REGISTER_MATCHER(eachOf); REGISTER_MATCHER(elaboratedType); REGISTER_MATCHER(enumConstantDecl); REGISTER_MATCHER(enumDecl); REGISTER_MATCHER(equalsBoundNode); REGISTER_MATCHER(explicitCastExpr); REGISTER_MATCHER(expr); REGISTER_MATCHER(fieldDecl); REGISTER_MATCHER(floatLiteral); REGISTER_MATCHER(forEach); REGISTER_MATCHER(forEachConstructorInitializer); REGISTER_MATCHER(forEachDescendant); REGISTER_MATCHER(forEachSwitchCase); REGISTER_MATCHER(forField); REGISTER_MATCHER(forRangeStmt); REGISTER_MATCHER(forStmt); REGISTER_MATCHER(friendDecl); REGISTER_MATCHER(functionDecl); REGISTER_MATCHER(functionTemplateDecl); REGISTER_MATCHER(functionType); REGISTER_MATCHER(functionalCastExpr); REGISTER_MATCHER(gotoStmt); REGISTER_MATCHER(has); REGISTER_MATCHER(hasAncestor); REGISTER_MATCHER(hasAnyArgument); REGISTER_MATCHER(hasAnyConstructorInitializer); REGISTER_MATCHER(hasAnyParameter); REGISTER_MATCHER(hasAnySubstatement); REGISTER_MATCHER(hasAnyTemplateArgument); REGISTER_MATCHER(hasAnyUsingShadowDecl); REGISTER_MATCHER(hasArgument); REGISTER_MATCHER(hasArgumentOfType); REGISTER_MATCHER(hasBase); REGISTER_MATCHER(hasBody); REGISTER_MATCHER(hasCanonicalType); REGISTER_MATCHER(hasCaseConstant); REGISTER_MATCHER(hasCondition); REGISTER_MATCHER(hasConditionVariableStatement); REGISTER_MATCHER(hasDeclContext); REGISTER_MATCHER(hasDeclaration); REGISTER_MATCHER(hasDeducedType); REGISTER_MATCHER(hasDescendant); REGISTER_MATCHER(hasDestinationType); REGISTER_MATCHER(hasEitherOperand); REGISTER_MATCHER(hasElementType); REGISTER_MATCHER(hasFalseExpression); REGISTER_MATCHER(hasImplicitDestinationType); REGISTER_MATCHER(hasIncrement); REGISTER_MATCHER(hasIndex); REGISTER_MATCHER(hasInitializer); REGISTER_MATCHER(hasLHS); REGISTER_MATCHER(hasLocalQualifiers); REGISTER_MATCHER(hasLoopInit); REGISTER_MATCHER(hasMethod); REGISTER_MATCHER(hasName); REGISTER_MATCHER(hasObjectExpression); REGISTER_MATCHER(hasOperatorName); REGISTER_MATCHER(hasOverloadedOperatorName); REGISTER_MATCHER(hasParameter); REGISTER_MATCHER(hasParent); REGISTER_MATCHER(hasQualifier); REGISTER_MATCHER(hasRHS); REGISTER_MATCHER(hasSingleDecl); REGISTER_MATCHER(hasSize); REGISTER_MATCHER(hasSizeExpr); REGISTER_MATCHER(hasSourceExpression); REGISTER_MATCHER(hasTargetDecl); REGISTER_MATCHER(hasTemplateArgument); REGISTER_MATCHER(hasTrueExpression); REGISTER_MATCHER(hasTypeLoc); REGISTER_MATCHER(hasUnaryOperand); REGISTER_MATCHER(hasValueType); REGISTER_MATCHER(ifStmt); REGISTER_MATCHER(ignoringImpCasts); REGISTER_MATCHER(ignoringParenCasts); REGISTER_MATCHER(ignoringParenImpCasts); REGISTER_MATCHER(implicitCastExpr); REGISTER_MATCHER(incompleteArrayType); REGISTER_MATCHER(initListExpr); REGISTER_MATCHER(innerType); REGISTER_MATCHER(integerLiteral); REGISTER_MATCHER(isArrow); REGISTER_MATCHER(isConst); REGISTER_MATCHER(isConstQualified); REGISTER_MATCHER(isDefinition); REGISTER_MATCHER(isExplicitTemplateSpecialization); REGISTER_MATCHER(isExternC); REGISTER_MATCHER(isImplicit); REGISTER_MATCHER(isInteger); REGISTER_MATCHER(isOverride); REGISTER_MATCHER(isPrivate); REGISTER_MATCHER(isProtected); REGISTER_MATCHER(isPublic); REGISTER_MATCHER(isTemplateInstantiation); REGISTER_MATCHER(isVirtual); REGISTER_MATCHER(isWritten); REGISTER_MATCHER(lValueReferenceType); REGISTER_MATCHER(labelStmt); REGISTER_MATCHER(lambdaExpr); REGISTER_MATCHER(matchesName); REGISTER_MATCHER(materializeTemporaryExpr); REGISTER_MATCHER(member); REGISTER_MATCHER(memberCallExpr); REGISTER_MATCHER(memberExpr); REGISTER_MATCHER(memberPointerType); REGISTER_MATCHER(methodDecl); REGISTER_MATCHER(namedDecl); REGISTER_MATCHER(namesType); REGISTER_MATCHER(namespaceDecl); REGISTER_MATCHER(nestedNameSpecifier); REGISTER_MATCHER(nestedNameSpecifierLoc); REGISTER_MATCHER(newExpr); REGISTER_MATCHER(nullPtrLiteralExpr); REGISTER_MATCHER(nullStmt); REGISTER_MATCHER(ofClass); REGISTER_MATCHER(on); REGISTER_MATCHER(onImplicitObjectArgument); REGISTER_MATCHER(operatorCallExpr); REGISTER_MATCHER(parameterCountIs); REGISTER_MATCHER(parenType); REGISTER_MATCHER(parmVarDecl); REGISTER_MATCHER(pointee); REGISTER_MATCHER(pointerType); REGISTER_MATCHER(qualType); REGISTER_MATCHER(rValueReferenceType); REGISTER_MATCHER(recordDecl); REGISTER_MATCHER(recordType); REGISTER_MATCHER(referenceType); REGISTER_MATCHER(refersToDeclaration); REGISTER_MATCHER(refersToType); REGISTER_MATCHER(reinterpretCastExpr); REGISTER_MATCHER(returnStmt); REGISTER_MATCHER(returns); REGISTER_MATCHER(sizeOfExpr); REGISTER_MATCHER(specifiesNamespace); REGISTER_MATCHER(specifiesType); REGISTER_MATCHER(specifiesTypeLoc); REGISTER_MATCHER(statementCountIs); REGISTER_MATCHER(staticCastExpr); REGISTER_MATCHER(stmt); REGISTER_MATCHER(stringLiteral); REGISTER_MATCHER(switchCase); REGISTER_MATCHER(switchStmt); REGISTER_MATCHER(templateSpecializationType); REGISTER_MATCHER(temporaryObjectExpr); REGISTER_MATCHER(thisExpr); REGISTER_MATCHER(throughUsingDecl); REGISTER_MATCHER(throwExpr); REGISTER_MATCHER(to); REGISTER_MATCHER(tryStmt); REGISTER_MATCHER(type); REGISTER_MATCHER(typeLoc); REGISTER_MATCHER(typedefType); REGISTER_MATCHER(unaryExprOrTypeTraitExpr); REGISTER_MATCHER(unaryOperator); REGISTER_MATCHER(unaryTransformType); REGISTER_MATCHER(unless); REGISTER_MATCHER(unresolvedConstructExpr); REGISTER_MATCHER(unresolvedUsingValueDecl); REGISTER_MATCHER(userDefinedLiteral); REGISTER_MATCHER(usingDecl); REGISTER_MATCHER(varDecl); REGISTER_MATCHER(variableArrayType); REGISTER_MATCHER(whileStmt); REGISTER_MATCHER(withInitializer); } RegistryMaps::~RegistryMaps() { for (ConstructorMap::iterator it = Constructors.begin(), end = Constructors.end(); it != end; ++it) { delete it->second; } } static llvm::ManagedStatic<RegistryMaps> RegistryData; } // anonymous namespace // static llvm::Optional<MatcherCtor> Registry::lookupMatcherCtor(StringRef MatcherName, const SourceRange &NameRange, Diagnostics *Error) { ConstructorMap::const_iterator it = RegistryData->constructors().find(MatcherName); if (it == RegistryData->constructors().end()) { Error->addError(NameRange, Error->ET_RegistryNotFound) << MatcherName; return llvm::Optional<MatcherCtor>(); } return it->second; } // static VariantMatcher Registry::constructMatcher(MatcherCtor Ctor, const SourceRange &NameRange, ArrayRef<ParserValue> Args, Diagnostics *Error) { return Ctor->create(NameRange, Args, Error); } // static VariantMatcher Registry::constructBoundMatcher(MatcherCtor Ctor, const SourceRange &NameRange, StringRef BindID, ArrayRef<ParserValue> Args, Diagnostics *Error) { VariantMatcher Out = constructMatcher(Ctor, NameRange, Args, Error); if (Out.isNull()) return Out; llvm::Optional<DynTypedMatcher> Result = Out.getSingleMatcher(); if (Result.hasValue()) { llvm::Optional<DynTypedMatcher> Bound = Result->tryBind(BindID); if (Bound.hasValue()) { return VariantMatcher::SingleMatcher(*Bound); } } Error->addError(NameRange, Error->ET_RegistryNotBindable); return VariantMatcher(); } } // namespace dynamic } // namespace ast_matchers } // namespace clang <|endoftext|>
<commit_before>#include "channel.h" #include "emotes.h" #include "logging/loggingmanager.h" #include "messages/message.h" #include "windows.h" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <memory> namespace chatterino { Channel::Channel(const QString &channel) : messages() , name((channel.length() > 0 && channel[0] == '#') ? channel.mid(1) : channel) , bttvChannelEmotes() , ffzChannelEmotes() , subLink("https://www.twitch.tv/" + name + "/subscribe?ref=in_chat_subscriber_link") , channelLink("https://twitch.tv/" + name) , popoutPlayerLink("https://player.twitch.tv/?channel=" + name) , loggingChannel(logging::get(name)) { reloadChannelEmotes(); } void Channel::reloadBttvEmotes() { // bttv QNetworkAccessManager *manager = new QNetworkAccessManager(); QUrl url("https://api.betterttv.net/2/channels/" + this->name); QNetworkRequest request(url); QNetworkReply *reply = manager->get(request); QObject::connect(reply, &QNetworkReply::finished, [=] { if (reply->error() == QNetworkReply::NetworkError::NoError) { QByteArray data = reply->readAll(); QJsonDocument jsonDoc(QJsonDocument::fromJson(data)); QJsonObject root = jsonDoc.object(); auto emotes = root.value("emotes").toArray(); QString _template = "https:" + root.value("urlTemplate").toString(); for (const QJsonValue &emote : emotes) { QString id = emote.toObject().value("id").toString(); QString code = emote.toObject().value("code").toString(); // emote.value("imageType").toString(); QString tmp = _template; tmp.detach(); QString url = tmp.replace("{{id}}", id).replace("{{image}}", "1x"); this->getBttvChannelEmotes().insert( code, Emotes::getBttvChannelEmoteFromCaches().getOrAdd( id, [&code, &url] { return new messages::LazyLoadedImage( url, 1, code, code + "\nChannel Bttv Emote"); })); } } reply->deleteLater(); manager->deleteLater(); }); } void Channel::reloadFfzEmotes() { QNetworkAccessManager *manager = new QNetworkAccessManager(); QUrl url("http://api.frankerfacez.com/v1/room/" + this->name); QNetworkRequest request(url); QNetworkReply *reply = manager->get(request); QObject::connect(reply, &QNetworkReply::finished, [=] { if (reply->error() == QNetworkReply::NetworkError::NoError) { QByteArray data = reply->readAll(); QJsonDocument jsonDoc(QJsonDocument::fromJson(data)); QJsonObject root = jsonDoc.object(); auto sets = root.value("sets").toObject(); for (const QJsonValue &set : sets) { auto emoticons = set.toObject().value("emoticons").toArray(); for (const QJsonValue &emote : emoticons) { QJsonObject object = emote.toObject(); // margins int id = object.value("id").toInt(); QString code = object.value("name").toString(); QJsonObject urls = object.value("urls").toObject(); QString url1 = "http:" + urls.value("1").toString(); this->getFfzChannelEmotes().insert( code, Emotes::getFfzChannelEmoteFromCaches().getOrAdd( id, [&code, &url1] { return new messages::LazyLoadedImage( url1, 1, code, code + "\nGlobal Ffz Emote"); })); } } } reply->deleteLater(); manager->deleteLater(); }); } void Channel::addMessage(std::shared_ptr<messages::Message> message) { std::shared_ptr<messages::Message> deleted; if (this->loggingChannel.get() != nullptr) { this->loggingChannel->append(message); } if (this->messages.appendItem(message, deleted)) { this->messageRemovedFromStart(deleted); } this->messageAppended(message); Windows::repaintVisibleChatWidgets(this); } } // namespace chatterino <commit_msg>reformat channel.cpp KKona<commit_after>#include "channel.h" #include "emotes.h" #include "logging/loggingmanager.h" #include "messages/message.h" #include "windows.h" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> #include <memory> namespace chatterino { Channel::Channel(const QString &channel) : messages() , name((channel.length() > 0 && channel[0] == '#') ? channel.mid(1) : channel) , bttvChannelEmotes() , ffzChannelEmotes() , subLink("https://www.twitch.tv/" + name + "/subscribe?ref=in_chat_subscriber_link") , channelLink("https://twitch.tv/" + name) , popoutPlayerLink("https://player.twitch.tv/?channel=" + name) , loggingChannel(logging::get(name)) { reloadChannelEmotes(); } void Channel::reloadBttvEmotes() { // bttv QNetworkAccessManager *manager = new QNetworkAccessManager(); QUrl url("https://api.betterttv.net/2/channels/" + this->name); QNetworkRequest request(url); QNetworkReply *reply = manager->get(request); QObject::connect(reply, &QNetworkReply::finished, [=] { if (reply->error() == QNetworkReply::NetworkError::NoError) { QByteArray data = reply->readAll(); QJsonDocument jsonDoc(QJsonDocument::fromJson(data)); QJsonObject root = jsonDoc.object(); auto emotes = root.value("emotes").toArray(); QString _template = "https:" + root.value("urlTemplate").toString(); for (const QJsonValue &emote : emotes) { QString id = emote.toObject().value("id").toString(); QString code = emote.toObject().value("code").toString(); // emote.value("imageType").toString(); QString tmp = _template; tmp.detach(); QString url = tmp.replace("{{id}}", id).replace("{{image}}", "1x"); this->getBttvChannelEmotes().insert( code, Emotes::getBttvChannelEmoteFromCaches().getOrAdd( id, [&code, &url] { return new messages::LazyLoadedImage( url, 1, code, code + "\nChannel Bttv Emote"); })); } } reply->deleteLater(); manager->deleteLater(); }); } void Channel::reloadFfzEmotes() { QNetworkAccessManager *manager = new QNetworkAccessManager(); QUrl url("http://api.frankerfacez.com/v1/room/" + this->name); QNetworkRequest request(url); QNetworkReply *reply = manager->get(request); QObject::connect(reply, &QNetworkReply::finished, [=] { if (reply->error() == QNetworkReply::NetworkError::NoError) { QByteArray data = reply->readAll(); QJsonDocument jsonDoc(QJsonDocument::fromJson(data)); QJsonObject root = jsonDoc.object(); auto sets = root.value("sets").toObject(); for (const QJsonValue &set : sets) { auto emoticons = set.toObject().value("emoticons").toArray(); for (const QJsonValue &emote : emoticons) { QJsonObject object = emote.toObject(); // margins int id = object.value("id").toInt(); QString code = object.value("name").toString(); QJsonObject urls = object.value("urls").toObject(); QString url1 = "http:" + urls.value("1").toString(); this->getFfzChannelEmotes().insert( code, Emotes::getFfzChannelEmoteFromCaches().getOrAdd( id, [&code, &url1] { return new messages::LazyLoadedImage( url1, 1, code, code + "\nGlobal Ffz Emote"); })); } } } reply->deleteLater(); manager->deleteLater(); }); } void Channel::addMessage(std::shared_ptr<messages::Message> message) { std::shared_ptr<messages::Message> deleted; if (this->loggingChannel.get() != nullptr) { this->loggingChannel->append(message); } if (this->messages.appendItem(message, deleted)) { this->messageRemovedFromStart(deleted); } this->messageAppended(message); Windows::repaintVisibleChatWidgets(this); } } // namespace chatterino <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CLIENT_COMMON_CLIENT_HPP_ #define JUBATUS_CLIENT_COMMON_CLIENT_HPP_ #include <stdint.h> #include <map> #include <string> #include <jubatus/msgpack/rpc/client.h> namespace jubatus { namespace client { namespace common { class client { public: client(const std::string& host, uint64_t port, const std::string& name, unsigned int timeout_sec) : c_(host, port), name_(name) { c_.set_timeout(timeout_sec); } msgpack::rpc::client& get_client() { return c_; } std::string get_config() { msgpack::rpc::future f = c_.call("get_config", name_); return f.get<std::string>(); } bool save(const std::string& id) { msgpack::rpc::future f = c_.call("save", name_, id); return f.get<bool>(); } bool load(const std::string& id) { msgpack::rpc::future f = c_.call("load", name_, id); return f.get<bool>(); } std::map<std::string, std::map<std::string, std::string> > get_status() { msgpack::rpc::future f = c_.call("get_status", name_); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } std::map<std::string, std::map<std::string, std::string> > get_proxy_status() { msgpack::rpc::future f = c_.call("get_proxy_status"); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } protected: msgpack::rpc::client c_; std::string name_; }; } // namespace common } // namespace client } // namespace jubatus #endif // JUBATUS_CLIENT_COMMON_CLIENT_HPP_ <commit_msg>Fix for cpplint<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License version 2.1 as published by the Free Software Foundation. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #ifndef JUBATUS_CLIENT_COMMON_CLIENT_HPP_ #define JUBATUS_CLIENT_COMMON_CLIENT_HPP_ #include <stdint.h> #include <map> #include <string> #include <jubatus/msgpack/rpc/client.h> namespace jubatus { namespace client { namespace common { class client { public: client(const std::string& host, uint64_t port, const std::string& name, unsigned int timeout_sec) : c_(host, port), name_(name) { c_.set_timeout(timeout_sec); } msgpack::rpc::client& get_client() { return c_; } std::string get_config() { msgpack::rpc::future f = c_.call("get_config", name_); return f.get<std::string>(); } bool save(const std::string& id) { msgpack::rpc::future f = c_.call("save", name_, id); return f.get<bool>(); } bool load(const std::string& id) { msgpack::rpc::future f = c_.call("load", name_, id); return f.get<bool>(); } std::map<std::string, std::map<std::string, std::string> > get_status() { msgpack::rpc::future f = c_.call("get_status", name_); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } std::map<std::string, std::map<std::string, std::string> > get_proxy_status() { msgpack::rpc::future f = c_.call("get_proxy_status"); return f.get<std::map<std::string, std::map<std::string, std::string> > >(); } protected: msgpack::rpc::client c_; std::string name_; }; } // namespace common } // namespace client } // namespace jubatus #endif // JUBATUS_CLIENT_COMMON_CLIENT_HPP_ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <utility> #include "compute.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "accounts.hpp" budget::status budget::compute_year_status(){ auto today = budget::local_day(); return compute_year_status(today.year(), today.month()); } budget::status budget::compute_year_status(year year){ return compute_year_status(year, 12); } budget::status budget::compute_year_status(year year, month month){ budget::status status; auto sm = start_month(year); for(auto& expense : all_expenses()){ if(expense.date.year() == year && expense.date.month() >= sm && expense.date.month() <= month){ status.expenses += expense.amount; } } budget::money year_earnings; for(auto& earning : all_earnings()){ if(earning.date.year() == year && earning.date.month() >= sm && earning.date.month() <= month){ status.earnings += earning.amount; } } for(unsigned short i = sm; i <= month; ++i){ budget::month month = i; for(auto& c : all_accounts(year, month)){ status.budget += c.amount; } } status.balance = status.budget + status.earnings - status.expenses; return status; } budget::status budget::compute_month_status(){ auto today = budget::local_day(); return compute_month_status(today.year(), today.month()); } budget::status budget::compute_month_status(month month){ auto today = budget::local_day(); return compute_month_status(today.year(), month); } budget::status budget::compute_month_status(year year, month month){ budget::status status; for(auto& expense : all_expenses()){ if(expense.date.year() == year && expense.date.month() == month){ status.expenses += expense.amount; } } for(auto& earning : all_earnings()){ if(earning.date.year() == year && earning.date.month() == month){ status.earnings += earning.amount; } } for(auto& c : all_accounts(year, month)){ status.budget += c.amount; } status.balance = status.budget + status.earnings - status.expenses; return std::move(status); } budget::status budget::compute_avg_month_status(){ auto today = budget::local_day(); return compute_avg_month_status(today.year(), today.month()); } budget::status budget::compute_avg_month_status(month month){ auto today = budget::local_day(); return compute_avg_month_status(today.year(), month); } budget::status budget::compute_avg_month_status(year year, month month){ budget::status avg_status; for(budget::month m = 1; m < month; m = m + 1){ auto status = compute_month_status(year, m); avg_status.expenses += status.expenses; avg_status.earnings += status.earnings; avg_status.budget += status.budget; avg_status.balance += status.balance; } avg_status.expenses /= month.value; avg_status.earnings /= month.value; avg_status.budget /= month.value; avg_status.balance /= month.value; return std::move(avg_status); } <commit_msg>Fix average status computation<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <utility> #include "compute.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "accounts.hpp" budget::status budget::compute_year_status(){ auto today = budget::local_day(); return compute_year_status(today.year(), today.month()); } budget::status budget::compute_year_status(year year){ return compute_year_status(year, 12); } budget::status budget::compute_year_status(year year, month month){ budget::status status; auto sm = start_month(year); for(auto& expense : all_expenses()){ if(expense.date.year() == year && expense.date.month() >= sm && expense.date.month() <= month){ status.expenses += expense.amount; } } budget::money year_earnings; for(auto& earning : all_earnings()){ if(earning.date.year() == year && earning.date.month() >= sm && earning.date.month() <= month){ status.earnings += earning.amount; } } for(unsigned short i = sm; i <= month; ++i){ budget::month month = i; for(auto& c : all_accounts(year, month)){ status.budget += c.amount; } } status.balance = status.budget + status.earnings - status.expenses; return status; } budget::status budget::compute_month_status(){ auto today = budget::local_day(); return compute_month_status(today.year(), today.month()); } budget::status budget::compute_month_status(month month){ auto today = budget::local_day(); return compute_month_status(today.year(), month); } budget::status budget::compute_month_status(year year, month month){ budget::status status; for(auto& expense : all_expenses()){ if(expense.date.year() == year && expense.date.month() == month){ status.expenses += expense.amount; } } for(auto& earning : all_earnings()){ if(earning.date.year() == year && earning.date.month() == month){ status.earnings += earning.amount; } } for(auto& c : all_accounts(year, month)){ status.budget += c.amount; } status.balance = status.budget + status.earnings - status.expenses; return std::move(status); } budget::status budget::compute_avg_month_status(){ auto today = budget::local_day(); return compute_avg_month_status(today.year(), today.month()); } budget::status budget::compute_avg_month_status(month month){ auto today = budget::local_day(); return compute_avg_month_status(today.year(), month); } budget::status budget::compute_avg_month_status(year year, month month){ budget::status avg_status; for(budget::month m = 1; m < month; m = m + 1){ auto status = compute_month_status(year, m); avg_status.expenses += status.expenses; avg_status.earnings += status.earnings; avg_status.budget += status.budget; avg_status.balance += status.balance; } if(month.value > 1){ avg_status.expenses /= month.value - 1; avg_status.earnings /= month.value - 1; avg_status.budget /= month.value - 1; avg_status.balance /= month.value - 1; } return std::move(avg_status); } <|endoftext|>
<commit_before>#include <iostream> #include <SLRenderer/SLRenderer.hpp> #include <glfw/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // main int main(int argc, char** argv) { ////////////////////////////////////////////////////////////////////////// // set error handling glfwSetErrorCallback([](int error, const char* description) { std::cout << "Error: " << description << std::endl; }); // init glfw glfwInit(); // select OpenGL ES version glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); // // select OpenGL version // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // create window GLFWwindow* window = glfwCreateWindow(800, 600, "GLFW OpenGL3", nullptr, nullptr); // set current context glfwMakeContextCurrent(window); // setup thescene ready for rendering int width = 0, height = 0; glfwGetFramebufferSize(window, &width, &height); ////////////////////////////////////////////////////////////////////////// // create renderer ISLRenderer* renderer = SLRendererFabric::CreateRenderer(SL_RENDERER_TYPE_GL3); std::cout << renderer->GetDescription() << std::endl; // create buffers ISLBuffer* positionBuffer = renderer->CreateBuffer(nullptr, 1024); ISLBuffer* noramlBuffer = renderer->CreateBuffer(nullptr, 1024); ISLIndexBuffer* indexBuffer = renderer->CreateIndexBuffer(nullptr, 1024); // create texture ISLTexture2D* baseTexture = renderer->CreateTexture2D(nullptr, 0, 1, 1, SL_PIXEL_DATA_TYPE_RGRA); // create mesh and setup buffers ISLMesh* mesh = renderer->CreateMesh(); mesh->SetPositionBuffer(positionBuffer); mesh->SetNormalBuffer(noramlBuffer); mesh->SetIndexBuffer(indexBuffer); mesh->SetBaseTexture(baseTexture); mesh->SetBaseColor(1.0f, 1.0f, 1.0f, 1.0f); // create model glm::mat4 transform(1.0f); ISLModel* model = renderer->CreateModel(); model->AddMesh(mesh); model->SetTransform(&transform[0][0]); model->SetVisibilityMode(SL_MESH_GROUP_VISIBILITY_MODE_VISIBLE); // create camera glm::mat4 matProj = glm::lookAt(glm::vec3(0.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); ISLCamera* camera = renderer->CreateCamera(); camera->SetProjection(glm::value_ptr(matProj)); camera->SetNearPlane(0.1f); camera->SetFarPlane(100.0f); camera->SetViewport(800, 600); // create scene ISLScene* scene = renderer->CreateScene(); scene->AddModel(model); scene->SetCamera(camera); ////////////////////////////////////////////////////////////////////////// // main loop double dt = 0, last_update_time = 0; while (!glfwWindowShouldClose(window)) { // render! renderer->Render(); // display and process events through callbacks glfwSwapBuffers(window); glfwPollEvents(); // get frame time dt = glfwGetTime(); if ((dt - last_update_time) > 0.2) last_update_time = dt; } ////////////////////////////////////////////////////////////////////////// // delete camera renderer->DeleteCamera(camera); // delete model renderer->DeleteModel(model); // delete mesh renderer->DeleteMesh(mesh); // delete texture renderer->DeleteTexture2D(baseTexture); // delete buffers renderer->DeleteIndexBuffer(indexBuffer); renderer->DeleteBuffer(noramlBuffer); renderer->DeleteBuffer(positionBuffer); ////////////////////////////////////////////////////////////////////////// // exit glfwTerminate(); // exit return EXIT_SUCCESS; }<commit_msg>gles2 project fixed<commit_after>#include <iostream> #include <SLRenderer/SLRenderer.hpp> #include <glfw/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> // main int main(int argc, char** argv) { ////////////////////////////////////////////////////////////////////////// // set error handling glfwSetErrorCallback([](int error, const char* description) { std::cout << "Error: " << description << std::endl; }); // init glfw glfwInit(); // select OpenGL ES version glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API); glfwWindowHint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); // // select OpenGL version // glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); // create window GLFWwindow* window = glfwCreateWindow(800, 600, "GLFW OpenGLES2", nullptr, nullptr); // set current context glfwMakeContextCurrent(window); // setup thescene ready for rendering int width = 0, height = 0; glfwGetFramebufferSize(window, &width, &height); ////////////////////////////////////////////////////////////////////////// // create renderer ISLRenderer* renderer = SLRendererFabric::CreateRenderer(SL_RENDERER_TYPE_GLES2); std::cout << renderer->GetDescription() << std::endl; // create buffers ISLBuffer* positionBuffer = renderer->CreateBuffer(nullptr, 1024); ISLBuffer* noramlBuffer = renderer->CreateBuffer(nullptr, 1024); ISLIndexBuffer* indexBuffer = renderer->CreateIndexBuffer(nullptr, 1024); // create texture ISLTexture2D* baseTexture = renderer->CreateTexture2D(nullptr, 0, 1, 1, SL_PIXEL_DATA_TYPE_RGRA); // create mesh and setup buffers ISLMesh* mesh = renderer->CreateMesh(); mesh->SetPositionBuffer(positionBuffer); mesh->SetNormalBuffer(noramlBuffer); mesh->SetIndexBuffer(indexBuffer); mesh->SetBaseTexture(baseTexture); mesh->SetBaseColor(1.0f, 1.0f, 1.0f, 1.0f); // create model glm::mat4 transform(1.0f); ISLModel* model = renderer->CreateModel(); model->AddMesh(mesh); model->SetTransform(&transform[0][0]); model->SetVisibilityMode(SL_MESH_GROUP_VISIBILITY_MODE_VISIBLE); // create camera glm::mat4 matProj = glm::lookAt(glm::vec3(0.0f, -10.0f, 0.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); ISLCamera* camera = renderer->CreateCamera(); camera->SetProjection(glm::value_ptr(matProj)); camera->SetNearPlane(0.1f); camera->SetFarPlane(100.0f); camera->SetViewport(800, 600); // create scene ISLScene* scene = renderer->CreateScene(); scene->AddModel(model); scene->SetCamera(camera); ////////////////////////////////////////////////////////////////////////// // main loop double dt = 0, last_update_time = 0; while (!glfwWindowShouldClose(window)) { // render! renderer->Render(); // display and process events through callbacks glfwSwapBuffers(window); glfwPollEvents(); // get frame time dt = glfwGetTime(); if ((dt - last_update_time) > 0.2) last_update_time = dt; } ////////////////////////////////////////////////////////////////////////// // delete camera renderer->DeleteCamera(camera); // delete model renderer->DeleteModel(model); // delete mesh renderer->DeleteMesh(mesh); // delete texture renderer->DeleteTexture2D(baseTexture); // delete buffers renderer->DeleteIndexBuffer(indexBuffer); renderer->DeleteBuffer(noramlBuffer); renderer->DeleteBuffer(positionBuffer); ////////////////////////////////////////////////////////////////////////// // exit glfwTerminate(); // exit return EXIT_SUCCESS; }<|endoftext|>
<commit_before>#include "CarbonLibrary-WifiFork.h" SparkCarbon::SparkCarbon() { _carbonClient = NULL; } // IP address with port bool SparkCarbon::begin(TCPClient * carbonClient, IPAddress carbonServer, uint16_t carbonPort) { _carbonClient = carbonClient; _carbonServer = carbonServer; _carbonPort = carbonPort; return true; } // IP address without port bool SparkCarbon::begin(TCPClient * carbonClient, IPAddress carbonServer) { _carbonClient = carbonClient; _carbonServer = carbonServer; _carbonPort = 2003; return true; } // DNS name with port bool SparkCarbon::begin(TCPClient * carbonClient, const char *carbonServer, uint16_t carbonPort) { _carbonClient = carbonClient; _carbonPort = carbonPort; // Resolve DNS hostname // Adapted from: https://github.com/spark/core-firmware/blob/master/src/spark_wiring_tcpclient.cpp#L47-L63 uint32_t ip_addr = 0; _carbonServer = WiFi.resolve((char*)carbonServer); return true; // if(gethostbyname((char*)carbonServer, strlen(carbonServer), &ip_addr) > 0) { // IPAddress remote_addr(BYTE_N(ip_addr, 3), BYTE_N(ip_addr, 2), BYTE_N(ip_addr, 1), BYTE_N(ip_addr, 0)); // _carbonServer = remote_addr; // // return true; // } else // return false; } // DNS name without port bool SparkCarbon::begin(TCPClient * carbonClient, const char *carbonServer) { _carbonClient = carbonClient; _carbonPort = 2003; // Resolve DNS hostname // Adapted from: https://github.com/spark/core-firmware/blob/master/src/spark_wiring_tcpclient.cpp#L47-L63 uint32_t ip_addr = 0; if(gethostbyname((char*)carbonServer, strlen(carbonServer), &ip_addr) > 0) { IPAddress remote_addr(BYTE_N(ip_addr, 3), BYTE_N(ip_addr, 2), BYTE_N(ip_addr, 1), BYTE_N(ip_addr, 0)); _carbonServer = remote_addr; return true; } else return false; } // Send data with a string metric and a string value bool SparkCarbon::sendData(String carbonMetric, String carbonValue, uint32_t carbonTimestamp) { if(_carbonClient->connect(_carbonServer, _carbonPort)) { _carbonClient->print(carbonMetric); _carbonClient->print(" "); _carbonClient->print(carbonValue); _carbonClient->print(" "); _carbonClient->print(carbonTimestamp); _carbonClient->println(""); delay(10); _carbonClient->stop(); _carbonClient->flush(); return true; } else return false; } // Send data with a string metric and an integer value bool SparkCarbon::sendData(String carbonMetric, uint32_t carbonValue, uint32_t carbonTimestamp) { if(_carbonClient->connect(_carbonServer, _carbonPort)) { _carbonClient->print(carbonMetric); _carbonClient->print(" "); _carbonClient->print(carbonValue); _carbonClient->print(" "); _carbonClient->print(carbonTimestamp); _carbonClient->println(""); delay(10); _carbonClient->stop(); _carbonClient->flush(); return true; } else return false; } <commit_msg>Replace the other gethostbyname with WiFi.Resolve<commit_after>#include "CarbonLibrary-WifiFork.h" SparkCarbon::SparkCarbon() { _carbonClient = NULL; } // IP address with port bool SparkCarbon::begin(TCPClient * carbonClient, IPAddress carbonServer, uint16_t carbonPort) { _carbonClient = carbonClient; _carbonServer = carbonServer; _carbonPort = carbonPort; return true; } // IP address without port bool SparkCarbon::begin(TCPClient * carbonClient, IPAddress carbonServer) { _carbonClient = carbonClient; _carbonServer = carbonServer; _carbonPort = 2003; return true; } // DNS name with port bool SparkCarbon::begin(TCPClient * carbonClient, const char *carbonServer, uint16_t carbonPort) { _carbonClient = carbonClient; _carbonPort = carbonPort; // Resolve DNS hostname // Adapted from: https://github.com/spark/core-firmware/blob/master/src/spark_wiring_tcpclient.cpp#L47-L63 uint32_t ip_addr = 0; _carbonServer = WiFi.resolve((char*)carbonServer); return true; // if(gethostbyname((char*)carbonServer, strlen(carbonServer), &ip_addr) > 0) { // IPAddress remote_addr(BYTE_N(ip_addr, 3), BYTE_N(ip_addr, 2), BYTE_N(ip_addr, 1), BYTE_N(ip_addr, 0)); // _carbonServer = remote_addr; // // return true; // } else // return false; } // DNS name without port bool SparkCarbon::begin(TCPClient * carbonClient, const char *carbonServer) { _carbonClient = carbonClient; _carbonPort = 2003; // Resolve DNS hostname // Adapted from: https://github.com/spark/core-firmware/blob/master/src/spark_wiring_tcpclient.cpp#L47-L63 uint32_t ip_addr = 0; _carbonServer = WiFi.resolve((char*)carbonServer); return true; // if(gethostbyname((char*)carbonServer, strlen(carbonServer), &ip_addr) > 0) { // IPAddress remote_addr(BYTE_N(ip_addr, 3), BYTE_N(ip_addr, 2), BYTE_N(ip_addr, 1), BYTE_N(ip_addr, 0)); // _carbonServer = remote_addr; // // return true; // } else // return false; } // Send data with a string metric and a string value bool SparkCarbon::sendData(String carbonMetric, String carbonValue, uint32_t carbonTimestamp) { if(_carbonClient->connect(_carbonServer, _carbonPort)) { _carbonClient->print(carbonMetric); _carbonClient->print(" "); _carbonClient->print(carbonValue); _carbonClient->print(" "); _carbonClient->print(carbonTimestamp); _carbonClient->println(""); delay(10); _carbonClient->stop(); _carbonClient->flush(); return true; } else return false; } // Send data with a string metric and an integer value bool SparkCarbon::sendData(String carbonMetric, uint32_t carbonValue, uint32_t carbonTimestamp) { if(_carbonClient->connect(_carbonServer, _carbonPort)) { _carbonClient->print(carbonMetric); _carbonClient->print(" "); _carbonClient->print(carbonValue); _carbonClient->print(" "); _carbonClient->print(carbonTimestamp); _carbonClient->println(""); delay(10); _carbonClient->stop(); _carbonClient->flush(); return true; } else return false; } <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * @(#)root/roofitcore:$Id$ * Authors: * * WV, Wouter Verkerke, NIKHEF * GR, Gerhard Raven, NIKHEF/VU * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ///////////////////////////////////////////////////////////////////////////////////// // BEGIN_HTML // The class RooEffProd implements the product of a PDF with an efficiency function. // The normalization integral of the product is calculated numerically, but the // event generation is handled by a specialized generator context that implements // the event generation in a more efficient for cases where the PDF has an internal // generator that is smarter than accept reject. // END_HTML // #include "RooFit.h" #include "RooEffProd.h" #include "RooEffGenContext.h" #include "RooNameReg.h" #include "RooRealVar.h" ClassImp(RooEffProd) ; //_____________________________________________________________________________ RooEffProd::RooEffProd(const char *name, const char *title, RooAbsPdf& inPdf, RooAbsReal& inEff) : RooAbsPdf(name,title), _cacheMgr(this,10), _pdf("pdf","pre-efficiency pdf", this,inPdf), _eff("eff","efficiency function",this,inEff), _nset(0), _fixedNset(0) { // Constructor of a a production of p.d.f inPdf with efficiency // function inEff. } //_____________________________________________________________________________ RooEffProd::RooEffProd(const RooEffProd& other, const char* name) : RooAbsPdf(other, name), _cacheMgr(other._cacheMgr,this), _pdf("pdf",this,other._pdf), _eff("acc",this,other._eff), _nset(0), _fixedNset(0) { // Copy constructor } //_____________________________________________________________________________ RooEffProd::~RooEffProd() { // Destructor } //_____________________________________________________________________________ Double_t RooEffProd::getValV(const RooArgSet* set) const { // Return p.d.f. value normalized over given set of observables _nset = _fixedNset ? _fixedNset : set ; return RooAbsPdf::getValV(set) ; } //_____________________________________________________________________________ Double_t RooEffProd::evaluate() const { // Calculate and return 'raw' unnormalized value of p.d.f return eff()->getVal() * pdf()->getVal(_nset); } //_____________________________________________________________________________ RooAbsGenContext* RooEffProd::genContext(const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, Bool_t verbose) const { // Return specialized generator context for RooEffProds that implements generation // in a more efficient way than can be done for generic correlated products assert(pdf()!=0); assert(eff()!=0); return new RooEffGenContext(*this,*pdf(),*eff(),vars,prototype,auxProto,verbose) ; } //_____________________________________________________________________________ Int_t RooEffProd::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const { // Return internal integration capabilities of the p.d.f. Given a set 'allVars' for which // integration is requested, returned the largest subset for which internal (analytical) // integration is implemented (in argument analVars). The return value is a unique integer // code that identifies the integration configuration (integrated observables and range name). // // This implementation in RooEffProd catches all integrals without normalization and reroutes them // through a custom integration routine that properly accounts for the use of normalized p.d.f. // in the evaluate() expression, which breaks the default RooAbsPdf normalization handling // No special handling required if a normalization set is given if (normSet && normSet->getSize()>0) { return 0 ; } // No special handling required if running with a fixed normalization set if (_fixedNset) { return 0 ; } // Special handling of integrals w/o normalization set. We need to pass _a_ normalization set // to pdf().getVal(nset) in evaluate() because for certain p.d.fs the shape depends on the // chosen normalization set. This functions correctly automatically for plain getVal() calls, // however when the (numeric) normalization is calculated, getVal() is called without any normalization // set causing the normalization to be calculated for a possibly different shape. To fix that // integrals over a RooEffProd without normalization setup are explicitly handled here. These integrals // are calculated using a clone of the RooEffProd that has a fixed normalization set passed to the // underlying p.d.f regardless of the normalization set passed to getVal(). Here the set of observables // over which is integrated is passed. // Declare that we can analytically integrate all requested observables analVars.add(allVars) ; // Check if cache was previously created Int_t sterileIndex(-1) ; CacheElem* cache = (CacheElem*) _cacheMgr.getObj(&allVars,&allVars,&sterileIndex,RooNameReg::ptr(rangeName)) ; if (cache) { return _cacheMgr.lastIndex()+1; } // Construct cache with clone of p.d.f that has fixed normalization set that is passed to input pdf cache = new CacheElem ; cache->_intObs.addClone(allVars) ; cache->_clone = (RooEffProd*) clone(Form("%s_clone",GetName())) ; cache->_clone->_fixedNset = &cache->_intObs ; cache->_int = cache->_clone->createIntegral(cache->_intObs) ; // Store cache and return index as code Int_t code = _cacheMgr.setObj(&allVars,&allVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)) ; return code+1 ; } //_____________________________________________________________________________ Double_t RooEffProd::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* /*rangeName*/) const { // Return value of integral identified by code, which should be a return value of getAnalyticalIntegralWN, // Code zero is always handled and signifies no integration (return value is normalized p.d.f. value) // Return analytical integral defined by given scenario code // No integration scenario if (code==0) { return getVal(normSet) ; } // Partial integration scenarios CacheElem* cache = (CacheElem*) _cacheMgr.getObjByIndex(code-1) ; return cache->_int->getVal() ; } //_____________________________________________________________________________ RooArgList RooEffProd::CacheElem::containedArgs(Action) { // Report all RooAbsArg derived objects contained in Cache Element (used in function optimization and // and server redirect management of the cache) RooArgList ret(_intObs) ; ret.add(*_int) ; ret.add(*_clone) ; return ret ; } <commit_msg><commit_after>/***************************************************************************** * Project: RooFit * * Package: RooFitCore * * @(#)root/roofitcore:$Id$ * Authors: * * WV, Wouter Verkerke, NIKHEF * GR, Gerhard Raven, NIKHEF/VU * * * * Redistribution and use in source and binary forms, * * with or without modification, are permitted according to the terms * * listed in LICENSE (http://roofit.sourceforge.net/license.txt) * *****************************************************************************/ ///////////////////////////////////////////////////////////////////////////////////// // BEGIN_HTML // The class RooEffProd implements the product of a PDF with an efficiency function. // The normalization integral of the product is calculated numerically, but the // event generation is handled by a specialized generator context that implements // the event generation in a more efficient for cases where the PDF has an internal // generator that is smarter than accept reject. // END_HTML // #include "RooFit.h" #include "RooEffProd.h" #include "RooEffGenContext.h" #include "RooNameReg.h" #include "RooRealVar.h" ClassImp(RooEffProd) ; //_____________________________________________________________________________ RooEffProd::RooEffProd(const char *name, const char *title, RooAbsPdf& inPdf, RooAbsReal& inEff) : RooAbsPdf(name,title), _cacheMgr(this,10), _pdf("pdf","pre-efficiency pdf", this,inPdf), _eff("eff","efficiency function",this,inEff), _nset(0), _fixedNset(0) { // Constructor of a a production of p.d.f inPdf with efficiency // function inEff. } //_____________________________________________________________________________ RooEffProd::RooEffProd(const RooEffProd& other, const char* name) : RooAbsPdf(other, name), _cacheMgr(other._cacheMgr,this), _pdf("pdf",this,other._pdf), _eff("acc",this,other._eff), _nset(0), _fixedNset(0) { // Copy constructor } //_____________________________________________________________________________ RooEffProd::~RooEffProd() { // Destructor } //_____________________________________________________________________________ Double_t RooEffProd::getValV(const RooArgSet* set) const { // Return p.d.f. value normalized over given set of observables _nset = _fixedNset ? _fixedNset : set ; return RooAbsPdf::getValV(set) ; } //_____________________________________________________________________________ Double_t RooEffProd::evaluate() const { // Calculate and return 'raw' unnormalized value of p.d.f return eff()->getVal() * pdf()->getVal(_nset); } //_____________________________________________________________________________ RooAbsGenContext* RooEffProd::genContext(const RooArgSet &vars, const RooDataSet *prototype, const RooArgSet* auxProto, Bool_t verbose) const { // Return specialized generator context for RooEffProds that implements generation // in a more efficient way than can be done for generic correlated products assert(pdf()!=0); assert(eff()!=0); return new RooEffGenContext(*this,*pdf(),*eff(),vars,prototype,auxProto,verbose) ; } //_____________________________________________________________________________ Int_t RooEffProd::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* normSet, const char* rangeName) const { // Return internal integration capabilities of the p.d.f. Given a set 'allVars' for which // integration is requested, returned the largest subset for which internal (analytical) // integration is implemented (in argument analVars). The return value is a unique integer // code that identifies the integration configuration (integrated observables and range name). // // This implementation in RooEffProd catches all integrals without normalization and reroutes them // through a custom integration routine that properly accounts for the use of normalized p.d.f. // in the evaluate() expression, which breaks the default RooAbsPdf normalization handling // No special handling required if a normalization set is given if (normSet && normSet->getSize()>0) { return 0 ; } // No special handling required if running with a fixed normalization set if (_fixedNset) { return 0 ; } // Special handling of integrals w/o normalization set. We need to pass _a_ normalization set // to pdf().getVal(nset) in evaluate() because for certain p.d.fs the shape depends on the // chosen normalization set. This functions correctly automatically for plain getVal() calls, // however when the (numeric) normalization is calculated, getVal() is called without any normalization // set causing the normalization to be calculated for a possibly different shape. To fix that // integrals over a RooEffProd without normalization setup are explicitly handled here. These integrals // are calculated using a clone of the RooEffProd that has a fixed normalization set passed to the // underlying p.d.f regardless of the normalization set passed to getVal(). Here the set of observables // over which is integrated is passed. // Declare that we can analytically integrate all requested observables analVars.add(allVars) ; // Check if cache was previously created Int_t sterileIndex(-1) ; CacheElem* cache = (CacheElem*) _cacheMgr.getObj(&allVars,&allVars,&sterileIndex,RooNameReg::ptr(rangeName)) ; if (cache) { return _cacheMgr.lastIndex()+1; } // Construct cache with clone of p.d.f that has fixed normalization set that is passed to input pdf cache = new CacheElem ; cache->_intObs.addClone(allVars) ; cache->_clone = (RooEffProd*) clone(Form("%s_clone",GetName())) ; cache->_clone->_fixedNset = &cache->_intObs ; cache->_int = cache->_clone->createIntegral(cache->_intObs,rangeName) ; // Store cache and return index as code Int_t code = _cacheMgr.setObj(&allVars,&allVars,(RooAbsCacheElement*)cache,RooNameReg::ptr(rangeName)) ; return code+1 ; } //_____________________________________________________________________________ Double_t RooEffProd::analyticalIntegralWN(Int_t code, const RooArgSet* normSet, const char* /*rangeName*/) const { // Return value of integral identified by code, which should be a return value of getAnalyticalIntegralWN, // Code zero is always handled and signifies no integration (return value is normalized p.d.f. value) // Return analytical integral defined by given scenario code // No integration scenario if (code==0) { return getVal(normSet) ; } // Partial integration scenarios CacheElem* cache = (CacheElem*) _cacheMgr.getObjByIndex(code-1) ; return cache->_int->getVal() ; } //_____________________________________________________________________________ RooArgList RooEffProd::CacheElem::containedArgs(Action) { // Report all RooAbsArg derived objects contained in Cache Element (used in function optimization and // and server redirect management of the cache) RooArgList ret(_intObs) ; ret.add(*_int) ; ret.add(*_clone) ; return ret ; } <|endoftext|>
<commit_before>/* * Copyright 2010-2017 JetBrains s.r.o. * * 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. */ #if KONAN_OBJC_INTEROP #include <objc/objc.h> #include <objc/runtime.h> #include <objc/message.h> #include <cstdio> #include <cstdint> #include "Memory.h" #include "MemoryPrivate.hpp" #include "Natives.h" #include "Utils.h" extern "C" { Class Kotlin_Interop_getObjCClass(const char* name); struct KotlinClassData { const TypeInfo* typeInfo; int32_t bodyOffset; }; static inline struct KotlinClassData* GetKotlinClassData(Class clazz) { void* ivars = object_getIndexedIvars(reinterpret_cast<id>(clazz)); return static_cast<struct KotlinClassData*>(ivars); } static inline void SetKotlinTypeInfo(Class clazz, const TypeInfo* typeInfo) { GetKotlinClassData(clazz)->typeInfo = typeInfo; } const TypeInfo* GetObjCKotlinTypeInfo(ObjHeader* obj) RUNTIME_NOTHROW; const TypeInfo* GetObjCKotlinTypeInfo(ObjHeader* obj) RUNTIME_NOTHROW { RuntimeAssert(obj->has_meta_object(), ""); void* objcPtr = obj->meta_object()->associatedObject_; RuntimeAssert(objcPtr != nullptr, ""); Class clazz = object_getClass(reinterpret_cast<id>(objcPtr)); return GetKotlinClassData(clazz)->typeInfo; } id objc_msgSendSuper2(struct objc_super *super, SEL op, ...); static void DeallocImp(id self, SEL _cmd) { // TODO: doesn't support overriding Kotlin classes. Class clazz = object_getClass(self); RuntimeAssert(clazz != nullptr, "Must not be null"); struct KotlinClassData* classData = GetKotlinClassData(clazz); void* body = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(self) + classData->bodyOffset); const TypeInfo* typeInfo = classData->typeInfo; DeinitInstanceBody(typeInfo, body); // Call super.dealloc: struct objc_super s = {self, clazz}; auto messenger = reinterpret_cast<void (*) (struct objc_super*, SEL _cmd)>(objc_msgSendSuper2); messenger(&s, _cmd); } static void AddDeallocMethod(Class clazz) { Class nsObjectClass = Kotlin_Interop_getObjCClass("NSObject"); SEL deallocSelector = sel_registerName("dealloc"); Method nsObjectDeallocMethod = class_getInstanceMethod(nsObjectClass, deallocSelector); RuntimeAssert(nsObjectDeallocMethod != nullptr, "[NSObject dealloc] method not found"); const char* nsObjectDeallocMethodTypeEncoding = method_getTypeEncoding(nsObjectDeallocMethod); RuntimeAssert(nsObjectDeallocMethodTypeEncoding != nullptr, "[NSObject dealloc] method has no encoding provided"); // TODO: something of the above can be cached. BOOL added = class_addMethod(clazz, deallocSelector, (IMP)DeallocImp, nsObjectDeallocMethodTypeEncoding); RuntimeAssert(added, "Unable to add dealloc method to Objective-C class"); } struct ObjCMethodDescription { void* (*imp)(void*, void*, ...); const char* selector; const char* encoding; }; struct KotlinObjCClassInfo { const char* name; const char* superclassName; const char** protocolNames; const struct ObjCMethodDescription* instanceMethods; int32_t instanceMethodsNum; const struct ObjCMethodDescription* classMethods; int32_t classMethodsNum; int32_t bodySize; int32_t* bodyOffset; const TypeInfo* typeInfo; const TypeInfo* metaTypeInfo; void** createdClass; }; static void AddMethods(Class clazz, const struct ObjCMethodDescription* methods, int32_t methodsNum) { for (int32_t i = 0; i < methodsNum; ++i) { const struct ObjCMethodDescription* method = &methods[i]; BOOL added = class_addMethod(clazz, sel_registerName(method->selector), (IMP)method->imp, method->encoding); RuntimeAssert(added == YES, "Unable to add method to Objective-C class"); } } static SimpleMutex classCreationMutex; static int anonymousClassNextId = 0; void* CreateKotlinObjCClass(const KotlinObjCClassInfo* info) { LockGuard<SimpleMutex> lockGuard(classCreationMutex); void* createdClass = *info->createdClass; if (createdClass != nullptr) { return createdClass; } char classNameBuffer[64]; const char* className = info->name; if (className == nullptr) { snprintf(classNameBuffer, sizeof(classNameBuffer), "kobjc%d", anonymousClassNextId++); className = classNameBuffer; } Class superclass = Kotlin_Interop_getObjCClass(info->superclassName); Class newClass = objc_allocateClassPair(superclass, className, sizeof(struct KotlinClassData)); RuntimeAssert(newClass != nullptr, "Failed to allocate Objective-C class"); Class newMetaclass = object_getClass(reinterpret_cast<id>(newClass)); for (size_t i = 0;; ++i) { const char* protocolName = info->protocolNames[i]; if (protocolName == nullptr) break; Protocol* proto = objc_getProtocol(protocolName); if (proto != nullptr) { BOOL added = class_addProtocol(newClass, proto); RuntimeAssert(added == YES, "Unable to add protocol to Objective-C class"); added = class_addProtocol(newMetaclass, proto); RuntimeAssert(added == YES, "Unable to add protocol to Objective-C metaclass"); } } AddDeallocMethod(newClass); AddMethods(newClass, info->instanceMethods, info->instanceMethodsNum); AddMethods(newMetaclass, info->classMethods, info->classMethodsNum); SetKotlinTypeInfo(newClass, info->typeInfo); SetKotlinTypeInfo(newMetaclass, info->metaTypeInfo); char bodyTypeEncoding[16]; snprintf(bodyTypeEncoding, sizeof(bodyTypeEncoding), "[%dc]", info->bodySize); BOOL added = class_addIvar(newClass, "kotlinBody", info->bodySize, /* log2(align) = */ 3, bodyTypeEncoding); RuntimeAssert(added == YES, "Unable to add ivar to Objective-C class"); objc_registerClassPair(newClass); Ivar body = class_getInstanceVariable(newClass, "kotlinBody"); RuntimeAssert(body != nullptr, "Unable to get ivar added to Objective-C class"); int32_t offset = (int32_t)ivar_getOffset(body); GetKotlinClassData(newClass)->bodyOffset = offset; *info->bodyOffset = offset; *info->createdClass = newClass; return newClass; } void* objc_autoreleasePoolPush(); void objc_autoreleasePoolPop(void* ptr); id objc_allocWithZone(Class clazz); id objc_retain(id ptr); void objc_release(id ptr); void* Kotlin_objc_autoreleasePoolPush() { return objc_autoreleasePoolPush(); } void Kotlin_objc_autoreleasePoolPop(void* ptr) { objc_autoreleasePoolPop(ptr); } id Kotlin_objc_allocWithZone(Class clazz) { return objc_allocWithZone(clazz); } id Kotlin_objc_retain(id ptr) { return objc_retain(ptr); } void Kotlin_objc_release(id ptr) { objc_release(ptr); } Class Kotlin_objc_lookUpClass(const char* name) { return objc_lookUpClass(name); } } // extern "C" #else // KONAN_OBJC_INTEROP #include "KAssert.h" extern "C" { void* Kotlin_objc_autoreleasePoolPush() { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void Kotlin_objc_autoreleasePoolPop(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); } void* Kotlin_objc_allocWithZone(void* clazz) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void* Kotlin_objc_retain(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void Kotlin_objc_release(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); } void* Kotlin_objc_lookUpClass(const char* name) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } } // extern "C" #endif // KONAN_OBJC_INTEROP <commit_msg>Fix runtime compilation warnings<commit_after>/* * Copyright 2010-2017 JetBrains s.r.o. * * 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. */ #if KONAN_OBJC_INTEROP #include <objc/objc.h> #include <objc/runtime.h> #include <objc/message.h> #include <cstdio> #include <cstdint> #include "Memory.h" #include "MemoryPrivate.hpp" #include "Natives.h" #include "Utils.h" extern "C" { Class Kotlin_Interop_getObjCClass(const char* name); struct KotlinClassData { const TypeInfo* typeInfo; int32_t bodyOffset; }; static inline struct KotlinClassData* GetKotlinClassData(Class clazz) { void* ivars = object_getIndexedIvars(reinterpret_cast<id>(clazz)); return static_cast<struct KotlinClassData*>(ivars); } static inline void SetKotlinTypeInfo(Class clazz, const TypeInfo* typeInfo) { GetKotlinClassData(clazz)->typeInfo = typeInfo; } const TypeInfo* GetObjCKotlinTypeInfo(ObjHeader* obj) RUNTIME_NOTHROW; RUNTIME_NOTHROW const TypeInfo* GetObjCKotlinTypeInfo(ObjHeader* obj) { RuntimeAssert(obj->has_meta_object(), ""); void* objcPtr = obj->meta_object()->associatedObject_; RuntimeAssert(objcPtr != nullptr, ""); Class clazz = object_getClass(reinterpret_cast<id>(objcPtr)); return GetKotlinClassData(clazz)->typeInfo; } id objc_msgSendSuper2(struct objc_super *super, SEL op, ...); static void DeallocImp(id self, SEL _cmd) { // TODO: doesn't support overriding Kotlin classes. Class clazz = object_getClass(self); RuntimeAssert(clazz != nullptr, "Must not be null"); struct KotlinClassData* classData = GetKotlinClassData(clazz); void* body = reinterpret_cast<void*>(reinterpret_cast<uintptr_t>(self) + classData->bodyOffset); const TypeInfo* typeInfo = classData->typeInfo; DeinitInstanceBody(typeInfo, body); // Call super.dealloc: struct objc_super s = {self, clazz}; auto messenger = reinterpret_cast<void (*) (struct objc_super*, SEL _cmd)>(objc_msgSendSuper2); messenger(&s, _cmd); } static void AddDeallocMethod(Class clazz) { Class nsObjectClass = Kotlin_Interop_getObjCClass("NSObject"); SEL deallocSelector = sel_registerName("dealloc"); Method nsObjectDeallocMethod = class_getInstanceMethod(nsObjectClass, deallocSelector); RuntimeAssert(nsObjectDeallocMethod != nullptr, "[NSObject dealloc] method not found"); const char* nsObjectDeallocMethodTypeEncoding = method_getTypeEncoding(nsObjectDeallocMethod); RuntimeAssert(nsObjectDeallocMethodTypeEncoding != nullptr, "[NSObject dealloc] method has no encoding provided"); // TODO: something of the above can be cached. BOOL added = class_addMethod(clazz, deallocSelector, (IMP)DeallocImp, nsObjectDeallocMethodTypeEncoding); RuntimeAssert(added, "Unable to add dealloc method to Objective-C class"); } struct ObjCMethodDescription { void* (*imp)(void*, void*, ...); const char* selector; const char* encoding; }; struct KotlinObjCClassInfo { const char* name; const char* superclassName; const char** protocolNames; const struct ObjCMethodDescription* instanceMethods; int32_t instanceMethodsNum; const struct ObjCMethodDescription* classMethods; int32_t classMethodsNum; int32_t bodySize; int32_t* bodyOffset; const TypeInfo* typeInfo; const TypeInfo* metaTypeInfo; void** createdClass; }; static void AddMethods(Class clazz, const struct ObjCMethodDescription* methods, int32_t methodsNum) { for (int32_t i = 0; i < methodsNum; ++i) { const struct ObjCMethodDescription* method = &methods[i]; BOOL added = class_addMethod(clazz, sel_registerName(method->selector), (IMP)method->imp, method->encoding); RuntimeAssert(added == YES, "Unable to add method to Objective-C class"); } } static SimpleMutex classCreationMutex; static int anonymousClassNextId = 0; void* CreateKotlinObjCClass(const KotlinObjCClassInfo* info) { LockGuard<SimpleMutex> lockGuard(classCreationMutex); void* createdClass = *info->createdClass; if (createdClass != nullptr) { return createdClass; } char classNameBuffer[64]; const char* className = info->name; if (className == nullptr) { snprintf(classNameBuffer, sizeof(classNameBuffer), "kobjc%d", anonymousClassNextId++); className = classNameBuffer; } Class superclass = Kotlin_Interop_getObjCClass(info->superclassName); Class newClass = objc_allocateClassPair(superclass, className, sizeof(struct KotlinClassData)); RuntimeAssert(newClass != nullptr, "Failed to allocate Objective-C class"); Class newMetaclass = object_getClass(reinterpret_cast<id>(newClass)); for (size_t i = 0;; ++i) { const char* protocolName = info->protocolNames[i]; if (protocolName == nullptr) break; Protocol* proto = objc_getProtocol(protocolName); if (proto != nullptr) { BOOL added = class_addProtocol(newClass, proto); RuntimeAssert(added == YES, "Unable to add protocol to Objective-C class"); added = class_addProtocol(newMetaclass, proto); RuntimeAssert(added == YES, "Unable to add protocol to Objective-C metaclass"); } } AddDeallocMethod(newClass); AddMethods(newClass, info->instanceMethods, info->instanceMethodsNum); AddMethods(newMetaclass, info->classMethods, info->classMethodsNum); SetKotlinTypeInfo(newClass, info->typeInfo); SetKotlinTypeInfo(newMetaclass, info->metaTypeInfo); char bodyTypeEncoding[16]; snprintf(bodyTypeEncoding, sizeof(bodyTypeEncoding), "[%dc]", info->bodySize); BOOL added = class_addIvar(newClass, "kotlinBody", info->bodySize, /* log2(align) = */ 3, bodyTypeEncoding); RuntimeAssert(added == YES, "Unable to add ivar to Objective-C class"); objc_registerClassPair(newClass); Ivar body = class_getInstanceVariable(newClass, "kotlinBody"); RuntimeAssert(body != nullptr, "Unable to get ivar added to Objective-C class"); int32_t offset = (int32_t)ivar_getOffset(body); GetKotlinClassData(newClass)->bodyOffset = offset; *info->bodyOffset = offset; *info->createdClass = newClass; return newClass; } void* objc_autoreleasePoolPush(); void objc_autoreleasePoolPop(void* ptr); id objc_allocWithZone(Class clazz); id objc_retain(id ptr); void objc_release(id ptr); void* Kotlin_objc_autoreleasePoolPush() { return objc_autoreleasePoolPush(); } void Kotlin_objc_autoreleasePoolPop(void* ptr) { objc_autoreleasePoolPop(ptr); } id Kotlin_objc_allocWithZone(Class clazz) { return objc_allocWithZone(clazz); } id Kotlin_objc_retain(id ptr) { return objc_retain(ptr); } void Kotlin_objc_release(id ptr) { objc_release(ptr); } Class Kotlin_objc_lookUpClass(const char* name) { return objc_lookUpClass(name); } } // extern "C" #else // KONAN_OBJC_INTEROP #include "KAssert.h" extern "C" { void* Kotlin_objc_autoreleasePoolPush() { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void Kotlin_objc_autoreleasePoolPop(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); } void* Kotlin_objc_allocWithZone(void* clazz) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void* Kotlin_objc_retain(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } void Kotlin_objc_release(void* ptr) { RuntimeAssert(false, "Objective-C interop is disabled"); } void* Kotlin_objc_lookUpClass(const char* name) { RuntimeAssert(false, "Objective-C interop is disabled"); return nullptr; } } // extern "C" #endif // KONAN_OBJC_INTEROP <|endoftext|>
<commit_before>// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/frames/quic_frame.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" #include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" namespace quic { QuicFrame::QuicFrame() {} QuicFrame::QuicFrame(QuicPaddingFrame padding_frame) : padding_frame(padding_frame) {} QuicFrame::QuicFrame(QuicStreamFrame stream_frame) : stream_frame(stream_frame) {} QuicFrame::QuicFrame(QuicCryptoFrame* crypto_frame) : type(CRYPTO_FRAME), crypto_frame(crypto_frame) {} QuicFrame::QuicFrame(QuicAckFrame* frame) : type(ACK_FRAME), ack_frame(frame) {} QuicFrame::QuicFrame(QuicMtuDiscoveryFrame frame) : mtu_discovery_frame(frame) {} QuicFrame::QuicFrame(QuicStopWaitingFrame frame) : stop_waiting_frame(frame) {} QuicFrame::QuicFrame(QuicPingFrame frame) : ping_frame(frame) {} QuicFrame::QuicFrame(QuicRstStreamFrame* frame) : type(RST_STREAM_FRAME), rst_stream_frame(frame) {} QuicFrame::QuicFrame(QuicConnectionCloseFrame* frame) : type(CONNECTION_CLOSE_FRAME), connection_close_frame(frame) {} QuicFrame::QuicFrame(QuicGoAwayFrame* frame) : type(GOAWAY_FRAME), goaway_frame(frame) {} QuicFrame::QuicFrame(QuicWindowUpdateFrame* frame) : type(WINDOW_UPDATE_FRAME), window_update_frame(frame) {} QuicFrame::QuicFrame(QuicBlockedFrame* frame) : type(BLOCKED_FRAME), blocked_frame(frame) {} QuicFrame::QuicFrame(QuicNewConnectionIdFrame* frame) : type(NEW_CONNECTION_ID_FRAME), new_connection_id_frame(frame) {} QuicFrame::QuicFrame(QuicRetireConnectionIdFrame* frame) : type(RETIRE_CONNECTION_ID_FRAME), retire_connection_id_frame(frame) {} QuicFrame::QuicFrame(QuicMaxStreamsFrame frame) : max_streams_frame(frame) {} QuicFrame::QuicFrame(QuicStreamsBlockedFrame frame) : streams_blocked_frame(frame) {} QuicFrame::QuicFrame(QuicPathResponseFrame* frame) : type(PATH_RESPONSE_FRAME), path_response_frame(frame) {} QuicFrame::QuicFrame(QuicPathChallengeFrame* frame) : type(PATH_CHALLENGE_FRAME), path_challenge_frame(frame) {} QuicFrame::QuicFrame(QuicStopSendingFrame* frame) : type(STOP_SENDING_FRAME), stop_sending_frame(frame) {} QuicFrame::QuicFrame(QuicMessageFrame* frame) : type(MESSAGE_FRAME), message_frame(frame) {} QuicFrame::QuicFrame(QuicNewTokenFrame* frame) : type(NEW_TOKEN_FRAME), new_token_frame(frame) {} void DeleteFrames(QuicFrames* frames) { for (QuicFrame& frame : *frames) { DeleteFrame(&frame); } frames->clear(); } void DeleteFrame(QuicFrame* frame) { switch (frame->type) { // Frames smaller than a pointer are inlined, so don't need to be deleted. case PADDING_FRAME: case MTU_DISCOVERY_FRAME: case PING_FRAME: case MAX_STREAMS_FRAME: case STOP_WAITING_FRAME: case STREAMS_BLOCKED_FRAME: case STREAM_FRAME: break; case ACK_FRAME: delete frame->ack_frame; break; case RST_STREAM_FRAME: delete frame->rst_stream_frame; break; case CONNECTION_CLOSE_FRAME: delete frame->connection_close_frame; break; case GOAWAY_FRAME: delete frame->goaway_frame; break; case BLOCKED_FRAME: delete frame->blocked_frame; break; case WINDOW_UPDATE_FRAME: delete frame->window_update_frame; break; case PATH_CHALLENGE_FRAME: delete frame->path_challenge_frame; break; case STOP_SENDING_FRAME: delete frame->stop_sending_frame; break; case NEW_CONNECTION_ID_FRAME: delete frame->new_connection_id_frame; break; case RETIRE_CONNECTION_ID_FRAME: delete frame->retire_connection_id_frame; break; case PATH_RESPONSE_FRAME: delete frame->path_response_frame; break; case MESSAGE_FRAME: delete frame->message_frame; break; case CRYPTO_FRAME: delete frame->crypto_frame; break; case NEW_TOKEN_FRAME: delete frame->new_token_frame; break; case NUM_FRAME_TYPES: DCHECK(false) << "Cannot delete type: " << frame->type; } } void RemoveFramesForStream(QuicFrames* frames, QuicStreamId stream_id) { auto it = frames->begin(); while (it != frames->end()) { if (it->type != STREAM_FRAME || it->stream_frame.stream_id != stream_id) { ++it; continue; } it = frames->erase(it); } } bool IsControlFrame(QuicFrameType type) { switch (type) { case RST_STREAM_FRAME: case GOAWAY_FRAME: case WINDOW_UPDATE_FRAME: case BLOCKED_FRAME: case STREAMS_BLOCKED_FRAME: case MAX_STREAMS_FRAME: case PING_FRAME: case STOP_SENDING_FRAME: return true; default: return false; } } QuicControlFrameId GetControlFrameId(const QuicFrame& frame) { switch (frame.type) { case RST_STREAM_FRAME: return frame.rst_stream_frame->control_frame_id; case GOAWAY_FRAME: return frame.goaway_frame->control_frame_id; case WINDOW_UPDATE_FRAME: return frame.window_update_frame->control_frame_id; case BLOCKED_FRAME: return frame.blocked_frame->control_frame_id; case STREAMS_BLOCKED_FRAME: return frame.streams_blocked_frame.control_frame_id; case MAX_STREAMS_FRAME: return frame.max_streams_frame.control_frame_id; case PING_FRAME: return frame.ping_frame.control_frame_id; case STOP_SENDING_FRAME: return frame.stop_sending_frame->control_frame_id; default: return kInvalidControlFrameId; } } void SetControlFrameId(QuicControlFrameId control_frame_id, QuicFrame* frame) { switch (frame->type) { case RST_STREAM_FRAME: frame->rst_stream_frame->control_frame_id = control_frame_id; return; case GOAWAY_FRAME: frame->goaway_frame->control_frame_id = control_frame_id; return; case WINDOW_UPDATE_FRAME: frame->window_update_frame->control_frame_id = control_frame_id; return; case BLOCKED_FRAME: frame->blocked_frame->control_frame_id = control_frame_id; return; case PING_FRAME: frame->ping_frame.control_frame_id = control_frame_id; return; case STREAMS_BLOCKED_FRAME: frame->streams_blocked_frame.control_frame_id = control_frame_id; return; case MAX_STREAMS_FRAME: frame->max_streams_frame.control_frame_id = control_frame_id; return; case STOP_SENDING_FRAME: frame->stop_sending_frame->control_frame_id = control_frame_id; return; default: QUIC_BUG << "Try to set control frame id of a frame without control frame id"; } } QuicFrame CopyRetransmittableControlFrame(const QuicFrame& frame) { QuicFrame copy; switch (frame.type) { case RST_STREAM_FRAME: copy = QuicFrame(new QuicRstStreamFrame(*frame.rst_stream_frame)); break; case GOAWAY_FRAME: copy = QuicFrame(new QuicGoAwayFrame(*frame.goaway_frame)); break; case WINDOW_UPDATE_FRAME: copy = QuicFrame(new QuicWindowUpdateFrame(*frame.window_update_frame)); break; case BLOCKED_FRAME: copy = QuicFrame(new QuicBlockedFrame(*frame.blocked_frame)); break; case PING_FRAME: copy = QuicFrame(QuicPingFrame(frame.ping_frame.control_frame_id)); break; case STOP_SENDING_FRAME: copy = QuicFrame(new QuicStopSendingFrame(*frame.stop_sending_frame)); break; case STREAMS_BLOCKED_FRAME: copy = QuicFrame(QuicStreamsBlockedFrame(frame.streams_blocked_frame)); break; case MAX_STREAMS_FRAME: copy = QuicFrame(QuicMaxStreamsFrame(frame.max_streams_frame)); break; default: QUIC_BUG << "Try to copy a non-retransmittable control frame: " << frame; copy = QuicFrame(QuicPingFrame(kInvalidControlFrameId)); break; } return copy; } std::ostream& operator<<(std::ostream& os, const QuicFrame& frame) { switch (frame.type) { case PADDING_FRAME: { os << "type { PADDING_FRAME } " << frame.padding_frame; break; } case RST_STREAM_FRAME: { os << "type { RST_STREAM_FRAME } " << *(frame.rst_stream_frame); break; } case CONNECTION_CLOSE_FRAME: { os << "type { CONNECTION_CLOSE_FRAME } " << *(frame.connection_close_frame); break; } case GOAWAY_FRAME: { os << "type { GOAWAY_FRAME } " << *(frame.goaway_frame); break; } case WINDOW_UPDATE_FRAME: { os << "type { WINDOW_UPDATE_FRAME } " << *(frame.window_update_frame); break; } case BLOCKED_FRAME: { os << "type { BLOCKED_FRAME } " << *(frame.blocked_frame); break; } case STREAM_FRAME: { os << "type { STREAM_FRAME } " << frame.stream_frame; break; } case ACK_FRAME: { os << "type { ACK_FRAME } " << *(frame.ack_frame); break; } case STOP_WAITING_FRAME: { os << "type { STOP_WAITING_FRAME } " << frame.stop_waiting_frame; break; } case PING_FRAME: { os << "type { PING_FRAME } " << frame.ping_frame; break; } case MTU_DISCOVERY_FRAME: { os << "type { MTU_DISCOVERY_FRAME } "; break; } case NEW_CONNECTION_ID_FRAME: os << "type { NEW_CONNECTION_ID } " << *(frame.new_connection_id_frame); break; case RETIRE_CONNECTION_ID_FRAME: os << "type { RETIRE_CONNECTION_ID } " << *(frame.retire_connection_id_frame); break; case MAX_STREAMS_FRAME: os << "type { MAX_STREAMS } " << frame.max_streams_frame; break; case STREAMS_BLOCKED_FRAME: os << "type { STREAMS_BLOCKED } " << frame.streams_blocked_frame; break; case PATH_RESPONSE_FRAME: os << "type { PATH_RESPONSE } " << *(frame.path_response_frame); break; case PATH_CHALLENGE_FRAME: os << "type { PATH_CHALLENGE } " << *(frame.path_challenge_frame); break; case STOP_SENDING_FRAME: os << "type { STOP_SENDING } " << *(frame.stop_sending_frame); break; case MESSAGE_FRAME: os << "type { MESSAGE_FRAME }" << *(frame.message_frame); break; case NEW_TOKEN_FRAME: os << "type { NEW_TOKEN_FRAME }" << *(frame.new_token_frame); break; default: { QUIC_LOG(ERROR) << "Unknown frame type: " << frame.type; break; } } return os; } } // namespace quic <commit_msg>gfe-relnote: (n/a) Emit CRYPTO_FRAME in operator<<(QuicFrame). Logging only change.<commit_after>// Copyright (c) 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/core/frames/quic_frame.h" #include "net/third_party/quiche/src/quic/core/quic_constants.h" #include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h" #include "net/third_party/quiche/src/quic/platform/api/quic_logging.h" namespace quic { QuicFrame::QuicFrame() {} QuicFrame::QuicFrame(QuicPaddingFrame padding_frame) : padding_frame(padding_frame) {} QuicFrame::QuicFrame(QuicStreamFrame stream_frame) : stream_frame(stream_frame) {} QuicFrame::QuicFrame(QuicCryptoFrame* crypto_frame) : type(CRYPTO_FRAME), crypto_frame(crypto_frame) {} QuicFrame::QuicFrame(QuicAckFrame* frame) : type(ACK_FRAME), ack_frame(frame) {} QuicFrame::QuicFrame(QuicMtuDiscoveryFrame frame) : mtu_discovery_frame(frame) {} QuicFrame::QuicFrame(QuicStopWaitingFrame frame) : stop_waiting_frame(frame) {} QuicFrame::QuicFrame(QuicPingFrame frame) : ping_frame(frame) {} QuicFrame::QuicFrame(QuicRstStreamFrame* frame) : type(RST_STREAM_FRAME), rst_stream_frame(frame) {} QuicFrame::QuicFrame(QuicConnectionCloseFrame* frame) : type(CONNECTION_CLOSE_FRAME), connection_close_frame(frame) {} QuicFrame::QuicFrame(QuicGoAwayFrame* frame) : type(GOAWAY_FRAME), goaway_frame(frame) {} QuicFrame::QuicFrame(QuicWindowUpdateFrame* frame) : type(WINDOW_UPDATE_FRAME), window_update_frame(frame) {} QuicFrame::QuicFrame(QuicBlockedFrame* frame) : type(BLOCKED_FRAME), blocked_frame(frame) {} QuicFrame::QuicFrame(QuicNewConnectionIdFrame* frame) : type(NEW_CONNECTION_ID_FRAME), new_connection_id_frame(frame) {} QuicFrame::QuicFrame(QuicRetireConnectionIdFrame* frame) : type(RETIRE_CONNECTION_ID_FRAME), retire_connection_id_frame(frame) {} QuicFrame::QuicFrame(QuicMaxStreamsFrame frame) : max_streams_frame(frame) {} QuicFrame::QuicFrame(QuicStreamsBlockedFrame frame) : streams_blocked_frame(frame) {} QuicFrame::QuicFrame(QuicPathResponseFrame* frame) : type(PATH_RESPONSE_FRAME), path_response_frame(frame) {} QuicFrame::QuicFrame(QuicPathChallengeFrame* frame) : type(PATH_CHALLENGE_FRAME), path_challenge_frame(frame) {} QuicFrame::QuicFrame(QuicStopSendingFrame* frame) : type(STOP_SENDING_FRAME), stop_sending_frame(frame) {} QuicFrame::QuicFrame(QuicMessageFrame* frame) : type(MESSAGE_FRAME), message_frame(frame) {} QuicFrame::QuicFrame(QuicNewTokenFrame* frame) : type(NEW_TOKEN_FRAME), new_token_frame(frame) {} void DeleteFrames(QuicFrames* frames) { for (QuicFrame& frame : *frames) { DeleteFrame(&frame); } frames->clear(); } void DeleteFrame(QuicFrame* frame) { switch (frame->type) { // Frames smaller than a pointer are inlined, so don't need to be deleted. case PADDING_FRAME: case MTU_DISCOVERY_FRAME: case PING_FRAME: case MAX_STREAMS_FRAME: case STOP_WAITING_FRAME: case STREAMS_BLOCKED_FRAME: case STREAM_FRAME: break; case ACK_FRAME: delete frame->ack_frame; break; case RST_STREAM_FRAME: delete frame->rst_stream_frame; break; case CONNECTION_CLOSE_FRAME: delete frame->connection_close_frame; break; case GOAWAY_FRAME: delete frame->goaway_frame; break; case BLOCKED_FRAME: delete frame->blocked_frame; break; case WINDOW_UPDATE_FRAME: delete frame->window_update_frame; break; case PATH_CHALLENGE_FRAME: delete frame->path_challenge_frame; break; case STOP_SENDING_FRAME: delete frame->stop_sending_frame; break; case NEW_CONNECTION_ID_FRAME: delete frame->new_connection_id_frame; break; case RETIRE_CONNECTION_ID_FRAME: delete frame->retire_connection_id_frame; break; case PATH_RESPONSE_FRAME: delete frame->path_response_frame; break; case MESSAGE_FRAME: delete frame->message_frame; break; case CRYPTO_FRAME: delete frame->crypto_frame; break; case NEW_TOKEN_FRAME: delete frame->new_token_frame; break; case NUM_FRAME_TYPES: DCHECK(false) << "Cannot delete type: " << frame->type; } } void RemoveFramesForStream(QuicFrames* frames, QuicStreamId stream_id) { auto it = frames->begin(); while (it != frames->end()) { if (it->type != STREAM_FRAME || it->stream_frame.stream_id != stream_id) { ++it; continue; } it = frames->erase(it); } } bool IsControlFrame(QuicFrameType type) { switch (type) { case RST_STREAM_FRAME: case GOAWAY_FRAME: case WINDOW_UPDATE_FRAME: case BLOCKED_FRAME: case STREAMS_BLOCKED_FRAME: case MAX_STREAMS_FRAME: case PING_FRAME: case STOP_SENDING_FRAME: return true; default: return false; } } QuicControlFrameId GetControlFrameId(const QuicFrame& frame) { switch (frame.type) { case RST_STREAM_FRAME: return frame.rst_stream_frame->control_frame_id; case GOAWAY_FRAME: return frame.goaway_frame->control_frame_id; case WINDOW_UPDATE_FRAME: return frame.window_update_frame->control_frame_id; case BLOCKED_FRAME: return frame.blocked_frame->control_frame_id; case STREAMS_BLOCKED_FRAME: return frame.streams_blocked_frame.control_frame_id; case MAX_STREAMS_FRAME: return frame.max_streams_frame.control_frame_id; case PING_FRAME: return frame.ping_frame.control_frame_id; case STOP_SENDING_FRAME: return frame.stop_sending_frame->control_frame_id; default: return kInvalidControlFrameId; } } void SetControlFrameId(QuicControlFrameId control_frame_id, QuicFrame* frame) { switch (frame->type) { case RST_STREAM_FRAME: frame->rst_stream_frame->control_frame_id = control_frame_id; return; case GOAWAY_FRAME: frame->goaway_frame->control_frame_id = control_frame_id; return; case WINDOW_UPDATE_FRAME: frame->window_update_frame->control_frame_id = control_frame_id; return; case BLOCKED_FRAME: frame->blocked_frame->control_frame_id = control_frame_id; return; case PING_FRAME: frame->ping_frame.control_frame_id = control_frame_id; return; case STREAMS_BLOCKED_FRAME: frame->streams_blocked_frame.control_frame_id = control_frame_id; return; case MAX_STREAMS_FRAME: frame->max_streams_frame.control_frame_id = control_frame_id; return; case STOP_SENDING_FRAME: frame->stop_sending_frame->control_frame_id = control_frame_id; return; default: QUIC_BUG << "Try to set control frame id of a frame without control frame id"; } } QuicFrame CopyRetransmittableControlFrame(const QuicFrame& frame) { QuicFrame copy; switch (frame.type) { case RST_STREAM_FRAME: copy = QuicFrame(new QuicRstStreamFrame(*frame.rst_stream_frame)); break; case GOAWAY_FRAME: copy = QuicFrame(new QuicGoAwayFrame(*frame.goaway_frame)); break; case WINDOW_UPDATE_FRAME: copy = QuicFrame(new QuicWindowUpdateFrame(*frame.window_update_frame)); break; case BLOCKED_FRAME: copy = QuicFrame(new QuicBlockedFrame(*frame.blocked_frame)); break; case PING_FRAME: copy = QuicFrame(QuicPingFrame(frame.ping_frame.control_frame_id)); break; case STOP_SENDING_FRAME: copy = QuicFrame(new QuicStopSendingFrame(*frame.stop_sending_frame)); break; case STREAMS_BLOCKED_FRAME: copy = QuicFrame(QuicStreamsBlockedFrame(frame.streams_blocked_frame)); break; case MAX_STREAMS_FRAME: copy = QuicFrame(QuicMaxStreamsFrame(frame.max_streams_frame)); break; default: QUIC_BUG << "Try to copy a non-retransmittable control frame: " << frame; copy = QuicFrame(QuicPingFrame(kInvalidControlFrameId)); break; } return copy; } std::ostream& operator<<(std::ostream& os, const QuicFrame& frame) { switch (frame.type) { case PADDING_FRAME: { os << "type { PADDING_FRAME } " << frame.padding_frame; break; } case RST_STREAM_FRAME: { os << "type { RST_STREAM_FRAME } " << *(frame.rst_stream_frame); break; } case CONNECTION_CLOSE_FRAME: { os << "type { CONNECTION_CLOSE_FRAME } " << *(frame.connection_close_frame); break; } case GOAWAY_FRAME: { os << "type { GOAWAY_FRAME } " << *(frame.goaway_frame); break; } case WINDOW_UPDATE_FRAME: { os << "type { WINDOW_UPDATE_FRAME } " << *(frame.window_update_frame); break; } case BLOCKED_FRAME: { os << "type { BLOCKED_FRAME } " << *(frame.blocked_frame); break; } case STREAM_FRAME: { os << "type { STREAM_FRAME } " << frame.stream_frame; break; } case ACK_FRAME: { os << "type { ACK_FRAME } " << *(frame.ack_frame); break; } case STOP_WAITING_FRAME: { os << "type { STOP_WAITING_FRAME } " << frame.stop_waiting_frame; break; } case PING_FRAME: { os << "type { PING_FRAME } " << frame.ping_frame; break; } case CRYPTO_FRAME: { os << "type { CRYPTO_FRAME } " << frame.crypto_frame; break; } case MTU_DISCOVERY_FRAME: { os << "type { MTU_DISCOVERY_FRAME } "; break; } case NEW_CONNECTION_ID_FRAME: os << "type { NEW_CONNECTION_ID } " << *(frame.new_connection_id_frame); break; case RETIRE_CONNECTION_ID_FRAME: os << "type { RETIRE_CONNECTION_ID } " << *(frame.retire_connection_id_frame); break; case MAX_STREAMS_FRAME: os << "type { MAX_STREAMS } " << frame.max_streams_frame; break; case STREAMS_BLOCKED_FRAME: os << "type { STREAMS_BLOCKED } " << frame.streams_blocked_frame; break; case PATH_RESPONSE_FRAME: os << "type { PATH_RESPONSE } " << *(frame.path_response_frame); break; case PATH_CHALLENGE_FRAME: os << "type { PATH_CHALLENGE } " << *(frame.path_challenge_frame); break; case STOP_SENDING_FRAME: os << "type { STOP_SENDING } " << *(frame.stop_sending_frame); break; case MESSAGE_FRAME: os << "type { MESSAGE_FRAME }" << *(frame.message_frame); break; case NEW_TOKEN_FRAME: os << "type { NEW_TOKEN_FRAME }" << *(frame.new_token_frame); break; default: { QUIC_LOG(ERROR) << "Unknown frame type: " << frame.type; break; } } return os; } } // namespace quic <|endoftext|>
<commit_before>//===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// /// The AMDGPUAsmPrinter is used to print both assembly string and also binary /// code. When passed an MCAsmStreamer it prints assembly and when passed /// an MCObjectStreamer it outputs binary code. // //===----------------------------------------------------------------------===// // #include "AMDGPUAsmPrinter.h" #include "AMDGPU.h" #include "R600Defines.h" #include "R600MachineFunctionInfo.h" #include "R600RegisterInfo.h" #include "SIDefines.h" #include "SIMachineFunctionInfo.h" #include "SIRegisterInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Support/ELF.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetLoweringObjectFile.h" using namespace llvm; static AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm, MCStreamer &Streamer) { return new AMDGPUAsmPrinter(tm, Streamer); } extern "C" void LLVMInitializeR600AsmPrinter() { TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass); } AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer) : AsmPrinter(TM, Streamer) { DisasmEnabled = TM.getSubtarget<AMDGPUSubtarget>().dumpCode() && ! Streamer.hasRawTextSupport(); } /// We need to override this function so we can avoid /// the call to EmitFunctionHeader(), which the MCPureStreamer can't handle. bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { SetupMachineFunction(MF); if (OutStreamer.hasRawTextSupport()) { OutStreamer.EmitRawText("@" + MF.getName() + ":"); } MCContext &Context = getObjFileLowering().getContext(); const MCSectionELF *ConfigSection = Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0, SectionKind::getReadOnly()); OutStreamer.SwitchSection(ConfigSection); const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); SIProgramInfo KernelInfo; if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) { findNumUsedRegistersSI(MF, KernelInfo.NumSGPR, KernelInfo.NumVGPR); EmitProgramInfoSI(MF, KernelInfo); } else { EmitProgramInfoR600(MF); } DisasmLines.clear(); HexLines.clear(); DisasmLineMaxLen = 0; OutStreamer.SwitchSection(getObjFileLowering().getTextSection()); EmitFunctionBody(); if (isVerbose() && OutStreamer.hasRawTextSupport()) { const MCSectionELF *CommentSection = Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0, SectionKind::getReadOnly()); OutStreamer.SwitchSection(CommentSection); if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) { OutStreamer.emitRawComment(" Kernel info:", false); OutStreamer.emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR), false); OutStreamer.emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR), false); } else { R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); OutStreamer.EmitRawText( Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->StackSize))); } } if (STM.dumpCode()) { #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) MF.dump(); #endif if (DisasmEnabled) { OutStreamer.SwitchSection(Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0, SectionKind::getReadOnly())); for (size_t i = 0; i < DisasmLines.size(); ++i) { std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' '); Comment += " ; " + HexLines[i] + "\n"; OutStreamer.EmitBytes(StringRef(DisasmLines[i])); OutStreamer.EmitBytes(StringRef(Comment)); } } } return false; } void AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) { unsigned MaxGPR = 0; bool killPixel = false; const R600RegisterInfo * RI = static_cast<const R600RegisterInfo*>(TM.getRegisterInfo()); R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; if (MI.getOpcode() == AMDGPU::KILLGT) killPixel = true; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand & MO = MI.getOperand(op_idx); if (!MO.isReg()) continue; unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff; // Register with value > 127 aren't GPR if (HWReg > 127) continue; MaxGPR = std::max(MaxGPR, HWReg); } } } unsigned RsrcReg; if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) { // Evergreen / Northern Islands switch (MFI->ShaderType) { default: // Fall through case ShaderType::COMPUTE: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break; case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break; case ShaderType::PIXEL: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break; case ShaderType::VERTEX: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break; } } else { // R600 / R700 switch (MFI->ShaderType) { default: // Fall through case ShaderType::GEOMETRY: // Fall through case ShaderType::COMPUTE: // Fall through case ShaderType::VERTEX: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break; case ShaderType::PIXEL: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break; } } OutStreamer.EmitIntValue(RsrcReg, 4); OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) | S_STACK_SIZE(MFI->StackSize), 4); OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4); OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4); if (MFI->ShaderType == ShaderType::COMPUTE) { OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4); OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4); } } void AMDGPUAsmPrinter::findNumUsedRegistersSI(MachineFunction &MF, unsigned &NumSGPR, unsigned &NumVGPR) const { unsigned MaxSGPR = 0; unsigned MaxVGPR = 0; bool VCCUsed = false; const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM.getRegisterInfo()); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand &MO = MI.getOperand(op_idx); unsigned width = 0; bool isSGPR = false; if (!MO.isReg()) { continue; } unsigned reg = MO.getReg(); if (reg == AMDGPU::VCC) { VCCUsed = true; continue; } switch (reg) { default: break; case AMDGPU::SCC: case AMDGPU::EXEC: case AMDGPU::M0: continue; } if (AMDGPU::SReg_32RegClass.contains(reg)) { isSGPR = true; width = 1; } else if (AMDGPU::VReg_32RegClass.contains(reg)) { isSGPR = false; width = 1; } else if (AMDGPU::SReg_64RegClass.contains(reg)) { isSGPR = true; width = 2; } else if (AMDGPU::VReg_64RegClass.contains(reg)) { isSGPR = false; width = 2; } else if (AMDGPU::VReg_96RegClass.contains(reg)) { isSGPR = false; width = 3; } else if (AMDGPU::SReg_128RegClass.contains(reg)) { isSGPR = true; width = 4; } else if (AMDGPU::VReg_128RegClass.contains(reg)) { isSGPR = false; width = 4; } else if (AMDGPU::SReg_256RegClass.contains(reg)) { isSGPR = true; width = 8; } else if (AMDGPU::VReg_256RegClass.contains(reg)) { isSGPR = false; width = 8; } else if (AMDGPU::SReg_512RegClass.contains(reg)) { isSGPR = true; width = 16; } else if (AMDGPU::VReg_512RegClass.contains(reg)) { isSGPR = false; width = 16; } else { llvm_unreachable("Unknown register class"); } unsigned hwReg = RI->getEncodingValue(reg) & 0xff; unsigned maxUsed = hwReg + width - 1; if (isSGPR) { MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR; } else { MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR; } } } } if (VCCUsed) MaxSGPR += 2; NumSGPR = MaxSGPR; NumVGPR = MaxVGPR; } void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &Out, MachineFunction &MF) const { findNumUsedRegistersSI(MF, Out.NumSGPR, Out.NumVGPR); } void AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF, const SIProgramInfo &KernelInfo) { const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); unsigned RsrcReg; switch (MFI->ShaderType) { default: // Fall through case ShaderType::COMPUTE: RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break; case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break; case ShaderType::PIXEL: RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break; case ShaderType::VERTEX: RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break; } OutStreamer.EmitIntValue(RsrcReg, 4); OutStreamer.EmitIntValue(S_00B028_VGPRS(KernelInfo.NumVGPR / 4) | S_00B028_SGPRS(KernelInfo.NumSGPR / 8), 4); unsigned LDSAlignShift; if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { // LDS is allocated in 64 dword blocks LDSAlignShift = 8; } else { // LDS is allocated in 128 dword blocks LDSAlignShift = 9; } unsigned LDSBlocks = RoundUpToAlignment(MFI->LDSSize, 1 << LDSAlignShift) >> LDSAlignShift; if (MFI->ShaderType == ShaderType::COMPUTE) { OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(LDSBlocks), 4); } if (MFI->ShaderType == ShaderType::PIXEL) { OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(LDSBlocks), 4); OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); OutStreamer.EmitIntValue(MFI->PSInputAddr, 4); } } <commit_msg>Use emitRawComment to avoid a call to hasRawTextSupport.<commit_after>//===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// /// The AMDGPUAsmPrinter is used to print both assembly string and also binary /// code. When passed an MCAsmStreamer it prints assembly and when passed /// an MCObjectStreamer it outputs binary code. // //===----------------------------------------------------------------------===// // #include "AMDGPUAsmPrinter.h" #include "AMDGPU.h" #include "R600Defines.h" #include "R600MachineFunctionInfo.h" #include "R600RegisterInfo.h" #include "SIDefines.h" #include "SIMachineFunctionInfo.h" #include "SIRegisterInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCStreamer.h" #include "llvm/Support/ELF.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetLoweringObjectFile.h" using namespace llvm; static AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm, MCStreamer &Streamer) { return new AMDGPUAsmPrinter(tm, Streamer); } extern "C" void LLVMInitializeR600AsmPrinter() { TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass); } AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer) : AsmPrinter(TM, Streamer) { DisasmEnabled = TM.getSubtarget<AMDGPUSubtarget>().dumpCode() && ! Streamer.hasRawTextSupport(); } /// We need to override this function so we can avoid /// the call to EmitFunctionHeader(), which the MCPureStreamer can't handle. bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { SetupMachineFunction(MF); OutStreamer.emitRawComment(Twine('@') + MF.getName() + Twine(':')); MCContext &Context = getObjFileLowering().getContext(); const MCSectionELF *ConfigSection = Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0, SectionKind::getReadOnly()); OutStreamer.SwitchSection(ConfigSection); const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); SIProgramInfo KernelInfo; if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) { findNumUsedRegistersSI(MF, KernelInfo.NumSGPR, KernelInfo.NumVGPR); EmitProgramInfoSI(MF, KernelInfo); } else { EmitProgramInfoR600(MF); } DisasmLines.clear(); HexLines.clear(); DisasmLineMaxLen = 0; OutStreamer.SwitchSection(getObjFileLowering().getTextSection()); EmitFunctionBody(); if (isVerbose() && OutStreamer.hasRawTextSupport()) { const MCSectionELF *CommentSection = Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0, SectionKind::getReadOnly()); OutStreamer.SwitchSection(CommentSection); if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) { OutStreamer.emitRawComment(" Kernel info:", false); OutStreamer.emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR), false); OutStreamer.emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR), false); } else { R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); OutStreamer.EmitRawText( Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->StackSize))); } } if (STM.dumpCode()) { #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) MF.dump(); #endif if (DisasmEnabled) { OutStreamer.SwitchSection(Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0, SectionKind::getReadOnly())); for (size_t i = 0; i < DisasmLines.size(); ++i) { std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' '); Comment += " ; " + HexLines[i] + "\n"; OutStreamer.EmitBytes(StringRef(DisasmLines[i])); OutStreamer.EmitBytes(StringRef(Comment)); } } } return false; } void AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) { unsigned MaxGPR = 0; bool killPixel = false; const R600RegisterInfo * RI = static_cast<const R600RegisterInfo*>(TM.getRegisterInfo()); R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>(); const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; if (MI.getOpcode() == AMDGPU::KILLGT) killPixel = true; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand & MO = MI.getOperand(op_idx); if (!MO.isReg()) continue; unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff; // Register with value > 127 aren't GPR if (HWReg > 127) continue; MaxGPR = std::max(MaxGPR, HWReg); } } } unsigned RsrcReg; if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) { // Evergreen / Northern Islands switch (MFI->ShaderType) { default: // Fall through case ShaderType::COMPUTE: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break; case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break; case ShaderType::PIXEL: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break; case ShaderType::VERTEX: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break; } } else { // R600 / R700 switch (MFI->ShaderType) { default: // Fall through case ShaderType::GEOMETRY: // Fall through case ShaderType::COMPUTE: // Fall through case ShaderType::VERTEX: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break; case ShaderType::PIXEL: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break; } } OutStreamer.EmitIntValue(RsrcReg, 4); OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) | S_STACK_SIZE(MFI->StackSize), 4); OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4); OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4); if (MFI->ShaderType == ShaderType::COMPUTE) { OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4); OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4); } } void AMDGPUAsmPrinter::findNumUsedRegistersSI(MachineFunction &MF, unsigned &NumSGPR, unsigned &NumVGPR) const { unsigned MaxSGPR = 0; unsigned MaxVGPR = 0; bool VCCUsed = false; const SIRegisterInfo * RI = static_cast<const SIRegisterInfo*>(TM.getRegisterInfo()); for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end(); BB != BB_E; ++BB) { MachineBasicBlock &MBB = *BB; for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ++I) { MachineInstr &MI = *I; unsigned numOperands = MI.getNumOperands(); for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) { MachineOperand &MO = MI.getOperand(op_idx); unsigned width = 0; bool isSGPR = false; if (!MO.isReg()) { continue; } unsigned reg = MO.getReg(); if (reg == AMDGPU::VCC) { VCCUsed = true; continue; } switch (reg) { default: break; case AMDGPU::SCC: case AMDGPU::EXEC: case AMDGPU::M0: continue; } if (AMDGPU::SReg_32RegClass.contains(reg)) { isSGPR = true; width = 1; } else if (AMDGPU::VReg_32RegClass.contains(reg)) { isSGPR = false; width = 1; } else if (AMDGPU::SReg_64RegClass.contains(reg)) { isSGPR = true; width = 2; } else if (AMDGPU::VReg_64RegClass.contains(reg)) { isSGPR = false; width = 2; } else if (AMDGPU::VReg_96RegClass.contains(reg)) { isSGPR = false; width = 3; } else if (AMDGPU::SReg_128RegClass.contains(reg)) { isSGPR = true; width = 4; } else if (AMDGPU::VReg_128RegClass.contains(reg)) { isSGPR = false; width = 4; } else if (AMDGPU::SReg_256RegClass.contains(reg)) { isSGPR = true; width = 8; } else if (AMDGPU::VReg_256RegClass.contains(reg)) { isSGPR = false; width = 8; } else if (AMDGPU::SReg_512RegClass.contains(reg)) { isSGPR = true; width = 16; } else if (AMDGPU::VReg_512RegClass.contains(reg)) { isSGPR = false; width = 16; } else { llvm_unreachable("Unknown register class"); } unsigned hwReg = RI->getEncodingValue(reg) & 0xff; unsigned maxUsed = hwReg + width - 1; if (isSGPR) { MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR; } else { MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR; } } } } if (VCCUsed) MaxSGPR += 2; NumSGPR = MaxSGPR; NumVGPR = MaxVGPR; } void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &Out, MachineFunction &MF) const { findNumUsedRegistersSI(MF, Out.NumSGPR, Out.NumVGPR); } void AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF, const SIProgramInfo &KernelInfo) { const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>(); SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); unsigned RsrcReg; switch (MFI->ShaderType) { default: // Fall through case ShaderType::COMPUTE: RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break; case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break; case ShaderType::PIXEL: RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break; case ShaderType::VERTEX: RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break; } OutStreamer.EmitIntValue(RsrcReg, 4); OutStreamer.EmitIntValue(S_00B028_VGPRS(KernelInfo.NumVGPR / 4) | S_00B028_SGPRS(KernelInfo.NumSGPR / 8), 4); unsigned LDSAlignShift; if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { // LDS is allocated in 64 dword blocks LDSAlignShift = 8; } else { // LDS is allocated in 128 dword blocks LDSAlignShift = 9; } unsigned LDSBlocks = RoundUpToAlignment(MFI->LDSSize, 1 << LDSAlignShift) >> LDSAlignShift; if (MFI->ShaderType == ShaderType::COMPUTE) { OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(LDSBlocks), 4); } if (MFI->ShaderType == ShaderType::PIXEL) { OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(LDSBlocks), 4); OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); OutStreamer.EmitIntValue(MFI->PSInputAddr, 4); } } <|endoftext|>
<commit_before>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the MapValue function, which is shared by various parts of // the lib/Transforms/Utils library. // //===----------------------------------------------------------------------===// #include "ValueMapper.h" #include "llvm/Type.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/Metadata.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM) { Value *&VMSlot = VM[V]; if (VMSlot) return VMSlot; // Does it exist in the map yet? // NOTE: VMSlot can be invalidated by any reference to VM, which can grow the // DenseMap. This includes any recursive calls to MapValue. // Global values and non-function-local metadata do not need to be seeded into // the ValueMap if they are using the identity mapping. if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MDString>(V) || (isa<MDNode>(V) && !cast<MDNode>(V)->isFunctionLocal())) return VMSlot = const_cast<Value*>(V); if (const MDNode *MD = dyn_cast<MDNode>(V)) { SmallVector<Value*, 4> Elts; for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i) Elts.push_back(MD->getOperand(i) ? MapValue(MD->getOperand(i), VM) : 0); return VM[V] = MDNode::get(V->getContext(), Elts.data(), Elts.size()); } Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)); if (C == 0) return 0; if (isa<ConstantInt>(C) || isa<ConstantFP>(C) || isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C) || isa<MDString>(C)) return VMSlot = C; // Primitive constants map directly if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) { for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This array must contain a reference to a global, make a new array // and return it. // std::vector<Constant*> Values; Values.reserve(CA->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantArray::get(CA->getType(), Values); } } return VM[V] = C; } if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This struct must contain a reference to a global, make a new struct // and return it. // std::vector<Constant*> Values; Values.reserve(CS->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantStruct::get(CS->getType(), Values); } } return VM[V] = C; } if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { std::vector<Constant*> Ops; for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i) Ops.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = CE->getWithOperands(Ops); } if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) { for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This vector value must contain a reference to a global, make a new // vector constant and return it. // std::vector<Constant*> Values; Values.reserve(CV->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantVector::get(Values); } } return VM[V] = C; } BlockAddress *BA = cast<BlockAddress>(C); Function *F = cast<Function>(MapValue(BA->getFunction(), VM)); BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM)); return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock()); } /// RemapInstruction - Convert the instruction operands from referencing the /// current values into those specified by ValueMap. /// void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &ValueMap) { for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) { Value *V = MapValue(*op, ValueMap); assert(V && "Referenced value not in value map!"); *op = V; } } <commit_msg>If a metadata operand is seeded in value map and the metadata should also be seeded in value map. This is not limited to function local metadata. <commit_after>//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the MapValue function, which is shared by various parts of // the lib/Transforms/Utils library. // //===----------------------------------------------------------------------===// #include "ValueMapper.h" #include "llvm/Type.h" #include "llvm/Constants.h" #include "llvm/Function.h" #include "llvm/Metadata.h" #include "llvm/ADT/SmallVector.h" using namespace llvm; Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM) { ValueToValueMapTy::iterator VMI = VM.find(V); if (VMI != VM.end()) return VMI->second; // Does it exist in the map yet? // Global values, metadata strings and inline asm do not need to be seeded into // the ValueMap if they are using the identity mapping. if (isa<GlobalValue>(V) || isa<InlineAsm>(V) || isa<MDString>(V)) { VM.insert(std::make_pair(V, const_cast<Value*>(V))); return const_cast<Value*>(V); } if (const MDNode *MD = dyn_cast<MDNode>(V)) { // Insert a place holder in map to handle mdnode cycles. Value *TmpV = MDString::get(V->getContext(), std::string("llvm.md.clone.tmp." + VM.size())); VM.insert(std::make_pair(V, MDNode::get(V->getContext(), &TmpV, 1))); bool ReuseMD = true; SmallVector<Value*, 4> Elts; // If metadata element is mapped to a new value then seed metadata // in the map. for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i) { if (!MD->getOperand(i)) Elts.push_back(0); else { Value *MappedOp = MapValue(MD->getOperand(i), VM); if (MappedOp != MD->getOperand(i)) ReuseMD = false; Elts.push_back(MappedOp); } } if (ReuseMD) { VM.insert(std::make_pair(V, const_cast<Value*>(V))); return const_cast<Value*>(V); } MDNode *NewMD = MDNode::get(V->getContext(), Elts.data(), Elts.size()); VM.insert(std::make_pair(V, NewMD)); return NewMD; } Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)); if (C == 0) return 0; if (isa<ConstantInt>(C) || isa<ConstantFP>(C) || isa<ConstantPointerNull>(C) || isa<ConstantAggregateZero>(C) || isa<UndefValue>(C) || isa<MDString>(C)) return VM[V] = C; // Primitive constants map directly if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) { for (User::op_iterator b = CA->op_begin(), i = b, e = CA->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This array must contain a reference to a global, make a new array // and return it. // std::vector<Constant*> Values; Values.reserve(CA->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantArray::get(CA->getType(), Values); } } return VM[V] = C; } if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) { for (User::op_iterator b = CS->op_begin(), i = b, e = CS->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This struct must contain a reference to a global, make a new struct // and return it. // std::vector<Constant*> Values; Values.reserve(CS->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantStruct::get(CS->getType(), Values); } } return VM[V] = C; } if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { std::vector<Constant*> Ops; for (User::op_iterator i = CE->op_begin(), e = CE->op_end(); i != e; ++i) Ops.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = CE->getWithOperands(Ops); } if (ConstantVector *CV = dyn_cast<ConstantVector>(C)) { for (User::op_iterator b = CV->op_begin(), i = b, e = CV->op_end(); i != e; ++i) { Value *MV = MapValue(*i, VM); if (MV != *i) { // This vector value must contain a reference to a global, make a new // vector constant and return it. // std::vector<Constant*> Values; Values.reserve(CV->getNumOperands()); for (User::op_iterator j = b; j != i; ++j) Values.push_back(cast<Constant>(*j)); Values.push_back(cast<Constant>(MV)); for (++i; i != e; ++i) Values.push_back(cast<Constant>(MapValue(*i, VM))); return VM[V] = ConstantVector::get(Values); } } return VM[V] = C; } BlockAddress *BA = cast<BlockAddress>(C); Function *F = cast<Function>(MapValue(BA->getFunction(), VM)); BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(),VM)); return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock()); } /// RemapInstruction - Convert the instruction operands from referencing the /// current values into those specified by ValueMap. /// void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &ValueMap) { for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) { Value *V = MapValue(*op, ValueMap); assert(V && "Referenced value not in value map!"); *op = V; } } <|endoftext|>
<commit_before>#include <QtCore/qmath.h> #include <utils/RgbTransform.h> RgbTransform::RgbTransform() { init(1.0, 1.0, 1.0, 0.0, false, 100, 100); } RgbTransform::RgbTransform(double gammaR, double gammaG, double gammaB, double backlightThreshold, bool backlightColored, uint8_t brightness, uint8_t brightnessCompensation) { init(gammaR, gammaG, gammaB, backlightThreshold, backlightColored, brightness, brightnessCompensation); } void RgbTransform::init(double gammaR, double gammaG, double gammaB, double backlightThreshold, bool backlightColored, uint8_t brightness, uint8_t brightnessCompensation) { _backLightEnabled = true; setGamma(gammaR,gammaG,gammaB); setBacklightThreshold(backlightThreshold); setBacklightColored(backlightColored); setBrightness(brightness); setBrightnessCompensation(brightnessCompensation); initializeMapping(); } RgbTransform::~RgbTransform() { } double RgbTransform::getGammaR() const { return _gammaR; } double RgbTransform::getGammaG() const { return _gammaG; } double RgbTransform::getGammaB() const { return _gammaB; } void RgbTransform::setGamma(double gammaR, double gammaG, double gammaB) { _gammaR = gammaR; _gammaG = (gammaG < 0.0) ? _gammaR : gammaG; _gammaB = (gammaB < 0.0) ? _gammaR : gammaB; initializeMapping(); } void RgbTransform::initializeMapping() { for (int i = 0; i < 256; ++i) { _mappingR[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaR) * 255), 0), 255); _mappingG[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaG) * 255), 0), 255); _mappingB[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaB) * 255), 0), 255); } } int RgbTransform::getBacklightThreshold() const { return _backlightThreshold; } void RgbTransform::setBacklightThreshold(int backlightThreshold) { _backlightThreshold = backlightThreshold; _sumBrightnessLow = 765.0 * ((qPow(2.0,(_backlightThreshold/100)*2)-1) / 3.0); } bool RgbTransform::getBacklightColored() const { return _backlightColored; } void RgbTransform::setBacklightColored(bool backlightColored) { _backlightColored = backlightColored; } bool RgbTransform::getBackLightEnabled() const { return _backLightEnabled; } void RgbTransform::setBackLightEnabled(bool enable) { _backLightEnabled = enable; } uint8_t RgbTransform::getBrightness() const { return _brightness; } void RgbTransform::setBrightness(uint8_t brightness) { _brightness = brightness; updateBrightnessComponents(); } void RgbTransform::setBrightnessCompensation(uint8_t brightnessCompensation) { _brightnessCompensation = brightnessCompensation; updateBrightnessComponents(); } uint8_t RgbTransform::getBrightnessCompensation() const { return _brightnessCompensation; } void RgbTransform::updateBrightnessComponents() { double Fw = _brightnessCompensation*2.0/100.0+1.0; double Fcmy = _brightnessCompensation/100.0+1.0; double B_in= 0; _brightness_rgb = 0; _brightness_cmy = 0; _brightness_w = 0; if (_brightness > 0) { B_in = (_brightness<50)? -0.09*_brightness+7.5 : -0.04*_brightness+5.0; _brightness_rgb = std::ceil(qMin(255.0,255.0/B_in)); _brightness_cmy = std::ceil(qMin(255.0,255.0/(B_in*Fcmy))); _brightness_w = std::ceil(qMin(255.0,255.0/(B_in*Fw))); } } void RgbTransform::getBrightnessComponents(uint8_t & rgb, uint8_t & cmy, uint8_t & w ) { rgb = _brightness_rgb; cmy = _brightness_cmy; w = _brightness_w; } void RgbTransform::transform(uint8_t & red, uint8_t & green, uint8_t & blue) { // apply gamma red = _mappingR[red]; green = _mappingR[green]; blue = _mappingR[blue]; // apply brightnesss int rgbSum = red+green+blue; if ( _backLightEnabled && _sumBrightnessLow>0 && rgbSum < _sumBrightnessLow) { if (_backlightColored) { if (rgbSum == 0) { if (red ==0) red = 1; if (green==0) green = 1; if (blue ==0) blue = 1; rgbSum = red+green+blue; } double cL =qMin((int)(_sumBrightnessLow /rgbSum), 255); red *= cL; green *= cL; blue *= cL; } else { red = qMin((int)(_sumBrightnessLow/3.0), 255); green = red; blue = red; } } } <commit_msg>RGBTransform fix gamma adjustment of green, blue always taking red value<commit_after>#include <QtCore/qmath.h> #include <utils/RgbTransform.h> RgbTransform::RgbTransform() { init(1.0, 1.0, 1.0, 0.0, false, 100, 100); } RgbTransform::RgbTransform(double gammaR, double gammaG, double gammaB, double backlightThreshold, bool backlightColored, uint8_t brightness, uint8_t brightnessCompensation) { init(gammaR, gammaG, gammaB, backlightThreshold, backlightColored, brightness, brightnessCompensation); } void RgbTransform::init(double gammaR, double gammaG, double gammaB, double backlightThreshold, bool backlightColored, uint8_t brightness, uint8_t brightnessCompensation) { _backLightEnabled = true; setGamma(gammaR,gammaG,gammaB); setBacklightThreshold(backlightThreshold); setBacklightColored(backlightColored); setBrightness(brightness); setBrightnessCompensation(brightnessCompensation); initializeMapping(); } RgbTransform::~RgbTransform() { } double RgbTransform::getGammaR() const { return _gammaR; } double RgbTransform::getGammaG() const { return _gammaG; } double RgbTransform::getGammaB() const { return _gammaB; } void RgbTransform::setGamma(double gammaR, double gammaG, double gammaB) { _gammaR = gammaR; _gammaG = (gammaG < 0.0) ? _gammaR : gammaG; _gammaB = (gammaB < 0.0) ? _gammaR : gammaB; initializeMapping(); } void RgbTransform::initializeMapping() { for (int i = 0; i < 256; ++i) { _mappingR[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaR) * 255), 0), 255); _mappingG[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaG) * 255), 0), 255); _mappingB[i] = qMin(qMax((int)(qPow(i / 255.0, _gammaB) * 255), 0), 255); } } int RgbTransform::getBacklightThreshold() const { return _backlightThreshold; } void RgbTransform::setBacklightThreshold(int backlightThreshold) { _backlightThreshold = backlightThreshold; _sumBrightnessLow = 765.0 * ((qPow(2.0,(_backlightThreshold/100)*2)-1) / 3.0); } bool RgbTransform::getBacklightColored() const { return _backlightColored; } void RgbTransform::setBacklightColored(bool backlightColored) { _backlightColored = backlightColored; } bool RgbTransform::getBackLightEnabled() const { return _backLightEnabled; } void RgbTransform::setBackLightEnabled(bool enable) { _backLightEnabled = enable; } uint8_t RgbTransform::getBrightness() const { return _brightness; } void RgbTransform::setBrightness(uint8_t brightness) { _brightness = brightness; updateBrightnessComponents(); } void RgbTransform::setBrightnessCompensation(uint8_t brightnessCompensation) { _brightnessCompensation = brightnessCompensation; updateBrightnessComponents(); } uint8_t RgbTransform::getBrightnessCompensation() const { return _brightnessCompensation; } void RgbTransform::updateBrightnessComponents() { double Fw = _brightnessCompensation*2.0/100.0+1.0; double Fcmy = _brightnessCompensation/100.0+1.0; double B_in= 0; _brightness_rgb = 0; _brightness_cmy = 0; _brightness_w = 0; if (_brightness > 0) { B_in = (_brightness<50)? -0.09*_brightness+7.5 : -0.04*_brightness+5.0; _brightness_rgb = std::ceil(qMin(255.0,255.0/B_in)); _brightness_cmy = std::ceil(qMin(255.0,255.0/(B_in*Fcmy))); _brightness_w = std::ceil(qMin(255.0,255.0/(B_in*Fw))); } } void RgbTransform::getBrightnessComponents(uint8_t & rgb, uint8_t & cmy, uint8_t & w ) { rgb = _brightness_rgb; cmy = _brightness_cmy; w = _brightness_w; } void RgbTransform::transform(uint8_t & red, uint8_t & green, uint8_t & blue) { // apply gamma red = _mappingR[red]; green = _mappingG[green]; blue = _mappingB[blue]; // apply brightnesss int rgbSum = red+green+blue; if ( _backLightEnabled && _sumBrightnessLow>0 && rgbSum < _sumBrightnessLow) { if (_backlightColored) { if (rgbSum == 0) { if (red ==0) red = 1; if (green==0) green = 1; if (blue ==0) blue = 1; rgbSum = red+green+blue; } double cL =qMin((int)(_sumBrightnessLow /rgbSum), 255); red *= cL; green *= cL; blue *= cL; } else { red = qMin((int)(_sumBrightnessLow/3.0), 255); green = red; blue = red; } } } <|endoftext|>
<commit_before>// python2/3 module for tinyobjloader // // usage: // import tinyobjloader as tol // model = tol.LoadObj(name) // print(model["shapes"]) // print(model["materials"] // note: // `shape.mesh.index_t` is represented as flattened array: (vertex_index, normal_index, texcoord_index) * num_faces #include <Python.h> #include <vector> #include "../tiny_obj_loader.h" typedef std::vector<double> vectd; typedef std::vector<int> vecti; PyObject* pyTupleFromfloat3(float array[3]) { int i; PyObject* tuple = PyTuple_New(3); for (i = 0; i <= 2; i++) { PyTuple_SetItem(tuple, i, PyFloat_FromDouble(array[i])); } return tuple; } extern "C" { static PyObject* pyLoadObj(PyObject* self, PyObject* args) { PyObject *rtndict, *pyshapes, *pymaterials, *pymaterial_indices, *attribobj, *current, *meshobj; char const* current_name; char const* filename; vectd vect; std::vector<tinyobj::index_t> indices; std::vector<unsigned char> face_verts; tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!PyArg_ParseTuple(args, "s", &filename)) return NULL; std::string err; tinyobj::LoadObj(&attrib, &shapes, &materials, &err, filename); pyshapes = PyDict_New(); pymaterials = PyDict_New(); pymaterial_indices = PyDict_New(); rtndict = PyDict_New(); attribobj = PyDict_New(); for (int i = 0; i <= 2; i++) { current = PyList_New(0); switch (i) { case 0: current_name = "vertices"; vect = vectd(attrib.vertices.begin(), attrib.vertices.end()); break; case 1: current_name = "normals"; vect = vectd(attrib.normals.begin(), attrib.normals.end()); break; case 2: current_name = "texcoords"; vect = vectd(attrib.texcoords.begin(), attrib.texcoords.end()); break; } for (vectd::iterator it = vect.begin(); it != vect.end(); it++) { PyList_Insert(current, it - vect.begin(), PyFloat_FromDouble(*it)); } PyDict_SetItemString(attribobj, current_name, current); } for (std::vector<tinyobj::shape_t>::iterator shape = shapes.begin(); shape != shapes.end(); shape++) { meshobj = PyDict_New(); tinyobj::mesh_t cm = (*shape).mesh; { current = PyList_New(0); for (size_t i = 0; i < cm.indices.size(); i++) { // Flatten index array: v_idx, vn_idx, vt_idx, v_idx, vn_idx, vt_idx, // ... PyList_Insert(current, 3 * i + 0, PyLong_FromLong(cm.indices[i].vertex_index)); PyList_Insert(current, 3 * i + 1, PyLong_FromLong(cm.indices[i].normal_index)); PyList_Insert(current, 3 * i + 2, PyLong_FromLong(cm.indices[i].texcoord_index)); } PyDict_SetItemString(meshobj, "indices", current); } { current = PyList_New(0); for (size_t i = 0; i < cm.num_face_vertices.size(); i++) { // Widen data type to long. PyList_Insert(current, i, PyLong_FromLong(cm.num_face_vertices[i])); } PyDict_SetItemString(meshobj, "num_face_vertices", current); } { current = PyList_New(0); for (size_t i = 0; i < cm.material_ids.size(); i++) { PyList_Insert(current, i, PyLong_FromLong(cm.material_ids[i])); } PyDict_SetItemString(meshobj, "material_ids", current); } PyDict_SetItemString(pyshapes, (*shape).name.c_str(), meshobj); } long material_index = 0; for (std::vector<tinyobj::material_t>::iterator mat = materials.begin(); mat != materials.end(); mat++) { PyObject* matobj = PyDict_New(); PyObject* unknown_parameter = PyDict_New(); for (std::map<std::string, std::string>::iterator p = (*mat).unknown_parameter.begin(); p != (*mat).unknown_parameter.end(); ++p) { PyDict_SetItemString(unknown_parameter, p->first.c_str(), PyUnicode_FromString(p->second.c_str())); } PyDict_SetItemString(matobj, "shininess", PyFloat_FromDouble((*mat).shininess)); PyDict_SetItemString(matobj, "ior", PyFloat_FromDouble((*mat).ior)); PyDict_SetItemString(matobj, "dissolve", PyFloat_FromDouble((*mat).dissolve)); PyDict_SetItemString(matobj, "illum", PyLong_FromLong((*mat).illum)); PyDict_SetItemString(matobj, "ambient_texname", PyUnicode_FromString((*mat).ambient_texname.c_str())); PyDict_SetItemString(matobj, "diffuse_texname", PyUnicode_FromString((*mat).diffuse_texname.c_str())); PyDict_SetItemString(matobj, "specular_texname", PyUnicode_FromString((*mat).specular_texname.c_str())); PyDict_SetItemString( matobj, "specular_highlight_texname", PyUnicode_FromString((*mat).specular_highlight_texname.c_str())); PyDict_SetItemString(matobj, "bump_texname", PyUnicode_FromString((*mat).bump_texname.c_str())); PyDict_SetItemString( matobj, "displacement_texname", PyUnicode_FromString((*mat).displacement_texname.c_str())); PyDict_SetItemString(matobj, "alpha_texname", PyUnicode_FromString((*mat).alpha_texname.c_str())); PyDict_SetItemString(matobj, "ambient", pyTupleFromfloat3((*mat).ambient)); PyDict_SetItemString(matobj, "diffuse", pyTupleFromfloat3((*mat).diffuse)); PyDict_SetItemString(matobj, "specular", pyTupleFromfloat3((*mat).specular)); PyDict_SetItemString(matobj, "transmittance", pyTupleFromfloat3((*mat).transmittance)); PyDict_SetItemString(matobj, "emission", pyTupleFromfloat3((*mat).emission)); PyDict_SetItemString(matobj, "unknown_parameter", unknown_parameter); PyDict_SetItemString(pymaterials, (*mat).name.c_str(), matobj); PyDict_SetItemString(pymaterial_indices, PyLong_FromLong(material_index++), (*mat).name.c_str()); } PyDict_SetItemString(rtndict, "shapes", pyshapes); PyDict_SetItemString(rtndict, "materials", pymaterials); PyDict_SetItemString(rtndict, "material_indices", pymaterial_indices); PyDict_SetItemString(rtndict, "attribs", attribobj); return rtndict; } static PyMethodDef mMethods[] = { {"LoadObj", pyLoadObj, METH_VARARGS}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, "tinyobjloader", NULL, -1, mMethods}; PyMODINIT_FUNC PyInit_tinyobjloader(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC inittinyobjloader(void) { Py_InitModule3("tinyobjloader", mMethods, NULL); } #endif // PY_MAJOR_VERSION >= 3 } <commit_msg>Fix mapping for #131 and compilation error #139 #132 (related)<commit_after>// python2/3 module for tinyobjloader // // usage: // import tinyobjloader as tol // model = tol.LoadObj(name) // print(model["shapes"]) // print(model["materials"] // note: // `shape.mesh.index_t` is represented as flattened array: (vertex_index, normal_index, texcoord_index) * num_faces #include <Python.h> #include <vector> #include "../tiny_obj_loader.h" typedef std::vector<double> vectd; typedef std::vector<int> vecti; PyObject* pyTupleFromfloat3(float array[3]) { int i; PyObject* tuple = PyTuple_New(3); for (i = 0; i <= 2; i++) { PyTuple_SetItem(tuple, i, PyFloat_FromDouble(array[i])); } return tuple; } extern "C" { static PyObject* pyLoadObj(PyObject* self, PyObject* args) { PyObject *rtndict, *pyshapes, *pymaterials, *pymaterial_indices, *attribobj, *current, *meshobj; char const* current_name; char const* filename; vectd vect; std::vector<tinyobj::index_t> indices; std::vector<unsigned char> face_verts; tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; if (!PyArg_ParseTuple(args, "s", &filename)) return NULL; std::string err; tinyobj::LoadObj(&attrib, &shapes, &materials, &err, filename); pyshapes = PyDict_New(); pymaterials = PyDict_New(); pymaterial_indices = PyList_New(0); rtndict = PyDict_New(); attribobj = PyDict_New(); for (int i = 0; i <= 2; i++) { current = PyList_New(0); switch (i) { case 0: current_name = "vertices"; vect = vectd(attrib.vertices.begin(), attrib.vertices.end()); break; case 1: current_name = "normals"; vect = vectd(attrib.normals.begin(), attrib.normals.end()); break; case 2: current_name = "texcoords"; vect = vectd(attrib.texcoords.begin(), attrib.texcoords.end()); break; } for (vectd::iterator it = vect.begin(); it != vect.end(); it++) { PyList_Insert(current, it - vect.begin(), PyFloat_FromDouble(*it)); } PyDict_SetItemString(attribobj, current_name, current); } for (std::vector<tinyobj::shape_t>::iterator shape = shapes.begin(); shape != shapes.end(); shape++) { meshobj = PyDict_New(); tinyobj::mesh_t cm = (*shape).mesh; { current = PyList_New(0); for (size_t i = 0; i < cm.indices.size(); i++) { // Flatten index array: v_idx, vn_idx, vt_idx, v_idx, vn_idx, vt_idx, // ... PyList_Insert(current, 3 * i + 0, PyLong_FromLong(cm.indices[i].vertex_index)); PyList_Insert(current, 3 * i + 1, PyLong_FromLong(cm.indices[i].normal_index)); PyList_Insert(current, 3 * i + 2, PyLong_FromLong(cm.indices[i].texcoord_index)); } PyDict_SetItemString(meshobj, "indices", current); } { current = PyList_New(0); for (size_t i = 0; i < cm.num_face_vertices.size(); i++) { // Widen data type to long. PyList_Insert(current, i, PyLong_FromLong(cm.num_face_vertices[i])); } PyDict_SetItemString(meshobj, "num_face_vertices", current); } { current = PyList_New(0); for (size_t i = 0; i < cm.material_ids.size(); i++) { PyList_Insert(current, i, PyLong_FromLong(cm.material_ids[i])); } PyDict_SetItemString(meshobj, "material_ids", current); } PyDict_SetItemString(pyshapes, (*shape).name.c_str(), meshobj); } for (std::vector<tinyobj::material_t>::iterator mat = materials.begin(); mat != materials.end(); mat++) { PyObject* matobj = PyDict_New(); PyObject* unknown_parameter = PyDict_New(); for (std::map<std::string, std::string>::iterator p = mat->unknown_parameter.begin(); p != mat->unknown_parameter.end(); ++p) { PyDict_SetItemString(unknown_parameter, p->first.c_str(), PyUnicode_FromString(p->second.c_str())); } PyDict_SetItemString(matobj, "shininess", PyFloat_FromDouble(mat->shininess)); PyDict_SetItemString(matobj, "ior", PyFloat_FromDouble(mat->ior)); PyDict_SetItemString(matobj, "dissolve", PyFloat_FromDouble(mat->dissolve)); PyDict_SetItemString(matobj, "illum", PyLong_FromLong(mat->illum)); PyDict_SetItemString(matobj, "ambient_texname", PyUnicode_FromString(mat->ambient_texname.c_str())); PyDict_SetItemString(matobj, "diffuse_texname", PyUnicode_FromString(mat->diffuse_texname.c_str())); PyDict_SetItemString(matobj, "specular_texname", PyUnicode_FromString(mat->specular_texname.c_str())); PyDict_SetItemString( matobj, "specular_highlight_texname", PyUnicode_FromString(mat->specular_highlight_texname.c_str())); PyDict_SetItemString(matobj, "bump_texname", PyUnicode_FromString(mat->bump_texname.c_str())); PyDict_SetItemString( matobj, "displacement_texname", PyUnicode_FromString(mat->displacement_texname.c_str())); PyDict_SetItemString(matobj, "alpha_texname", PyUnicode_FromString(mat->alpha_texname.c_str())); PyDict_SetItemString(matobj, "ambient", pyTupleFromfloat3(mat->ambient)); PyDict_SetItemString(matobj, "diffuse", pyTupleFromfloat3(mat->diffuse)); PyDict_SetItemString(matobj, "specular", pyTupleFromfloat3(mat->specular)); PyDict_SetItemString(matobj, "transmittance", pyTupleFromfloat3(mat->transmittance)); PyDict_SetItemString(matobj, "emission", pyTupleFromfloat3(mat->emission)); PyDict_SetItemString(matobj, "unknown_parameter", unknown_parameter); PyDict_SetItemString(pymaterials, mat->name.c_str(), matobj); PyList_Append(pymaterial_indices, PyUnicode_FromString(mat->name.c_str())); } PyDict_SetItemString(rtndict, "shapes", pyshapes); PyDict_SetItemString(rtndict, "materials", pymaterials); PyDict_SetItemString(rtndict, "material_indices", pymaterial_indices); PyDict_SetItemString(rtndict, "attribs", attribobj); return rtndict; } static PyMethodDef mMethods[] = { {"LoadObj", pyLoadObj, METH_VARARGS}, {NULL, NULL, 0, NULL} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, "tinyobjloader", NULL, -1, mMethods}; PyMODINIT_FUNC PyInit_tinyobjloader(void) { return PyModule_Create(&moduledef); } #else PyMODINIT_FUNC inittinyobjloader(void) { Py_InitModule3("tinyobjloader", mMethods, NULL); } #endif // PY_MAJOR_VERSION >= 3 } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include <cryptopp/md5.h> #include "bytes_ostream.hh" #include "query-request.hh" #include "db/serializer.hh" namespace query { class result_digest { bytes _digest; public: result_digest(bytes&& digest) : _digest(std::move(digest)) {} const bytes& get() const { return _digest; } bool operator==(const result_digest& rh) const { return _digest == rh._digest; } bool operator!=(const result_digest& rh) const { return _digest != rh._digest; } size_t serialized_size() const { return _digest.size(); } void serialize(bytes::iterator& out) const { out = std::copy(_digest.begin(), _digest.end(), out); } static result_digest deserialize(bytes_view& in) { auto result = result_digest(bytes(in.begin(), in.end())); in.remove_prefix(in.size()); return result; } }; // // The query results are stored in a serialized form. This is in order to // address the following problems, which a structured format has: // // - high level of indirection (vector of vectors of vectors of blobs), which // is not CPU cache friendly // // - high allocation rate due to fine-grained object structure // // On replica side, the query results are probably going to be serialized in // the transport layer anyway, so serializing the results up-front doesn't add // net work. There is no processing of the query results on replica other than // concatenation in case of range queries and checksum calculation. If query // results are collected in serialized form from different cores, we can // concatenate them without copying by simply appending the fragments into the // packet. // // On coordinator side, the query results would have to be parsed from the // transport layer buffers anyway, so the fact that iterators parse it also // doesn't add net work, but again saves allocations and copying. The CQL // server doesn't need complex data structures to process the results, it just // goes over it linearly consuming it. // // The coordinator side could be optimized even further for CQL queries which // do not need processing (eg. select * from cf where ...). We could make the // replica send the query results in the format which is expected by the CQL // binary protocol client. So in the typical case the coordinator would just // pass the data using zero-copy to the client, prepending a header. // // Users which need more complex structure of query results, should // transform it to such using appropriate visitors. // TODO: insert reference to such visitors here. // // Query results have dynamic format. In some queries (maybe even in typical // ones), we don't need to send partition or clustering keys back to the // client, because they are already specified in the query request, and not // queried for. The query results hold keys optionally. // // Also, meta-data like cell timestamp and expiry is optional. It is only needed // if the query has writetime() or ttl() functions in it, which it typically // won't have. // // Related headers: // - query-result-reader.hh // - query-result-writer.hh // // Query results are serialized to the following form: // // <result> ::= <partition>* // <partition> ::= <row-count> [ <partition-key> ] [ <static-row> ] <row>* // <static-row> ::= <row> // <row> ::= <row-length> <cell>+ // <cell> ::= <atomic-cell> | <collection-cell> // <atomic-cell> ::= <present-byte> [ <timestamp> <expiry> ] <value> // <collection-cell> ::= <blob> // // <value> ::= <blob> // <blob> ::= <blob-length> <uint8_t>* // <timestamp> ::= <uint64_t> // <expiry> ::= <int32_t> // <present-byte> ::= <int8_t> // <row-length> ::= <uint32_t> // <row-count> ::= <uint32_t> // <blob-length> ::= <uint32_t> // class result { bytes_ostream _w; public: class builder; class partition_writer; class row_writer; friend class result_merger; result() {} result(bytes_ostream&& w) : _w(std::move(w)) {} result(result&&) = default; result(const result&) = default; result& operator=(result&&) = default; result& operator=(const result&) = default; const bytes_ostream& buf() const { return _w; } result_digest digest() { CryptoPP::Weak::MD5 hash; bytes b(bytes::initialized_later(), CryptoPP::Weak::MD5::DIGESTSIZE); bytes_view v = _w.linearize(); hash.CalculateDigest(reinterpret_cast<unsigned char*>(b.begin()), reinterpret_cast<const unsigned char*>(v.begin()), v.size()); return result_digest(std::move(b)); } sstring pretty_print(schema_ptr, const query::partition_slice&) const; }; } <commit_msg>Remove old result_digest serializer<commit_after>/* * Copyright 2015 Cloudius Systems */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include <cryptopp/md5.h> #include "bytes_ostream.hh" #include "query-request.hh" #include "db/serializer.hh" namespace query { class result_digest { bytes _digest; public: result_digest(bytes&& digest) : _digest(std::move(digest)) {} const bytes& get() const { return _digest; } bool operator==(const result_digest& rh) const { return _digest == rh._digest; } bool operator!=(const result_digest& rh) const { return _digest != rh._digest; } }; // // The query results are stored in a serialized form. This is in order to // address the following problems, which a structured format has: // // - high level of indirection (vector of vectors of vectors of blobs), which // is not CPU cache friendly // // - high allocation rate due to fine-grained object structure // // On replica side, the query results are probably going to be serialized in // the transport layer anyway, so serializing the results up-front doesn't add // net work. There is no processing of the query results on replica other than // concatenation in case of range queries and checksum calculation. If query // results are collected in serialized form from different cores, we can // concatenate them without copying by simply appending the fragments into the // packet. // // On coordinator side, the query results would have to be parsed from the // transport layer buffers anyway, so the fact that iterators parse it also // doesn't add net work, but again saves allocations and copying. The CQL // server doesn't need complex data structures to process the results, it just // goes over it linearly consuming it. // // The coordinator side could be optimized even further for CQL queries which // do not need processing (eg. select * from cf where ...). We could make the // replica send the query results in the format which is expected by the CQL // binary protocol client. So in the typical case the coordinator would just // pass the data using zero-copy to the client, prepending a header. // // Users which need more complex structure of query results, should // transform it to such using appropriate visitors. // TODO: insert reference to such visitors here. // // Query results have dynamic format. In some queries (maybe even in typical // ones), we don't need to send partition or clustering keys back to the // client, because they are already specified in the query request, and not // queried for. The query results hold keys optionally. // // Also, meta-data like cell timestamp and expiry is optional. It is only needed // if the query has writetime() or ttl() functions in it, which it typically // won't have. // // Related headers: // - query-result-reader.hh // - query-result-writer.hh // // Query results are serialized to the following form: // // <result> ::= <partition>* // <partition> ::= <row-count> [ <partition-key> ] [ <static-row> ] <row>* // <static-row> ::= <row> // <row> ::= <row-length> <cell>+ // <cell> ::= <atomic-cell> | <collection-cell> // <atomic-cell> ::= <present-byte> [ <timestamp> <expiry> ] <value> // <collection-cell> ::= <blob> // // <value> ::= <blob> // <blob> ::= <blob-length> <uint8_t>* // <timestamp> ::= <uint64_t> // <expiry> ::= <int32_t> // <present-byte> ::= <int8_t> // <row-length> ::= <uint32_t> // <row-count> ::= <uint32_t> // <blob-length> ::= <uint32_t> // class result { bytes_ostream _w; public: class builder; class partition_writer; class row_writer; friend class result_merger; result() {} result(bytes_ostream&& w) : _w(std::move(w)) {} result(result&&) = default; result(const result&) = default; result& operator=(result&&) = default; result& operator=(const result&) = default; const bytes_ostream& buf() const { return _w; } result_digest digest() { CryptoPP::Weak::MD5 hash; bytes b(bytes::initialized_later(), CryptoPP::Weak::MD5::DIGESTSIZE); bytes_view v = _w.linearize(); hash.CalculateDigest(reinterpret_cast<unsigned char*>(b.begin()), reinterpret_cast<const unsigned char*>(v.begin()), v.size()); return result_digest(std::move(b)); } sstring pretty_print(schema_ptr, const query::partition_slice&) const; }; } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema_fwd.hh" #include "query-request.hh" #include "mutation_fragment.hh" #include "partition_version.hh" #include "tracing/tracing.hh" #include "row_cache.hh" namespace cache { /* * Represent a flat reader to the underlying source. * This reader automatically makes sure that it's up to date with all cache updates */ class autoupdating_underlying_reader final { row_cache& _cache; read_context& _read_context; flat_mutation_reader_opt _reader; utils::phased_barrier::phase_type _reader_creation_phase = 0; dht::partition_range _range = { }; std::optional<dht::decorated_key> _last_key; std::optional<dht::decorated_key> _new_last_key; future<> close_reader() noexcept { return _reader ? _reader->close() : make_ready_future<>(); } public: autoupdating_underlying_reader(row_cache& cache, read_context& context) : _cache(cache) , _read_context(context) { } future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) { _last_key = std::move(_new_last_key); auto start = population_range_start(); auto phase = _cache.phase_of(start); auto refresh_reader = make_ready_future<>(); if (!_reader || _reader_creation_phase != phase) { if (_last_key) { auto cmp = dht::ring_position_comparator(*_cache._schema); auto&& new_range = _range.split_after(*_last_key, cmp); if (!new_range) { return close_reader().then([] { return make_ready_future<mutation_fragment_opt>(); }); } _range = std::move(*new_range); _last_key = {}; } if (_reader) { ++_cache._tracker._stats.underlying_recreations; } refresh_reader = close_reader().then([this, phase] { _reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range); _reader_creation_phase = phase; }); } return refresh_reader.then([this, timeout] { return _reader->next_partition().then([this, timeout] { if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) { return make_ready_future<mutation_fragment_opt>(); } return (*_reader)(timeout).then([this] (auto&& mfopt) { if (mfopt) { assert(mfopt->is_partition_start()); _new_last_key = mfopt->as_partition_start().key(); } return std::move(mfopt); }); }); }); } future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) { auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range)); return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout); } future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) { _range = std::move(range); _last_key = { }; _new_last_key = { }; if (_reader) { if (_reader_creation_phase == phase) { ++_cache._tracker._stats.underlying_partition_skips; return _reader->fast_forward_to(_range, timeout); } else { ++_cache._tracker._stats.underlying_recreations; } } return close_reader().then([this, &snapshot, phase] { _reader = _cache.create_underlying_reader(_read_context, snapshot, _range); _reader_creation_phase = phase; }); } utils::phased_barrier::phase_type creation_phase() const { return _reader_creation_phase; } const dht::partition_range& range() const { return _range; } flat_mutation_reader& underlying() { return *_reader; } dht::ring_position_view population_range_start() const { return _last_key ? dht::ring_position_view::for_after_key(*_last_key) : dht::ring_position_view::for_range_start(_range); } }; class read_context final : public enable_lw_shared_from_this<read_context> { row_cache& _cache; schema_ptr _schema; reader_permit _permit; const dht::partition_range& _range; const query::partition_slice& _slice; const io_priority_class& _pc; tracing::trace_state_ptr _trace_state; mutation_reader::forwarding _fwd_mr; bool _range_query; // When reader enters a partition, it must be set up for reading that // partition from the underlying mutation source (_underlying) in one of two ways: // // 1) either _underlying is already in that partition // // 2) _underlying is before the partition, then _underlying_snapshot and _key // are set so that _underlying_flat can be fast forwarded to the right partition. // autoupdating_underlying_reader _underlying; uint64_t _underlying_created = 0; mutation_source_opt _underlying_snapshot; dht::partition_range _sm_range; std::optional<dht::decorated_key> _key; bool _partition_exists; row_cache::phase_type _phase; public: read_context(row_cache& cache, schema_ptr schema, reader_permit permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) : _cache(cache) , _schema(std::move(schema)) , _permit(std::move(permit)) , _range(range) , _slice(slice) , _pc(pc) , _trace_state(std::move(trace_state)) , _fwd_mr(fwd_mr) , _range_query(!query::is_single_partition(range)) , _underlying(_cache, *this) { ++_cache._tracker._stats.reads; if (!_range_query) { _key = range.start()->value().as_decorated_key(); } } ~read_context() { ++_cache._tracker._stats.reads_done; if (_underlying_created) { _cache._stats.reads_with_misses.mark(); ++_cache._tracker._stats.reads_with_misses; } else { _cache._stats.reads_with_no_misses.mark(); } } read_context(const read_context&) = delete; row_cache& cache() { return _cache; } const schema_ptr& schema() const { return _schema; } reader_permit permit() const { return _permit; } const dht::partition_range& range() const { return _range; } const query::partition_slice& slice() const { return _slice; } const io_priority_class& pc() const { return _pc; } tracing::trace_state_ptr trace_state() const { return _trace_state; } mutation_reader::forwarding fwd_mr() const { return _fwd_mr; } bool is_range_query() const { return _range_query; } autoupdating_underlying_reader& underlying() { return _underlying; } row_cache::phase_type phase() const { return _phase; } const dht::decorated_key& key() const { return *_key; } bool partition_exists() const { return _partition_exists; } void on_underlying_created() { ++_underlying_created; } bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); } public: future<> ensure_underlying(db::timeout_clock::time_point timeout) { if (_underlying_snapshot) { return create_underlying(timeout).then([this, timeout] { return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) { _partition_exists = bool(mfopt); }); }); } // We know that partition exists because all the callers of // enter_partition(const dht::decorated_key&, row_cache::phase_type) // check that and there's no other way of setting _underlying_snapshot // to empty. Except for calling create_underlying. _partition_exists = true; return make_ready_future<>(); } public: future<> create_underlying(db::timeout_clock::time_point timeout); void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = snapshot; _key = dk; } // Precondition: each caller needs to make sure that partition with |dk| key // exists in underlying before calling this function. void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = {}; _key = dk; } }; } <commit_msg>row_cache: autoupdating_underlying_reader: add close method<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema_fwd.hh" #include "query-request.hh" #include "mutation_fragment.hh" #include "partition_version.hh" #include "tracing/tracing.hh" #include "row_cache.hh" namespace cache { /* * Represent a flat reader to the underlying source. * This reader automatically makes sure that it's up to date with all cache updates */ class autoupdating_underlying_reader final { row_cache& _cache; read_context& _read_context; flat_mutation_reader_opt _reader; utils::phased_barrier::phase_type _reader_creation_phase = 0; dht::partition_range _range = { }; std::optional<dht::decorated_key> _last_key; std::optional<dht::decorated_key> _new_last_key; future<> close_reader() noexcept { return _reader ? _reader->close() : make_ready_future<>(); } public: autoupdating_underlying_reader(row_cache& cache, read_context& context) : _cache(cache) , _read_context(context) { } future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) { _last_key = std::move(_new_last_key); auto start = population_range_start(); auto phase = _cache.phase_of(start); auto refresh_reader = make_ready_future<>(); if (!_reader || _reader_creation_phase != phase) { if (_last_key) { auto cmp = dht::ring_position_comparator(*_cache._schema); auto&& new_range = _range.split_after(*_last_key, cmp); if (!new_range) { return close_reader().then([] { return make_ready_future<mutation_fragment_opt>(); }); } _range = std::move(*new_range); _last_key = {}; } if (_reader) { ++_cache._tracker._stats.underlying_recreations; } refresh_reader = close_reader().then([this, phase] { _reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range); _reader_creation_phase = phase; }); } return refresh_reader.then([this, timeout] { return _reader->next_partition().then([this, timeout] { if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) { return make_ready_future<mutation_fragment_opt>(); } return (*_reader)(timeout).then([this] (auto&& mfopt) { if (mfopt) { assert(mfopt->is_partition_start()); _new_last_key = mfopt->as_partition_start().key(); } return std::move(mfopt); }); }); }); } future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) { auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range)); return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout); } future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) { _range = std::move(range); _last_key = { }; _new_last_key = { }; if (_reader) { if (_reader_creation_phase == phase) { ++_cache._tracker._stats.underlying_partition_skips; return _reader->fast_forward_to(_range, timeout); } else { ++_cache._tracker._stats.underlying_recreations; } } return close_reader().then([this, &snapshot, phase] { _reader = _cache.create_underlying_reader(_read_context, snapshot, _range); _reader_creation_phase = phase; }); } future<> close() noexcept { return close_reader(); } utils::phased_barrier::phase_type creation_phase() const { return _reader_creation_phase; } const dht::partition_range& range() const { return _range; } flat_mutation_reader& underlying() { return *_reader; } dht::ring_position_view population_range_start() const { return _last_key ? dht::ring_position_view::for_after_key(*_last_key) : dht::ring_position_view::for_range_start(_range); } }; class read_context final : public enable_lw_shared_from_this<read_context> { row_cache& _cache; schema_ptr _schema; reader_permit _permit; const dht::partition_range& _range; const query::partition_slice& _slice; const io_priority_class& _pc; tracing::trace_state_ptr _trace_state; mutation_reader::forwarding _fwd_mr; bool _range_query; // When reader enters a partition, it must be set up for reading that // partition from the underlying mutation source (_underlying) in one of two ways: // // 1) either _underlying is already in that partition // // 2) _underlying is before the partition, then _underlying_snapshot and _key // are set so that _underlying_flat can be fast forwarded to the right partition. // autoupdating_underlying_reader _underlying; uint64_t _underlying_created = 0; mutation_source_opt _underlying_snapshot; dht::partition_range _sm_range; std::optional<dht::decorated_key> _key; bool _partition_exists; row_cache::phase_type _phase; public: read_context(row_cache& cache, schema_ptr schema, reader_permit permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) : _cache(cache) , _schema(std::move(schema)) , _permit(std::move(permit)) , _range(range) , _slice(slice) , _pc(pc) , _trace_state(std::move(trace_state)) , _fwd_mr(fwd_mr) , _range_query(!query::is_single_partition(range)) , _underlying(_cache, *this) { ++_cache._tracker._stats.reads; if (!_range_query) { _key = range.start()->value().as_decorated_key(); } } ~read_context() { ++_cache._tracker._stats.reads_done; if (_underlying_created) { _cache._stats.reads_with_misses.mark(); ++_cache._tracker._stats.reads_with_misses; } else { _cache._stats.reads_with_no_misses.mark(); } } read_context(const read_context&) = delete; row_cache& cache() { return _cache; } const schema_ptr& schema() const { return _schema; } reader_permit permit() const { return _permit; } const dht::partition_range& range() const { return _range; } const query::partition_slice& slice() const { return _slice; } const io_priority_class& pc() const { return _pc; } tracing::trace_state_ptr trace_state() const { return _trace_state; } mutation_reader::forwarding fwd_mr() const { return _fwd_mr; } bool is_range_query() const { return _range_query; } autoupdating_underlying_reader& underlying() { return _underlying; } row_cache::phase_type phase() const { return _phase; } const dht::decorated_key& key() const { return *_key; } bool partition_exists() const { return _partition_exists; } void on_underlying_created() { ++_underlying_created; } bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); } public: future<> ensure_underlying(db::timeout_clock::time_point timeout) { if (_underlying_snapshot) { return create_underlying(timeout).then([this, timeout] { return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) { _partition_exists = bool(mfopt); }); }); } // We know that partition exists because all the callers of // enter_partition(const dht::decorated_key&, row_cache::phase_type) // check that and there's no other way of setting _underlying_snapshot // to empty. Except for calling create_underlying. _partition_exists = true; return make_ready_future<>(); } public: future<> create_underlying(db::timeout_clock::time_point timeout); void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = snapshot; _key = dk; } // Precondition: each caller needs to make sure that partition with |dk| key // exists in underlying before calling this function. void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = {}; _key = dk; } }; } <|endoftext|>
<commit_before>#include "MainComponent.h" #include "RenderableComponent.h" #include "wiRenderer.h" #include "wiHelper.h" #include "wiTimer.h" #include "wiCpuInfo.h" #include "wiInputManager.h" #include "wiBackLog.h" #include "MainComponent_BindLua.h" #include "WickedEngine.h" MainComponent::MainComponent() { screenW = 0; screenH = 0; fullscreen = false; activeComponent = new RenderableComponent(); setFrameSkip(true); setTargetFrameRate(60); setApplicationControlLostThreshold(10); infoDisplay = InfoDisplayer(); colorGradingPaletteDisplayEnabled = false; } MainComponent::~MainComponent() { activeComponent->Unload(); } void MainComponent::Initialize() { wiLua::GetGlobal()->RegisterObject(MainComponent_BindLua::className, "main", new MainComponent_BindLua(this)); } void MainComponent::activateComponent(RenderableComponent* component) { if (component == nullptr) { return; } activeComponent->Stop(); component->Start(); activeComponent = component; } void MainComponent::run() { static bool startupScriptProcessed = false; if (!startupScriptProcessed) { wiLua::GetGlobal()->RunFile("startup.lua"); startupScriptProcessed = true; } static wiTimer timer = wiTimer(); static double accumulator = 0.0; const double elapsedTime = timer.elapsed() / 1000.0; timer.record(); wiLua::GetGlobal()->SetDeltaTime(elapsedTime); if (frameskip) { accumulator += elapsedTime; if (accumulator > applicationControlLostThreshold) //application probably lost control accumulator = 0; while (accumulator >= targetFrameRateInv) { Update(); accumulator -= targetFrameRateInv; } } else { Update(); } Render(); wiRenderer::Present(bind(&MainComponent::Compose, this)); } void MainComponent::Update() { wiInputManager::Update(); wiCpuInfo::Frame(); wiBackLog::Update(); wiLua::GetGlobal()->Update(); getActiveComponent()->Update(); } void MainComponent::Render() { wiLua::GetGlobal()->Render(); getActiveComponent()->Render(); } void MainComponent::Compose() { getActiveComponent()->Compose(); // Draw the information display if (infoDisplay.active) { stringstream ss(""); if (infoDisplay.watermark) { ss << string("Wicked Engine ") + string(WICKED_ENGINE_VERSION) << endl; } if (infoDisplay.fpsinfo) { ss.precision(2); ss << fixed << wiFrameRate::FPS() << " FPS" << endl; } if (infoDisplay.cpuinfo) { ss << "CPU: " << wiCpuInfo::GetCpuPercentage() << "%" << endl; } wiFont(ss.str(), wiFontProps(0, 0, infoDisplay.size, WIFALIGN_LEFT, WIFALIGN_TOP, infoDisplay.size)).Draw(); } // Draw the color grading palette if (colorGradingPaletteDisplayEnabled) { wiImage::BatchBegin(); wiImage::Draw(wiTextureHelper::getInstance()->getColorGradeDefault(), wiImageEffects(0, 0, 256, 16)); } wiBackLog::Draw(); } #ifndef WINSTORE_SUPPORT bool MainComponent::setWindow(HWND hWnd, HINSTANCE hInst) { window = hWnd; instance = hInst; if (screenH == 0 && screenW == 0) { RECT rect = RECT(); GetClientRect(hWnd, &rect); screenW = rect.right - rect.left; screenH = rect.bottom - rect.top; } if (FAILED(wiRenderer::InitDevice(window, screenW, screenH, !fullscreen))) { wiHelper::messageBox("Could not initialize D3D device!", "Fatal Error!", window); return false; } return true; } #else bool MainComponent::setWindow(Windows::UI::Core::CoreWindow^ window) { screenW = (int)window->Bounds.Width; screenH = (int)window->Bounds.Height; if (FAILED(wiRenderer::InitDevice(window))) { wiHelper::messageBox("Could not initialize D3D device!", "Fatal Error!"); return false; } return true; } #endif <commit_msg>color grading palette display updated<commit_after>#include "MainComponent.h" #include "RenderableComponent.h" #include "wiRenderer.h" #include "wiHelper.h" #include "wiTimer.h" #include "wiCpuInfo.h" #include "wiInputManager.h" #include "wiBackLog.h" #include "MainComponent_BindLua.h" #include "WickedEngine.h" MainComponent::MainComponent() { screenW = 0; screenH = 0; fullscreen = false; activeComponent = new RenderableComponent(); setFrameSkip(true); setTargetFrameRate(60); setApplicationControlLostThreshold(10); infoDisplay = InfoDisplayer(); colorGradingPaletteDisplayEnabled = false; } MainComponent::~MainComponent() { activeComponent->Unload(); } void MainComponent::Initialize() { wiLua::GetGlobal()->RegisterObject(MainComponent_BindLua::className, "main", new MainComponent_BindLua(this)); } void MainComponent::activateComponent(RenderableComponent* component) { if (component == nullptr) { return; } activeComponent->Stop(); component->Start(); activeComponent = component; } void MainComponent::run() { static bool startupScriptProcessed = false; if (!startupScriptProcessed) { wiLua::GetGlobal()->RunFile("startup.lua"); startupScriptProcessed = true; } static wiTimer timer = wiTimer(); static double accumulator = 0.0; const double elapsedTime = timer.elapsed() / 1000.0; timer.record(); wiLua::GetGlobal()->SetDeltaTime(elapsedTime); if (frameskip) { accumulator += elapsedTime; if (accumulator > applicationControlLostThreshold) //application probably lost control accumulator = 0; while (accumulator >= targetFrameRateInv) { Update(); accumulator -= targetFrameRateInv; } } else { Update(); } Render(); wiRenderer::Present(bind(&MainComponent::Compose, this)); } void MainComponent::Update() { wiInputManager::Update(); wiCpuInfo::Frame(); wiBackLog::Update(); wiLua::GetGlobal()->Update(); getActiveComponent()->Update(); } void MainComponent::Render() { wiLua::GetGlobal()->Render(); getActiveComponent()->Render(); } void MainComponent::Compose() { getActiveComponent()->Compose(); // Draw the information display if (infoDisplay.active) { stringstream ss(""); if (infoDisplay.watermark) { ss << string("Wicked Engine ") + string(WICKED_ENGINE_VERSION) << endl; } if (infoDisplay.fpsinfo) { ss.precision(2); ss << fixed << wiFrameRate::FPS() << " FPS" << endl; } if (infoDisplay.cpuinfo) { ss << "CPU: " << wiCpuInfo::GetCpuPercentage() << "%" << endl; } wiFont(ss.str(), wiFontProps(0, 0, infoDisplay.size, WIFALIGN_LEFT, WIFALIGN_TOP, infoDisplay.size)).Draw(); } // Draw the color grading palette if (colorGradingPaletteDisplayEnabled) { wiImage::BatchBegin(); wiImage::Draw(wiTextureHelper::getInstance()->getColorGradeDefault(), wiImageEffects(0, 0, 256, 16)); wiImage::Draw(wiRenderer::GetColorGrading(), wiImageEffects(screenW-256, 0, 256, 16)); } wiBackLog::Draw(); } #ifndef WINSTORE_SUPPORT bool MainComponent::setWindow(HWND hWnd, HINSTANCE hInst) { window = hWnd; instance = hInst; if (screenH == 0 && screenW == 0) { RECT rect = RECT(); GetClientRect(hWnd, &rect); screenW = rect.right - rect.left; screenH = rect.bottom - rect.top; } if (FAILED(wiRenderer::InitDevice(window, screenW, screenH, !fullscreen))) { wiHelper::messageBox("Could not initialize D3D device!", "Fatal Error!", window); return false; } return true; } #else bool MainComponent::setWindow(Windows::UI::Core::CoreWindow^ window) { screenW = (int)window->Bounds.Width; screenH = (int)window->Bounds.Height; if (FAILED(wiRenderer::InitDevice(window))) { wiHelper::messageBox("Could not initialize D3D device!", "Fatal Error!"); return false; } return true; } #endif <|endoftext|>
<commit_before>#include "../stdafx.h" #include "GraphView.h" #include "../Document.h" #include "../res/resource.h" #include "ViewUtil.h" #include "../SideView.h" #include "../MainWindow.h" #include "../MainView.h" #include "../CPlotApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif enum { ID_desc = 2000, ID_visible }; IMPLEMENT_DYNAMIC(GraphView, CWnd) BEGIN_MESSAGE_MAP(GraphView, CWnd) ON_WM_CREATE() ON_WM_SIZE() ON_BN_CLICKED(ID_visible, OnVisible) ON_BN_CLICKED(ID_desc, OnSelect) //ON_LBN_DBLCLK(ID_name, OnEdit) END_MESSAGE_MAP() GraphView::GraphView(SideSectionGraphs &parent, Graph &g) : parent(parent), g_id(g.oid()) { } BOOL GraphView::PreCreateWindow(CREATESTRUCT &cs) { cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN; return CWnd::PreCreateWindow(cs); } BOOL GraphView::Create(const RECT &rect, CWnd *parent, UINT ID) { static bool init = false; if (!init) { WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS)); wndcls.style = CS_DBLCLKS; wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hInstance = AfxGetInstanceHandle(); wndcls.hCursor = theApp.LoadStandardCursor(IDC_ARROW); wndcls.lpszMenuName = NULL; wndcls.lpszClassName = _T("GraphView"); if (!AfxRegisterClass(&wndcls)) throw std::runtime_error("AfxRegisterClass(GraphView) failed"); init = true; } return CWnd::Create(_T("GraphView"), NULL, WS_CHILD | WS_TABSTOP, rect, parent, ID); } int GraphView::OnCreate(LPCREATESTRUCT cs) { if (CWnd::OnCreate(cs) < 0) return -1; EnableScrollBarCtrl(SB_BOTH, FALSE); START_CREATE; desc.Create(_T(""), WS_CHILD | BS_PUSHBUTTON, whatever, this, ID_desc); desc.SetFont(&controlFont()); desc.m_nFlatStyle = CMFCButton::BUTTONSTYLE_NOBORDERS; desc.m_bDrawFocus = false; desc.m_nAlignStyle = CMFCButton::ALIGN_LEFT; CHECK(visible, ""); return 0; } int GraphView::height(int w) const { DS0; return DS(10+22); } void GraphView::OnVisible() { Graph *g = graph(); if (!g) return; g->options.hidden = !g->options.hidden; visible.SetCheck(!g->options.hidden); Plot &plot = parent.document().plot; plot.update_axis(); parent.Recalc(g); } void GraphView::OnSelect() { Graph *g = graph(); if (!g) return; Plot &plot = parent.document().plot; plot.set_current_graph(g); parent.Update(false); MainWindow *w = (MainWindow*)GetParentFrame(); w->GetMainView().Update(); } void GraphView::Update(bool full) { CRect bounds; GetClientRect(bounds); Graph *g = graph(); if (!g) return; DS0; visible.SetCheck(!g->options.hidden); desc.SetWindowText(Convert(g->description_line())); Plot &plot = parent.document().plot; bool bold = (plot.number_of_graphs() > 1 && plot.current_graph() == g); desc.SetFont(&controlFont(bold)); if (!full) return; const int W = bounds.Width(); const int SPC = DS(5); // amount of spacing const int w1 = DS(20); // checkbox width const int x0 = SPC; // row x start / amount of space on the left const int x1 = W - SPC; int y = SPC; // y for next control const int h_label = DS(14), h_edit = DS(20), h_delta = DS(20), h_button = DS(20), h_row = DS(22); MOVE(visible, x0, x0 + w1, y, h_button, h_row); MOVE(desc, x0 + w1 + SPC, x1, y, h_label, h_row); } void GraphView::OnInitialUpdate() { Update(true); } void GraphView::OnSize(UINT type, int w, int h) { CWnd::OnSize(type, w, h); EnableScrollBarCtrl(SB_BOTH, FALSE); Update(true); } <commit_msg>update when changing current graph<commit_after>#include "../stdafx.h" #include "GraphView.h" #include "../Document.h" #include "../res/resource.h" #include "ViewUtil.h" #include "../SideView.h" #include "../MainWindow.h" #include "../MainView.h" #include "../CPlotApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif enum { ID_desc = 2000, ID_visible }; IMPLEMENT_DYNAMIC(GraphView, CWnd) BEGIN_MESSAGE_MAP(GraphView, CWnd) ON_WM_CREATE() ON_WM_SIZE() ON_BN_CLICKED(ID_visible, OnVisible) ON_BN_CLICKED(ID_desc, OnSelect) //ON_LBN_DBLCLK(ID_name, OnEdit) END_MESSAGE_MAP() GraphView::GraphView(SideSectionGraphs &parent, Graph &g) : parent(parent), g_id(g.oid()) { } BOOL GraphView::PreCreateWindow(CREATESTRUCT &cs) { cs.style |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN; return CWnd::PreCreateWindow(cs); } BOOL GraphView::Create(const RECT &rect, CWnd *parent, UINT ID) { static bool init = false; if (!init) { WNDCLASS wndcls; memset(&wndcls, 0, sizeof(WNDCLASS)); wndcls.style = CS_DBLCLKS; wndcls.lpfnWndProc = ::DefWindowProc; wndcls.hInstance = AfxGetInstanceHandle(); wndcls.hCursor = theApp.LoadStandardCursor(IDC_ARROW); wndcls.lpszMenuName = NULL; wndcls.lpszClassName = _T("GraphView"); if (!AfxRegisterClass(&wndcls)) throw std::runtime_error("AfxRegisterClass(GraphView) failed"); init = true; } return CWnd::Create(_T("GraphView"), NULL, WS_CHILD | WS_TABSTOP, rect, parent, ID); } int GraphView::OnCreate(LPCREATESTRUCT cs) { if (CWnd::OnCreate(cs) < 0) return -1; EnableScrollBarCtrl(SB_BOTH, FALSE); START_CREATE; desc.Create(_T(""), WS_CHILD | BS_PUSHBUTTON, whatever, this, ID_desc); desc.SetFont(&controlFont()); desc.m_nFlatStyle = CMFCButton::BUTTONSTYLE_NOBORDERS; desc.m_bDrawFocus = false; desc.m_nAlignStyle = CMFCButton::ALIGN_LEFT; CHECK(visible, ""); return 0; } int GraphView::height(int w) const { DS0; return DS(10+22); } void GraphView::OnVisible() { Graph *g = graph(); if (!g) return; g->options.hidden = !g->options.hidden; visible.SetCheck(!g->options.hidden); Plot &plot = parent.document().plot; plot.update_axis(); parent.Recalc(g); } void GraphView::OnSelect() { Graph *g = graph(); if (!g) return; Plot &plot = parent.document().plot; plot.set_current_graph(g); parent.parent().UpdateAll(); MainWindow *w = (MainWindow*)GetParentFrame(); w->GetMainView().Update(); } void GraphView::Update(bool full) { CRect bounds; GetClientRect(bounds); Graph *g = graph(); if (!g) return; DS0; visible.SetCheck(!g->options.hidden); desc.SetWindowText(Convert(g->description_line())); Plot &plot = parent.document().plot; bool bold = (plot.number_of_graphs() > 1 && plot.current_graph() == g); desc.SetFont(&controlFont(bold)); if (!full) return; const int W = bounds.Width(); const int SPC = DS(5); // amount of spacing const int w1 = DS(20); // checkbox width const int x0 = SPC; // row x start / amount of space on the left const int x1 = W - SPC; int y = SPC; // y for next control const int h_label = DS(14), h_edit = DS(20), h_delta = DS(20), h_button = DS(20), h_row = DS(22); MOVE(visible, x0, x0 + w1, y, h_button, h_row); MOVE(desc, x0 + w1 + SPC, x1, y, h_label, h_row); } void GraphView::OnInitialUpdate() { Update(true); } void GraphView::OnSize(UINT type, int w, int h) { CWnd::OnSize(type, w, h); EnableScrollBarCtrl(SB_BOTH, FALSE); Update(true); } <|endoftext|>
<commit_before>#include "vector.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "LSM303.h" #include "L3G4200D.h" #include <sys/time.h> /* promising: http://elinux.org/Interfacing_with_I2C_Devices https://i2c.wiki.kernel.org/index.php/Main_Page */ // TODO: read http://www.cs.cmu.edu/~spiff/moedit99/expmap.pdf int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void streamRawValues(LSM303& compass, L3G4200D& gyro) { compass.enableDefault(); gyro.enableDefault(); while(1) { compass.read(); gyro.read(); printf("%7d %7d %7d, %7d %7d %7d, %7d %7d %7d\n", compass.m(0), compass.m(1), compass.m(2), compass.a(0), compass.a(1), compass.a(2), gyro.g(0), gyro.g(1), gyro.g(2) ); usleep(100*1000); } } void calibrate(LSM303& compass) { compass.enableDefault(); int_vector mag_max, mag_min; while(1) { compass.read(); mag_min = mag_min.cwiseMin(compass.m); mag_max = mag_max.cwiseMax(compass.m); printf("%7d %7d %7d %7d %7d %7d\n", mag_min(0), mag_min(1), mag_min(2), mag_max(0), mag_max(1), mag_max(2)); usleep(10*1000); // TODO: have some way of writing to ~/.lsm303_mag_cal } } void loadCalibration(int_vector& mag_min, int_vector& mag_max) { // TODO: recalibrate for my new IMU // TODO: load from ~/.lsm303_mag_cal instead of hardcoding mag_min = int_vector(-519, -476, -765); mag_max = int_vector(475, 623, 469); } static void enableSensors(LSM303& compass, L3G4200D& gyro) { compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode // 15 Hz default gyro.writeReg(L3G4200D_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz gyro.writeReg(L3G4200D_CTRL_REG4, 0x20); // 2000 dps full scale } // Calculate offsets, assuming the MiniMU is resting // with is z axis pointing up. static void calculateOffsets(LSM303& compass, L3G4200D& gyro, vector& accel_offset, vector& gyro_offset) { // LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256. // TODO: unify this with the other place in the code where we scale accelerometer readings. const int gravity = 256; gyro_offset = accel_offset = vector::Zero(); const int sampleCount = 32; for(int i = 0; i < sampleCount; i++) { gyro.read(); compass.readAcc(); gyro_offset += gyro.g.cast<float>(); accel_offset += compass.a.cast<float>(); usleep(20*1000); } gyro_offset /= sampleCount; accel_offset /= sampleCount; accel_offset(2) -= gravity; if (accel_offset.norm() > 50) { fprintf(stderr, "Unable to calculate accelerometer offset because board was not resting in the correct orientation.\n"); accel_offset = vector::Zero(); } } // Returns the measured angular velocity vector // in units of radians per second, in the body coordinate system. static vector readGyro(L3G4200D& gyro, const vector& gyro_offset) { // At the full-scale=2000 dps setting, the gyro datasheet says // we get 0.07 dps/digit. const float gyro_scale = 0.07 * 3.14159265 / 180; gyro.read(); return ( gyro.g.cast<float>() - gyro_offset ) * gyro_scale; } // Returns acceleration vector in units of g, where g is 9.8 m/s^2, // in the body coordinate system. static vector readAcc(LSM303& compass, const vector& accel_offset) { // LSM303 accelerometer: At 8 g sensitivity, the datasheet says // we get 3.9 mg/digit. // TODO: double check this figure using the correct datasheet const float accel_scale = 0.0039; compass.readAcc(); return ( compass.a.cast<float>() - accel_offset ) * accel_scale; } // Returns the magnetic field vector in the body coordinate system. // For each component, a value of 1 corresponds to the max value // and a value of -1 corresponds to the min value. static vector readMag(LSM303& compass, const int_vector& mag_min, const int_vector& mag_max) { compass.readMag(); vector m; m(0) = (float)(compass.m(0) - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1; m(1) = (float)(compass.m(1) - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1; m(2) = (float)(compass.m(2) - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1; return m; } static matrix updateMatrix(const vector& w, float dt) { matrix u = matrix::Identity(); u(2,0) = -w(1) * dt; u(0,2) = w(1) * dt; u(0,1) = -w(2) * dt; u(1,0) = w(2) * dt; u(1,2) = -w(0) * dt; u(2,1) = w(0) * dt; return u; } static matrix normalize(const matrix & m) { //float error = m.row(0).dot(m.row(1)); matrix norm; norm.row(0) = m.row(0) + m.row(1).cross(m.row(2))/10; norm.row(1) = m.row(1) + m.row(2).cross(m.row(0))/10; norm.row(2) = m.row(2) + m.row(0).cross(m.row(1))/10; norm.row(0).normalize(); norm.row(1).normalize(); norm.row(2).normalize(); return norm; } void fuse_gyro_only(matrix& rotation, float dt, const vector& angular_velocity) { rotation *= updateMatrix(angular_velocity, dt); rotation = normalize(rotation); } #define Kp_ROLLPITCH 1 #define Ki_ROLLPITCH 0.00002 #define Kp_YAW 1.2 #define Ki_YAW 0.00002 void fuse(matrix& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector magnetic_east = magnetic_field.cross(up); vector east = magnetic_east; // a rough approximation vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); // We trust the accelerometer more if it is telling us 1G. float accel_weight = 1 - 2*abs(1 - acceleration.norm()); if (accel_weight < 0){ accel_weight = 0; } vector omegaP(0,0,0); //static vector omegaI; // TMPHAX //rotation = matrix::Identity(); //acceleration = vector(0,1,0); // Add a "torque" that makes our up vector (rotation.row(2)) // get closer to the acceleration vector. vector errorRollPitch = acceleration.cross(rotation.row(2)) * accel_weight; fprintf(stderr, "errorRollPitch = %7.4f %7.4f %7.4f\n", errorRollPitch(0), errorRollPitch(1), errorRollPitch(2)); omegaP += errorRollPitch * Kp_ROLLPITCH; //omegaI += errorRollPitch * Ki_ROLLPITCH; // Add a "torque" that makes our east vector (rotation.row(0)) // get closer to east vector calculated from the compass. //vector errorYaw = east.cross(rotation.row(0)); //omegaP += errorYaw * Kp_YAW; //omegaI += errorYaw * Ki_YAW; rotation *= updateMatrix(angular_velocity + omegaP, dt); rotation = normalize(rotation); } // DCM algorithm: http://diydrones.com/forum/topics/robust-estimator-of-the void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void ahrs(LSM303& compass, L3G4200D& gyro) { int_vector mag_min, mag_max; loadCalibration(mag_min, mag_max); enableSensors(compass, gyro); vector accel_offset, gyro_offset; calculateOffsets(compass, gyro, accel_offset, gyro_offset); fprintf(stderr, "Gyro offset: %7f %7f %7f\nAccel offset: %7f %7f %7f (%7f)\n", gyro_offset(0), gyro_offset(1), gyro_offset(2), accel_offset(0), accel_offset(1), accel_offset(2), accel_offset.norm()); // The rotation matrix that can convert a vector in body coordinates // to ground coordinates. matrix rotation = matrix::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw "time went backwards"; } vector angular_velocity = readGyro(gyro, gyro_offset); vector acceleration = readAcc(compass, accel_offset); vector magnetic_field = readMag(compass, mag_min, mag_max); // TODO: read mag at 10Hz instead? Why do others do that? fuse(rotation, dt, angular_velocity, acceleration, magnetic_field); //fprintf(stderr, "g: %8d %8d %8d\n", gyro.g(0), gyro.g(1), gyro.g(2)); //fprintf(stderr, "m: %7.4f %7.4f %7.4f m_raw: %8d %8d %8d\n", magnetic_field(0), magnetic_field(1), magnetic_field(2), compass.m(0), compass.m(1), compass.m(2)); //fprintf(stderr, "dt: %7.4f w: %7.4f %7.4f %7.4f\n", dt, angular_velocity(0), angular_velocity(1), angular_velocity(2)); //rotation = rotationFromCompass; // TMPHAX printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", rotation(0,0), rotation(0,1), rotation(0,2), rotation(1,0), rotation(1,1), rotation(1,2), rotation(2,0), rotation(2,1), rotation(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); //std::cout << rotation; // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } void tmphaxTest() { const float turnAmount = 3.14159265/2; // radians const float turnTime = 0.5; // seconds const int pieces = turnTime/0.02; const vector angular_velocity(0, 0, turnAmount/turnTime); const float dt = turnTime/pieces; matrix rotation = matrix::Identity(); for (int i = 0; i < pieces; i++) { fuse_gyro_only(rotation, dt, angular_velocity); } print(rotation); putchar('\n'); printf("tmphaxTest done\n"); exit(3); } int main(int argc, char *argv[]) { I2CBus i2c("/dev/i2c-0"); LSM303 compass(i2c); L3G4200D gyro(i2c); //tmphaxTest(); uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M); if (result != 0x3C) { std::cerr << "Error getting \"Who Am I\" register." << std::endl; exit(2); } if (argc > 1) { if (0 == strcmp("cal", argv[1])) { calibrate(compass); } else if (0 == strcmp("raw", argv[1])) { streamRawValues(compass, gyro); } else { fprintf(stderr, "Unknown action '%s'.\n", argv[1]); exit(3); } } else { ahrs(compass, gyro); } return 0; } <commit_msg>made drift correction but it seems kind of bad<commit_after>#include "vector.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "LSM303.h" #include "L3G4200D.h" #include <sys/time.h> /* promising: http://elinux.org/Interfacing_with_I2C_Devices https://i2c.wiki.kernel.org/index.php/Main_Page */ // TODO: read http://www.cs.cmu.edu/~spiff/moedit99/expmap.pdf int millis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } void streamRawValues(LSM303& compass, L3G4200D& gyro) { compass.enableDefault(); gyro.enableDefault(); while(1) { compass.read(); gyro.read(); printf("%7d %7d %7d, %7d %7d %7d, %7d %7d %7d\n", compass.m(0), compass.m(1), compass.m(2), compass.a(0), compass.a(1), compass.a(2), gyro.g(0), gyro.g(1), gyro.g(2) ); usleep(100*1000); } } void calibrate(LSM303& compass) { compass.enableDefault(); int_vector mag_max, mag_min; while(1) { compass.read(); mag_min = mag_min.cwiseMin(compass.m); mag_max = mag_max.cwiseMax(compass.m); printf("%7d %7d %7d %7d %7d %7d\n", mag_min(0), mag_min(1), mag_min(2), mag_max(0), mag_max(1), mag_max(2)); usleep(10*1000); // TODO: have some way of writing to ~/.lsm303_mag_cal } } void loadCalibration(int_vector& mag_min, int_vector& mag_max) { // TODO: recalibrate for my new IMU // TODO: load from ~/.lsm303_mag_cal instead of hardcoding mag_min = int_vector(-519, -476, -765); mag_max = int_vector(475, 623, 469); } static void enableSensors(LSM303& compass, L3G4200D& gyro) { compass.writeAccReg(LSM303_CTRL_REG1_A, 0x47); // normal power mode, all axes enabled, 50 Hz compass.writeAccReg(LSM303_CTRL_REG4_A, 0x20); // 8 g full scale compass.writeMagReg(LSM303_MR_REG_M, 0x00); // continuous conversion mode // 15 Hz default gyro.writeReg(L3G4200D_CTRL_REG1, 0x0F); // normal power mode, all axes enabled, 100 Hz gyro.writeReg(L3G4200D_CTRL_REG4, 0x20); // 2000 dps full scale } // Calculate offsets, assuming the MiniMU is resting // with is z axis pointing up. static void calculateOffsets(LSM303& compass, L3G4200D& gyro, vector& accel_offset, vector& gyro_offset) { // LSM303 accelerometer: 8 g sensitivity. 3.8 mg/digit; 1 g = 256. // TODO: unify this with the other place in the code where we scale accelerometer readings. const int gravity = 256; gyro_offset = accel_offset = vector::Zero(); const int sampleCount = 32; for(int i = 0; i < sampleCount; i++) { gyro.read(); compass.readAcc(); gyro_offset += gyro.g.cast<float>(); accel_offset += compass.a.cast<float>(); usleep(20*1000); } gyro_offset /= sampleCount; accel_offset /= sampleCount; accel_offset(2) -= gravity; if (accel_offset.norm() > 50) { fprintf(stderr, "Unable to calculate accelerometer offset because board was not resting in the correct orientation.\n"); accel_offset = vector::Zero(); } } // Returns the measured angular velocity vector // in units of radians per second, in the body coordinate system. static vector readGyro(L3G4200D& gyro, const vector& gyro_offset) { // At the full-scale=2000 dps setting, the gyro datasheet says // we get 0.07 dps/digit. const float gyro_scale = 0.07 * 3.14159265 / 180; gyro.read(); return ( gyro.g.cast<float>() - gyro_offset ) * gyro_scale; } // Returns acceleration vector in units of g, where g is 9.8 m/s^2, // in the body coordinate system. static vector readAcc(LSM303& compass, const vector& accel_offset) { // LSM303 accelerometer: At 8 g sensitivity, the datasheet says // we get 3.9 mg/digit. // TODO: double check this figure using the correct datasheet const float accel_scale = 0.0039; compass.readAcc(); return ( compass.a.cast<float>() - accel_offset ) * accel_scale; } // Returns the magnetic field vector in the body coordinate system. // For each component, a value of 1 corresponds to the max value // and a value of -1 corresponds to the min value. static vector readMag(LSM303& compass, const int_vector& mag_min, const int_vector& mag_max) { compass.readMag(); vector m; m(0) = (float)(compass.m(0) - mag_min(0)) / (mag_max(0) - mag_min(0)) * 2 - 1; m(1) = (float)(compass.m(1) - mag_min(1)) / (mag_max(1) - mag_min(1)) * 2 - 1; m(2) = (float)(compass.m(2) - mag_min(2)) / (mag_max(2) - mag_min(2)) * 2 - 1; return m; } static matrix updateMatrix(const vector& w, float dt) { matrix u = matrix::Identity(); u(2,0) = -w(1) * dt; u(0,2) = w(1) * dt; u(0,1) = -w(2) * dt; u(1,0) = w(2) * dt; u(1,2) = -w(0) * dt; u(2,1) = w(0) * dt; return u; } static matrix normalize(const matrix & m) { //float error = m.row(0).dot(m.row(1)); matrix norm; norm.row(0) = m.row(0) + m.row(1).cross(m.row(2))/10; norm.row(1) = m.row(1) + m.row(2).cross(m.row(0))/10; norm.row(2) = m.row(2) + m.row(0).cross(m.row(1))/10; norm.row(0).normalize(); norm.row(1).normalize(); norm.row(2).normalize(); return norm; } void fuse_gyro_only(matrix& rotation, float dt, const vector& angular_velocity) { rotation *= updateMatrix(angular_velocity, dt); rotation = normalize(rotation); } #define Kp_ROLLPITCH 1 #define Ki_ROLLPITCH 0.00002 #define Kp_YAW 1 #define Ki_YAW 0.00002 #define PI 3.14159265 void fuse(matrix& rotation, float dt, const vector& angular_velocity, const vector& acceleration, const vector& magnetic_field) { vector up = acceleration; // usually true vector magnetic_east = magnetic_field.cross(up); vector east = magnetic_east; // a rough approximation vector north = up.cross(east); matrix rotationFromCompass; rotationFromCompass.row(0) = east; rotationFromCompass.row(1) = north; rotationFromCompass.row(2) = up; rotationFromCompass.row(0).normalize(); rotationFromCompass.row(1).normalize(); rotationFromCompass.row(2).normalize(); // The board's x axis in earth coordinates. vector x = rotationFromCompass.col(0); x.normalize(); x(2) = 0; float heading_weight = x.norm(); // 0 = east, pi/2 = north float heading = atan2(x(1), x(0)); fprintf(stderr, "B = %7.4f %7.4f %7.4f (%7.4f) w=%7.4f h=%7.4f\n", magnetic_field(0), magnetic_field(1), magnetic_field(2), magnetic_field.norm(), heading_weight, heading*180/PI); // We trust the accelerometer more if it is telling us 1G. float accel_weight = 1 - 2*abs(1 - acceleration.norm()); if (accel_weight < 0){ accel_weight = 0; } vector omegaP(0,0,0); //static vector omegaI; // Add a "torque" that makes our up vector (rotation.row(2)) // get closer to the acceleration vector. vector errorRollPitch = acceleration.cross(rotation.row(2)) * accel_weight; //fprintf(stderr, "errorRollPitch = %7.4f %7.4f %7.4f\n", errorRollPitch(0), errorRollPitch(1), errorRollPitch(2)); omegaP += errorRollPitch * Kp_ROLLPITCH; //omegaI += errorRollPitch * Ki_ROLLPITCH; // Add a "torque" that makes our east vector (rotation.row(0)) // get closer to east vector calculated from the compass. vector errorYaw = east.cross(rotation.row(0)); omegaP += errorYaw * Kp_YAW; //omegaI += errorYaw * Ki_YAW; rotation *= updateMatrix(angular_velocity + omegaP, dt); rotation = normalize(rotation); } // DCM algorithm: http://diydrones.com/forum/topics/robust-estimator-of-the void print(matrix m) { printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f", m(0,0), m(0,1), m(0,2), m(1,0), m(1,1), m(1,2), m(2,0), m(2,1), m(2,2)); } void ahrs(LSM303& compass, L3G4200D& gyro) { int_vector mag_min, mag_max; loadCalibration(mag_min, mag_max); enableSensors(compass, gyro); vector accel_offset, gyro_offset; calculateOffsets(compass, gyro, accel_offset, gyro_offset); fprintf(stderr, "Gyro offset: %7f %7f %7f\nAccel offset: %7f %7f %7f (%7f)\n", gyro_offset(0), gyro_offset(1), gyro_offset(2), accel_offset(0), accel_offset(1), accel_offset(2), accel_offset.norm()); // The rotation matrix that can convert a vector in body coordinates // to ground coordinates. matrix rotation = matrix::Identity(); int start = millis(); // truncate 64-bit return value while(1) { int last_start = start; start = millis(); float dt = (start-last_start)/1000.0; if (dt < 0){ throw "time went backwards"; } vector angular_velocity = readGyro(gyro, gyro_offset); vector acceleration = readAcc(compass, accel_offset); vector magnetic_field = readMag(compass, mag_min, mag_max); // TODO: read mag at 10Hz instead? Why do others do that? fuse(rotation, dt, angular_velocity, acceleration, magnetic_field); //fprintf(stderr, "g: %8d %8d %8d\n", gyro.g(0), gyro.g(1), gyro.g(2)); //fprintf(stderr, "m: %7.4f %7.4f %7.4f m_raw: %8d %8d %8d\n", magnetic_field(0), magnetic_field(1), magnetic_field(2), compass.m(0), compass.m(1), compass.m(2)); //fprintf(stderr, "dt: %7.4f w: %7.4f %7.4f %7.4f\n", dt, angular_velocity(0), angular_velocity(1), angular_velocity(2)); //rotation = rotationFromCompass; // TMPHAX printf("%7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", rotation(0,0), rotation(0,1), rotation(0,2), rotation(1,0), rotation(1,1), rotation(1,2), rotation(2,0), rotation(2,1), rotation(2,2), acceleration(0), acceleration(1), acceleration(2), magnetic_field(0), magnetic_field(1), magnetic_field(2)); fflush(stdout); //std::cout << rotation; // Ensure that each iteration of the loop takes at least 20 ms. while(millis() - start < 20) { usleep(1000); } } } void tmphaxTest() { const float turnAmount = 3.14159265/2; // radians const float turnTime = 0.5; // seconds const int pieces = turnTime/0.02; const vector angular_velocity(0, 0, turnAmount/turnTime); const float dt = turnTime/pieces; matrix rotation = matrix::Identity(); for (int i = 0; i < pieces; i++) { fuse_gyro_only(rotation, dt, angular_velocity); } print(rotation); putchar('\n'); printf("tmphaxTest done\n"); exit(3); } int main(int argc, char *argv[]) { I2CBus i2c("/dev/i2c-0"); LSM303 compass(i2c); L3G4200D gyro(i2c); //tmphaxTest(); uint8_t result = compass.readMagReg(LSM303_WHO_AM_I_M); if (result != 0x3C) { std::cerr << "Error getting \"Who Am I\" register." << std::endl; exit(2); } if (argc > 1) { if (0 == strcmp("cal", argv[1])) { calibrate(compass); } else if (0 == strcmp("raw", argv[1])) { streamRawValues(compass, gyro); } else { fprintf(stderr, "Unknown action '%s'.\n", argv[1]); exit(3); } } else { ahrs(compass, gyro); } return 0; } <|endoftext|>
<commit_before>// based on http://stackoverflow.com/questions/4636456/stack-trace-for-c-using-gcc/4732119#4732119 #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <signal.h> extern int done; extern int emcOperatorError(int id, const char *fmt, ...); void backtrace(int signo) { char pid_buf[30]; char name_buf[512]; char filename[512]; signal(signo, SIG_IGN); // prevent multiple invocations on same signal sprintf(pid_buf, "%d", getpid()); sprintf(filename,"/tmp/backtrace.%s", pid_buf); name_buf[readlink("/proc/self/exe", name_buf, 511)]=0; int child_pid = fork(); if (!child_pid) { fclose(stderr); stderr = freopen(filename, "a", stderr); dup2(2,1); // child: redirect output to stderr fprintf(stdout,"stack trace for %s pid=%s signal=%d\n",name_buf,pid_buf, signo); execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL); emcOperatorError(0, "backtrace for %s (pid %s signal %d): gdb failed to start", name_buf, pid_buf, signo); abort(); /* If gdb failed to start */ } else { int status; waitpid(child_pid, &status,0); if (signo == SIGUSR1) { // continue running after backtrace signal(SIGUSR1, backtrace); fprintf(stderr, "%s continuing status=%d\n", name_buf, status); } else { // this takes emcmodule.cc:EMC_COMMAND_TIMEOUT seconds to display: if (status == 0) // backtrace succeeded emcOperatorError(0, "%s (pid %d) died on signal %d, backtrace stored in %s", name_buf, getpid(), signo, filename); fprintf(stderr, "%s exiting\n", name_buf); done = 1; // signal task to exit main loop } } } <commit_msg>task/backtrace: polish a bit<commit_after>// based on http://stackoverflow.com/questions/4636456/stack-trace-for-c-using-gcc/4732119#4732119 #include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <signal.h> extern int done; extern int emcOperatorError(int id, const char *fmt, ...); extern int emcOperatorText(int id, const char *fmt, ...); void backtrace(int signo) { char pid_buf[30]; char name_buf[512]; char filename[512]; signal(signo, SIG_IGN); // prevent multiple invocations on same signal sprintf(pid_buf, "%d", getpid()); sprintf(filename,"/tmp/backtrace.%s", pid_buf); name_buf[readlink("/proc/self/exe", name_buf, 511)]=0; int child_pid = fork(); if (!child_pid) { fclose(stderr); stderr = freopen(filename, "a", stderr); dup2(2,1); // child: redirect output to stderr fprintf(stdout,"stack trace for %s pid=%s signal=%d\n",name_buf,pid_buf, signo); execlp("gdb", "gdb", "--batch", "-n", "-ex", "thread", "-ex", "bt", name_buf, pid_buf, NULL); emcOperatorError(0, "backtrace for %s (pid %s signal %d): gdb failed to start", name_buf, pid_buf, signo); abort(); /* If gdb failed to start */ } else { int status; waitpid(child_pid, &status,0); if (signo == SIGUSR1) { // continue running after backtrace signal(SIGUSR1, backtrace); emcOperatorText(0, "backtrace for %s stored in %s, continuing", name_buf, filename); fprintf(stderr, "%s: backtrace stored in %s, continuing\n", name_buf, filename); } else { // this takes emcmodule.cc:EMC_COMMAND_TIMEOUT seconds to display: if (status == 0) // backtrace succeeded emcOperatorError(0, "%s (pid %d) died on signal %d, backtrace stored in %s", name_buf, getpid(), signo, filename); fprintf(stderr, "%s exiting\n", name_buf); done = 1; // signal task to exit main loop } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ShapeDetectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <fstream> #include "ShapeDetectApp.h" #include "AppUtility.h" #include "RawVolumeReader.h" #include "itkImageRegionIterator.h" #include "itkExceptionObject.h" #include "itkFastMarchingImageFilter.h" #include "vnl/vnl_math.h" #include <string> ShapeDetectApp ::ShapeDetectApp() { this->Initialize(); } void ShapeDetectApp ::Initialize() { m_InputImage = InputImageType::New(); m_EdgePotentialImage = ImageType::New(); m_SegmentationMask = ImageType::New(); m_DetectionFilter = DetectionFilterType::New(); m_Sigma = 1.0; m_DumpPGMFiles = true; } void ShapeDetectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !WritePGMFiles<InputImageType>( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } this->ComputeEdgePotentialMap(); std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // run the filter std::cout << "Generating time crossing map." << std::endl; this->ComputeTimeCrossingMap(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating time crossing map." << std::endl; this->ComputeTimeCrossingMap(); this->ThresholdTimeCrossingMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding time crossing map." << std::endl; this->ThresholdTimeCrossingMap(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void ShapeDetectApp ::ComputeTimeCrossingMap() { // connect edge potential map m_DetectionFilter->SetSpeedImage( m_EdgePotentialImage ); // setup trial points typedef DetectionFilterType::NodeType NodeType; typedef DetectionFilterType::NodeContainer NodeContainer; NodeContainer::Pointer trialPoints = NodeContainer::New(); NodeType node; node.SetValue( 0.0 ); node.SetIndex( m_Seed ); trialPoints->InsertElement(0, node); m_DetectionFilter->SetTrialPoints( trialPoints ); // specify the size of the output image m_DetectionFilter->SetOutputSize( m_InputImage->GetBufferedRegion().GetSize() ); // update the marcher m_DetectionFilter->Update(); } void ShapeDetectApp ::ThresholdTimeCrossingMap() { // threshold the time crossing map m_SegmentationMask->SetLargestPossibleRegion( m_InputImage->GetLargestPossibleRegion() ); m_SegmentationMask->SetBufferedRegion( m_InputImage->GetBufferedRegion() ); m_SegmentationMask->Allocate(); typedef itk::ImageRegionIterator<ImageType> Iterator; Iterator inIter( m_DetectionFilter->GetOutput(), m_DetectionFilter->GetOutput()->GetBufferedRegion() ); Iterator outIter( m_SegmentationMask, m_SegmentationMask->GetBufferedRegion() ); while( !inIter.IsAtEnd() ) { if( inIter.Get() <= m_Threshold ) { outIter.Set( 1 ); } else { outIter.Set( 0 ); } ++inIter; ++outIter; } } void ShapeDetectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !WritePGMFiles<ImageType>( m_SegmentationMask, m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } void ShapeDetectApp ::ComputeEdgePotentialMap() { // compute derivative of the input image DerivativeFilterPointer deriv = DerivativeFilterType::New(); deriv->SetInput( m_InputImage ); deriv->SetSigma( m_Sigma ); deriv->Update(); // allocate memory for the map m_EdgePotentialImage->SetLargestPossibleRegion( m_InputImage->GetLargestPossibleRegion() ); m_EdgePotentialImage->SetBufferedRegion( m_InputImage->GetBufferedRegion() ); m_EdgePotentialImage->Allocate(); //**** //FIXME - use an itk filter once API are consistent //**** // compute the magnitude typedef itk::ImageRegionIterator<DerivativeImageType> DerivativeIterator; typedef itk::ImageRegionIterator<ImageType> ImageIterator; DerivativeIterator derivIter( deriv->GetOutput(), deriv->GetOutput()->GetBufferedRegion() ); ImageIterator mapIter( m_EdgePotentialImage, m_EdgePotentialImage->GetBufferedRegion() ); while( !derivIter.IsAtEnd() ) { float accum = 0; VectorType grad = derivIter.Get(); for( int j = 0; j < ImageDimension; j++ ) { accum += vnl_math_sqr( grad[j] ); } accum = vnl_math_sqrt( accum ); // mapIter.Set( 1.0 / ( 1.0 + accum ) ); mapIter.Set( exp( -1.0 * accum ) ); ++derivIter; ++mapIter; } if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the edge potential map." << std::endl; if( !WritePGMFiles<ImageType>( m_EdgePotentialImage, m_PGMDirectory.c_str(), "map" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool ShapeDetectApp ::ReadImage( const char * filename, const SizeType& size, bool bigEndian, InputImageType::Pointer & imgPtr ) { // Read in a raw volume typedef itk::RawVolumeReader<InputPixelType,InputImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( filename ); reader->SetBigEndian( bigEndian ); reader->SetSize( size ); reader->Execute(); imgPtr = reader->GetImage(); return true; } <commit_msg>ENH: RawVolumeReader removed. It was replaced by explicit use of the ImageFileReader and RawImageIO classes.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ShapeDetectApp.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 <fstream> #include "ShapeDetectApp.h" #include "AppUtility.h" #include "itkImageRegionIterator.h" #include "itkExceptionObject.h" #include "itkFastMarchingImageFilter.h" #include "itkImageFileReader.h" #include "itkRawImageIO.h" #include "vnl/vnl_math.h" #include <string> ShapeDetectApp ::ShapeDetectApp() { this->Initialize(); } void ShapeDetectApp ::Initialize() { m_InputImage = InputImageType::New(); m_EdgePotentialImage = ImageType::New(); m_SegmentationMask = ImageType::New(); m_DetectionFilter = DetectionFilterType::New(); m_Sigma = 1.0; m_DumpPGMFiles = true; } void ShapeDetectApp ::Execute() { char currentLine[150]; char buffer[150]; unsigned int uNumbers[3]; float fValue; char symbol; std::cout << std::endl; // Get input file name while(1) { std::cout << "Input file name: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: filename expected." << std::endl; } m_InputFileName = buffer; // Get big endian flag while(1) { std::cout << "Input image big endian? [y|n]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%c", &symbol ) >= 1 && ( symbol == 'y' || symbol == 'n' ) ) break; std::cout << "Error: 'y' or 'n' expected." << std::endl; } if( symbol == 'y' ) { m_InputBigEndian = true; } else { m_InputBigEndian = false; } // Get input file size while(1) { std::cout << "Input image size: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_InputSize[j] = uNumbers[j]; } // Read in input image if( !this->ReadImage( m_InputFileName.c_str(), m_InputSize, m_InputBigEndian, m_InputImage ) ) { std::cout << "Error while reading in input volume: "; std::cout << m_InputFileName.c_str() << std::endl; return; } // Get input file name while(1) { std::cout << "PGM output directory: "; std::cin.getline( currentLine, 150); if( sscanf( currentLine, "%s", buffer ) >= 1 ) break; std::cout << "Error: directory name expected." << std::endl; } m_PGMDirectory = buffer; if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the input volume." << std::endl; if( !WritePGMFiles<InputImageType>( m_InputImage, m_PGMDirectory.c_str(), "input" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } this->ComputeEdgePotentialMap(); std::cout << std::endl << std::endl; // Set the initial seed while(1) { std::cout << "Set initial seed index: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%d%d%d", uNumbers, uNumbers+1, uNumbers+2 ) >= 3 ) break; std::cout << "Error: three unsigned integers expected." << std::endl; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } // run the filter std::cout << "Generating time crossing map." << std::endl; this->ComputeTimeCrossingMap(); while(1) { std::cout << std::endl << "Command [s|t|d|x]: "; std::cin.getline( currentLine, 150 ); if( sscanf( currentLine, "%s", buffer ) >= 1 ) { // parse the command switch ( buffer[0] ) { case 's' : if( sscanf( currentLine, "%c%d%d%d", &symbol, uNumbers, uNumbers+1, uNumbers+2 ) != 4 ) { std::cout << "Error: three unsigned integers expected" << std::endl; continue; } for( int j = 0; j < ImageDimension; j++ ) { m_Seed[j] = uNumbers[j]; } std::cout << "Re-generating time crossing map." << std::endl; this->ComputeTimeCrossingMap(); this->ThresholdTimeCrossingMap(); this->WriteSegmentationImage(); break; case 't' : if( sscanf( currentLine, "%c%f", &symbol, &fValue ) != 2 ) { std::cout << "Error: one floating point value expected" << std::endl; continue; } m_Threshold = fValue;; std::cout << "Re-thresholding time crossing map." << std::endl; this->ThresholdTimeCrossingMap(); this->WriteSegmentationImage(); break; break; case 'd': std::cout << "Seed: " << m_Seed << "Threshold: " << m_Threshold << std::endl; break; case 'x' : std::cout << "Goodbye. " << std::endl; return; break; default : std::cout << "Not a valid command." << std::endl; } //end switch } } //end while } void ShapeDetectApp ::ComputeTimeCrossingMap() { // connect edge potential map m_DetectionFilter->SetSpeedImage( m_EdgePotentialImage ); // setup trial points typedef DetectionFilterType::NodeType NodeType; typedef DetectionFilterType::NodeContainer NodeContainer; NodeContainer::Pointer trialPoints = NodeContainer::New(); NodeType node; node.SetValue( 0.0 ); node.SetIndex( m_Seed ); trialPoints->InsertElement(0, node); m_DetectionFilter->SetTrialPoints( trialPoints ); // specify the size of the output image m_DetectionFilter->SetOutputSize( m_InputImage->GetBufferedRegion().GetSize() ); // update the marcher m_DetectionFilter->Update(); } void ShapeDetectApp ::ThresholdTimeCrossingMap() { // threshold the time crossing map m_SegmentationMask->SetLargestPossibleRegion( m_InputImage->GetLargestPossibleRegion() ); m_SegmentationMask->SetBufferedRegion( m_InputImage->GetBufferedRegion() ); m_SegmentationMask->Allocate(); typedef itk::ImageRegionIterator<ImageType> Iterator; Iterator inIter( m_DetectionFilter->GetOutput(), m_DetectionFilter->GetOutput()->GetBufferedRegion() ); Iterator outIter( m_SegmentationMask, m_SegmentationMask->GetBufferedRegion() ); while( !inIter.IsAtEnd() ) { if( inIter.Get() <= m_Threshold ) { outIter.Set( 1 ); } else { outIter.Set( 0 ); } ++inIter; ++outIter; } } void ShapeDetectApp ::WriteSegmentationImage() { if( m_DumpPGMFiles ) { //dump out the segmented image if( !WritePGMFiles<ImageType>( m_SegmentationMask, m_PGMDirectory.c_str(), "seg" ) ) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } void ShapeDetectApp ::ComputeEdgePotentialMap() { // compute derivative of the input image DerivativeFilterPointer deriv = DerivativeFilterType::New(); deriv->SetInput( m_InputImage ); deriv->SetSigma( m_Sigma ); deriv->Update(); // allocate memory for the map m_EdgePotentialImage->SetLargestPossibleRegion( m_InputImage->GetLargestPossibleRegion() ); m_EdgePotentialImage->SetBufferedRegion( m_InputImage->GetBufferedRegion() ); m_EdgePotentialImage->Allocate(); //**** //FIXME - use an itk filter once API are consistent //**** // compute the magnitude typedef itk::ImageRegionIterator<DerivativeImageType> DerivativeIterator; typedef itk::ImageRegionIterator<ImageType> ImageIterator; DerivativeIterator derivIter( deriv->GetOutput(), deriv->GetOutput()->GetBufferedRegion() ); ImageIterator mapIter( m_EdgePotentialImage, m_EdgePotentialImage->GetBufferedRegion() ); while( !derivIter.IsAtEnd() ) { float accum = 0; VectorType grad = derivIter.Get(); for( int j = 0; j < ImageDimension; j++ ) { accum += vnl_math_sqr( grad[j] ); } accum = vnl_math_sqrt( accum ); // mapIter.Set( 1.0 / ( 1.0 + accum ) ); mapIter.Set( exp( -1.0 * accum ) ); ++derivIter; ++mapIter; } if( m_DumpPGMFiles ) { //dump out the input image std::cout << "Writing PGM files of the edge potential map." << std::endl; if( !WritePGMFiles<ImageType>( m_EdgePotentialImage, m_PGMDirectory.c_str(), "map" )) { std::cout << "Error while writing PGM files."; std::cout << "Please make sure the path is valid." << std::endl; return; } } } bool ShapeDetectApp ::ReadImage( const char * filename, const SizeType& size, bool bigEndian, InputImageType::Pointer & imgPtr ) { // Read in a raw volume typedef itk::RawImageIO< InputPixelType, ImageDimension > RawReaderType; RawReaderType::Pointer rawIO = RawReaderType::New(); rawIO->SetFileDimensionality( ImageDimension ); rawIO->SetDimensions( 0, size[0] ); rawIO->SetDimensions( 1, size[1] ); rawIO->SetDimensions( 2, size[2] ); typedef itk::ImageFileReader<InputImageType> ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetImageIO( rawIO ); reader->SetFileName( filename ); reader->Update(); imgPtr = reader->GetOutput(); return true; } <|endoftext|>
<commit_before>#include "include/logging.h" //Start the logger from a properties file void Logger::start_log_from_file(std::string initFileName) { //Read the properties file try { log4cpp::PropertyConfigurator::configure(initFileName); } catch ( log4cpp::ConfigureFailure &e ) { std::cout << "[log4cpp::ConfigureFailure] caught while reading" << initFileName << std::endl; std::cout << e.what(); exit(1); } //Find the categories defined in the file // std::vector<log4cpp::Category*> categories = log4cpp::Category::getCurrentCategories(); //Expose the logging handles log4cpp::Category& root = log4cpp::Category::getRoot(); // log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); root_log = &root; } //Bring down the logging module void Logger::end_log() { if (!root_log) { std::cout << "Shutdown called with no logging module present" << std::endl; } else { log4cpp::Category::shutdown(); } } //Constructor from a file Logger::Logger(std::string initFileName) { start_log_from_file(initFileName); } //Destructor Logger::~Logger() { end_log(); } //Exposures that log to the root category void Logger::debug(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(msg); } } void Logger::error(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(msg); } } void Logger::info(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(msg); } } void Logger::debug(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(msg); } } void Logger::error(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(msg); } } void Logger::info(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(msg); } } void Logger::debug(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } void Logger::debug(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } void Logger::debug(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } //Pull down different categories by name LoggingCategory* Logger::get_category(std::string name) { return log4cpp::Category::getInstance(name); } //--------------------------Logging Category Methods---------------------------// //Exposures that log to the root category void LoggingCategory::debug(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(msg); } } void LoggingCategory::error(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(msg); } } void LoggingCategory::info(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(msg); } } void LoggingCategory::debug(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(msg); } } void LoggingCategory::error(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(msg); } } void LoggingCategory::info(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(msg); } } void LoggingCategory::debug(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } void LoggingCategory::debug(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } void LoggingCategory::debug(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } <commit_msg>Logging Refactor to completely encapsulate implementation and allow for logging categories<commit_after>#include "include/logging.h" //Start the logger from a properties file void Logger::start_log_from_file(std::string initFileName) { //Read the properties file try { log4cpp::PropertyConfigurator::configure(initFileName); } catch ( log4cpp::ConfigureFailure &e ) { std::cout << "[log4cpp::ConfigureFailure] caught while reading" << initFileName << std::endl; std::cout << e.what(); exit(1); } //Find the categories defined in the file // std::vector<log4cpp::Category*> categories = log4cpp::Category::getCurrentCategories(); //Expose the logging handles log4cpp::Category& root = log4cpp::Category::getRoot(); // log4cpp::Category& sub1 = log4cpp::Category::getInstance(std::string("sub1")); root_log = &root; } //Bring down the logging module void Logger::end_log() { if (!root_log) { std::cout << "Shutdown called with no logging module present" << std::endl; } else { log4cpp::Category::shutdown(); } } //Constructor from a file Logger::Logger(std::string initFileName) { start_log_from_file(initFileName); } //Destructor Logger::~Logger() { end_log(); } //Exposures that log to the root category void Logger::debug(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(msg); } } void Logger::error(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(msg); } } void Logger::info(std::string msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(msg); } } void Logger::debug(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(msg); } } void Logger::error(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(msg); } } void Logger::info(const char * msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(msg); } } void Logger::debug(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(int msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } void Logger::debug(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(float msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } void Logger::debug(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->debug(std::to_string(msg)); } } void Logger::error(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->error(std::to_string(msg)); } } void Logger::info(double msg) { if (!root_log) { std::cout << msg << std::endl; } else { root_log->info(std::to_string(msg)); } } //Pull down different categories by name LoggingCategoryInterface* Logger::get_category(std::string name) { return new LoggingCategory(name); } //--------------------------Logging Category Methods---------------------------// //Exposures that log to the root category void LoggingCategory::debug(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(msg); } } void LoggingCategory::error(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(msg); } } void LoggingCategory::info(std::string msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(msg); } } void LoggingCategory::debug(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(msg); } } void LoggingCategory::error(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(msg); } } void LoggingCategory::info(const char * msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(msg); } } void LoggingCategory::debug(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(int msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } void LoggingCategory::debug(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(float msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } void LoggingCategory::debug(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->debug(std::to_string(msg)); } } void LoggingCategory::error(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->error(std::to_string(msg)); } } void LoggingCategory::info(double msg) { if (!int_category) { std::cout << name << ": " << msg << std::endl; } else { int_category->info(std::to_string(msg)); } } <|endoftext|>
<commit_before>// file: xSP3EphemerisStore.cpp #include "xSP3EphemerisStore.hpp" #include "SatID.hpp" #include "Exception.hpp" #include "SP3Data.hpp" #include "SP3Header.hpp" #include "SP3Stream.hpp" CPPUNIT_TEST_SUITE_REGISTRATION (xSP3EphemerisStore); void xSP3EphemerisStore :: setUp (void) { } /* **** General test for the SP3EphemerisStore class **** Test to assure the that RES throws its exceptions in the right place and **** that it loads the SP3 file correctly **** To further check this data, please view DumpData.txt for the dumped information */ void xSP3EphemerisStore :: RESTest (void) { using namespace std; cout << "Reading " << "NGA15081Test.SP3" << endl; Rinex3::SP3Stream roffs("NGA15081Test.SP3"); cout << "Writing " << "Output1.txt" << endl; Rinex3::SP3Stream out("Output1.txt",ios::out); //out.exceptions(fstream::failbit); Rinex3::SP3Header roh; Rinex3::SP3Data roe; roffs >> roh; out << roh; //roh.dump(cout); while (roffs >> roe) { out << roe; //roe.dump(cout); } } /* **** Test to assure the quality of SP3EphemerisStore class member getXvt() **** This test makes sure that exceptions are thrown if there is no ephemeris data **** for the given PRN and also that an exception is thrown if there is no data for **** the PRN at the given time. Furthermore, this test finds an Xvt for a given **** DayTime Time and PRN. **** To see the Xvt information for the selected Time and PRN please see **** getXvt.txt */ void xSP3EphemerisStore :: getXvtTest (void) { using namespace std; cout << "Reading " << "Output1.txt" << endl; Rinex3::SP3Stream roffs("Output1.txt"); cout << "Writing " << "Output2.txt" << endl; Rinex3::SP3Stream out("Output2.txt",ios::out); out.exceptions(fstream::failbit); Rinex3::SP3Header roh; Rinex3::SP3Data roe; roffs >> roh; out << roh; //roh.dump(cout); while (roffs >> roe) { out << roe; //roe.dump(cout); } } /* **** Test to assure the quality of SP3EphemerisStore class member dump() **** This test makes sure that dump() behaves as expected. With paramters from **** 0-2 with each giving more and more respective information, this information is **** then put into txt files. **** To see the dump with paramter 0, please view DumpData0.txt **** To see the dump with paramter 1, pleave view DumpData1.txt **** To see the dump with paramter 2, please uncomment the test and view the command **** line output (cout). */ void xSP3EphemerisStore :: dumpTest (void) { } /* **** Test to assure the quality of SP3EphemerisStore class member addEphemeris() **** This test assures that no exceptions are thrown when a an ephemeris, taken from Store **** is added to a blank Object. Then the test makes sure that only that Ephemeris **** is in the object by checking the start and end times of the Object **** Question: Why does this eph data begin two hours earlier than it does on the output? */ void xSP3EphemerisStore :: addEphemerisTest (void) { } /* **** Test to assure the quality of SP3EphemerisStore class member edit() **** This test assures that no exceptions are thrown when we edit a RES object **** then after we edit the RES Object, we test to make sure that our edit time **** parameters are now the time endpoints of the object. **** For further inspection of the edit, please view editTest.txt */ void xSP3EphemerisStore :: editTest (void) { } /* **** Test to assure the quality of SP3EphemerisStore class member clear() **** This test assures that no exceptions are thrown when we clear a SP3 object **** then after we clear the SP3 Object, we test to make sure that END_OF_TIME is our **** initial time and BEGINNING_OF_TIME is our final time **** For further inspection of the edit, please view clearTest.txt */ void xSP3EphemerisStore :: clearTest (void) { } void xSP3EphemerisStore :: dumpBadPositionsTest (void) { } void xSP3EphemerisStore :: dumpBadClocksTest (void) { } void xSP3EphemerisStore :: maxIntervalTest (void) { } void xSP3EphemerisStore :: getTimeTest (void) { } bool xSP3EphemerisStore :: fileEqualTest (char* handle1, char* handle2) { bool isEqual = false; ifstream File1; ifstream File2; std::string File1Line; std::string File2Line; File1.open(handle1); File2.open(handle2); while (!File1.eof()) { if (File2.eof()) return isEqual; getline (File1, File1Line); getline (File2, File2Line); if (File1Line != File2Line) return isEqual; } if (!File2.eof()) return isEqual; else return isEqual = true; } <commit_msg>Removed incorrect comments to the SP3Eph functional test<commit_after>// file: xSP3EphemerisStore.cpp #include "xSP3EphemerisStore.hpp" #include "SatID.hpp" #include "Exception.hpp" #include "SP3Data.hpp" #include "SP3Header.hpp" #include "SP3Stream.hpp" CPPUNIT_TEST_SUITE_REGISTRATION (xSP3EphemerisStore); void xSP3EphemerisStore :: setUp (void) { } void xSP3EphemerisStore :: RESTest (void) { using namespace std; cout << "Reading " << "NGA15081Test.SP3" << endl; Rinex3::SP3Stream roffs("NGA15081Test.SP3"); cout << "Writing " << "Output1.txt" << endl; Rinex3::SP3Stream out("Output1.txt",ios::out); //out.exceptions(fstream::failbit); Rinex3::SP3Header roh; Rinex3::SP3Data roe; roffs >> roh; out << roh; //roh.dump(cout); while (roffs >> roe) { out << roe; //roe.dump(cout); } } void xSP3EphemerisStore :: getXvtTest (void) { using namespace std; cout << "Reading " << "Output1.txt" << endl; Rinex3::SP3Stream roffs("Output1.txt"); cout << "Writing " << "Output2.txt" << endl; Rinex3::SP3Stream out("Output2.txt",ios::out); out.exceptions(fstream::failbit); Rinex3::SP3Header roh; Rinex3::SP3Data roe; roffs >> roh; out << roh; //roh.dump(cout); while (roffs >> roe) { out << roe; //roe.dump(cout); } } void xSP3EphemerisStore :: dumpTest (void) { } void xSP3EphemerisStore :: addEphemerisTest (void) { } void xSP3EphemerisStore :: editTest (void) { } void xSP3EphemerisStore :: clearTest (void) { } void xSP3EphemerisStore :: dumpBadPositionsTest (void) { } void xSP3EphemerisStore :: dumpBadClocksTest (void) { } void xSP3EphemerisStore :: maxIntervalTest (void) { } void xSP3EphemerisStore :: getTimeTest (void) { } bool xSP3EphemerisStore :: fileEqualTest (char* handle1, char* handle2) { bool isEqual = false; ifstream File1; ifstream File2; std::string File1Line; std::string File2Line; File1.open(handle1); File2.open(handle2); while (!File1.eof()) { if (File2.eof()) return isEqual; getline (File1, File1Line); getline (File2, File2Line); if (File1Line != File2Line) return isEqual; } if (!File2.eof()) return isEqual; else return isEqual = true; } <|endoftext|>
<commit_before>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "writingtotemporary.h" #include "Utils.h" #include "checkmanager.h" #include "StringUtils.h" #include <clang/AST/AST.h> #include <clang/Lex/Lexer.h> using namespace clang; using namespace std; WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci) : CheckBase(name, ci) , m_widenCriteria(isOptionSet("widen-criteria")) { } std::vector<string> WritingToTemporary::filesToIgnore() const { static const vector<string> files = { "qstring.h" }; return files; } vector<string> WritingToTemporary::supportedOptions() const { static const vector<string> options = { "widen-criteria" }; return options; } static bool isDisallowedClass(const string &className) { static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement", "QScriptValue", "QTextLine", "QTextBlock", "QDomNode", "QJSValue" }; return clazy_std::contains(disallowed, className); } static bool isDisallowedMethod(const string &name) { static const vector<string> disallowed = { "QColor::getCmyk", "QColor::getCmykF" }; return clazy_std::contains(disallowed, name); } static bool isKnownType(const string &className) { static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet", "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList", "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D", "QVector4D", "QSize", "QSizeF", "QSizePolicy", "QPoint", "QPointF", "QColor" }; return clazy_std::contains(types, className); } void WritingToTemporary::VisitStmt(clang::Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (!callExpr) return; // For a chain like getFoo().setBar(), returns {setBar(), getFoo()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar() FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee(); if (!secondFunc) return; CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc); if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic()) return; CXXRecordDecl *record = secondMethod->getParent(); if (!record || isDisallowedClass(record->getNameAsString())) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType()) return; qt = secondFunc->getReturnType(); const Type *secondFuncReturnType = qt.getTypePtrOrNull(); if (!secondFuncReturnType || !secondFuncReturnType->isVoidType()) return; if (!m_widenCriteria && !isKnownType(record->getNameAsString()) && !clazy_std::startsWith(secondFunc->getNameAsString(), "set")) return; const string &methodName = secondMethod->getQualifiedNameAsString(); if (isDisallowedMethod(methodName)) return; emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + methodName); } REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0) <commit_msg>writing-to-temporary: Whitelist QTextTableCell<commit_after>/* This file is part of the clazy static checker. Copyright (C) 2015 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com Author: Sérgio Martins <sergio.martins@kdab.com> Copyright (C) 2015 Sergio Martins <smartins@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "writingtotemporary.h" #include "Utils.h" #include "checkmanager.h" #include "StringUtils.h" #include <clang/AST/AST.h> #include <clang/Lex/Lexer.h> using namespace clang; using namespace std; WritingToTemporary::WritingToTemporary(const std::string &name, const clang::CompilerInstance &ci) : CheckBase(name, ci) , m_widenCriteria(isOptionSet("widen-criteria")) { } std::vector<string> WritingToTemporary::filesToIgnore() const { static const vector<string> files = { "qstring.h" }; return files; } vector<string> WritingToTemporary::supportedOptions() const { static const vector<string> options = { "widen-criteria" }; return options; } static bool isDisallowedClass(const string &className) { static const vector<string> disallowed = { "QTextCursor", "QDomElement", "KConfigGroup", "QWebElement", "QScriptValue", "QTextLine", "QTextBlock", "QDomNode", "QJSValue" }; return clazy_std::contains(disallowed, className); } static bool isDisallowedMethod(const string &name) { static const vector<string> disallowed = { "QColor::getCmyk", "QColor::getCmykF" }; return clazy_std::contains(disallowed, name); } static bool isKnownType(const string &className) { static const vector<string> types = { "QList", "QVector", "QMap", "QHash", "QString", "QSet", "QByteArray", "QUrl", "QVarLengthArray", "QLinkedList", "QRect", "QRectF", "QBitmap", "QVector2D", "QVector3D", "QVector4D", "QSize", "QSizeF", "QSizePolicy", "QPoint", "QPointF", "QColor", "QTextTableCell" }; return clazy_std::contains(types, className); } void WritingToTemporary::VisitStmt(clang::Stmt *stmt) { CallExpr *callExpr = dyn_cast<CallExpr>(stmt); if (!callExpr) return; // For a chain like getFoo().setBar(), returns {setBar(), getFoo()} vector<CallExpr *> callExprs = Utils::callListForChain(callExpr); if (callExprs.size() < 2) return; CallExpr *firstCallToBeEvaluated = callExprs.at(callExprs.size() - 1); // This is the call to getFoo() FunctionDecl *firstFunc = firstCallToBeEvaluated->getDirectCallee(); if (!firstFunc) return; CallExpr *secondCallToBeEvaluated = callExprs.at(callExprs.size() - 2); // This is the call to setBar() FunctionDecl *secondFunc = secondCallToBeEvaluated->getDirectCallee(); if (!secondFunc) return; CXXMethodDecl *secondMethod = dyn_cast<CXXMethodDecl>(secondFunc); if (!secondMethod || secondMethod->isConst() || secondMethod->isStatic()) return; CXXRecordDecl *record = secondMethod->getParent(); if (!record || isDisallowedClass(record->getNameAsString())) return; QualType qt = firstFunc->getReturnType(); const Type *firstFuncReturnType = qt.getTypePtrOrNull(); if (!firstFuncReturnType || firstFuncReturnType->isPointerType() || firstFuncReturnType->isReferenceType()) return; qt = secondFunc->getReturnType(); const Type *secondFuncReturnType = qt.getTypePtrOrNull(); if (!secondFuncReturnType || !secondFuncReturnType->isVoidType()) return; if (!m_widenCriteria && !isKnownType(record->getNameAsString()) && !clazy_std::startsWith(secondFunc->getNameAsString(), "set")) return; const string &methodName = secondMethod->getQualifiedNameAsString(); if (isDisallowedMethod(methodName)) return; emitWarning(stmt->getLocStart(), "Call to temporary is a no-op: " + methodName); } REGISTER_CHECK_WITH_FLAGS("writing-to-temporary", WritingToTemporary, CheckLevel0) <|endoftext|>
<commit_before>#include "WaterRenderer.h" #include "../World/Chunk/ChunkMesh.h" #include "../World/Block/BlockDatabase.h" #include "../Application.h" #include "../Camera.h" #include <iostream> void WaterRenderer::add(const ChunkMesh& mesh) { m_chunks.push_back(&mesh); } void WaterRenderer::render(const Camera& camera, Config* conf) { if (m_chunks.empty()) { return; } glEnable(GL_BLEND); glDisable(GL_CULL_FACE); m_shader.useProgram(); m_shader.loadProjectionViewMatrix(camera.getProjectionViewMatrix()); m_shader.loadProjectionViewMatrix(camera.getProjectionViewMatrix()); m_shader.loadTime(g_timeElapsed); for (const auto& mesh : m_chunks) { const ChunkMesh& m = *mesh; m.getModel().bindVAO(); GL::drawElements(m.getModel().getIndicesCount()); } m_chunks.clear(); } <commit_msg>Fixed bugs.<commit_after>#include "WaterRenderer.h" #include "../World/Chunk/ChunkMesh.h" #include "../World/Block/BlockDatabase.h" #include "../Application.h" #include "../Camera.h" #include <iostream> void WaterRenderer::add(const ChunkMesh& mesh) { m_chunks.push_back(&mesh); } void WaterRenderer::render(const Camera& camera, Config* conf) { if (m_chunks.empty()) { return; } glEnable(GL_BLEND); glDisable(GL_CULL_FACE); m_shader.useProgram(); m_shader.loadProjectionViewMatrix(camera.getProjectionViewMatrix()); m_shader.loadTime(g_timeElapsed); for (const auto& mesh : m_chunks) { const ChunkMesh& m = *mesh; m.getModel().bindVAO(); GL::drawElements(m.getModel().getIndicesCount()); } m_chunks.clear(); } <|endoftext|>
<commit_before>#include <stdio.h> #include <string.h> #include <sys/time.h> #include "files.h" #include "misc.h" #include "runpasses.h" #include "stringutil.h" #include "symtab.h" #include "../passes/pass.h" bool printPasses = false; struct PassInfo { char* name; Pass* pass; char* args; }; #define START_PASSLIST_REGISTRATION \ static Pass* stringToPass(char* passname) { #define STOP_PASSLIST_REGISTRATION \ INT_FATAL("Couldn't find a pass named %s", passname); \ return NULL; \ } #define REGISTER(pass) \ if (strcmp(passname, #pass) == 0) { \ return new pass(); \ } #include "passlist.cpp" #define FIRST {NULL, NULL, NULL} #define LAST {NULL, NULL, NULL} #define RUN(x, a) {#x, new x(), a} #include "passlist.h" static void runPass(char* passName, Pass* pass, char* args) { struct timeval startTime; struct timeval stopTime; struct timezone timezone; pass->setArgs(args); if (printPasses) { fprintf(stderr, "%32s :", passName); fflush(stderr); gettimeofday(&startTime, &timezone); } pass->run(Symboltable::getModuleList(pass->whichModules)); if (printPasses) { gettimeofday(&stopTime, &timezone); fprintf(stderr, "%8.3f seconds\n", ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) - (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6); } } static void parsePassFile(char* passfilename) { FILE* passfile = openInputFile(passfilename); char passname[80] = ""; char args[80] = ""; int readPass; bool readLastPass; do { readPass = fscanf(passfile, "%s", passname); } while (readPass == 1 && strcmp(passname, "FIRST,") != 0); do { readPass = fscanf(passfile, "%s", passname); readLastPass = strcmp(passname, "LAST") == 0; if (!readLastPass) { if (strncmp(passname, "//", 2) == 0) { char nextChar; do { fscanf(passfile, "%c", &nextChar); } while (nextChar != '\n'); } else if (strncmp(passname, "RUN(", 4) != 0) { fail("ill-formed passname: %s", passname); } else { char* passnameStart = passname + 4; // 4 == strlen("RUN(") int passnameLen = strlen(passnameStart); passnameStart[passnameLen-1] = '\0'; // overwrite comma bool readChar; char nextChar; do { readChar = fscanf(passfile, "%c", &nextChar); } while (readChar == 1 && nextChar != '\"'); int argLength = 0; do { readChar = fscanf(passfile, "%c", &nextChar); if (readChar) { args[argLength++] = nextChar; } } while (readChar == 1 && nextChar != '\"'); args[--argLength] = '\0'; char extraStuff[80]; fscanf(passfile, "%s", extraStuff); if (strcmp(extraStuff, "),") != 0) { fail("pass name ended poorly: %s", extraStuff); } Pass* pass = stringToPass(passnameStart); runPass(passnameStart, pass, args); } } } while (readPass == 1 && !readLastPass); closeInputFile(passfile); } void runPasses(char* passfilename) { if (strcmp(passfilename, "") == 0) { PassInfo* pass = passlist+1; // skip over FIRST while (pass->name != NULL) { runPass(pass->name, pass->pass, pass->args); pass++; } } else { parsePassFile(passfilename); } } <commit_msg><commit_after>#include <stdio.h> #include <string.h> #include <sys/time.h> #include "files.h" #include "misc.h" #include "runpasses.h" #include "stringutil.h" #include "symtab.h" #include "../passes/pass.h" bool printPasses = false; struct PassInfo { char* name; char* args; }; #define START_PASSLIST_REGISTRATION \ static Pass* stringToPass(char* passname) { #define STOP_PASSLIST_REGISTRATION \ INT_FATAL("Couldn't find a pass named %s", passname); \ return NULL; \ } #define REGISTER(pass) \ if (strcmp(passname, #pass) == 0) { \ return new pass(); \ } #include "passlist.cpp" #define FIRST {NULL, NULL} #define LAST {NULL, NULL} #define RUN(x, a) {#x, a} #include "passlist.h" static void runPass(char* passName, Pass* pass, char* args) { struct timeval startTime; struct timeval stopTime; struct timezone timezone; pass->setArgs(args); if (printPasses) { fprintf(stderr, "%32s :", passName); fflush(stderr); gettimeofday(&startTime, &timezone); } pass->run(Symboltable::getModuleList(pass->whichModules)); if (printPasses) { gettimeofday(&stopTime, &timezone); fprintf(stderr, "%8.3f seconds\n", ((double)((stopTime.tv_sec*1e6+stopTime.tv_usec) - (startTime.tv_sec*1e6+startTime.tv_usec))) / 1e6); } } static void parsePassFile(char* passfilename) { FILE* passfile = openInputFile(passfilename); char passname[80] = ""; char args[80] = ""; int readPass; bool readLastPass; do { readPass = fscanf(passfile, "%s", passname); } while (readPass == 1 && strcmp(passname, "FIRST,") != 0); do { readPass = fscanf(passfile, "%s", passname); readLastPass = strcmp(passname, "LAST") == 0; if (!readLastPass) { if (strncmp(passname, "//", 2) == 0) { char nextChar; do { fscanf(passfile, "%c", &nextChar); } while (nextChar != '\n'); } else if (strncmp(passname, "RUN(", 4) != 0) { fail("ill-formed passname: %s", passname); } else { char* passnameStart = passname + 4; // 4 == strlen("RUN(") int passnameLen = strlen(passnameStart); passnameStart[passnameLen-1] = '\0'; // overwrite comma bool readChar; char nextChar; do { readChar = fscanf(passfile, "%c", &nextChar); } while (readChar == 1 && nextChar != '\"'); int argLength = 0; do { readChar = fscanf(passfile, "%c", &nextChar); if (readChar) { args[argLength++] = nextChar; } } while (readChar == 1 && nextChar != '\"'); args[--argLength] = '\0'; char extraStuff[80]; fscanf(passfile, "%s", extraStuff); if (strcmp(extraStuff, "),") != 0) { fail("pass name ended poorly: %s", extraStuff); } Pass* pass = stringToPass(passnameStart); runPass(passnameStart, pass, args); } } } while (readPass == 1 && !readLastPass); closeInputFile(passfile); } void runPasses(char* passfilename) { if (strcmp(passfilename, "") == 0) { PassInfo* pass = passlist+1; // skip over FIRST while (pass->name != NULL) { runPass(pass->name, stringToPass(pass->name), pass->args); pass++; } } else { parsePassFile(passfilename); } } <|endoftext|>
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Games/Game.hpp> #include <Rosetta/Models/Entity.hpp> #include <Rosetta/Models/Player.hpp> #include <Rosetta/Models/Spell.hpp> namespace RosettaStone { Entity::Entity(Player& _owner, Card& _card) : owner(&_owner), card(_card) { auraEffects = new AuraEffects(this); for (auto& gameTag : _card.gameTags) { Entity::SetGameTag(gameTag.first, gameTag.second); } } Entity::Entity(const Entity& ent) { FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; } Entity::Entity(Entity&& ent) noexcept { FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; } Entity::~Entity() { FreeMemory(); } Entity& Entity::operator=(const Entity& ent) { if (this == &ent) { return *this; } FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; return *this; } Entity& Entity::operator=(Entity&& ent) noexcept { if (this == &ent) { return *this; } FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; return *this; } void Entity::Reset() { SetGameTag(GameTag::DAMAGE, 0); SetGameTag(GameTag::EXHAUSTED, 0); SetGameTag(GameTag::ATK, 0); SetGameTag(GameTag::HEALTH, 0); SetGameTag(GameTag::COST, 0); SetGameTag(GameTag::TAUNT, 0); SetGameTag(GameTag::FROZEN, 0); SetGameTag(GameTag::CHARGE, 0); SetGameTag(GameTag::WINDFURY, 0); SetGameTag(GameTag::DIVINE_SHIELD, 0); SetGameTag(GameTag::STEALTH, 0); SetGameTag(GameTag::NUM_ATTACKS_THIS_TURN, 0); } int Entity::GetGameTag(GameTag tag) const { if (m_gameTags.find(tag) == m_gameTags.end()) { if (auraEffects != nullptr) { return auraEffects->GetGameTag(tag); } return 0; } if (auraEffects != nullptr) { return m_gameTags.at(tag) + auraEffects->GetGameTag(tag); } return m_gameTags.at(tag); } void Entity::SetGameTag(GameTag tag, int value) { m_gameTags.insert_or_assign(tag, value); } int Entity::GetCost() const { return GetGameTag(GameTag::COST); } void Entity::SetCost(int cost) { SetGameTag(GameTag::COST, cost); } bool Entity::GetExhausted() const { return static_cast<bool>(GetGameTag(GameTag::EXHAUSTED)); } void Entity::SetExhausted(bool exhausted) { SetGameTag(GameTag::EXHAUSTED, static_cast<int>(exhausted)); } void Entity::Destroy() { isDestroyed = true; } Entity* Entity::GetFromCard(Player& player, Card&& card) { Entity* result; switch (card.GetCardType()) { case CardType::HERO: result = new Hero(player, card); break; case CardType::HERO_POWER: result = new HeroPower(player, card); break; case CardType::MINION: result = new Minion(player, card); break; case CardType::SPELL: result = new Spell(player, card); break; case CardType::WEAPON: result = new Weapon(player, card); break; default: throw std::invalid_argument( "Generic::DrawCard() - Invalid card type!"); } // Set entity ID result->id = player.GetGame()->GetNextID(); return result; } void Entity::FreeMemory() { delete auraEffects; delete onGoingEffect; m_gameTags.clear(); } } // namespace RosettaStone <commit_msg>fix: Correct code to consider case that the value of GameTag is negative<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <Rosetta/Games/Game.hpp> #include <Rosetta/Models/Entity.hpp> #include <Rosetta/Models/Player.hpp> #include <Rosetta/Models/Spell.hpp> namespace RosettaStone { Entity::Entity(Player& _owner, Card& _card) : owner(&_owner), card(_card) { auraEffects = new AuraEffects(this); for (auto& gameTag : _card.gameTags) { Entity::SetGameTag(gameTag.first, gameTag.second); } } Entity::Entity(const Entity& ent) { FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; } Entity::Entity(Entity&& ent) noexcept { FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; } Entity::~Entity() { FreeMemory(); } Entity& Entity::operator=(const Entity& ent) { if (this == &ent) { return *this; } FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; return *this; } Entity& Entity::operator=(Entity&& ent) noexcept { if (this == &ent) { return *this; } FreeMemory(); owner = ent.owner; card = ent.card; auraEffects = ent.auraEffects; onGoingEffect = ent.onGoingEffect; m_gameTags = ent.m_gameTags; return *this; } void Entity::Reset() { SetGameTag(GameTag::DAMAGE, 0); SetGameTag(GameTag::EXHAUSTED, 0); SetGameTag(GameTag::ATK, 0); SetGameTag(GameTag::HEALTH, 0); SetGameTag(GameTag::COST, 0); SetGameTag(GameTag::TAUNT, 0); SetGameTag(GameTag::FROZEN, 0); SetGameTag(GameTag::CHARGE, 0); SetGameTag(GameTag::WINDFURY, 0); SetGameTag(GameTag::DIVINE_SHIELD, 0); SetGameTag(GameTag::STEALTH, 0); SetGameTag(GameTag::NUM_ATTACKS_THIS_TURN, 0); } int Entity::GetGameTag(GameTag tag) const { int value = 0; if (m_gameTags.find(tag) == m_gameTags.end()) { if (auraEffects != nullptr) { value += auraEffects->GetGameTag(tag); } } else { value += m_gameTags.at(tag); if (auraEffects != nullptr) { value += auraEffects->GetGameTag(tag); } } return value > 0 ? value : 0; } void Entity::SetGameTag(GameTag tag, int value) { m_gameTags.insert_or_assign(tag, value); } int Entity::GetCost() const { return GetGameTag(GameTag::COST); } void Entity::SetCost(int cost) { SetGameTag(GameTag::COST, cost); } bool Entity::GetExhausted() const { return static_cast<bool>(GetGameTag(GameTag::EXHAUSTED)); } void Entity::SetExhausted(bool exhausted) { SetGameTag(GameTag::EXHAUSTED, static_cast<int>(exhausted)); } void Entity::Destroy() { isDestroyed = true; } Entity* Entity::GetFromCard(Player& player, Card&& card) { Entity* result; switch (card.GetCardType()) { case CardType::HERO: result = new Hero(player, card); break; case CardType::HERO_POWER: result = new HeroPower(player, card); break; case CardType::MINION: result = new Minion(player, card); break; case CardType::SPELL: result = new Spell(player, card); break; case CardType::WEAPON: result = new Weapon(player, card); break; default: throw std::invalid_argument( "Generic::DrawCard() - Invalid card type!"); } // Set entity ID result->id = player.GetGame()->GetNextID(); return result; } void Entity::FreeMemory() { delete auraEffects; delete onGoingEffect; m_gameTags.clear(); } } // namespace RosettaStone <|endoftext|>
<commit_before>/* This file is part of HadesMem. Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza). <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> HadesMem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // C++ Standard Library #include <memory> // Windows API #include <Windows.h> // DirectX #include <d3d9.h> #include <d3dx9.h> // Hades #include "Renderer.hpp" #include "HadesCommon/Error.hpp" namespace Hades { namespace D3D9 { class IDirect3DDevice9Hook : public IDirect3DDevice9 { public: class Error : public virtual HadesError { }; explicit IDirect3DDevice9Hook( IDirect3D9* pD3D9, IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentParams); // IUnknown methods STDMETHOD(QueryInterface)( THIS_ REFIID riid, void** ppvObj); STDMETHOD_(ULONG, AddRef)( THIS); STDMETHOD_(ULONG, Release)( THIS); // IDirect3DDevice9 methods STDMETHOD(TestCooperativeLevel)( THIS); STDMETHOD_(UINT, GetAvailableTextureMem)( THIS); STDMETHOD(EvictManagedResources)( THIS); STDMETHOD(GetDirect3D)( THIS_ IDirect3D9** ppD3D9); STDMETHOD(GetDeviceCaps)( THIS_ D3DCAPS9* pCaps); STDMETHOD(GetDisplayMode)( THIS_ UINT iSwapChain, D3DDISPLAYMODE* pMode); STDMETHOD(GetCreationParameters)( THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters); STDMETHOD(SetCursorProperties)( THIS_ UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9* pCursorBitmap); STDMETHOD_(void, SetCursorPosition)( THIS_ int X, int Y, DWORD Flags); STDMETHOD_(BOOL, ShowCursor)( THIS_ BOOL bShow); STDMETHOD(CreateAdditionalSwapChain)( THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain); STDMETHOD(GetSwapChain)( THIS_ UINT iSwapChain, IDirect3DSwapChain9** pSwapChain); STDMETHOD_(UINT, GetNumberOfSwapChains)( THIS); STDMETHOD(Reset)( THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters); STDMETHOD(Present)( THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion); STDMETHOD(GetBackBuffer)( THIS_ UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer); STDMETHOD(GetRasterStatus)( THIS_ UINT iSwapChain, D3DRASTER_STATUS* pRasterStatus); STDMETHOD(SetDialogBoxMode)( THIS_ BOOL bEnableDialogs); STDMETHOD_(void, SetGammaRamp)( THIS_ UINT iSwapChain, DWORD Flags, CONST D3DGAMMARAMP* pRamp); STDMETHOD_(void, GetGammaRamp)( THIS_ UINT iSwapChain, D3DGAMMARAMP* pRamp); STDMETHOD(CreateTexture)( THIS_ UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle); STDMETHOD(CreateVolumeTexture)( THIS_ UINT Width,UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle); STDMETHOD(CreateCubeTexture)( THIS_ UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle); STDMETHOD(CreateVertexBuffer)( THIS_ UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9** ppVertexBuffer, HANDLE* pSharedHandle); STDMETHOD(CreateIndexBuffer)( THIS_ UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9** ppIndexBuffer, HANDLE* pSharedHandle); STDMETHOD(CreateRenderTarget)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(CreateDepthStencilSurface)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(UpdateSurface)( THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, CONST POINT* pDestPoint); STDMETHOD(UpdateTexture)( THIS_ IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture); STDMETHOD(GetRenderTargetData)( THIS_ IDirect3DSurface9* pRenderTarget, IDirect3DSurface9* pDestSurface); STDMETHOD(GetFrontBufferData)( THIS_ UINT iSwapChain, IDirect3DSurface9* pDestSurface); STDMETHOD(StretchRect)( THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, CONST RECT* pDestRect, D3DTEXTUREFILTERTYPE Filter); STDMETHOD(ColorFill)( THIS_ IDirect3DSurface9* pSurface, CONST RECT* pRect, D3DCOLOR color); STDMETHOD(CreateOffscreenPlainSurface)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(SetRenderTarget)( THIS_ DWORD RenderTargetIndex, IDirect3DSurface9* pRenderTarget); STDMETHOD(GetRenderTarget)( THIS_ DWORD RenderTargetIndex, IDirect3DSurface9** ppRenderTarget); STDMETHOD(SetDepthStencilSurface)( THIS_ IDirect3DSurface9* pNewZStencil); STDMETHOD(GetDepthStencilSurface)( THIS_ IDirect3DSurface9** ppZStencilSurface); STDMETHOD(BeginScene)( THIS); STDMETHOD(EndScene)( THIS); STDMETHOD(Clear)( THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil); STDMETHOD(SetTransform)( THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix); STDMETHOD(GetTransform)( THIS_ D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix); STDMETHOD(MultiplyTransform)( THIS_ D3DTRANSFORMSTATETYPE, CONST D3DMATRIX*); STDMETHOD(SetViewport)( THIS_ CONST D3DVIEWPORT9* pViewport); STDMETHOD(GetViewport)( THIS_ D3DVIEWPORT9* pViewport); STDMETHOD(SetMaterial)( THIS_ CONST D3DMATERIAL9* pMaterial); STDMETHOD(GetMaterial)( THIS_ D3DMATERIAL9* pMaterial); STDMETHOD(SetLight)( THIS_ DWORD Index, CONST D3DLIGHT9*); STDMETHOD(GetLight)( THIS_ DWORD Index, D3DLIGHT9*); STDMETHOD(LightEnable)( THIS_ DWORD Index, BOOL Enable); STDMETHOD(GetLightEnable)( THIS_ DWORD Index, BOOL* pEnable); STDMETHOD(SetClipPlane)( THIS_ DWORD Index, CONST float* pPlane); STDMETHOD(GetClipPlane)( THIS_ DWORD Index, float* pPlane); STDMETHOD(SetRenderState)( THIS_ D3DRENDERSTATETYPE State, DWORD Value); STDMETHOD(GetRenderState)( THIS_ D3DRENDERSTATETYPE State, DWORD* pValue); STDMETHOD(CreateStateBlock)( THIS_ D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9** ppSB); STDMETHOD(BeginStateBlock)( THIS); STDMETHOD(EndStateBlock)( THIS_ IDirect3DStateBlock9** ppSB); STDMETHOD(SetClipStatus)( THIS_ CONST D3DCLIPSTATUS9* pClipStatus); STDMETHOD(GetClipStatus)( THIS_ D3DCLIPSTATUS9* pClipStatus); STDMETHOD(GetTexture)( THIS_ DWORD Stage, IDirect3DBaseTexture9** ppTexture); STDMETHOD(SetTexture)( THIS_ DWORD Stage, IDirect3DBaseTexture9* pTexture); STDMETHOD(GetTextureStageState)( THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue); STDMETHOD(SetTextureStageState)( THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value); STDMETHOD(GetSamplerState)( THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD* pValue); STDMETHOD(SetSamplerState)( THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value); STDMETHOD(ValidateDevice)( THIS_ DWORD* pNumPasses); STDMETHOD(SetPaletteEntries)( THIS_ UINT PaletteNumber, CONST PALETTEENTRY* pEntries); STDMETHOD(GetPaletteEntries)( THIS_ UINT PaletteNumber, PALETTEENTRY* pEntries); STDMETHOD(SetCurrentTexturePalette)( THIS_ UINT PaletteNumber); STDMETHOD(GetCurrentTexturePalette)( THIS_ UINT *PaletteNumber); STDMETHOD(SetScissorRect)( THIS_ CONST RECT* pRect); STDMETHOD(GetScissorRect)( THIS_ RECT* pRect); STDMETHOD(SetSoftwareVertexProcessing)( THIS_ BOOL bSoftware); STDMETHOD_(BOOL, GetSoftwareVertexProcessing)( THIS); STDMETHOD(SetNPatchMode)( THIS_ float nSegments); STDMETHOD_(float, GetNPatchMode)( THIS); STDMETHOD(DrawPrimitive)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount); STDMETHOD(DrawIndexedPrimitive)( THIS_ D3DPRIMITIVETYPE, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount); STDMETHOD(DrawPrimitiveUP)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); STDMETHOD(DrawIndexedPrimitiveUP)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); STDMETHOD(ProcessVertices)( THIS_ UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags); STDMETHOD(CreateVertexDeclaration)( THIS_ CONST D3DVERTEXELEMENT9* pVertexElements, IDirect3DVertexDeclaration9** ppDecl); STDMETHOD(SetVertexDeclaration)( THIS_ IDirect3DVertexDeclaration9* pDecl); STDMETHOD(GetVertexDeclaration)( THIS_ IDirect3DVertexDeclaration9** ppDecl); STDMETHOD(SetFVF)( THIS_ DWORD FVF); STDMETHOD(GetFVF)( THIS_ DWORD* pFVF); STDMETHOD(CreateVertexShader)( THIS_ CONST DWORD* pFunction, IDirect3DVertexShader9** ppShader); STDMETHOD(SetVertexShader)( THIS_ IDirect3DVertexShader9* pShader); STDMETHOD(GetVertexShader)( THIS_ IDirect3DVertexShader9** ppShader); STDMETHOD(SetVertexShaderConstantF)( THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount); STDMETHOD(GetVertexShaderConstantF)( THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount); STDMETHOD(SetVertexShaderConstantI)( THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount); STDMETHOD(GetVertexShaderConstantI)( THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount); STDMETHOD(SetVertexShaderConstantB)( THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount); STDMETHOD(GetVertexShaderConstantB)( THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount); STDMETHOD(SetStreamSource)( THIS_ UINT StreamNumber, IDirect3DVertexBuffer9* pStreamData, UINT OffsetInBytes, UINT Stride); STDMETHOD(GetStreamSource)( THIS_ UINT StreamNumber, IDirect3DVertexBuffer9** ppStreamData, UINT* pOffsetInBytes, UINT* pStride); STDMETHOD(SetStreamSourceFreq)( THIS_ UINT StreamNumber, UINT Setting); STDMETHOD(GetStreamSourceFreq)( THIS_ UINT StreamNumber, UINT* pSetting); STDMETHOD(SetIndices)( THIS_ IDirect3DIndexBuffer9* pIndexData); STDMETHOD(GetIndices)( THIS_ IDirect3DIndexBuffer9** ppIndexData); STDMETHOD(CreatePixelShader)( THIS_ CONST DWORD* pFunction, IDirect3DPixelShader9** ppShader); STDMETHOD(SetPixelShader)( THIS_ IDirect3DPixelShader9* pShader); STDMETHOD(GetPixelShader)( THIS_ IDirect3DPixelShader9** ppShader); STDMETHOD(SetPixelShaderConstantF)( THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount); STDMETHOD(GetPixelShaderConstantF)( THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount); STDMETHOD(SetPixelShaderConstantI)( THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount); STDMETHOD(GetPixelShaderConstantI)( THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount); STDMETHOD(SetPixelShaderConstantB)( THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount); STDMETHOD(GetPixelShaderConstantB)( THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount); STDMETHOD(DrawRectPatch)( THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo); STDMETHOD(DrawTriPatch)( THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo); STDMETHOD(DeletePatch)( THIS_ UINT Handle); STDMETHOD(CreateQuery)( THIS_ D3DQUERYTYPE Type, IDirect3DQuery9** ppQuery); private: IDirect3D9* m_pD3D; IDirect3DDevice9* m_pDevice; D3DPRESENT_PARAMETERS m_PresentParams; UINT m_RefCount; std::shared_ptr<GUI::D3D9Renderer> m_pRenderer; }; } } <commit_msg>* Todo note.<commit_after>/* This file is part of HadesMem. Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza). <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> HadesMem is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // C++ Standard Library #include <memory> // Windows API #include <Windows.h> // DirectX #include <d3d9.h> #include <d3dx9.h> // Hades #include "Renderer.hpp" #include "HadesCommon/Error.hpp" namespace Hades { namespace D3D9 { // Todo: Decouple device and renderer objects class IDirect3DDevice9Hook : public IDirect3DDevice9 { public: class Error : public virtual HadesError { }; explicit IDirect3DDevice9Hook( IDirect3D9* pD3D9, IDirect3DDevice9* pDevice, D3DPRESENT_PARAMETERS* pPresentParams); // IUnknown methods STDMETHOD(QueryInterface)( THIS_ REFIID riid, void** ppvObj); STDMETHOD_(ULONG, AddRef)( THIS); STDMETHOD_(ULONG, Release)( THIS); // IDirect3DDevice9 methods STDMETHOD(TestCooperativeLevel)( THIS); STDMETHOD_(UINT, GetAvailableTextureMem)( THIS); STDMETHOD(EvictManagedResources)( THIS); STDMETHOD(GetDirect3D)( THIS_ IDirect3D9** ppD3D9); STDMETHOD(GetDeviceCaps)( THIS_ D3DCAPS9* pCaps); STDMETHOD(GetDisplayMode)( THIS_ UINT iSwapChain, D3DDISPLAYMODE* pMode); STDMETHOD(GetCreationParameters)( THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters); STDMETHOD(SetCursorProperties)( THIS_ UINT XHotSpot, UINT YHotSpot, IDirect3DSurface9* pCursorBitmap); STDMETHOD_(void, SetCursorPosition)( THIS_ int X, int Y, DWORD Flags); STDMETHOD_(BOOL, ShowCursor)( THIS_ BOOL bShow); STDMETHOD(CreateAdditionalSwapChain)( THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters, IDirect3DSwapChain9** pSwapChain); STDMETHOD(GetSwapChain)( THIS_ UINT iSwapChain, IDirect3DSwapChain9** pSwapChain); STDMETHOD_(UINT, GetNumberOfSwapChains)( THIS); STDMETHOD(Reset)( THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters); STDMETHOD(Present)( THIS_ CONST RECT* pSourceRect, CONST RECT* pDestRect, HWND hDestWindowOverride, CONST RGNDATA* pDirtyRegion); STDMETHOD(GetBackBuffer)( THIS_ UINT iSwapChain, UINT iBackBuffer, D3DBACKBUFFER_TYPE Type, IDirect3DSurface9** ppBackBuffer); STDMETHOD(GetRasterStatus)( THIS_ UINT iSwapChain, D3DRASTER_STATUS* pRasterStatus); STDMETHOD(SetDialogBoxMode)( THIS_ BOOL bEnableDialogs); STDMETHOD_(void, SetGammaRamp)( THIS_ UINT iSwapChain, DWORD Flags, CONST D3DGAMMARAMP* pRamp); STDMETHOD_(void, GetGammaRamp)( THIS_ UINT iSwapChain, D3DGAMMARAMP* pRamp); STDMETHOD(CreateTexture)( THIS_ UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle); STDMETHOD(CreateVolumeTexture)( THIS_ UINT Width,UINT Height, UINT Depth, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DVolumeTexture9** ppVolumeTexture, HANDLE* pSharedHandle); STDMETHOD(CreateCubeTexture)( THIS_ UINT EdgeLength, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DCubeTexture9** ppCubeTexture, HANDLE* pSharedHandle); STDMETHOD(CreateVertexBuffer)( THIS_ UINT Length, DWORD Usage, DWORD FVF, D3DPOOL Pool, IDirect3DVertexBuffer9** ppVertexBuffer, HANDLE* pSharedHandle); STDMETHOD(CreateIndexBuffer)( THIS_ UINT Length, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DIndexBuffer9** ppIndexBuffer, HANDLE* pSharedHandle); STDMETHOD(CreateRenderTarget)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Lockable, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(CreateDepthStencilSurface)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DMULTISAMPLE_TYPE MultiSample, DWORD MultisampleQuality, BOOL Discard, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(UpdateSurface)( THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestinationSurface, CONST POINT* pDestPoint); STDMETHOD(UpdateTexture)( THIS_ IDirect3DBaseTexture9* pSourceTexture, IDirect3DBaseTexture9* pDestinationTexture); STDMETHOD(GetRenderTargetData)( THIS_ IDirect3DSurface9* pRenderTarget, IDirect3DSurface9* pDestSurface); STDMETHOD(GetFrontBufferData)( THIS_ UINT iSwapChain, IDirect3DSurface9* pDestSurface); STDMETHOD(StretchRect)( THIS_ IDirect3DSurface9* pSourceSurface, CONST RECT* pSourceRect, IDirect3DSurface9* pDestSurface, CONST RECT* pDestRect, D3DTEXTUREFILTERTYPE Filter); STDMETHOD(ColorFill)( THIS_ IDirect3DSurface9* pSurface, CONST RECT* pRect, D3DCOLOR color); STDMETHOD(CreateOffscreenPlainSurface)( THIS_ UINT Width, UINT Height, D3DFORMAT Format, D3DPOOL Pool, IDirect3DSurface9** ppSurface, HANDLE* pSharedHandle); STDMETHOD(SetRenderTarget)( THIS_ DWORD RenderTargetIndex, IDirect3DSurface9* pRenderTarget); STDMETHOD(GetRenderTarget)( THIS_ DWORD RenderTargetIndex, IDirect3DSurface9** ppRenderTarget); STDMETHOD(SetDepthStencilSurface)( THIS_ IDirect3DSurface9* pNewZStencil); STDMETHOD(GetDepthStencilSurface)( THIS_ IDirect3DSurface9** ppZStencilSurface); STDMETHOD(BeginScene)( THIS); STDMETHOD(EndScene)( THIS); STDMETHOD(Clear)( THIS_ DWORD Count, CONST D3DRECT* pRects, DWORD Flags, D3DCOLOR Color, float Z, DWORD Stencil); STDMETHOD(SetTransform)( THIS_ D3DTRANSFORMSTATETYPE State, CONST D3DMATRIX* pMatrix); STDMETHOD(GetTransform)( THIS_ D3DTRANSFORMSTATETYPE State, D3DMATRIX* pMatrix); STDMETHOD(MultiplyTransform)( THIS_ D3DTRANSFORMSTATETYPE, CONST D3DMATRIX*); STDMETHOD(SetViewport)( THIS_ CONST D3DVIEWPORT9* pViewport); STDMETHOD(GetViewport)( THIS_ D3DVIEWPORT9* pViewport); STDMETHOD(SetMaterial)( THIS_ CONST D3DMATERIAL9* pMaterial); STDMETHOD(GetMaterial)( THIS_ D3DMATERIAL9* pMaterial); STDMETHOD(SetLight)( THIS_ DWORD Index, CONST D3DLIGHT9*); STDMETHOD(GetLight)( THIS_ DWORD Index, D3DLIGHT9*); STDMETHOD(LightEnable)( THIS_ DWORD Index, BOOL Enable); STDMETHOD(GetLightEnable)( THIS_ DWORD Index, BOOL* pEnable); STDMETHOD(SetClipPlane)( THIS_ DWORD Index, CONST float* pPlane); STDMETHOD(GetClipPlane)( THIS_ DWORD Index, float* pPlane); STDMETHOD(SetRenderState)( THIS_ D3DRENDERSTATETYPE State, DWORD Value); STDMETHOD(GetRenderState)( THIS_ D3DRENDERSTATETYPE State, DWORD* pValue); STDMETHOD(CreateStateBlock)( THIS_ D3DSTATEBLOCKTYPE Type, IDirect3DStateBlock9** ppSB); STDMETHOD(BeginStateBlock)( THIS); STDMETHOD(EndStateBlock)( THIS_ IDirect3DStateBlock9** ppSB); STDMETHOD(SetClipStatus)( THIS_ CONST D3DCLIPSTATUS9* pClipStatus); STDMETHOD(GetClipStatus)( THIS_ D3DCLIPSTATUS9* pClipStatus); STDMETHOD(GetTexture)( THIS_ DWORD Stage, IDirect3DBaseTexture9** ppTexture); STDMETHOD(SetTexture)( THIS_ DWORD Stage, IDirect3DBaseTexture9* pTexture); STDMETHOD(GetTextureStageState)( THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD* pValue); STDMETHOD(SetTextureStageState)( THIS_ DWORD Stage, D3DTEXTURESTAGESTATETYPE Type, DWORD Value); STDMETHOD(GetSamplerState)( THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD* pValue); STDMETHOD(SetSamplerState)( THIS_ DWORD Sampler, D3DSAMPLERSTATETYPE Type, DWORD Value); STDMETHOD(ValidateDevice)( THIS_ DWORD* pNumPasses); STDMETHOD(SetPaletteEntries)( THIS_ UINT PaletteNumber, CONST PALETTEENTRY* pEntries); STDMETHOD(GetPaletteEntries)( THIS_ UINT PaletteNumber, PALETTEENTRY* pEntries); STDMETHOD(SetCurrentTexturePalette)( THIS_ UINT PaletteNumber); STDMETHOD(GetCurrentTexturePalette)( THIS_ UINT *PaletteNumber); STDMETHOD(SetScissorRect)( THIS_ CONST RECT* pRect); STDMETHOD(GetScissorRect)( THIS_ RECT* pRect); STDMETHOD(SetSoftwareVertexProcessing)( THIS_ BOOL bSoftware); STDMETHOD_(BOOL, GetSoftwareVertexProcessing)( THIS); STDMETHOD(SetNPatchMode)( THIS_ float nSegments); STDMETHOD_(float, GetNPatchMode)( THIS); STDMETHOD(DrawPrimitive)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT StartVertex, UINT PrimitiveCount); STDMETHOD(DrawIndexedPrimitive)( THIS_ D3DPRIMITIVETYPE, INT BaseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount); STDMETHOD(DrawPrimitiveUP)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT PrimitiveCount, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); STDMETHOD(DrawIndexedPrimitiveUP)( THIS_ D3DPRIMITIVETYPE PrimitiveType, UINT MinVertexIndex, UINT NumVertices, UINT PrimitiveCount, CONST void* pIndexData, D3DFORMAT IndexDataFormat, CONST void* pVertexStreamZeroData, UINT VertexStreamZeroStride); STDMETHOD(ProcessVertices)( THIS_ UINT SrcStartIndex, UINT DestIndex, UINT VertexCount, IDirect3DVertexBuffer9* pDestBuffer, IDirect3DVertexDeclaration9* pVertexDecl, DWORD Flags); STDMETHOD(CreateVertexDeclaration)( THIS_ CONST D3DVERTEXELEMENT9* pVertexElements, IDirect3DVertexDeclaration9** ppDecl); STDMETHOD(SetVertexDeclaration)( THIS_ IDirect3DVertexDeclaration9* pDecl); STDMETHOD(GetVertexDeclaration)( THIS_ IDirect3DVertexDeclaration9** ppDecl); STDMETHOD(SetFVF)( THIS_ DWORD FVF); STDMETHOD(GetFVF)( THIS_ DWORD* pFVF); STDMETHOD(CreateVertexShader)( THIS_ CONST DWORD* pFunction, IDirect3DVertexShader9** ppShader); STDMETHOD(SetVertexShader)( THIS_ IDirect3DVertexShader9* pShader); STDMETHOD(GetVertexShader)( THIS_ IDirect3DVertexShader9** ppShader); STDMETHOD(SetVertexShaderConstantF)( THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount); STDMETHOD(GetVertexShaderConstantF)( THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount); STDMETHOD(SetVertexShaderConstantI)( THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount); STDMETHOD(GetVertexShaderConstantI)( THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount); STDMETHOD(SetVertexShaderConstantB)( THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount); STDMETHOD(GetVertexShaderConstantB)( THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount); STDMETHOD(SetStreamSource)( THIS_ UINT StreamNumber, IDirect3DVertexBuffer9* pStreamData, UINT OffsetInBytes, UINT Stride); STDMETHOD(GetStreamSource)( THIS_ UINT StreamNumber, IDirect3DVertexBuffer9** ppStreamData, UINT* pOffsetInBytes, UINT* pStride); STDMETHOD(SetStreamSourceFreq)( THIS_ UINT StreamNumber, UINT Setting); STDMETHOD(GetStreamSourceFreq)( THIS_ UINT StreamNumber, UINT* pSetting); STDMETHOD(SetIndices)( THIS_ IDirect3DIndexBuffer9* pIndexData); STDMETHOD(GetIndices)( THIS_ IDirect3DIndexBuffer9** ppIndexData); STDMETHOD(CreatePixelShader)( THIS_ CONST DWORD* pFunction, IDirect3DPixelShader9** ppShader); STDMETHOD(SetPixelShader)( THIS_ IDirect3DPixelShader9* pShader); STDMETHOD(GetPixelShader)( THIS_ IDirect3DPixelShader9** ppShader); STDMETHOD(SetPixelShaderConstantF)( THIS_ UINT StartRegister, CONST float* pConstantData, UINT Vector4fCount); STDMETHOD(GetPixelShaderConstantF)( THIS_ UINT StartRegister, float* pConstantData, UINT Vector4fCount); STDMETHOD(SetPixelShaderConstantI)( THIS_ UINT StartRegister, CONST int* pConstantData, UINT Vector4iCount); STDMETHOD(GetPixelShaderConstantI)( THIS_ UINT StartRegister, int* pConstantData, UINT Vector4iCount); STDMETHOD(SetPixelShaderConstantB)( THIS_ UINT StartRegister, CONST BOOL* pConstantData, UINT BoolCount); STDMETHOD(GetPixelShaderConstantB)( THIS_ UINT StartRegister, BOOL* pConstantData, UINT BoolCount); STDMETHOD(DrawRectPatch)( THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DRECTPATCH_INFO* pRectPatchInfo); STDMETHOD(DrawTriPatch)( THIS_ UINT Handle, CONST float* pNumSegs, CONST D3DTRIPATCH_INFO* pTriPatchInfo); STDMETHOD(DeletePatch)( THIS_ UINT Handle); STDMETHOD(CreateQuery)( THIS_ D3DQUERYTYPE Type, IDirect3DQuery9** ppQuery); private: IDirect3D9* m_pD3D; IDirect3DDevice9* m_pDevice; D3DPRESENT_PARAMETERS m_PresentParams; UINT m_RefCount; std::shared_ptr<GUI::D3D9Renderer> m_pRenderer; }; } } <|endoftext|>
<commit_before>#include "review.h" #include "reviews.h" #include "helper.h" // Boost.Test does not play well with -Weffc++ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include <boost/test/unit_test.hpp> using namespace kdr; BOOST_AUTO_TEST_CASE(test_get_review) { const auto rs = get_reviews(); BOOST_REQUIRE(!rs.empty()); const review r = rs.back(); BOOST_CHECK(!r.get_grades().empty()); } BOOST_AUTO_TEST_CASE(test_is_meta_review) { const std::string md_filename{ get_default_folder_name() + std::string("/AnalysisRichel.md") }; BOOST_CHECK(is_meta_review(md_filename)); } BOOST_AUTO_TEST_CASE(test_Richels_analysis_is_not_a_review) { const std::string md_filename{ get_default_folder_name() + std::string("/AnalysisRichel.md") }; BOOST_REQUIRE(is_regular_file(md_filename)); BOOST_CHECK_THROW( review r(md_filename), std::invalid_argument ); } #pragma GCC diagnostic pop <commit_msg>Detect and display ungraded reviews<commit_after>#include "review.h" #include "reviews.h" #include "helper.h" // Boost.Test does not play well with -Weffc++ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Weffc++" #include <boost/test/unit_test.hpp> using namespace kdr; BOOST_AUTO_TEST_CASE(test_review_must_have_grades) { const auto rs = get_reviews(); for (const auto r: rs) { if (r.get_grades().empty()) { std::cerr << "Ungraded review: " << r.get_title() << '\n'; } BOOST_CHECK(!r.get_grades().empty()); } } BOOST_AUTO_TEST_CASE(test_is_meta_review) { const std::string md_filename{ get_default_folder_name() + std::string("/AnalysisRichel.md") }; BOOST_CHECK(is_meta_review(md_filename)); } BOOST_AUTO_TEST_CASE(test_Richels_analysis_is_not_a_review) { const std::string md_filename{ get_default_folder_name() + std::string("/AnalysisRichel.md") }; BOOST_REQUIRE(is_regular_file(md_filename)); BOOST_CHECK_THROW( review r(md_filename), std::invalid_argument ); } #pragma GCC diagnostic pop <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "SurgSim/Math/SegmentMeshShape.h" #include "SurgSim/DataStructures/AabbTree.h" #include "SurgSim/DataStructures/AabbTreeData.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Geometry.h" namespace SurgSim { namespace Math { SURGSIM_REGISTER(SurgSim::Math::Shape, SurgSim::Math::SegmentMeshShape, SegmentMeshShape); SegmentMeshShape::SegmentMeshShape() { setRadius(0.0); updateAabbTree(); } SegmentMeshShape::SegmentMeshShape(const SegmentMeshShape& other) : DataStructures::SegmentMeshPlain(other) { setRadius(other.m_radius); updateAabbTree(); } int SegmentMeshShape::getType() const { return SHAPE_TYPE_SEGMENTMESH; } double SegmentMeshShape::getVolume() const { SURGSIM_ASSERT("SegmentMeshShape: Volume calculation not implemented."); return std::numeric_limits<double>::quiet_NaN(); } Vector3d SegmentMeshShape::getCenter() const { SURGSIM_ASSERT("SegmentMeshShape: Center calculation not implemented."); return Vector3d::Constant(std::numeric_limits<double>::quiet_NaN()); } Matrix33d SegmentMeshShape::getSecondMomentOfVolume() const { SURGSIM_ASSERT("SegmentMeshShape: Second Moment Of Volume calculation not implemented."); return Matrix33d::Constant(std::numeric_limits<double>::quiet_NaN()); } bool SegmentMeshShape::isValid() const { // If the radius is less than DistanceEpsilon, the collision detection (which assumes the segments are capsules), /// will not work correctly. return (m_radius >= Geometry::DistanceEpsilon && m_segmentEndBoundingBoxHalfExtent.isApprox(Vector3d(m_radius, m_radius, m_radius))); } void SegmentMeshShape::setRadius(double radius) { m_radius = radius; m_segmentEndBoundingBoxHalfExtent = Vector3d(m_radius, m_radius, m_radius); } double SegmentMeshShape::getRadius() const { return m_radius; } bool SegmentMeshShape::doUpdate() { updateAabbTree(); return true; } bool SegmentMeshShape::doLoad(const std::string& fileName) { return DataStructures::SegmentMeshPlain::doLoad(fileName) && update(); } std::shared_ptr<const DataStructures::AabbTree> SegmentMeshShape::getAabbTree() const { return m_aabbTree; } std::shared_ptr<Shape> SegmentMeshShape::getTransformed(const RigidTransform3d& pose) { auto transformed = std::make_shared<SegmentMeshShape>(*this); transformed->transform(pose); transformed->update(); return transformed; } void SegmentMeshShape::updateAabbTree() { m_aabbTree = std::make_shared<DataStructures::AabbTree>(); std::list<DataStructures::AabbTreeData::Item> items; auto const& edges = getEdges(); for (size_t id = 0, count = edges.size(); id < count; ++id) { if (edges[id].isValid) { const auto& vertices = getEdgePositions(id); Aabbd aabb((vertices[0] - m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[0] + m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[1] - m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[1] + m_segmentEndBoundingBoxHalfExtent).eval()); items.emplace_back(std::make_pair(std::move(aabb), id)); } } m_aabbTree->set(std::move(items)); } bool SegmentMeshShape::isTransformable() const { return true; } }; // namespace Math }; // namespace SurgSim <commit_msg>Give SegmentMeshShape a default radius<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include "SurgSim/Math/SegmentMeshShape.h" #include "SurgSim/DataStructures/AabbTree.h" #include "SurgSim/DataStructures/AabbTreeData.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Geometry.h" namespace SurgSim { namespace Math { SURGSIM_REGISTER(SurgSim::Math::Shape, SurgSim::Math::SegmentMeshShape, SegmentMeshShape); SegmentMeshShape::SegmentMeshShape() { setRadius(0.001); updateAabbTree(); } SegmentMeshShape::SegmentMeshShape(const SegmentMeshShape& other) : DataStructures::SegmentMeshPlain(other) { setRadius(other.m_radius); updateAabbTree(); } int SegmentMeshShape::getType() const { return SHAPE_TYPE_SEGMENTMESH; } double SegmentMeshShape::getVolume() const { SURGSIM_ASSERT("SegmentMeshShape: Volume calculation not implemented."); return std::numeric_limits<double>::quiet_NaN(); } Vector3d SegmentMeshShape::getCenter() const { SURGSIM_ASSERT("SegmentMeshShape: Center calculation not implemented."); return Vector3d::Constant(std::numeric_limits<double>::quiet_NaN()); } Matrix33d SegmentMeshShape::getSecondMomentOfVolume() const { SURGSIM_ASSERT("SegmentMeshShape: Second Moment Of Volume calculation not implemented."); return Matrix33d::Constant(std::numeric_limits<double>::quiet_NaN()); } bool SegmentMeshShape::isValid() const { // If the radius is less than DistanceEpsilon, the collision detection (which assumes the segments are capsules), /// will not work correctly. return (m_radius >= Geometry::DistanceEpsilon && m_segmentEndBoundingBoxHalfExtent.isApprox(Vector3d(m_radius, m_radius, m_radius))); } void SegmentMeshShape::setRadius(double radius) { m_radius = radius; m_segmentEndBoundingBoxHalfExtent = Vector3d(m_radius, m_radius, m_radius); } double SegmentMeshShape::getRadius() const { return m_radius; } bool SegmentMeshShape::doUpdate() { updateAabbTree(); return true; } bool SegmentMeshShape::doLoad(const std::string& fileName) { return DataStructures::SegmentMeshPlain::doLoad(fileName) && update(); } std::shared_ptr<const DataStructures::AabbTree> SegmentMeshShape::getAabbTree() const { return m_aabbTree; } std::shared_ptr<Shape> SegmentMeshShape::getTransformed(const RigidTransform3d& pose) { auto transformed = std::make_shared<SegmentMeshShape>(*this); transformed->transform(pose); transformed->update(); return transformed; } void SegmentMeshShape::updateAabbTree() { m_aabbTree = std::make_shared<DataStructures::AabbTree>(); std::list<DataStructures::AabbTreeData::Item> items; auto const& edges = getEdges(); for (size_t id = 0; id < edges.size(); ++id) { if (edges[id].isValid) { const auto& vertices = getEdgePositions(id); Aabbd aabb((vertices[0] - m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[0] + m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[1] - m_segmentEndBoundingBoxHalfExtent).eval()); aabb.extend((vertices[1] + m_segmentEndBoundingBoxHalfExtent).eval()); items.emplace_back(aabb, id); } } m_aabbTree->set(std::move(items)); } bool SegmentMeshShape::isTransformable() const { return true; } }; // namespace Math }; // namespace SurgSim <|endoftext|>
<commit_before>#include "ghost/config.h" #include "ghost/types.h" #include "ghost/densemat.h" #include "ghost/util.h" #include "ghost/math.h" #include "ghost/tsmttsm.h" #include "ghost/tsmttsm_gen.h" #include "ghost/tsmttsm_avx_gen.h" #include <map> using namespace std; static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b) { return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,0))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,0))); } static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels; ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) { if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) { if (printerror) { ERROR_LOG("w must be stored row-major!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) { if (printerror) { ERROR_LOG("v must be stored row-major!"); } return GHOST_ERR_INVALID_ARG; } if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) { if (printerror) { ERROR_LOG("x must be stored col-major!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) { if (printerror) { ERROR_LOG("Different data types!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) { if (printerror) { ERROR_LOG("Scattered densemats not supported!"); } return GHOST_ERR_INVALID_ARG; } if (reduce != GHOST_GEMM_ALL_REDUCE) { if (printerror) { ERROR_LOG("Only Allreduce supported currently!"); } return GHOST_ERR_INVALID_ARG; } if (!strncasecmp(transv,"N",1)) { if (printerror) { ERROR_LOG("v must be transposed!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transw,"N",1)) { if (printerror) { ERROR_LOG("w must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } UNUSED(alpha); UNUSED(beta); return GHOST_SUCCESS; } ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv) { GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH); ghost_error_t ret; if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) { return ret; } if (ghost_tsmttsm_kernels.empty()) { #include "tsmttsm.def" #include "tsmttsm_avx.def" } ghost_tsmttsm_parameters_t p; ghost_tsmttsm_kernel_t kernel = NULL; #ifdef GHOST_HAVE_MIC p.impl = GHOST_IMPLEMENTATION_MIC; #elif defined(GHOST_HAVE_AVX) p.impl = GHOST_IMPLEMENTATION_AVX; #elif defined(GHOST_HAVE_SSE) p.impl = GHOST_IMPLEMENTATION_SSE; #else p.impl = GHOST_IMPLEMENTATION_PLAIN; #endif /*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) { p.impl = GHOST_IMPLEMENTATION_PLAIN; }*/ //p.impl = GHOST_IMPLEMENTATION_PLAIN; p.dt = x->traits.datatype; p.vcols = v->traits.ncols; p.wcols = w->traits.ncols; if (p.vcols % 4 || p.wcols % 4) { PERFWARNING_LOG("Use plain for non-multiple of four"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } kernel = ghost_tsmttsm_kernels[p]; if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary wcols"); p.wcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary vcols"); p.wcols = w->traits.ncols; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.wcols = -1; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try plain implementation"); p.impl = GHOST_IMPLEMENTATION_PLAIN; p.vcols = v->traits.ncols; p.wcols = w->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary wcols"); p.wcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary vcols"); p.wcols = w->traits.ncols; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.wcols = -1; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { INFO_LOG("Could not find TSMTTSM kernel with %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols); return GHOST_ERR_INVALID_ARG; //return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL); } ret = kernel(x,v,w,alpha,beta,conjv); #ifdef GHOST_HAVE_INSTR_TIMING ghost_gemm_perf_args_t tsmttsm_perfargs; tsmttsm_perfargs.xcols = p.wcols; tsmttsm_perfargs.vcols = p.vcols; if (v->context) { tsmttsm_perfargs.vrows = v->context->gnrows; } else { tsmttsm_perfargs.vrows = v->traits.nrows; } tsmttsm_perfargs.dt = x->traits.datatype; ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s"); #endif GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH); return ret; } <commit_msg>be more verbose<commit_after>#include "ghost/config.h" #include "ghost/types.h" #include "ghost/densemat.h" #include "ghost/util.h" #include "ghost/math.h" #include "ghost/tsmttsm.h" #include "ghost/tsmttsm_gen.h" #include "ghost/tsmttsm_avx_gen.h" #include <map> using namespace std; static bool operator<(const ghost_tsmttsm_parameters_t &a, const ghost_tsmttsm_parameters_t &b) { return ghost_hash(a.dt,a.wcols,ghost_hash(a.vcols,a.impl,ghost_hash(a.xstor,a.wstor,0))) < ghost_hash(b.dt,b.wcols,ghost_hash(b.vcols,b.impl,ghost_hash(b.xstor,b.wstor,0))); } static map<ghost_tsmttsm_parameters_t, ghost_tsmttsm_kernel_t> ghost_tsmttsm_kernels; ghost_error_t ghost_tsmttsm_valid(ghost_densemat_t *x, ghost_densemat_t *v, const char * transv, ghost_densemat_t *w, const char *transw, void *alpha, void *beta, int reduce, int printerror) { if (w->traits.storage != GHOST_DENSEMAT_ROWMAJOR) { if (printerror) { ERROR_LOG("w must be stored row-major!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.storage != GHOST_DENSEMAT_ROWMAJOR) { if (printerror) { ERROR_LOG("v must be stored row-major!"); } return GHOST_ERR_INVALID_ARG; } if (x->traits.storage != GHOST_DENSEMAT_COLMAJOR) { if (printerror) { ERROR_LOG("x must be stored col-major!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.datatype != w->traits.datatype || v->traits.datatype != x->traits.datatype) { if (printerror) { ERROR_LOG("Different data types!"); } return GHOST_ERR_INVALID_ARG; } if (v->traits.flags & GHOST_DENSEMAT_SCATTERED || w->traits.flags & GHOST_DENSEMAT_SCATTERED || x->traits.flags & GHOST_DENSEMAT_SCATTERED) { if (printerror) { ERROR_LOG("Scattered densemats not supported!"); } return GHOST_ERR_INVALID_ARG; } if (reduce != GHOST_GEMM_ALL_REDUCE) { if (printerror) { ERROR_LOG("Only Allreduce supported currently!"); } return GHOST_ERR_INVALID_ARG; } if (!strncasecmp(transv,"N",1)) { if (printerror) { ERROR_LOG("v must be transposed!"); } return GHOST_ERR_INVALID_ARG; } if (strncasecmp(transw,"N",1)) { if (printerror) { ERROR_LOG("w must not be transposed!"); } return GHOST_ERR_INVALID_ARG; } UNUSED(alpha); UNUSED(beta); return GHOST_SUCCESS; } ghost_error_t ghost_tsmttsm(ghost_densemat_t *x, ghost_densemat_t *v, ghost_densemat_t *w, void *alpha, void *beta,int reduce,int conjv) { GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH); ghost_error_t ret; if ((ret = ghost_tsmttsm_valid(x,v,"T",w,"N",alpha,beta,reduce,1)) != GHOST_SUCCESS) { return ret; } if (ghost_tsmttsm_kernels.empty()) { #include "tsmttsm.def" #include "tsmttsm_avx.def" } ghost_tsmttsm_parameters_t p; ghost_tsmttsm_kernel_t kernel = NULL; #ifdef GHOST_HAVE_MIC p.impl = GHOST_IMPLEMENTATION_MIC; #elif defined(GHOST_HAVE_AVX) p.impl = GHOST_IMPLEMENTATION_AVX; #elif defined(GHOST_HAVE_SSE) p.impl = GHOST_IMPLEMENTATION_SSE; #else p.impl = GHOST_IMPLEMENTATION_PLAIN; #endif /*if (x->traits.ncolspadded < 4 || x->traits.flags & GHOST_DENSEMAT_VIEW) { p.impl = GHOST_IMPLEMENTATION_PLAIN; }*/ //p.impl = GHOST_IMPLEMENTATION_PLAIN; p.dt = x->traits.datatype; p.vcols = v->traits.ncols; p.wcols = w->traits.ncols; if (p.vcols % 4 || p.wcols % 4) { PERFWARNING_LOG("Use plain for non-multiple of four"); p.impl = GHOST_IMPLEMENTATION_PLAIN; } kernel = ghost_tsmttsm_kernels[p]; if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary wcols"); p.wcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary vcols"); p.wcols = w->traits.ncols; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.wcols = -1; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try plain implementation"); p.impl = GHOST_IMPLEMENTATION_PLAIN; p.vcols = v->traits.ncols; p.wcols = w->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary wcols"); p.wcols = -1; p.vcols = v->traits.ncols; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary vcols"); p.wcols = w->traits.ncols; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { PERFWARNING_LOG("Try kernel with arbitrary block sizes"); p.wcols = -1; p.vcols = -1; kernel = ghost_tsmttsm_kernels[p]; } if (!kernel) { INFO_LOG("Could not find TSMTTSM kernel with %d %d %d %d %d. Fallback to GEMM",p.dt,p.wcols,p.vcols,p.xstor,p.wstor); return GHOST_ERR_INVALID_ARG; //return ghost_gemm(x,v,"T",w,"N",alpha,beta,GHOST_GEMM_ALL_REDUCE,GHOST_GEMM_NOT_SPECIAL); } ret = kernel(x,v,w,alpha,beta,conjv); #ifdef GHOST_HAVE_INSTR_TIMING ghost_gemm_perf_args_t tsmttsm_perfargs; tsmttsm_perfargs.xcols = p.wcols; tsmttsm_perfargs.vcols = p.vcols; if (v->context) { tsmttsm_perfargs.vrows = v->context->gnrows; } else { tsmttsm_perfargs.vrows = v->traits.nrows; } tsmttsm_perfargs.dt = x->traits.datatype; ghost_timing_set_perfFunc(__ghost_functag,ghost_gemm_perf_GFs,(void *)&tsmttsm_perfargs,sizeof(tsmttsm_perfargs),"GF/s"); #endif GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH); return ret; } <|endoftext|>
<commit_before>#include "twister.h" const unsigned CYCLE = 0x100; //Suggest we wrap these arrays inside an fsm or test base class const unsigned C_TRANS_ = 0xff; int block_units[][0x10] = { 0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65 }; int triad_units[][0x03] = { 0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x08, 0xaf, 0x08, 0xf0 }; const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee, 0xcf, 0xad, 0xdf, 0xff, 0xce, 0x32, 0x40, 0xd3, 0x27, 0x82, 0xda, 0xee, 0xff, 0xfc, 0xbf, 0x1c, 0x90, 0x13, 0x4a, 0xa5, 0xe0, 0x21, 0x9f, 0xe1, 0xc6, 0xaf, 0x05, 0x81, 0xf0, 0xee, 0xe4, 0x38, 0x1f, 0x60, 0x24, 0x0c, 0x35, 0x51, 0x32, 0xcf, 0x12, 0x9a, 0x30, 0x44, 0x72, 0x51, 0x3c, 0x61, 0x2d, 0x5f, 0x04, 0x1c, 0x52, 0xca, 0xdf, 0x12, 0x0b, 0x30, 0xa0, 0x1e, 0x03, 0x14, 0x09, 0x73, 0x23, 0xf2, 0xca, 0xa2, 0x51, 0xc6, 0x01, 0xdf, 0x41, 0x96, 0xa0, 0x51, 0x19, 0x71, 0x23, 0x47, 0xcb, 0xbd, 0xba, 0xac, 0xdf, 0xdf, 0xde, 0xcd, 0xfd, 0xca }; int ENTRY_LINK__ = 0x05; int ENTRY_LINK__TEST = 0x09; int ENTRY_C_REF_ECM = 0x10; int ENTRY_C_REF_ECM_TEST = 0x03; int ENTRY_C_OUTER = 0x51; int ENTRY_C_OUTER_PROD = 0x41; int ENTRY_C_OUTER_PROD_TEST = 0x33; int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57; int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9; int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf; int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1; int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5; int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2; int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5; int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff; int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff; unsigned reflect(unsigned center, unsigned (*r)(unsigned)) { return (*r)(center)^center; } unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos) { return (*s)(pos)^a; } void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^base(d, g, d); } data[i] = d; } } void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^(*g)(d); } data[i] = d; } } void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d); } data[i] = d; } } vector<double> f_dist(vector<unsigned char>& in) { vector<double> fdist; fdist.resize(256); for(unsigned i = 0; i<in.size(); i++) { fdist[in[i]]++; } for(unsigned i=0; i<fdist.size(); i++) { fdist[i] = (fdist[i] / in.size()) * 100; } return fdist; } double s_entropy(vector<double>& v) { double entropy = 0; double p; for(unsigned i = 0; i < v.size(); i++) { p = v[i] / 100; if (p == 0) continue; entropy += p * std::log(p) / std::log(2); } return -entropy; } void rms(const string& s, string& r) { for(unsigned int i=0; i<s.size(); i++) { if(::isspace(s[i])) continue; r+= s[i]; } } //add extended euc double sw(double weight, int i, int j, int (*inv)(int, int)) { return weight*(*inv)(i, j); } //Suggest we wrap these routines in a base class in particular for testing //and expose test api void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int)) { if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s) { (*center)(s); return; } if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s) { (*p)(s); return; } if(s == 1) { (*p)(n); return; } for(int i=0; i< s; i++) { hPerm(s-1, n, p, inv, p); if(s%2 == 1) (*inv)(0, s-1); else (*inv)(i, s-1); } } double ic(const string& t) { string text; rms(t, text); vector<double> freq(256,0); for(unsigned int i=0; i<text.size(); i++) { if(text[i] == ' ') continue; freq[text[i]] ++; } double sum=0; for(unsigned int i=0; i<freq.size(); i++) { if(freq[i] != 0) { double c = freq[i]; if(c != 0) sum += c * (c - 1); } } double ic = 26 * sum / (text.size() * (text.size() - 1)); return ic; } int outer_sect(int (*s)(int), int (*t)(int), int r, int q) { return (*s)(r) * (*t)(q); } void multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m) { unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m); unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m); *chanIndicator = *chanIndicator ^ *crossCh; *crossCh = *chanIndicator ^ *crossCh; *chanIndicator = *chanIndicator ^ *crossCh; } void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m) { //test seq (*p)(transition_seq[ENTRY_LINK__], m); (*p)(transition_seq[ENTRY_LINK__TEST], m); //stream test , suggest these tests should be moved to a state transition class // // // (*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff ); (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]); } //Suggest we wrap these in util base class, abstract col cont std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y)) { if(__alpha == 0) return make_tuple(__beta,0,1); int __com=0; int x=0; int y=0; tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col); return make_tuple(__com, y-(__beta/__alpha)*x, x); } //frmwk wrapper pending nh release, util base // std::tuple<int, int, int> extended_gcd(int __alpha, int __beta) { if(__alpha == 0) return make_tuple(__beta,0,1); int __com=0; int x=0; int y=0; tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha); return make_tuple(__com, y-(__beta/__alpha)*x, x); } <commit_msg>cross ref test tbd<commit_after>#include "twister.h" const unsigned CYCLE = 0x100; //Suggest we wrap these arrays inside an fsm or test base class const unsigned C_TRANS_ = 0xff; int block_units[][0x10] = { 0x74, 0x63, 0x69, 0x67, 0x72, 0x68, 0x6e, 0x6c, 0x61, 0x67, 0x74, 0x6c, 0x69, 0x73, 0x61, 0x61, 0x6f, 0x6d, 0x6f, 0x72, 0x6e, 0x72, 0x69, 0x6d, 0x6e, 0x6e, 0x65, 0x74, 0x72, 0x6e, 0x6b, 0x73, 0x61, 0x6f, 0x65, 0x69, 0x73, 0x64, 0x6c, 0x65, 0x69, 0x6b, 0x68, 0x68, 0x68, 0x65, 0x72, 0x64, 0x66, 0x74, 0x61, 0x73, 0x6f, 0x69, 0x65, 0x74, 0x69, 0x68, 0x6e, 0x65, 0x62, 0x74, 0x6b, 0x65 }; int triad_units[][0x03] = { 0x31, 0xfe, 0x45, 0x74, 0x68, 0x65, 0x74, 0x68, 0x61, 0x65, 0x74, 0x68, 0x66, 0x6f, 0x72, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67, 0x65, 0x72, 0x65, 0x68, 0x61, 0x74, 0x68, 0x69, 0x73, 0x1a, 0x36, 0x49, 0x91, 0x43, 0x53, 0xa9, 0xc3, 0x08, 0xaf, 0x08, 0xf0 }; const int transition_seq[] = { 0xce, 0xab, 0xdf, 0xcf, 0xee, 0xcf, 0xad, 0xdf, 0xff, 0xce, 0x32, 0x40, 0xd3, 0x27, 0x82, 0xda, 0xee, 0xff, 0xfc, 0xbf, 0x1c, 0x90, 0x13, 0x4a, 0xa5, 0xe0, 0x21, 0x9f, 0xe1, 0xc6, 0xaf, 0x05, 0x81, 0xf0, 0xee, 0xe4, 0x38, 0x1f, 0x60, 0x24, 0x0c, 0x35, 0x51, 0x32, 0xcf, 0x12, 0x9a, 0x30, 0x44, 0x72, 0x51, 0x3c, 0x61, 0x2d, 0x5f, 0x04, 0x1c, 0x52, 0xca, 0xdf, 0x12, 0x0b, 0x30, 0xa0, 0x1e, 0x03, 0x14, 0x09, 0x73, 0x23, 0xf2, 0xca, 0xa2, 0x51, 0xc6, 0x01, 0xdf, 0x41, 0x96, 0xa0, 0x51, 0x19, 0x71, 0x23, 0x47, 0xcb, 0xbd, 0xba, 0xac, 0xdf, 0xdf, 0xde, 0xcd, 0xfd, 0xca }; int ENTRY_LINK__ = 0x05; int ENTRY_LINK__TEST = 0x09; int ENTRY_C_REF_ECM = 0x10; int ENTRY_C_REF_ECM_TEST = 0x03; int ENTRY_C_OUTER = 0x51; int ENTRY_C_OUTER_PROD = 0x41; int ENTRY_C_OUTER_PROD_TEST = 0x33; int ENTRY_C_OUTER_PROD_TOR_TEST = 0x57; int ENTRY_A_OUTER_PROD_TOR_TEST = 0xc9; int ENTRY_B_OUTER_PROD_EUC_TEST = 0xaf; int ENTRY_C_OUTER_PROD_EUC_TEST = 0xa1; int ENTRY_C_INNER_PROD_EUC_TEST = 0xc5; int ENTRY_C_INNER_PROD_ELIP_TEST = 0xa2; int ENTRY_C_INNER_PROD_RELAY_TEST = 0xf5; int ENTRY_C_BLOCK_REL_FLAG_TEST = 0x0fffffff; int ENTRY_C_BLOCK_REL_FLAG_VECTOR = 0x0effffff; unsigned reflect(unsigned center, unsigned (*r)(unsigned)) { return (*r)(center)^center; } unsigned char base(unsigned char a, unsigned char (*s)(unsigned char), int pos) { return (*s)(pos)^a; } void transHomExt(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^base(d, g, d); } data[i] = d; } } void transHom(vector<unsigned char>& data, unsigned char (*f)(unsigned char), unsigned char (*g)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d)^(*g)(d); } data[i] = d; } } void trans(vector<unsigned char>& data, unsigned char (*f)(unsigned char)) { for(unsigned i = 0; i<data.size(); i++) { unsigned char d = data[i]; for(unsigned j=0; j<CYCLE; j++) { d = (*f)(d); } data[i] = d; } } vector<double> f_dist(vector<unsigned char>& in) { vector<double> fdist; fdist.resize(256); for(unsigned i = 0; i<in.size(); i++) { fdist[in[i]]++; } for(unsigned i=0; i<fdist.size(); i++) { fdist[i] = (fdist[i] / in.size()) * 100; } return fdist; } double s_entropy(vector<double>& v) { double entropy = 0; double p; for(unsigned i = 0; i < v.size(); i++) { p = v[i] / 100; if (p == 0) continue; entropy += p * std::log(p) / std::log(2); } return -entropy; } void rms(const string& s, string& r) { for(unsigned int i=0; i<s.size(); i++) { if(::isspace(s[i])) continue; r+= s[i]; } } //add extended euc double sw(double weight, int i, int j, int (*inv)(int, int)) { return weight*(*inv)(i, j); } //Suggest we wrap these routines in a base class in particular for testing //and expose test api void hPerm(int s, int n, void (*p)(int), void (*inv)(int, int), void (*center)(int)) { if(transition_seq[ENTRY_C_INNER_PROD_RELAY_TEST] == s) { (*center)(s); return; } if(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ] == s) { (*p)(s); return; } if(s == 1) { (*p)(n); return; } for(int i=0; i< s; i++) { hPerm(s-1, n, p, inv, p); if(s%2 == 1) (*inv)(0, s-1); else (*inv)(i, s-1); } } double ic(const string& t) { string text; rms(t, text); vector<double> freq(256,0); for(unsigned int i=0; i<text.size(); i++) { if(text[i] == ' ') continue; freq[text[i]] ++; } double sum=0; for(unsigned int i=0; i<freq.size(); i++) { if(freq[i] != 0) { double c = freq[i]; if(c != 0) sum += c * (c - 1); } } double ic = 26 * sum / (text.size() * (text.size() - 1)); return ic; } int outer_sect(int (*s)(int), int (*t)(int), int r, int q) { return (*s)(r) * (*t)(q); } //chain cross ref - test - void multiChan(unsigned char* (*p)(unsigned char, unsigned char), unsigned char m) { unsigned char* chanIndicator = (*p)(transition_seq[ENTRY_C_REF_ECM], m); unsigned char* crossCh = (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST], m); *chanIndicator = *chanIndicator ^ *crossCh; *crossCh = *chanIndicator ^ *crossCh; *chanIndicator = *chanIndicator ^ *crossCh; } void switchIO(unsigned char (*p)(unsigned char, unsigned char), unsigned char m) { //test seq (*p)(transition_seq[ENTRY_LINK__], m); (*p)(transition_seq[ENTRY_LINK__TEST], m); //stream test , suggest these tests should be moved to a state transition class // // // (*p)(transition_seq[ENTRY_C_REF_ECM], m ^ 0xff ); (*p)(transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST ], m); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_LINK__TEST]); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_REF_ECM]); (*p)(transition_seq[ENTRY_LINK__TEST], m ^ transition_seq[ENTRY_C_INNER_PROD_ELIP_TEST]); } //Suggest we wrap these in util base class, abstract col cont std::tuple<int, int, int> extended_gcd(int __alpha, int __beta, int (*col)(int x, int y)) { if(__alpha == 0) return make_tuple(__beta,0,1); int __com=0; int x=0; int y=0; tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha, col); return make_tuple(__com, y-(__beta/__alpha)*x, x); } //frmwk wrapper pending nh release, util base // std::tuple<int, int, int> extended_gcd(int __alpha, int __beta) { if(__alpha == 0) return make_tuple(__beta,0,1); int __com=0; int x=0; int y=0; tie(__com, x, y) = extended_gcd(__beta%__alpha, __alpha); return make_tuple(__com, y-(__beta/__alpha)*x, x); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer_gdi.h" #include "remoting/host/differ.h" #include "gfx/rect.h" namespace remoting { // 3780 pixels per meter is equivalent to 96 DPI, typical on desktop monitors. static const int kPixelsPerMeter = 3780; // 32 bit RGBA is 4 bytes per pixel. static const int kBytesPerPixel = 4; CapturerGdi::CapturerGdi(MessageLoop* message_loop) : Capturer(message_loop), desktop_dc_(NULL), memory_dc_(NULL), capture_fullscreen_(true) { memset(target_bitmap_, 0, sizeof(target_bitmap_)); memset(buffers_, 0, sizeof(buffers_)); } CapturerGdi::~CapturerGdi() { ReleaseBuffers(); } void CapturerGdi::ReleaseBuffers() { for (int i = kNumBuffers - 1; i >= 0; i--) { if (target_bitmap_[i]) { DeleteObject(target_bitmap_[i]); target_bitmap_[i] = NULL; } if (buffers_[i]) { DeleteObject(buffers_[i]); buffers_[i] = NULL; } } desktop_dc_ = NULL; if (memory_dc_) { DeleteDC(memory_dc_); memory_dc_ = NULL; } } void CapturerGdi::ScreenConfigurationChanged() { ReleaseBuffers(); desktop_dc_ = GetDC(GetDesktopWindow()); memory_dc_ = CreateCompatibleDC(desktop_dc_); // Create a bitmap to keep the desktop image. width_ = GetSystemMetrics(SM_CXSCREEN); height_ = GetSystemMetrics(SM_CYSCREEN); int rounded_width = (width_ + 3) & (~3); // Dimensions of screen. pixel_format_ = media::VideoFrame::RGB32; bytes_per_row_ = rounded_width * kBytesPerPixel; // Create a differ for this screen size. differ_.reset(new Differ(width_, height_, 4, bytes_per_row_)); // Create a device independant bitmap (DIB) that is the same size. BITMAPINFO bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biHeight = height_; bmi.bmiHeader.biWidth = width_; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = kBytesPerPixel * 8; bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biSizeImage = bytes_per_row_ * height_; bmi.bmiHeader.biXPelsPerMeter = kPixelsPerMeter; bmi.bmiHeader.biYPelsPerMeter = kPixelsPerMeter; // Create memory for the buffers. for (int i = 0; i < kNumBuffers; i++) { target_bitmap_[i] = CreateDIBSection(desktop_dc_, &bmi, DIB_RGB_COLORS, static_cast<void**>(&buffers_[i]), NULL, 0); } capture_fullscreen_ = true; } void CapturerGdi::CalculateInvalidRects() { ClearInvalidRects(); CaptureImage(); if (capture_fullscreen_) { InvalidateFullScreen(); } else { // Calculate the difference between the previous and current screen. int prev_buffer_id = current_buffer_ - 1; if (prev_buffer_id < 0) { prev_buffer_id = kNumBuffers - 1; } void* prev_buffer = buffers_[prev_buffer_id]; void* curr_buffer = buffers_[current_buffer_]; InvalidRects rects; differ_->CalcDirtyRects(prev_buffer, curr_buffer, &rects); InvalidateRects(rects); } capture_fullscreen_ = false; } void CapturerGdi::CaptureRects(const InvalidRects& rects, CaptureCompletedCallback* callback) { DataPlanes planes; planes.data[0] = static_cast<uint8*>(buffers_[current_buffer_]); planes.strides[0] = bytes_per_row_; scoped_refptr<CaptureData> data(new CaptureData(planes, width(), height(), pixel_format())); data->mutable_dirty_rects() = rects; FinishCapture(data, callback); } void CapturerGdi::CaptureImage() { // Select the target bitmap into the memory dc. SelectObject(memory_dc_, target_bitmap_[current_buffer_]); // And then copy the rect from desktop to memory. BitBlt(memory_dc_, 0, 0, width_, height_, desktop_dc_, 0, 0, SRCCOPY | CAPTUREBLT); } } // namespace remoting <commit_msg>Fix GDI capturer initialization.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer_gdi.h" #include "remoting/host/differ.h" #include "gfx/rect.h" namespace remoting { // 3780 pixels per meter is equivalent to 96 DPI, typical on desktop monitors. static const int kPixelsPerMeter = 3780; // 32 bit RGBA is 4 bytes per pixel. static const int kBytesPerPixel = 4; CapturerGdi::CapturerGdi(MessageLoop* message_loop) : Capturer(message_loop), desktop_dc_(NULL), memory_dc_(NULL), capture_fullscreen_(true) { memset(target_bitmap_, 0, sizeof(target_bitmap_)); memset(buffers_, 0, sizeof(buffers_)); ScreenConfigurationChanged(); } CapturerGdi::~CapturerGdi() { ReleaseBuffers(); } void CapturerGdi::ReleaseBuffers() { for (int i = kNumBuffers - 1; i >= 0; i--) { if (target_bitmap_[i]) { DeleteObject(target_bitmap_[i]); target_bitmap_[i] = NULL; } if (buffers_[i]) { DeleteObject(buffers_[i]); buffers_[i] = NULL; } } desktop_dc_ = NULL; if (memory_dc_) { DeleteDC(memory_dc_); memory_dc_ = NULL; } } void CapturerGdi::ScreenConfigurationChanged() { ReleaseBuffers(); desktop_dc_ = GetDC(GetDesktopWindow()); memory_dc_ = CreateCompatibleDC(desktop_dc_); // Create a bitmap to keep the desktop image. width_ = GetSystemMetrics(SM_CXSCREEN); height_ = GetSystemMetrics(SM_CYSCREEN); int rounded_width = (width_ + 3) & (~3); // Dimensions of screen. pixel_format_ = media::VideoFrame::RGB32; bytes_per_row_ = rounded_width * kBytesPerPixel; // Create a differ for this screen size. differ_.reset(new Differ(width_, height_, 4, bytes_per_row_)); // Create a device independant bitmap (DIB) that is the same size. BITMAPINFO bmi; memset(&bmi, 0, sizeof(bmi)); bmi.bmiHeader.biHeight = height_; bmi.bmiHeader.biWidth = width_; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = kBytesPerPixel * 8; bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader); bmi.bmiHeader.biSizeImage = bytes_per_row_ * height_; bmi.bmiHeader.biXPelsPerMeter = kPixelsPerMeter; bmi.bmiHeader.biYPelsPerMeter = kPixelsPerMeter; // Create memory for the buffers. for (int i = 0; i < kNumBuffers; i++) { target_bitmap_[i] = CreateDIBSection(desktop_dc_, &bmi, DIB_RGB_COLORS, static_cast<void**>(&buffers_[i]), NULL, 0); } capture_fullscreen_ = true; } void CapturerGdi::CalculateInvalidRects() { ClearInvalidRects(); CaptureImage(); if (capture_fullscreen_) { InvalidateFullScreen(); } else { // Calculate the difference between the previous and current screen. int prev_buffer_id = current_buffer_ - 1; if (prev_buffer_id < 0) { prev_buffer_id = kNumBuffers - 1; } void* prev_buffer = buffers_[prev_buffer_id]; void* curr_buffer = buffers_[current_buffer_]; InvalidRects rects; differ_->CalcDirtyRects(prev_buffer, curr_buffer, &rects); InvalidateRects(rects); } capture_fullscreen_ = false; } void CapturerGdi::CaptureRects(const InvalidRects& rects, CaptureCompletedCallback* callback) { DataPlanes planes; planes.data[0] = static_cast<uint8*>(buffers_[current_buffer_]); planes.strides[0] = bytes_per_row_; scoped_refptr<CaptureData> data(new CaptureData(planes, width(), height(), pixel_format())); data->mutable_dirty_rects() = rects; FinishCapture(data, callback); } void CapturerGdi::CaptureImage() { // Select the target bitmap into the memory dc. SelectObject(memory_dc_, target_bitmap_[current_buffer_]); // And then copy the rect from desktop to memory. BitBlt(memory_dc_, 0, 0, width_, height_, desktop_dc_, 0, 0, SRCCOPY | CAPTUREBLT); } } // namespace remoting <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" #include <ApplicationServices/ApplicationServices.h> #include <OpenGL/CGLMacro.h> #include <OpenGL/OpenGL.h> #include <stddef.h> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "remoting/host/capturer_helper.h" namespace remoting { namespace { // A class to perform capturing for mac. class CapturerMac : public Capturer { public: CapturerMac(); virtual ~CapturerMac(); // Capturer interface. virtual void ScreenConfigurationChanged() OVERRIDE; virtual media::VideoFrame::Format pixel_format() const OVERRIDE; virtual void ClearInvalidRects() OVERRIDE; virtual void InvalidateRects(const InvalidRects& inval_rects) OVERRIDE; virtual void InvalidateScreen(const gfx::Size& size) OVERRIDE; virtual void InvalidateFullScreen() OVERRIDE; virtual void CaptureInvalidRects(CaptureCompletedCallback* callback) OVERRIDE; virtual const gfx::Size& size_most_recent() const OVERRIDE; private: void CaptureRects(const InvalidRects& rects, CaptureCompletedCallback* callback); void ScreenRefresh(CGRectCount count, const CGRect *rect_array); void ScreenUpdateMove(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array); static void ScreenRefreshCallback(CGRectCount count, const CGRect *rect_array, void *user_parameter); static void ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array, void *user_parameter); static void DisplaysReconfiguredCallback(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *user_parameter); void ReleaseBuffers(); CGLContextObj cgl_context_; static const int kNumBuffers = 2; scoped_array<uint8> buffers_[kNumBuffers]; // A thread-safe list of invalid rectangles, and the size of the most // recently captured screen. CapturerHelper helper_; // Screen size. int width_; int height_; int bytes_per_row_; // The current buffer with valid data for reading. int current_buffer_; // Format of pixels returned in buffer. media::VideoFrame::Format pixel_format_; DISALLOW_COPY_AND_ASSIGN(CapturerMac); }; CapturerMac::CapturerMac() : cgl_context_(NULL), width_(0), height_(0), bytes_per_row_(0), current_buffer_(0), pixel_format_(media::VideoFrame::RGB32) { // TODO(dmaclach): move this initialization out into session_manager, // or at least have session_manager call into here to initialize it. CGError err = CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this); DCHECK_EQ(err, kCGErrorSuccess); err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this); DCHECK_EQ(err, kCGErrorSuccess); err = CGDisplayRegisterReconfigurationCallback( CapturerMac::DisplaysReconfiguredCallback, this); DCHECK_EQ(err, kCGErrorSuccess); ScreenConfigurationChanged(); InvalidateScreen(gfx::Size(width_, height_)); } CapturerMac::~CapturerMac() { ReleaseBuffers(); CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this); CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this); CGDisplayRemoveReconfigurationCallback( CapturerMac::DisplaysReconfiguredCallback, this); } void CapturerMac::ReleaseBuffers() { if (cgl_context_) { CGLDestroyContext(cgl_context_); cgl_context_ = NULL; } } void CapturerMac::ScreenConfigurationChanged() { ReleaseBuffers(); CGDirectDisplayID mainDevice = CGMainDisplayID(); width_ = CGDisplayPixelsWide(mainDevice); height_ = CGDisplayPixelsHigh(mainDevice); pixel_format_ = media::VideoFrame::RGB32; bytes_per_row_ = width_ * sizeof(uint32_t); size_t buffer_size = height_ * bytes_per_row_; for (int i = 0; i < kNumBuffers; ++i) { buffers_[i].reset(new uint8[buffer_size]); } CGLPixelFormatAttribute attributes[] = { kCGLPFAFullScreen, kCGLPFADisplayMask, (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice), (CGLPixelFormatAttribute)0 }; CGLPixelFormatObj pixel_format = NULL; GLint matching_pixel_format_count = 0; CGLError err = CGLChoosePixelFormat(attributes, &pixel_format, &matching_pixel_format_count); DCHECK_EQ(err, kCGLNoError); err = CGLCreateContext(pixel_format, NULL, &cgl_context_); DCHECK_EQ(err, kCGLNoError); CGLDestroyPixelFormat(pixel_format); CGLSetFullScreen(cgl_context_); CGLSetCurrentContext(cgl_context_); } media::VideoFrame::Format CapturerMac::pixel_format() const { return pixel_format_; } void CapturerMac::ClearInvalidRects() { helper_.ClearInvalidRects(); } void CapturerMac::InvalidateRects(const InvalidRects& inval_rects) { helper_.InvalidateRects(inval_rects); } void CapturerMac::InvalidateScreen(const gfx::Size& size) { helper_.InvalidateScreen(size); } void CapturerMac::InvalidateFullScreen() { helper_.InvalidateFullScreen(); } void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { InvalidRects rects; helper_.SwapInvalidRects(rects); CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glReadBuffer(GL_FRONT); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment. glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); // Read a block of pixels from the frame buffer. uint8* current_buffer = buffers_[current_buffer_].get(); glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, current_buffer); glPopClientAttrib(); DataPlanes planes; planes.data[0] = buffers_[current_buffer_].get() + height_ * bytes_per_row_; planes.strides[0] = -bytes_per_row_; scoped_refptr<CaptureData> data( new CaptureData(planes, gfx::Size(width_, height_), pixel_format())); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); callback->Run(data); delete callback; } const gfx::Size& CapturerMac::size_most_recent() const { return helper_.size_most_recent(); } void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) { InvalidRects rects; for (CGRectCount i = 0; i < count; ++i) { rects.insert(gfx::Rect(rect_array[i])); } InvalidateRects(rects); } void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array) { InvalidRects rects; for (CGRectCount i = 0; i < count; ++i) { CGRect rect = rect_array[i]; rects.insert(gfx::Rect(rect)); rect = CGRectOffset(rect, delta.dX, delta.dY); rects.insert(gfx::Rect(rect)); } InvalidateRects(rects); } void CapturerMac::ScreenRefreshCallback(CGRectCount count, const CGRect *rect_array, void *user_parameter) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenRefresh(count, rect_array); } void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array, void *user_parameter) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenUpdateMove(delta, count, rect_array); } void CapturerMac::DisplaysReconfiguredCallback( CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *user_parameter) { if ((display == CGMainDisplayID()) && !(flags & kCGDisplayBeginConfigurationFlag)) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenConfigurationChanged(); } } } // namespace // static Capturer* Capturer::Create() { return new CapturerMac(); } } // namespace remoting <commit_msg>Use pixel buffer objects where supported to improve capturer speed.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/capturer.h" #include <ApplicationServices/ApplicationServices.h> #include <OpenGL/CGLMacro.h> #include <OpenGL/OpenGL.h> #include <stddef.h> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "remoting/host/capturer_helper.h" namespace remoting { namespace { class scoped_pixel_buffer_object { public: scoped_pixel_buffer_object(); ~scoped_pixel_buffer_object(); bool Init(CGLContextObj cgl_context, int size_in_bytes); void Release(); GLuint get() const { return pixel_buffer_object_; } private: CGLContextObj cgl_context_; GLuint pixel_buffer_object_; DISALLOW_COPY_AND_ASSIGN(scoped_pixel_buffer_object); }; scoped_pixel_buffer_object::scoped_pixel_buffer_object() : cgl_context_(NULL), pixel_buffer_object_(0) { } scoped_pixel_buffer_object::~scoped_pixel_buffer_object() { Release(); } bool scoped_pixel_buffer_object::Init(CGLContextObj cgl_context, int size_in_bytes) { cgl_context_ = cgl_context; CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glGenBuffersARB(1, &pixel_buffer_object_); if (glGetError() == GL_NO_ERROR) { glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_); glBufferDataARB(GL_PIXEL_PACK_BUFFER_ARB, size_in_bytes, NULL, GL_STREAM_READ_ARB); glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); if (glGetError() != GL_NO_ERROR) { Release(); } } else { cgl_context_ = NULL; pixel_buffer_object_ = 0; } return pixel_buffer_object_ != 0; } void scoped_pixel_buffer_object::Release() { if (pixel_buffer_object_) { CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glDeleteBuffersARB(1, &pixel_buffer_object_); cgl_context_ = NULL; pixel_buffer_object_ = 0; } } // A class to perform capturing for mac. class CapturerMac : public Capturer { public: CapturerMac(); virtual ~CapturerMac(); // Capturer interface. virtual void ScreenConfigurationChanged() OVERRIDE; virtual media::VideoFrame::Format pixel_format() const OVERRIDE; virtual void ClearInvalidRects() OVERRIDE; virtual void InvalidateRects(const InvalidRects& inval_rects) OVERRIDE; virtual void InvalidateScreen(const gfx::Size& size) OVERRIDE; virtual void InvalidateFullScreen() OVERRIDE; virtual void CaptureInvalidRects(CaptureCompletedCallback* callback) OVERRIDE; virtual const gfx::Size& size_most_recent() const OVERRIDE; private: void FastBlit(uint8* buffer); void SlowBlit(uint8* buffer); void CaptureRects(const InvalidRects& rects, CaptureCompletedCallback* callback); void ScreenRefresh(CGRectCount count, const CGRect *rect_array); void ScreenUpdateMove(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array); static void ScreenRefreshCallback(CGRectCount count, const CGRect *rect_array, void *user_parameter); static void ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array, void *user_parameter); static void DisplaysReconfiguredCallback(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *user_parameter); void ReleaseBuffers(); CGLContextObj cgl_context_; static const int kNumBuffers = 2; scoped_pixel_buffer_object pixel_buffer_object_; scoped_array<uint8> buffers_[kNumBuffers]; // A thread-safe list of invalid rectangles, and the size of the most // recently captured screen. CapturerHelper helper_; // Screen size. int width_; int height_; int bytes_per_row_; // The current buffer with valid data for reading. int current_buffer_; // Format of pixels returned in buffer. media::VideoFrame::Format pixel_format_; DISALLOW_COPY_AND_ASSIGN(CapturerMac); }; CapturerMac::CapturerMac() : cgl_context_(NULL), width_(0), height_(0), bytes_per_row_(0), current_buffer_(0), pixel_format_(media::VideoFrame::RGB32) { // TODO(dmaclach): move this initialization out into session_manager, // or at least have session_manager call into here to initialize it. CGError err = CGRegisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this); DCHECK_EQ(err, kCGErrorSuccess); err = CGScreenRegisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this); DCHECK_EQ(err, kCGErrorSuccess); err = CGDisplayRegisterReconfigurationCallback( CapturerMac::DisplaysReconfiguredCallback, this); DCHECK_EQ(err, kCGErrorSuccess); ScreenConfigurationChanged(); InvalidateScreen(gfx::Size(width_, height_)); } CapturerMac::~CapturerMac() { ReleaseBuffers(); CGUnregisterScreenRefreshCallback(CapturerMac::ScreenRefreshCallback, this); CGScreenUnregisterMoveCallback(CapturerMac::ScreenUpdateMoveCallback, this); CGDisplayRemoveReconfigurationCallback( CapturerMac::DisplaysReconfiguredCallback, this); } void CapturerMac::ReleaseBuffers() { if (cgl_context_) { pixel_buffer_object_.Release(); CGLDestroyContext(cgl_context_); cgl_context_ = NULL; } } void CapturerMac::ScreenConfigurationChanged() { ReleaseBuffers(); CGDirectDisplayID mainDevice = CGMainDisplayID(); width_ = CGDisplayPixelsWide(mainDevice); height_ = CGDisplayPixelsHigh(mainDevice); pixel_format_ = media::VideoFrame::RGB32; bytes_per_row_ = width_ * sizeof(uint32_t); size_t buffer_size = height_ * bytes_per_row_; for (int i = 0; i < kNumBuffers; ++i) { buffers_[i].reset(new uint8[buffer_size]); } CGLPixelFormatAttribute attributes[] = { kCGLPFAFullScreen, kCGLPFADisplayMask, (CGLPixelFormatAttribute)CGDisplayIDToOpenGLDisplayMask(mainDevice), (CGLPixelFormatAttribute)0 }; CGLPixelFormatObj pixel_format = NULL; GLint matching_pixel_format_count = 0; CGLError err = CGLChoosePixelFormat(attributes, &pixel_format, &matching_pixel_format_count); DCHECK_EQ(err, kCGLNoError); err = CGLCreateContext(pixel_format, NULL, &cgl_context_); DCHECK_EQ(err, kCGLNoError); CGLDestroyPixelFormat(pixel_format); CGLSetFullScreen(cgl_context_); CGLSetCurrentContext(cgl_context_); pixel_buffer_object_.Init(cgl_context_, buffer_size); } media::VideoFrame::Format CapturerMac::pixel_format() const { return pixel_format_; } void CapturerMac::ClearInvalidRects() { helper_.ClearInvalidRects(); } void CapturerMac::InvalidateRects(const InvalidRects& inval_rects) { helper_.InvalidateRects(inval_rects); } void CapturerMac::InvalidateScreen(const gfx::Size& size) { helper_.InvalidateScreen(size); } void CapturerMac::InvalidateFullScreen() { helper_.InvalidateFullScreen(); } void CapturerMac::CaptureInvalidRects(CaptureCompletedCallback* callback) { InvalidRects rects; helper_.SwapInvalidRects(rects); uint8* current_buffer = buffers_[current_buffer_].get(); if (pixel_buffer_object_.get() != 0) { FastBlit(current_buffer); } else { SlowBlit(current_buffer); } DataPlanes planes; planes.data[0] = current_buffer + height_ * bytes_per_row_; planes.strides[0] = -bytes_per_row_; scoped_refptr<CaptureData> data( new CaptureData(planes, gfx::Size(width_, height_), pixel_format())); data->mutable_dirty_rects() = rects; current_buffer_ = (current_buffer_ + 1) % kNumBuffers; helper_.set_size_most_recent(data->size()); callback->Run(data); delete callback; } void CapturerMac::FastBlit(uint8* buffer) { CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pixel_buffer_object_.get()); glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, 0); GLubyte* ptr = static_cast<GLubyte*>( glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB)); if (ptr == NULL) { // If the buffer can't be mapped, assume that it's no longer valid, release // it and fall back on SlowBlit for this (and subsequent) captures. pixel_buffer_object_.Release(); SlowBlit(buffer); } else { memcpy(buffer, ptr, height_ * bytes_per_row_); } if (!glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB)) { // If glUnmapBuffer returns false, then the contents of the data store are // undefined. This might be because the screen mode has changed, in which // case it will be recreated in ScreenConfigurationChanged, but releasing // the object here is the best option. Capturing will fall back on SlowBlit // until such time as the pixel buffer object is recreated. pixel_buffer_object_.Release(); } glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0); } void CapturerMac::SlowBlit(uint8* buffer) { CGLContextObj CGL_MACRO_CONTEXT = cgl_context_; glReadBuffer(GL_FRONT); glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT); glPixelStorei(GL_PACK_ALIGNMENT, 4); // Force 4-byte alignment. glPixelStorei(GL_PACK_ROW_LENGTH, 0); glPixelStorei(GL_PACK_SKIP_ROWS, 0); glPixelStorei(GL_PACK_SKIP_PIXELS, 0); // Read a block of pixels from the frame buffer. glReadPixels(0, 0, width_, height_, GL_BGRA, GL_UNSIGNED_BYTE, buffer); glPopClientAttrib(); } const gfx::Size& CapturerMac::size_most_recent() const { return helper_.size_most_recent(); } void CapturerMac::ScreenRefresh(CGRectCount count, const CGRect *rect_array) { InvalidRects rects; for (CGRectCount i = 0; i < count; ++i) { rects.insert(gfx::Rect(rect_array[i])); } InvalidateRects(rects); } void CapturerMac::ScreenUpdateMove(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array) { InvalidRects rects; for (CGRectCount i = 0; i < count; ++i) { CGRect rect = rect_array[i]; rects.insert(gfx::Rect(rect)); rect = CGRectOffset(rect, delta.dX, delta.dY); rects.insert(gfx::Rect(rect)); } InvalidateRects(rects); } void CapturerMac::ScreenRefreshCallback(CGRectCount count, const CGRect *rect_array, void *user_parameter) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenRefresh(count, rect_array); } void CapturerMac::ScreenUpdateMoveCallback(CGScreenUpdateMoveDelta delta, size_t count, const CGRect *rect_array, void *user_parameter) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenUpdateMove(delta, count, rect_array); } void CapturerMac::DisplaysReconfiguredCallback( CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void *user_parameter) { if ((display == CGMainDisplayID()) && !(flags & kCGDisplayBeginConfigurationFlag)) { CapturerMac *capturer = reinterpret_cast<CapturerMac *>(user_parameter); capturer->ScreenConfigurationChanged(); } } } // namespace // static Capturer* Capturer::Create() { return new CapturerMac(); } } // namespace remoting <|endoftext|>
<commit_before>//@author A0094446X #include "stdafx.h" #include <QApplication> #include <QList> #include <QPair> #include "task_panel_manager.h" namespace You { namespace GUI { using Date = boost::gregorian::date; const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies"; MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI) : BaseManager(parentGUI), deleteAction(QString("Delete"), this), editAction(QString("Edit"), this), addAction(QString("Add"), this), deleteSignalMapper(this), editSignalMapper(this) { } MainWindow::TaskPanelManager::~TaskPanelManager() { } void MainWindow::TaskPanelManager::setup() { QStringList columnHeaders({ TASK_COLUMN_1, TASK_COLUMN_2, TASK_COLUMN_3, TASK_COLUMN_4, TASK_COLUMN_5, TASK_COLUMN_6 }); QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel; connect(taskTreePanel, SIGNAL(itemSelectionChanged()), parentGUI, SLOT(taskSelected())); connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(contextMenu(const QPoint &))); taskTreePanel->setColumnCount(columnHeaders.size()); taskTreePanel->setHeaderItem(createItem(columnHeaders).release()); // TODO(angathorion): remove magic constants. QHeaderView* header = taskTreePanel->header(); header->setStretchLastSection(true); for (int i = 1; i < columnHeaders.size(); ++i) { if (i == 2) { continue; } header->resizeSection(i, header->defaultSectionSize()); } taskTreePanel->header()->setMinimumSectionSize(75); taskTreePanel->setColumnHidden(0, true); taskTreePanel->setColumnHidden(5, true); } void MainWindow::TaskPanelManager::addTask(const Task& task) { std::unique_ptr<QTreeWidgetItem> item(createItem(task)); parentGUI->ui.taskTreePanel->addTopLevelItem(item.release()); updateRowNumbers(); } void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent, const QStringList& rowStrings) { std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings)); parent->addChild(item.release()); updateRowNumbers(); } void MainWindow::TaskPanelManager::editTask(const Task& task) { QList<QTreeWidgetItem*> items = findItems(task.getID()); assert(items.length() == 1); QTreeWidgetItem item = *items.at(0); QStringList wstr = taskToStrVec(task); *items.at(0) = *createItem(wstr); updateRowNumbers(); } void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) { QList<QTreeWidgetItem*> items = findItems(taskID); assert(items.length() == 1); deleteTask(items.at(0)); updateRowNumbers(); } void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) { delete task; } std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem( const Task& task) { return createItem(taskToStrVec(task)); } std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem( const QStringList& rowStrings) { return std::make_unique<QTreeWidgetItem>(rowStrings); } QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems( You::Controller::Task::ID taskID) const { return parentGUI->ui.taskTreePanel->findItems( boost::lexical_cast<QString>(taskID), 0); } QStringList MainWindow::TaskPanelManager::taskToStrVec( const You::Controller::Task& task) { QStringList result; // Insert id result.push_back(boost::lexical_cast<QString>(task.getID())); // Insert dummy count result.push_back("0"); // Insert description result.push_back(QString::fromStdWString(task.getDescription())); // Insert deadline std::wstringstream wss; if (task.getDeadline() == Task::NEVER) { wss << L"Never"; } else if (isPastDue(task.getDeadline())) { wss << L"Overdue (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 0)) { wss << L"Today (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 1)) { wss << L"Tomorrow (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 2)) { wss << L"In two days (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 7)) { wss << L"Within one week (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 14)) { wss << L"Within two weeks (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 21)) { wss << L"Within three weeks (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 28)) { wss << L"Within one month (" << task.getDeadline() << L")"; } else { wss << L"More than a month away (" << task.getDeadline() << L")"; } result.push_back(boost::lexical_cast<QString>(wss.str())); // Insert priority QString priority[] { "High", "Normal" }; switch (task.getPriority()) { case Task::Priority::HIGH: result.push_back(priority[0]); case Task::Priority::NORMAL: result.push_back(priority[1]); } // Insert dependencies std::wstringstream ss; if (task.getDependencies().size() != 0) { ss << task.getDependencies().at(0); for (int i = 1; i < task.getDependencies().size(); i++) { ss << ", " << task.getDependencies().at(i); } result.push_back(QString::fromStdWString(ss.str())); } else { result.push_back("None"); } return result; } void MainWindow::TaskPanelManager::updateRowNumbers() { int rowNum = 0; for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) { (*it)->setData(1, Qt::DisplayRole, rowNum++); } } bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) { Task::Time now = boost::posix_time::second_clock::local_time(); if (deadline < now) { return true; } else { return false; } } bool MainWindow::TaskPanelManager::isDueAfter( Task::Time deadline, int daysLeft) { Date by = Date(deadline.date()); Date today = boost::gregorian::day_clock::local_day(); if (by.modjulian_day() - today.modjulian_day() == daysLeft) { return true; } else { return false; } } bool MainWindow::TaskPanelManager::isDueWithin( Task::Time deadline, int daysLeft) { Date by = Date(deadline.date()); Date today = boost::gregorian::day_clock::local_day(); if (by.julian_day() - today.julian_day() < daysLeft) { return true; } else { return false; } } void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) { /// Try to get the item at the position of the context menu QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos); itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel)); /// Adds the Add Task action. This is always present in the menu. itemContextMenu->addAction(&addAction); connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask())); /// Adds the Edit Task and Delete Task actions if an item is selected. /// QSignalMapper is necessary because arguments need to be passed /// as part of the signal. if (item) { deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt()); connect(&deleteAction, SIGNAL(triggered()), &deleteSignalMapper, SLOT(map())); itemContextMenu->addAction(&deleteAction); connect(&deleteSignalMapper, SIGNAL(mapped(int)), parentGUI, SLOT(contextDeleteTask(int))); editSignalMapper.setMapping(&editAction, item->text(1).toInt()); connect(&editAction, SIGNAL(triggered()), &editSignalMapper, SLOT(map())); itemContextMenu->addAction(&editAction); connect(&editSignalMapper, SIGNAL(mapped(int)), parentGUI, SLOT(contextEditTask(int))); } itemContextMenu->popup( parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos)); } } // namespace GUI } // namespace You <commit_msg>Dependency fix<commit_after>//@author A0094446X #include "stdafx.h" #include <QApplication> #include <QList> #include <QPair> #include "task_panel_manager.h" namespace You { namespace GUI { using Date = boost::gregorian::date; const QString MainWindow::TaskPanelManager::TASK_COLUMN_1 = "Hidden ID Column"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_2 = "Index"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_3 = "Description"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_4 = "Deadline"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_5 = "Priority"; const QString MainWindow::TaskPanelManager::TASK_COLUMN_6 = "Dependencies"; MainWindow::TaskPanelManager::TaskPanelManager(MainWindow* const parentGUI) : BaseManager(parentGUI), deleteAction(QString("Delete"), this), editAction(QString("Edit"), this), addAction(QString("Add"), this), deleteSignalMapper(this), editSignalMapper(this) { } MainWindow::TaskPanelManager::~TaskPanelManager() { } void MainWindow::TaskPanelManager::setup() { QStringList columnHeaders({ TASK_COLUMN_1, TASK_COLUMN_2, TASK_COLUMN_3, TASK_COLUMN_4, TASK_COLUMN_5, TASK_COLUMN_6 }); QTreeWidget* taskTreePanel = parentGUI->ui.taskTreePanel; connect(taskTreePanel, SIGNAL(itemSelectionChanged()), parentGUI, SLOT(taskSelected())); connect(taskTreePanel, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(contextMenu(const QPoint &))); taskTreePanel->setColumnCount(columnHeaders.size()); taskTreePanel->setHeaderItem(createItem(columnHeaders).release()); // TODO(angathorion): remove magic constants. QHeaderView* header = taskTreePanel->header(); header->setStretchLastSection(true); for (int i = 1; i < columnHeaders.size(); ++i) { if (i == 2) { continue; } header->resizeSection(i, header->defaultSectionSize()); } taskTreePanel->header()->setMinimumSectionSize(75); taskTreePanel->setColumnHidden(0, true); taskTreePanel->setColumnHidden(5, true); } void MainWindow::TaskPanelManager::addTask(const Task& task) { std::unique_ptr<QTreeWidgetItem> item(createItem(task)); parentGUI->ui.taskTreePanel->addTopLevelItem(item.release()); updateRowNumbers(); } void MainWindow::TaskPanelManager::addSubtask(QTreeWidgetItem* parent, const QStringList& rowStrings) { std::unique_ptr<QTreeWidgetItem> item(createItem(rowStrings)); parent->addChild(item.release()); updateRowNumbers(); } void MainWindow::TaskPanelManager::editTask(const Task& task) { QList<QTreeWidgetItem*> items = findItems(task.getID()); assert(items.length() == 1); QTreeWidgetItem item = *items.at(0); QStringList wstr = taskToStrVec(task); *items.at(0) = *createItem(wstr); updateRowNumbers(); } void MainWindow::TaskPanelManager::deleteTask(Task::ID taskID) { QList<QTreeWidgetItem*> items = findItems(taskID); assert(items.length() == 1); deleteTask(items.at(0)); updateRowNumbers(); } void MainWindow::TaskPanelManager::deleteTask(QTreeWidgetItem* task) { delete task; } std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem( const Task& task) { return createItem(taskToStrVec(task)); } std::unique_ptr<QTreeWidgetItem> MainWindow::TaskPanelManager::createItem( const QStringList& rowStrings) { return std::make_unique<QTreeWidgetItem>(rowStrings); } QList<QTreeWidgetItem*> MainWindow::TaskPanelManager::findItems( You::Controller::Task::ID taskID) const { return parentGUI->ui.taskTreePanel->findItems( boost::lexical_cast<QString>(taskID), 0); } QStringList MainWindow::TaskPanelManager::taskToStrVec( const You::Controller::Task& task) { QStringList result; // Insert id result.push_back(boost::lexical_cast<QString>(task.getID())); // Insert dummy count result.push_back("0"); // Insert description result.push_back(QString::fromStdWString(task.getDescription())); // Insert deadline std::wstringstream wss; if (task.getDeadline() == Task::NEVER) { wss << L"Never"; } else if (isPastDue(task.getDeadline())) { wss << L"Overdue (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 0)) { wss << L"Today (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 1)) { wss << L"Tomorrow (" << task.getDeadline() << L")"; } else if (isDueAfter(task.getDeadline(), 2)) { wss << L"In two days (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 7)) { wss << L"Within one week (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 14)) { wss << L"Within two weeks (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 21)) { wss << L"Within three weeks (" << task.getDeadline() << L")"; } else if (isDueWithin(task.getDeadline(), 28)) { wss << L"Within one month (" << task.getDeadline() << L")"; } else { wss << L"More than a month away (" << task.getDeadline() << L")"; } result.push_back(boost::lexical_cast<QString>(wss.str())); // Insert priority QString priority[] { "High", "Normal" }; switch (task.getPriority()) { case Task::Priority::HIGH: result.push_back(priority[0]); case Task::Priority::NORMAL: result.push_back(priority[1]); } // Insert dependencies std::ostringstream ss; if (task.getDependencies().size() != 0) { Task::Dependencies dependencies = task.getDependencies(); std::copy(dependencies.begin(), dependencies.end() - 1, std::ostream_iterator<int64_t>(ss, ", ")); ss << dependencies.back(); result.push_back(QString::fromStdString(ss.str())); } else { result.push_back("None"); } return result; } void MainWindow::TaskPanelManager::updateRowNumbers() { int rowNum = 0; for (QTreeWidgetItemIterator it(parentGUI->ui.taskTreePanel); *it; ++it) { (*it)->setData(1, Qt::DisplayRole, rowNum++); } } bool MainWindow::TaskPanelManager::isPastDue(Task::Time deadline) { Task::Time now = boost::posix_time::second_clock::local_time(); if (deadline < now) { return true; } else { return false; } } bool MainWindow::TaskPanelManager::isDueAfter( Task::Time deadline, int daysLeft) { Date by = Date(deadline.date()); Date today = boost::gregorian::day_clock::local_day(); if (by.modjulian_day() - today.modjulian_day() == daysLeft) { return true; } else { return false; } } bool MainWindow::TaskPanelManager::isDueWithin( Task::Time deadline, int daysLeft) { Date by = Date(deadline.date()); Date today = boost::gregorian::day_clock::local_day(); if (by.julian_day() - today.julian_day() < daysLeft) { return true; } else { return false; } } void MainWindow::TaskPanelManager::contextMenu(const QPoint &pos) { /// Try to get the item at the position of the context menu QTreeWidgetItem *item = parentGUI->ui.taskTreePanel->itemAt(pos); itemContextMenu.reset(new QMenu(parentGUI->ui.taskTreePanel)); /// Adds the Add Task action. This is always present in the menu. itemContextMenu->addAction(&addAction); connect(&addAction, SIGNAL(triggered()), parentGUI, SLOT(contextAddTask())); /// Adds the Edit Task and Delete Task actions if an item is selected. /// QSignalMapper is necessary because arguments need to be passed /// as part of the signal. if (item) { deleteSignalMapper.setMapping(&deleteAction, item->text(1).toInt()); connect(&deleteAction, SIGNAL(triggered()), &deleteSignalMapper, SLOT(map())); itemContextMenu->addAction(&deleteAction); connect(&deleteSignalMapper, SIGNAL(mapped(int)), parentGUI, SLOT(contextDeleteTask(int))); editSignalMapper.setMapping(&editAction, item->text(1).toInt()); connect(&editAction, SIGNAL(triggered()), &editSignalMapper, SLOT(map())); itemContextMenu->addAction(&editAction); connect(&editSignalMapper, SIGNAL(mapped(int)), parentGUI, SLOT(contextEditTask(int))); } itemContextMenu->popup( parentGUI->ui.taskTreePanel->viewport()->mapToGlobal(pos)); } } // namespace GUI } // namespace You <|endoftext|>
<commit_before>#include "ZeroCopyNetworkReaderStream.h" #include <errno.h> #include <sys/types.h> #include <sys/socket.h> ZeroCopyNetworkReaderStream::ZeroCopyNetworkReaderStream( int fd, protobuf::uint32 totalMessageSize, protobuf::uint8* pDataBuffer, protobuf::uint32 bufferSize) : m_fd(fd), m_remainingMessageSizeBytes(totalMessageSize), m_pDataBuffer(pDataBuffer), m_bufferSize(bufferSize), m_numBytesLastRead(0), m_backupPos(m_numBytesLastRead), m_byteCount(0) { } //-------------------------------------------------------------------------------------------------- ZeroCopyNetworkReaderStream::~ZeroCopyNetworkReaderStream() { } //-------------------------------------------------------------------------------------------------- bool ZeroCopyNetworkReaderStream::Next(const void** data, int* size) { if (data == 0 || size == 0) { return false; } *size = 0; if (m_remainingMessageSizeBytes == 0) { return false; } if (m_backupPos < m_numBytesLastRead) { // A BackUp() call has been issued *size = m_numBytesLastRead - m_backupPos; *data = &m_pDataBuffer[m_backupPos]; // We've returned everything from the backup position to the end of the last read m_backupPos = m_numBytesLastRead; return true; } const protobuf::uint32 numBytesToRead = std::min(m_remainingMessageSizeBytes, m_bufferSize); ssize_t bytesRead = -1; do { bytesRead = recv(m_fd, m_pDataBuffer, numBytesToRead, MSG_WAITALL); } while (bytesRead == -1 && errno == EINTR); if (bytesRead == 0) { //pan::log(pan::notice, "Peer has performed an orderly shutdown on fd: ", pan::i(m_fd), // " during normal receive"); return false; } if (bytesRead == -1) { //pan::log(pan::error, "Failed to read message, numBytesToRead: ", pan::i(numBytesToRead), // ", m_remainingMessageSizeBytes: ", pan::i(m_remainingMessageSizeBytes), ", m_fd: ", pan::i(m_fd), ". ", ErrnoInserter()); return false; } // TODO: for non-blocking I/O sockets the following test isn't correct if (bytesRead != numBytesToRead) { //pan::log(pan::error, "Partially read message, bytesRead: ", pan::i(bytesRead), // ", numBytesToRead: ", pan::i(numBytesToRead), ", m_remainingMessageSizeBytes: ", pan::i(m_remainingMessageSizeBytes), ". ", ErrnoInserter()); return false; } *data = m_pDataBuffer; *size = bytesRead; m_numBytesLastRead = m_backupPos = bytesRead; m_remainingMessageSizeBytes -= bytesRead; m_byteCount += bytesRead; return true; } //-------------------------------------------------------------------------------------------------- void ZeroCopyNetworkReaderStream::BackUp(int count) { m_backupPos -= count; } //-------------------------------------------------------------------------------------------------- bool ZeroCopyNetworkReaderStream::Skip(int count) { if (m_backupPos < m_numBytesLastRead) { const protobuf::uint32 numBytesToSkipInBackup = std::min(m_numBytesLastRead - m_backupPos, (protobuf::uint32) count); m_backupPos += numBytesToSkipInBackup; count -= numBytesToSkipInBackup; } if (count == 0) { return (m_remainingMessageSizeBytes > 0); } // Read the remaining <count> bytes from the stream and dump them // TODO: can we simply seek() instead of actually reading the data? char dumpBuf[128]; protobuf::uint32 bytesToDump = std::min(m_remainingMessageSizeBytes, (protobuf::uint32) count); while (bytesToDump > 0) { protobuf::uint32 bytesToDumpThisIteration = std::min(bytesToDump, (protobuf::uint32) sizeof(dumpBuf)); ssize_t bytesRead = -1; do { bytesRead = recv(m_fd, dumpBuf, bytesToDumpThisIteration, MSG_WAITALL); } while (bytesRead == -1 && errno == EINTR); if (bytesRead == 0) { //pan::log(pan::notice, "Peer has performed an orderly shutdown on m_fd ", pan::i(m_fd), // " during data dump"); return false; } if (bytesRead == -1) { //pan::log(pan::error, "Failed to read data to dump, bytesToDumpThisIteration: ", // pan::i(bytesToDumpThisIteration), ". ", ErrnoInserter()); return false; } // TODO: proper error handling of read() m_remainingMessageSizeBytes -= bytesToDumpThisIteration; m_byteCount += bytesToDumpThisIteration; } return (m_remainingMessageSizeBytes > 0); } //-------------------------------------------------------------------------------------------------- protobuf::int64 ZeroCopyNetworkReaderStream::ByteCount() const { return m_byteCount; } <commit_msg>Comment out more logging code (oops)<commit_after>#include "ZeroCopyNetworkReaderStream.h" #include <errno.h> #include <sys/types.h> #include <sys/socket.h> ZeroCopyNetworkReaderStream::ZeroCopyNetworkReaderStream( int fd, protobuf::uint32 totalMessageSize, protobuf::uint8* pDataBuffer, protobuf::uint32 bufferSize) : m_fd(fd), m_remainingMessageSizeBytes(totalMessageSize), m_pDataBuffer(pDataBuffer), m_bufferSize(bufferSize), m_numBytesLastRead(0), m_backupPos(m_numBytesLastRead), m_byteCount(0) { } //-------------------------------------------------------------------------------------------------- ZeroCopyNetworkReaderStream::~ZeroCopyNetworkReaderStream() { } //-------------------------------------------------------------------------------------------------- bool ZeroCopyNetworkReaderStream::Next(const void** data, int* size) { if (data == 0 || size == 0) { return false; } *size = 0; if (m_remainingMessageSizeBytes == 0) { return false; } if (m_backupPos < m_numBytesLastRead) { // A BackUp() call has been issued *size = m_numBytesLastRead - m_backupPos; *data = &m_pDataBuffer[m_backupPos]; // We've returned everything from the backup position to the end of the last read m_backupPos = m_numBytesLastRead; return true; } const protobuf::uint32 numBytesToRead = std::min(m_remainingMessageSizeBytes, m_bufferSize); ssize_t bytesRead = -1; do { bytesRead = recv(m_fd, m_pDataBuffer, numBytesToRead, MSG_WAITALL); } while (bytesRead == -1 && errno == EINTR); if (bytesRead == 0) { //pan::log(pan::notice, "Peer has performed an orderly shutdown on fd: ", pan::i(m_fd), // " during normal receive"); return false; } if (bytesRead == -1) { //pan::log(pan::error, "Failed to read message, numBytesToRead: ", pan::i(numBytesToRead), // ", m_remainingMessageSizeBytes: ", pan::i(m_remainingMessageSizeBytes), ", m_fd: ", // pan::i(m_fd), ". ", ErrnoInserter()); return false; } // TODO: for non-blocking I/O sockets the following test isn't correct if (bytesRead != numBytesToRead) { //pan::log(pan::error, "Partially read message, bytesRead: ", pan::i(bytesRead), // ", numBytesToRead: ", pan::i(numBytesToRead), ", m_remainingMessageSizeBytes: ", // pan::i(m_remainingMessageSizeBytes), ". ", ErrnoInserter()); return false; } *data = m_pDataBuffer; *size = bytesRead; m_numBytesLastRead = m_backupPos = bytesRead; m_remainingMessageSizeBytes -= bytesRead; m_byteCount += bytesRead; return true; } //-------------------------------------------------------------------------------------------------- void ZeroCopyNetworkReaderStream::BackUp(int count) { m_backupPos -= count; } //-------------------------------------------------------------------------------------------------- bool ZeroCopyNetworkReaderStream::Skip(int count) { if (m_backupPos < m_numBytesLastRead) { const protobuf::uint32 numBytesToSkipInBackup = std::min(m_numBytesLastRead - m_backupPos, (protobuf::uint32) count); m_backupPos += numBytesToSkipInBackup; count -= numBytesToSkipInBackup; } if (count == 0) { return (m_remainingMessageSizeBytes > 0); } // Read the remaining <count> bytes from the stream and dump them // TODO: can we simply seek() instead of actually reading the data? char dumpBuf[128]; protobuf::uint32 bytesToDump = std::min(m_remainingMessageSizeBytes, (protobuf::uint32) count); while (bytesToDump > 0) { protobuf::uint32 bytesToDumpThisIteration = std::min(bytesToDump, (protobuf::uint32) sizeof(dumpBuf)); ssize_t bytesRead = -1; do { bytesRead = recv(m_fd, dumpBuf, bytesToDumpThisIteration, MSG_WAITALL); } while (bytesRead == -1 && errno == EINTR); if (bytesRead == 0) { //pan::log(pan::notice, "Peer has performed an orderly shutdown on m_fd ", pan::i(m_fd), // " during data dump"); return false; } if (bytesRead == -1) { //pan::log(pan::error, "Failed to read data to dump, bytesToDumpThisIteration: ", // pan::i(bytesToDumpThisIteration), ". ", ErrnoInserter()); return false; } // TODO: proper error handling of read() m_remainingMessageSizeBytes -= bytesToDumpThisIteration; m_byteCount += bytesToDumpThisIteration; } return (m_remainingMessageSizeBytes > 0); } //-------------------------------------------------------------------------------------------------- protobuf::int64 ZeroCopyNetworkReaderStream::ByteCount() const { return m_byteCount; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include <stdlib.h> #include <xplc/xplc.h> #include "servmgr.h" IServiceManager* XPLC::getServiceManager() { return new ServiceManager; } <commit_msg>Service manager was not a singleton: fixed.<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * * XPLC - Cross-Platform Lightweight Components * Copyright (C) 2000, Pierre Phaneuf * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public License * as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. */ #include <stdlib.h> #include <xplc/xplc.h> #include "servmgr.h" static ServiceManager* servmgr; IServiceManager* XPLC::getServiceManager() { if(!servmgr) servmgr = new ServiceManager; if(servmgr) servmgr->addRef(); return servmgr; } <|endoftext|>
<commit_before><commit_msg>Enumerating Kelly references.<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; } <commit_msg>Coverity: Initialize target_message_loop_ in the constructor.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/icon_loader.h" #include "base/message_loop.h" #include "base/mime_util.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "third_party/skia/include/core/SkBitmap.h" IconLoader::IconLoader(const IconGroupID& group, IconSize size, Delegate* delegate) : target_message_loop_(NULL), group_(group), icon_size_(size), bitmap_(NULL), delegate_(delegate) { } IconLoader::~IconLoader() { delete bitmap_; } void IconLoader::Start() { target_message_loop_ = MessageLoop::current(); #if defined(OS_LINUX) // This call must happen on the UI thread before we can start loading icons. mime_util::DetectGtkTheme(); #endif g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE, NewRunnableMethod(this, &IconLoader::ReadIcon)); } void IconLoader::NotifyDelegate() { if (delegate_->OnBitmapLoaded(this, bitmap_)) bitmap_ = NULL; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_SHARED_RESOURCES: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("shared")); break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::DIR_USER_DATA_TEMP: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Temp")); create_dir = true; break; case chrome::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); #elif defined(OS_MACOSX) NOTIMPLEMENTED(); return false; #else // Linux and Chrome OS cur = cur.Append(FILE_PATH_LITERAL("libpdf.so")); #endif if (!file_util::PathExists(cur)) return false; break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <commit_msg>[Mac] stop the output that is slowing down all the tests that seem to walk this code path.<commit_after>// Copyright (c) 2006-2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths_internal.h" #include "chrome/common/chrome_switches.h" #if defined(OS_MACOSX) #include "base/mac_util.h" #endif namespace { // File name of the internal Flash plugin on different platforms. const FilePath::CharType kInternalFlashPluginFileName[] = #if defined(OS_MACOSX) FILE_PATH_LITERAL("Flash Player Plugin for Chrome.plugin"); #elif defined(OS_WIN) FILE_PATH_LITERAL("gcswf32.dll"); #else // OS_LINUX, etc. FILE_PATH_LITERAL("libgcflashplayer.so"); #endif } // namespace namespace chrome { // Gets the path for internal (or bundled) plugins. bool GetInternalPluginsDirectory(FilePath* result) { #if defined(OS_MACOSX) // If called from Chrome, get internal plugins from the versioned directory. if (mac_util::AmIBundled()) { *result = chrome::GetVersionedDirectory(); DCHECK(!result->empty()); return true; } // In tests, just look in the module directory (below). #endif // The rest of the world expects plugins in the module directory. return PathService::Get(base::DIR_MODULE, result); } bool GetGearsPluginPathFromCommandLine(FilePath* path) { #ifndef NDEBUG // for debugging, support a cmd line based override FilePath plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kGearsPluginPathOverride); *path = plugin_path; return !plugin_path.empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifdef NDEBUG // Release builds write to the data dir return PathService::Get(chrome::DIR_USER_DATA, result); #else // Debug builds write next to the binary (in the build tree) #if defined(OS_MACOSX) if (!PathService::Get(base::DIR_EXE, result)) return false; if (mac_util::AmIBundled()) { // If we're called from chrome, dump it beside the app (outside the // app bundle), if we're called from a unittest, we'll already // outside the bundle so use the exe dir. // exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium. *result = result->DirName(); *result = result->DirName(); *result = result->DirName(); } return true; #else return PathService::Get(base::DIR_EXE, result); #endif // defined(OS_MACOSX) #endif // NDEBUG case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; FilePath cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) { NOTREACHED(); return false; } create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: if (!GetUserDocumentsDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS_SAFE: #if defined(OS_WIN) if (!GetUserDownloadsDirectorySafe(&cur)) return false; break; #else // Fall through for all other platforms. #endif case chrome::DIR_DEFAULT_DOWNLOADS: if (!GetUserDownloadsDirectory(&cur)) return false; // Do not create the download directory here, we have done it twice now // and annoyed a lot of users. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Crash Reports")); create_dir = true; break; case chrome::DIR_USER_DESKTOP: if (!GetUserDesktop(&cur)) return false; break; case chrome::DIR_RESOURCES: #if defined(OS_MACOSX) cur = mac_util::MainAppBundlePath(); cur = cur.Append(FILE_PATH_LITERAL("Resources")); #else if (!PathService::Get(chrome::DIR_APP, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("resources")); #endif break; case chrome::DIR_SHARED_RESOURCES: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("shared")); break; case chrome::DIR_BOOKMARK_MANAGER: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("bookmark_manager")); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("inspector")); break; case chrome::DIR_NET_INTERNALS: if (!PathService::Get(chrome::DIR_RESOURCES, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("net_internals")); break; case chrome::DIR_APP_DICTIONARIES: #if defined(OS_LINUX) || defined(OS_MACOSX) // We can't write into the EXE dir on Linux, so keep dictionaries // alongside the safe browsing database in the user data dir. // And we don't want to write into the bundle on the Mac, so push // it to the user data dir there also. if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; #else if (!PathService::Get(base::DIR_EXE, &cur)) return false; #endif cur = cur.Append(FILE_PATH_LITERAL("Dictionaries")); create_dir = true; break; case chrome::DIR_USER_DATA_TEMP: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("Temp")); create_dir = true; break; case chrome::DIR_INTERNAL_PLUGINS: if (!GetInternalPluginsDirectory(&cur)) return false; break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("script.log")); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { #if defined(OS_WIN) // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("plugins")); cur = cur.Append(FILE_PATH_LITERAL("gears")); cur = cur.Append(FILE_PATH_LITERAL("gears.dll")); } #else // No gears.dll on non-Windows systems. return false; #endif } break; case chrome::FILE_FLASH_PLUGIN: if (!GetInternalPluginsDirectory(&cur)) return false; cur = cur.Append(kInternalFlashPluginFileName); if (!file_util::PathExists(cur)) return false; break; case chrome::FILE_PDF_PLUGIN: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; #if defined(OS_WIN) cur = cur.Append(FILE_PATH_LITERAL("pdf.dll")); #elif defined(OS_MACOSX) // http://crbug.com/44900 return false; #else // Linux and Chrome OS cur = cur.Append(FILE_PATH_LITERAL("libpdf.so")); #endif if (!file_util::PathExists(cur)) return false; break; #if defined(OS_CHROMEOS) case chrome::FILE_CHROMEOS_API: if (!PathService::Get(base::DIR_MODULE, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chromeos")); cur = cur.Append(FILE_PATH_LITERAL("libcros.so")); break; #endif // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("test")); cur = cur.Append(FILE_PATH_LITERAL("data")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur)) return false; cur = cur.Append(FILE_PATH_LITERAL("chrome")); cur = cur.Append(FILE_PATH_LITERAL("tools")); cur = cur.Append(FILE_PATH_LITERAL("test")); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = cur; return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <|endoftext|>
<commit_before>// UjoImro, 2013 // Experimental code for the CARP Project // Copyright (c) RealEyes, 2013 // This version tests the responseMap calculation with input dumps #include <chrono> #include <string> #include <stdlib.h> #include <opencv2/core/core.hpp> #include <boost/preprocessor.hpp> #include <boost/serialization/vector.hpp> #include <boost/archive/binary_iarchive.hpp> #include "cast.h" #include "mlp.hpp" #include "mlp_impl.h" extern int EF_ALIGNMENT = 0; extern int EF_PROTECT_BELOW = 0; extern int EF_PROTECT_FREE = 0; extern int EF_ALLOW_MALLOC_0 = 1; extern int EF_FILL = 1922; namespace { struct hack_t; } MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ); mlp * convertHackToMlp ( const hack_t & hack ); void freeClassifiers( mlp * classifiers[], int size ); MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ); MatFloat convertCVToMatFloat ( const cv::Mat_<double> & input ); cv::Mat_<double> convertMatFloatToCV( MatFloat input ); void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] ); void freeResponseMaps( MatFloat * responseMaps[], int size ); namespace { struct hack_t { int m_visibleLandmarks_size; int m_mapSize; cv::Mat_<double> shape; cv::Mat_<uint8_t> alignedImage; std::vector<gel::MLP<double> > m_classifiers; std::vector<cv::Mat_<double> > responseMaps; template <class MT0> void serialize( MT0 & archiver, unsigned int ) { GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size ); GEL_EXPORT_VAR( archiver, m_mapSize ); GEL_EXPORT_VAR( archiver, shape ); GEL_EXPORT_VAR( archiver, alignedImage ); GEL_EXPORT_VAR( archiver, m_classifiers ); GEL_EXPORT_VAR( archiver, responseMaps ); } // serialize }; // struct hack_t class conductor_t { public: int id; hack_t hack; std::ifstream dumpStream; boost::archive::binary_iarchive importer; public: conductor_t() : id(0), dumpStream("response_dumps.bin", std::ios::in | std::ios::binary ), importer(dumpStream) { }; // conductor_t }; // conductor_t } // unnamed namespace mlp * convertHackToMlp ( const hack_t & hack ) { assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size()); assert(hack.m_visibleLandmarks_size==hack.responseMaps.size()); mlp * result; result = reinterpret_cast<mlp*>( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) ); // we export each classifier for (int q=0; q<hack.m_visibleLandmarks_size; q++) { result[q].m_patchSize = hack.m_classifiers[q].m_patchSize; result[q].m_wIn = convertCVToMatFloat(hack.m_classifiers[q].m_wIn); result[q].m_wOut = convertCVToMatFloat(hack.m_classifiers[q].m_wOut); result[q].m_U = convertCVToMatFloat(hack.m_classifiers[q].m_U); result[q].hidden_num = hack.m_classifiers[q].hidden_num; result[q].rho2 = hack.m_classifiers[q].rho2; } // for q in m_visibleLandmarks_size return result; } // convertHackToMlp void freeClassifiers( mlp * classifiers[], int size ) { mlp * result = *classifiers; for (int q=0; q<size; q++ ) freeMLP( &(result[q]) ); free(*classifiers); *classifiers=NULL; return; } // freeClassifiers MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ) { MatChar result = CreateMatChar( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result.data[ q * result.step + w + result.start ] = input(q,w); return result; } // convertCVToMatChar MatFloat convertCVToMatFloat ( const cv::Mat_<double> & input ) { MatFloat result = CreateMatFloat( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result.data[ q * result.step + w + result.start ] = input(q,w); return result; } // convertCVToMatFloat cv::Mat_<double> convertMatFloatToCV( MatFloat input ) { cv::Mat_<double> result( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result(q,w) = input.data[ q * input.step + w + input.start ]; return result; } // convertMatFloatToCV void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] ) { *responseMaps = (MatFloat*)malloc( sizeof(MatFloat) * size ); assert(*responseMaps); MatFloat * result = *responseMaps; for ( int q=0; q<size; q++ ) result[q] = CreateMatFloat( 2 * mapSize + 1, 2 * mapSize + 1 ); return; } void freeResponseMaps( MatFloat * responseMaps[], int size ) { MatFloat * result = *responseMaps; assert(result); for ( int q=0; q<size; q++ ) freeMatFloat(&(result[q])); free(result); *responseMaps=NULL; return; } template <class T0> auto microseconds( T0 t0 ) -> decltype(std::chrono::duration_cast<std::chrono::microseconds>(t0).count()) { return std::chrono::duration_cast<std::chrono::microseconds>(t0).count(); } int main() { conductor_t conductor; int fail = 0; long int elapsed_time = 0; for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); ((conductor.id != -1) and (conductor.id != 25)); // conductor.id != -1; conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id) ) { PRINT(conductor.id); conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack); // here comes the function call { // preparing the inputs MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage); MatFloat shape = convertCVToMatFloat(conductor.hack.shape); mlp * m_classifiers = convertHackToMlp(conductor.hack); MatFloat * responseMaps; allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps ); auto start = std::chrono::high_resolution_clock::now(); calculateMaps( conductor.hack.m_visibleLandmarks_size, conductor.hack.m_mapSize, alignedImage, shape, m_classifiers, &responseMaps ); auto end = std::chrono::high_resolution_clock::now(); elapsed_time = microseconds(end - start); // releasing the inputs freeMatChar(&alignedImage); freeMatFloat(&shape); freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size()); // converting the outputs std::vector< cv::Mat_<double> > calculatedResults; for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++) { cv::Mat_<double> nextResult; nextResult = convertMatFloatToCV( responseMaps[q] ); calculatedResults.push_back(nextResult); } // testing the output for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++) { // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = " // << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl; assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 1.5); if (cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) > 0.5 ) fail++; // PRINT(fail); int tolerance = 49 * conductor.id * 0.005 + 3; // PRINT(tolerance); assert(fail < tolerance); } // releasing the outputs freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size ); } // here comes the test // PRINT(cv::norm( )); } std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl; //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack); return EXIT_SUCCESS; } // LuM end of file <commit_msg>comment the memory debugger parameters<commit_after>// UjoImro, 2013 // Experimental code for the CARP Project // Copyright (c) RealEyes, 2013 // This version tests the responseMap calculation with input dumps #include <chrono> #include <string> #include <stdlib.h> #include <opencv2/core/core.hpp> #include <boost/preprocessor.hpp> #include <boost/serialization/vector.hpp> #include <boost/archive/binary_iarchive.hpp> #include "cast.h" #include "mlp.hpp" #include "mlp_impl.h" /* extern int EF_ALIGNMENT = 0; extern int EF_PROTECT_BELOW = 0; extern int EF_PROTECT_FREE = 0; extern int EF_ALLOW_MALLOC_0 = 1; extern int EF_FILL = 1922; */ namespace { struct hack_t; } MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ); mlp * convertHackToMlp ( const hack_t & hack ); void freeClassifiers( mlp * classifiers[], int size ); MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ); MatFloat convertCVToMatFloat ( const cv::Mat_<double> & input ); cv::Mat_<double> convertMatFloatToCV( MatFloat input ); void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] ); void freeResponseMaps( MatFloat * responseMaps[], int size ); namespace { struct hack_t { int m_visibleLandmarks_size; int m_mapSize; cv::Mat_<double> shape; cv::Mat_<uint8_t> alignedImage; std::vector<gel::MLP<double> > m_classifiers; std::vector<cv::Mat_<double> > responseMaps; template <class MT0> void serialize( MT0 & archiver, unsigned int ) { GEL_EXPORT_VAR( archiver, m_visibleLandmarks_size ); GEL_EXPORT_VAR( archiver, m_mapSize ); GEL_EXPORT_VAR( archiver, shape ); GEL_EXPORT_VAR( archiver, alignedImage ); GEL_EXPORT_VAR( archiver, m_classifiers ); GEL_EXPORT_VAR( archiver, responseMaps ); } // serialize }; // struct hack_t class conductor_t { public: int id; hack_t hack; std::ifstream dumpStream; boost::archive::binary_iarchive importer; public: conductor_t() : id(0), dumpStream("response_dumps.bin", std::ios::in | std::ios::binary ), importer(dumpStream) { }; // conductor_t }; // conductor_t } // unnamed namespace mlp * convertHackToMlp ( const hack_t & hack ) { assert(hack.m_visibleLandmarks_size==hack.m_classifiers.size()); assert(hack.m_visibleLandmarks_size==hack.responseMaps.size()); mlp * result; result = reinterpret_cast<mlp*>( malloc( sizeof(mlp) * hack.m_visibleLandmarks_size ) ); // we export each classifier for (int q=0; q<hack.m_visibleLandmarks_size; q++) { result[q].m_patchSize = hack.m_classifiers[q].m_patchSize; result[q].m_wIn = convertCVToMatFloat(hack.m_classifiers[q].m_wIn); result[q].m_wOut = convertCVToMatFloat(hack.m_classifiers[q].m_wOut); result[q].m_U = convertCVToMatFloat(hack.m_classifiers[q].m_U); result[q].hidden_num = hack.m_classifiers[q].hidden_num; result[q].rho2 = hack.m_classifiers[q].rho2; } // for q in m_visibleLandmarks_size return result; } // convertHackToMlp void freeClassifiers( mlp * classifiers[], int size ) { mlp * result = *classifiers; for (int q=0; q<size; q++ ) freeMLP( &(result[q]) ); free(*classifiers); *classifiers=NULL; return; } // freeClassifiers MatChar convertCVToMatChar ( const cv::Mat_<uint8_t> & input ) { MatChar result = CreateMatChar( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result.data[ q * result.step + w + result.start ] = input(q,w); return result; } // convertCVToMatChar MatFloat convertCVToMatFloat ( const cv::Mat_<double> & input ) { MatFloat result = CreateMatFloat( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result.data[ q * result.step + w + result.start ] = input(q,w); return result; } // convertCVToMatFloat cv::Mat_<double> convertMatFloatToCV( MatFloat input ) { cv::Mat_<double> result( input.rows, input.cols ); for ( int q=0; q<input.rows; q++) for ( int w=0; w<input.cols; w++ ) result(q,w) = input.data[ q * input.step + w + input.start ]; return result; } // convertMatFloatToCV void allocateResponseMaps( int mapSize, int size, MatFloat * responseMaps[] ) { *responseMaps = (MatFloat*)malloc( sizeof(MatFloat) * size ); assert(*responseMaps); MatFloat * result = *responseMaps; for ( int q=0; q<size; q++ ) result[q] = CreateMatFloat( 2 * mapSize + 1, 2 * mapSize + 1 ); return; } void freeResponseMaps( MatFloat * responseMaps[], int size ) { MatFloat * result = *responseMaps; assert(result); for ( int q=0; q<size; q++ ) freeMatFloat(&(result[q])); free(result); *responseMaps=NULL; return; } template <class T0> auto microseconds( T0 t0 ) -> decltype(std::chrono::duration_cast<std::chrono::microseconds>(t0).count()) { return std::chrono::duration_cast<std::chrono::microseconds>(t0).count(); } int main() { conductor_t conductor; int fail = 0; long int elapsed_time = 0; for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id); ((conductor.id != -1) and (conductor.id != 25)); // conductor.id != -1; conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id) ) { PRINT(conductor.id); conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack); // here comes the function call { // preparing the inputs MatChar alignedImage = convertCVToMatChar(conductor.hack.alignedImage); MatFloat shape = convertCVToMatFloat(conductor.hack.shape); mlp * m_classifiers = convertHackToMlp(conductor.hack); MatFloat * responseMaps; allocateResponseMaps( conductor.hack.m_mapSize, conductor.hack.m_visibleLandmarks_size, &responseMaps ); auto start = std::chrono::high_resolution_clock::now(); calculateMaps( conductor.hack.m_visibleLandmarks_size, conductor.hack.m_mapSize, alignedImage, shape, m_classifiers, &responseMaps ); auto end = std::chrono::high_resolution_clock::now(); elapsed_time = microseconds(end - start); // releasing the inputs freeMatChar(&alignedImage); freeMatFloat(&shape); freeClassifiers(&m_classifiers, conductor.hack.m_classifiers.size()); // converting the outputs std::vector< cv::Mat_<double> > calculatedResults; for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++) { cv::Mat_<double> nextResult; nextResult = convertMatFloatToCV( responseMaps[q] ); calculatedResults.push_back(nextResult); } // testing the output for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++) { // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = " // << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl; assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 1.5); if (cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) > 0.5 ) fail++; // PRINT(fail); int tolerance = 49 * conductor.id * 0.005 + 3; // PRINT(tolerance); assert(fail < tolerance); } // releasing the outputs freeResponseMaps( &responseMaps, conductor.hack.m_visibleLandmarks_size ); } // here comes the test // PRINT(cv::norm( )); } std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl; //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack); return EXIT_SUCCESS; } // LuM end of file <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #include <shlobj.h> #endif #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" namespace chrome { // Gets the default user data directory, regardless of whether // DIR_USER_DATA has been overridden by a command-line option. bool GetDefaultUserDataDirectory(std::wstring* result) { #if defined(OS_WIN) if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result)) return false; #if defined(GOOGLE_CHROME_BUILD) file_util::AppendToPath(result, L"Google"); #endif file_util::AppendToPath(result, chrome::kBrowserAppName); file_util::AppendToPath(result, chrome::kUserDataDirname); return true; #else // defined(OS_WIN) // TODO(port): Decide what to do on other platforms. NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) } bool GetGearsPluginPathFromCommandLine(std::wstring *path) { #ifndef NDEBUG // for debugging, support a cmd line based override CommandLine command_line; *path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride); return !path->empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifndef NDEBUG return PathService::Get(chrome::DIR_USER_DATA, result); #else return PathService::Get(base::DIR_EXE, result); #endif case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will need to create the directory if it does not already // exist. This flag can be set to true to prevent checking. bool exists = false; std::wstring cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) return false; break; case chrome::DIR_USER_DOCUMENTS: #if defined(OS_WIN) { wchar_t path_buf[MAX_PATH]; if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path_buf))) return false; cur.assign(path_buf); } #else // TODO(port): Get the path (possibly using xdg-user-dirs) // or decide we don't need it on other platforms. NOTIMPLEMENTED(); return false; #endif break; case chrome::DIR_DEFAULT_DOWNLOADS: // On Vista, we can get the download path using a Win API // (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx), // but it can be set to Desktop, which is dangerous. Instead, // we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing // 'downloads' is not a good idea because Chrome's UI language // can be changed. if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur)) return false; file_util::AppendToPath(&cur, L"Downloads"); // TODO(port): This will fail on other platforms unless we // implement DIR_USER_DOCUMENTS or use xdg-user-dirs to // get the download directory independently of DIR_USER_DOCUMENTS. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; file_util::AppendToPath(&cur, L"Crash Reports"); break; case chrome::DIR_USER_DESKTOP: #if defined(OS_WIN) { // We need to go compute the value. It would be nice to support paths // with names longer than MAX_PATH, but the system functions don't seem // to be designed for it either, with the exception of GetTempPath // (but other things will surely break if the temp path is too long, // so we don't bother handling it. wchar_t system_buffer[MAX_PATH]; system_buffer[0] = 0; if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, system_buffer))) return false; cur.assign(system_buffer); } #else // TODO(port): Get the path (possibly using xdg-user-dirs) // or decide we don't need it on other platforms. NOTIMPLEMENTED(); return false; #endif exists = true; break; case chrome::DIR_RESOURCES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"resources"); break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"Resources"); file_util::AppendToPath(&cur, L"Inspector"); exists = true; break; case chrome::DIR_THEMES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"themes"); break; case chrome::DIR_LOCALES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"locales"); break; case chrome::DIR_APP_DICTIONARIES: if (!PathService::Get(base::DIR_EXE, &cur)) return false; file_util::AppendToPath(&cur, L"Dictionaries"); break; case chrome::DIR_USER_SCRIPTS: // TODO(aa): Figure out where the script directory should live. #if defined(OS_WIN) cur = L"C:\\SCRIPTS\\"; #else NOTIMPLEMENTED(); return false; #endif exists = true; // don't trigger directory creation code break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; file_util::AppendToPath(&cur, chrome::kLocalStateFilename); exists = true; // don't trigger directory creation code break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; file_util::AppendToPath(&cur, L"script.log"); exists = true; break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!PathService::Get(base::DIR_MODULE, &cur)) return false; file_util::AppendToPath(&cur, L"gears.dll"); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; file_util::AppendToPath(&cur, L"plugins"); file_util::AppendToPath(&cur, L"gears"); file_util::AppendToPath(&cur, L"gears.dll"); } } exists = true; break; // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"test"); file_util::AppendToPath(&cur, L"data"); if (!file_util::PathExists(cur)) // we don't want to create this return false; exists = true; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"tools"); file_util::AppendToPath(&cur, L"test"); if (!file_util::PathExists(cur)) // we don't want to create this return false; exists = true; break; case chrome::FILE_PYTHON_RUNTIME: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); // chrome file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"third_party"); file_util::AppendToPath(&cur, L"python_24"); file_util::AppendToPath(&cur, L"python.exe"); if (!file_util::PathExists(cur)) // we don't want to create this return false; exists = true; break; case chrome::FILE_TEST_SERVER: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"tools"); file_util::AppendToPath(&cur, L"test"); file_util::AppendToPath(&cur, L"testserver"); file_util::AppendToPath(&cur, L"testserver.py"); if (!file_util::PathExists(cur)) // we don't want to create this return false; exists = true; break; default: return false; } if (!exists && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = FilePath::FromWStringHack(cur); return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <commit_msg>Don't create the default download directory just because we ask for its location. This is a first step toward not creating _any_ directories when we merely ask for their locations. Patch by Marc-André Decoste, r=cpu. See http://codereview.chromium.org/11586 .<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #include <shlobj.h> #endif #include "chrome/common/chrome_paths.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/sys_info.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" namespace chrome { // Gets the default user data directory, regardless of whether // DIR_USER_DATA has been overridden by a command-line option. bool GetDefaultUserDataDirectory(std::wstring* result) { #if defined(OS_WIN) if (!PathService::Get(base::DIR_LOCAL_APP_DATA, result)) return false; #if defined(GOOGLE_CHROME_BUILD) file_util::AppendToPath(result, L"Google"); #endif file_util::AppendToPath(result, chrome::kBrowserAppName); file_util::AppendToPath(result, chrome::kUserDataDirname); return true; #else // defined(OS_WIN) // TODO(port): Decide what to do on other platforms. NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) } bool GetGearsPluginPathFromCommandLine(std::wstring *path) { #ifndef NDEBUG // for debugging, support a cmd line based override CommandLine command_line; *path = command_line.GetSwitchValue(switches::kGearsPluginPathOverride); return !path->empty(); #else return false; #endif } bool PathProvider(int key, FilePath* result) { // Some keys are just aliases... switch (key) { case chrome::DIR_APP: return PathService::Get(base::DIR_MODULE, result); case chrome::DIR_LOGS: #ifndef NDEBUG return PathService::Get(chrome::DIR_USER_DATA, result); #else return PathService::Get(base::DIR_EXE, result); #endif case chrome::FILE_RESOURCE_MODULE: return PathService::Get(base::FILE_MODULE, result); } // Assume that we will not need to create the directory if it does not exist. // This flag can be set to true for the cases where we want to create it. bool create_dir = false; std::wstring cur; switch (key) { case chrome::DIR_USER_DATA: if (!GetDefaultUserDataDirectory(&cur)) return false; create_dir = true; break; case chrome::DIR_USER_DOCUMENTS: #if defined(OS_WIN) { wchar_t path_buf[MAX_PATH]; if (FAILED(SHGetFolderPath(NULL, CSIDL_MYDOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path_buf))) return false; cur.assign(path_buf); } #else // TODO(port): Get the path (possibly using xdg-user-dirs) // or decide we don't need it on other platforms. NOTIMPLEMENTED(); return false; #endif create_dir = true; break; case chrome::DIR_DEFAULT_DOWNLOADS: // On Vista, we can get the download path using a Win API // (http://msdn.microsoft.com/en-us/library/bb762584(VS.85).aspx), // but it can be set to Desktop, which is dangerous. Instead, // we just use 'Downloads' under DIR_USER_DOCUMENTS. Localizing // 'downloads' is not a good idea because Chrome's UI language // can be changed. if (!PathService::Get(chrome::DIR_USER_DOCUMENTS, &cur)) return false; file_util::AppendToPath(&cur, L"Downloads"); // TODO(port): This will fail on other platforms unless we // implement DIR_USER_DOCUMENTS or use xdg-user-dirs to // get the download directory independently of DIR_USER_DOCUMENTS. break; case chrome::DIR_CRASH_DUMPS: // The crash reports are always stored relative to the default user data // directory. This avoids the problem of having to re-initialize the // exception handler after parsing command line options, which may // override the location of the app's profile directory. if (!GetDefaultUserDataDirectory(&cur)) return false; file_util::AppendToPath(&cur, L"Crash Reports"); create_dir = true; break; case chrome::DIR_USER_DESKTOP: #if defined(OS_WIN) { // We need to go compute the value. It would be nice to support paths // with names longer than MAX_PATH, but the system functions don't seem // to be designed for it either, with the exception of GetTempPath // (but other things will surely break if the temp path is too long, // so we don't bother handling it. wchar_t system_buffer[MAX_PATH]; system_buffer[0] = 0; if (FAILED(SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, system_buffer))) return false; cur.assign(system_buffer); } #else // TODO(port): Get the path (possibly using xdg-user-dirs) // or decide we don't need it on other platforms. NOTIMPLEMENTED(); return false; #endif break; case chrome::DIR_RESOURCES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"resources"); create_dir = true; break; case chrome::DIR_INSPECTOR: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"Resources"); file_util::AppendToPath(&cur, L"Inspector"); break; case chrome::DIR_THEMES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"themes"); create_dir = true; break; case chrome::DIR_LOCALES: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::AppendToPath(&cur, L"locales"); create_dir = true; break; case chrome::DIR_APP_DICTIONARIES: if (!PathService::Get(base::DIR_EXE, &cur)) return false; file_util::AppendToPath(&cur, L"Dictionaries"); create_dir = true; break; case chrome::DIR_USER_SCRIPTS: // TODO(aa): Figure out where the script directory should live. #if defined(OS_WIN) cur = L"C:\\SCRIPTS\\"; #else NOTIMPLEMENTED(); return false; #endif break; case chrome::FILE_LOCAL_STATE: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; file_util::AppendToPath(&cur, chrome::kLocalStateFilename); break; case chrome::FILE_RECORDED_SCRIPT: if (!PathService::Get(chrome::DIR_USER_DATA, &cur)) return false; file_util::AppendToPath(&cur, L"script.log"); break; case chrome::FILE_GEARS_PLUGIN: if (!GetGearsPluginPathFromCommandLine(&cur)) { // Search for gears.dll alongside chrome.dll first. This new model // allows us to package gears.dll with the Chrome installer and update // it while Chrome is running. if (!PathService::Get(base::DIR_MODULE, &cur)) return false; file_util::AppendToPath(&cur, L"gears.dll"); if (!file_util::PathExists(cur)) { if (!PathService::Get(base::DIR_EXE, &cur)) return false; file_util::AppendToPath(&cur, L"plugins"); file_util::AppendToPath(&cur, L"gears"); file_util::AppendToPath(&cur, L"gears.dll"); } } break; // The following are only valid in the development environment, and // will fail if executed from an installed executable (because the // generated path won't exist). case chrome::DIR_TEST_DATA: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"test"); file_util::AppendToPath(&cur, L"data"); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::DIR_TEST_TOOLS: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"tools"); file_util::AppendToPath(&cur, L"test"); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::FILE_PYTHON_RUNTIME: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); // chrome file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"third_party"); file_util::AppendToPath(&cur, L"python_24"); file_util::AppendToPath(&cur, L"python.exe"); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; case chrome::FILE_TEST_SERVER: if (!PathService::Get(chrome::DIR_APP, &cur)) return false; file_util::UpOneDirectory(&cur); file_util::AppendToPath(&cur, L"tools"); file_util::AppendToPath(&cur, L"test"); file_util::AppendToPath(&cur, L"testserver"); file_util::AppendToPath(&cur, L"testserver.py"); if (!file_util::PathExists(cur)) // we don't want to create this return false; break; default: return false; } if (create_dir && !file_util::PathExists(cur) && !file_util::CreateDirectory(cur)) return false; *result = FilePath::FromWStringHack(cur); return true; } // This cannot be done as a static initializer sadly since Visual Studio will // eliminate this object file if there is no direct entry point into it. void RegisterPathProvider() { PathService::RegisterProvider(PathProvider, PATH_START, PATH_END); } } // namespace chrome <|endoftext|>
<commit_before>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <net/if.h> #include <boost/algorithm/string/trim.hpp> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/tables/networking/utils.h" namespace osquery { namespace tables { #define MAX_NETLINK_SIZE 8192 #define MAX_NETLINK_ATTEMPTS 8 constexpr auto kDefaultIpv6Route = "::"; constexpr auto kDefaultIpv4Route = "0.0.0.0"; std::string getNetlinkIP(int family, const char* buffer) { char dst[INET6_ADDRSTRLEN] = {0}; if (inet_ntop(family, buffer, dst, INET6_ADDRSTRLEN) == nullptr) { LOG(ERROR) << "Unsupported address family: " << family; return ""; } std::string address(dst); boost::trim(address); return address; } std::string getDefaultRouteIP(int family) { switch (family) { case AF_INET: return kDefaultIpv4Route; case AF_INET6: return kDefaultIpv6Route; default: LOG(ERROR) << "Unsupported address family: " << family; return ""; } } Status readNetlink(int socket_fd, int seq, char* output, size_t* size) { struct nlmsghdr* nl_hdr = nullptr; size_t message_size = 0; do { size_t latency = 0; size_t total_bytes = 0; ssize_t bytes = 0; while (bytes == 0) { bytes = recv(socket_fd, output, MAX_NETLINK_SIZE - message_size, 0); if (bytes < 0) { // Unrecoverable NETLINK error, bail. return Status(1, "Could not read from NETLINK"); } // Bytes were returned by we might need to read more. total_bytes += bytes; if (latency >= MAX_NETLINK_ATTEMPTS) { // Too many attempts to read bytes have occurred. // Prevent the NETLINK socket from handing and bail. return Status(1, "Netlink timeout"); } else if (bytes == 0) { if (total_bytes > 0) { // Bytes were read, but now no more are available, attempt to parse // the received NETLINK message. break; } ::usleep(20); latency += 1; } } // Assure valid header response, and not an error type. nl_hdr = (struct nlmsghdr*)output; if (NLMSG_OK(nl_hdr, bytes) == 0 || nl_hdr->nlmsg_type == NLMSG_ERROR) { return Status(1, "Read invalid NETLINK message"); } if (nl_hdr->nlmsg_type == NLMSG_DONE) { break; } // Move the buffer pointer output += bytes; message_size += bytes; if ((nl_hdr->nlmsg_flags & NLM_F_MULTI) == 0) { break; } } while (static_cast<pid_t>(nl_hdr->nlmsg_seq) != seq || static_cast<pid_t>(nl_hdr->nlmsg_pid) != getpid()); *size = message_size; return Status(0, "OK"); } void genNetlinkRoutes(const struct nlmsghdr* netlink_msg, QueryData& results) { std::string address; int mask = 0; char interface[IF_NAMESIZE] = {0}; struct rtmsg* message = static_cast<struct rtmsg*>(NLMSG_DATA(netlink_msg)); struct rtattr* attr = static_cast<struct rtattr*>(RTM_RTA(message)); uint32_t attr_size = RTM_PAYLOAD(netlink_msg); Row r; // Iterate over each route in the netlink message bool has_destination = false; r["metric"] = "0"; r["hopcount"] = INTEGER(0); while (RTA_OK(attr, attr_size)) { switch (attr->rta_type) { case RTA_OIF: if_indextoname(*(int*)RTA_DATA(attr), interface); r["interface"] = std::string(interface); break; case RTA_GATEWAY: address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["gateway"] = address; break; case RTA_PREFSRC: address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["source"] = address; break; case RTA_DST: if (message->rtm_dst_len != 32 && message->rtm_dst_len != 128) { mask = (int)message->rtm_dst_len; } address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["destination"] = address; has_destination = true; break; case RTA_PRIORITY: r["metric"] = INTEGER(*(int*)RTA_DATA(attr)); break; case RTA_METRICS: struct rtattr* xattr = static_cast<struct rtattr*> RTA_DATA(attr); auto xattr_size = RTA_PAYLOAD(attr); while (RTA_OK(xattr, xattr_size)) { switch (xattr->rta_type) { case RTAX_HOPLIMIT: r["hopcount"] = INTEGER(*reinterpret_cast<int*>(RTA_DATA(xattr))); break; } xattr = RTA_NEXT(xattr, xattr_size); } break; } attr = RTA_NEXT(attr, attr_size); } if (!has_destination) { r["destination"] = getDefaultRouteIP(message->rtm_family); if (message->rtm_dst_len) { mask = (int)message->rtm_dst_len; } } // Route type determination if (message->rtm_type == RTN_UNICAST) { r["type"] = "gateway"; } else if (message->rtm_type == RTN_LOCAL) { r["type"] = "local"; } else if (message->rtm_type == RTN_BROADCAST) { r["type"] = "broadcast"; } else if (message->rtm_type == RTN_ANYCAST) { r["type"] = "anycast"; } else { r["type"] = "other"; } r["flags"] = INTEGER(message->rtm_flags); // This is the cidr-formatted mask r["netmask"] = INTEGER(mask); // Fields not supported by Linux routes: r["mtu"] = "0"; results.push_back(r); } QueryData genRoutes(QueryContext& context) { QueryData results; int socket_fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (socket_fd < 0) { VLOG(1) << "Cannot open NETLINK socket"; return {}; } // Create netlink message header auto netlink_buffer = (void*)malloc(MAX_NETLINK_SIZE); if (netlink_buffer == nullptr) { close(socket_fd); return {}; } memset(netlink_buffer, 0, MAX_NETLINK_SIZE); auto netlink_msg = (struct nlmsghdr*)netlink_buffer; netlink_msg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); netlink_msg->nlmsg_type = RTM_GETROUTE; // routes from kernel routing table netlink_msg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST | NLM_F_ATOMIC; netlink_msg->nlmsg_seq = 0; netlink_msg->nlmsg_pid = getpid(); // Send the netlink request to the kernel if (send(socket_fd, netlink_msg, netlink_msg->nlmsg_len, 0) < 0) { TLOG << "Cannot write NETLINK request header to socket"; close(socket_fd); free(netlink_buffer); return {}; } // Wrap the read socket to support multi-netlink messages size_t size = 0; if (!readNetlink(socket_fd, 1, (char*)netlink_msg, &size).ok()) { TLOG << "Cannot read NETLINK response from socket"; close(socket_fd); free(netlink_buffer); return {}; } // Treat the netlink response as route information while (NLMSG_OK(netlink_msg, size)) { genNetlinkRoutes(netlink_msg, results); netlink_msg = NLMSG_NEXT(netlink_msg, size); } close(socket_fd); free(netlink_buffer); return results; } } } <commit_msg>route table: get the value of the MTU on Linux (#4981)<commit_after>/** * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under both the Apache 2.0 license (found in the * LICENSE file in the root directory of this source tree) and the GPLv2 (found * in the COPYING file in the root directory of this source tree). * You may select, at your option, one of the above-listed licenses. */ #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <net/if.h> #include <boost/algorithm/string/trim.hpp> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/tables.h> #include "osquery/tables/networking/utils.h" namespace osquery { namespace tables { #define MAX_NETLINK_SIZE 8192 #define MAX_NETLINK_ATTEMPTS 8 constexpr auto kDefaultIpv6Route = "::"; constexpr auto kDefaultIpv4Route = "0.0.0.0"; std::string getNetlinkIP(int family, const char* buffer) { char dst[INET6_ADDRSTRLEN] = {0}; if (inet_ntop(family, buffer, dst, INET6_ADDRSTRLEN) == nullptr) { LOG(ERROR) << "Unsupported address family: " << family; return ""; } std::string address(dst); boost::trim(address); return address; } std::string getDefaultRouteIP(int family) { switch (family) { case AF_INET: return kDefaultIpv4Route; case AF_INET6: return kDefaultIpv6Route; default: LOG(ERROR) << "Unsupported address family: " << family; return ""; } } Status readNetlink(int socket_fd, int seq, char* output, size_t* size) { struct nlmsghdr* nl_hdr = nullptr; size_t message_size = 0; do { size_t latency = 0; size_t total_bytes = 0; ssize_t bytes = 0; while (bytes == 0) { bytes = recv(socket_fd, output, MAX_NETLINK_SIZE - message_size, 0); if (bytes < 0) { // Unrecoverable NETLINK error, bail. return Status(1, "Could not read from NETLINK"); } // Bytes were returned by we might need to read more. total_bytes += bytes; if (latency >= MAX_NETLINK_ATTEMPTS) { // Too many attempts to read bytes have occurred. // Prevent the NETLINK socket from handing and bail. return Status(1, "Netlink timeout"); } else if (bytes == 0) { if (total_bytes > 0) { // Bytes were read, but now no more are available, attempt to parse // the received NETLINK message. break; } ::usleep(20); latency += 1; } } // Assure valid header response, and not an error type. nl_hdr = (struct nlmsghdr*)output; if (NLMSG_OK(nl_hdr, bytes) == 0 || nl_hdr->nlmsg_type == NLMSG_ERROR) { return Status(1, "Read invalid NETLINK message"); } if (nl_hdr->nlmsg_type == NLMSG_DONE) { break; } // Move the buffer pointer output += bytes; message_size += bytes; if ((nl_hdr->nlmsg_flags & NLM_F_MULTI) == 0) { break; } } while (static_cast<pid_t>(nl_hdr->nlmsg_seq) != seq || static_cast<pid_t>(nl_hdr->nlmsg_pid) != getpid()); *size = message_size; return Status(0, "OK"); } void genNetlinkRoutes(const struct nlmsghdr* netlink_msg, QueryData& results) { std::string address; int mask = 0; char interface[IF_NAMESIZE] = {0}; struct rtmsg* message = static_cast<struct rtmsg*>(NLMSG_DATA(netlink_msg)); struct rtattr* attr = static_cast<struct rtattr*>(RTM_RTA(message)); uint32_t attr_size = RTM_PAYLOAD(netlink_msg); Row r; // Iterate over each route in the netlink message bool has_destination = false; r["metric"] = "0"; r["hopcount"] = INTEGER(0); r["mtu"] = INTEGER(0); while (RTA_OK(attr, attr_size)) { switch (attr->rta_type) { case RTA_OIF: if_indextoname(*(int*)RTA_DATA(attr), interface); r["interface"] = std::string(interface); break; case RTA_GATEWAY: address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["gateway"] = address; break; case RTA_PREFSRC: address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["source"] = address; break; case RTA_DST: if (message->rtm_dst_len != 32 && message->rtm_dst_len != 128) { mask = (int)message->rtm_dst_len; } address = getNetlinkIP(message->rtm_family, (char*)RTA_DATA(attr)); r["destination"] = address; has_destination = true; break; case RTA_PRIORITY: r["metric"] = INTEGER(*(int*)RTA_DATA(attr)); break; case RTA_METRICS: struct rtattr* xattr = static_cast<struct rtattr*> RTA_DATA(attr); auto xattr_size = RTA_PAYLOAD(attr); while (RTA_OK(xattr, xattr_size)) { switch (xattr->rta_type) { case RTAX_MTU: r["mtu"] = INTEGER(*reinterpret_cast<int*>(RTA_DATA(xattr))); break; case RTAX_HOPLIMIT: r["hopcount"] = INTEGER(*reinterpret_cast<int*>(RTA_DATA(xattr))); break; } xattr = RTA_NEXT(xattr, xattr_size); } break; } attr = RTA_NEXT(attr, attr_size); } if (!has_destination) { r["destination"] = getDefaultRouteIP(message->rtm_family); if (message->rtm_dst_len) { mask = (int)message->rtm_dst_len; } } // Route type determination if (message->rtm_type == RTN_UNICAST) { r["type"] = "gateway"; } else if (message->rtm_type == RTN_LOCAL) { r["type"] = "local"; } else if (message->rtm_type == RTN_BROADCAST) { r["type"] = "broadcast"; } else if (message->rtm_type == RTN_ANYCAST) { r["type"] = "anycast"; } else { r["type"] = "other"; } r["flags"] = INTEGER(message->rtm_flags); // This is the cidr-formatted mask r["netmask"] = INTEGER(mask); results.push_back(r); } QueryData genRoutes(QueryContext& context) { QueryData results; int socket_fd = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); if (socket_fd < 0) { VLOG(1) << "Cannot open NETLINK socket"; return {}; } // Create netlink message header auto netlink_buffer = (void*)malloc(MAX_NETLINK_SIZE); if (netlink_buffer == nullptr) { close(socket_fd); return {}; } memset(netlink_buffer, 0, MAX_NETLINK_SIZE); auto netlink_msg = (struct nlmsghdr*)netlink_buffer; netlink_msg->nlmsg_len = NLMSG_LENGTH(sizeof(struct rtmsg)); netlink_msg->nlmsg_type = RTM_GETROUTE; // routes from kernel routing table netlink_msg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST | NLM_F_ATOMIC; netlink_msg->nlmsg_seq = 0; netlink_msg->nlmsg_pid = getpid(); // Send the netlink request to the kernel if (send(socket_fd, netlink_msg, netlink_msg->nlmsg_len, 0) < 0) { TLOG << "Cannot write NETLINK request header to socket"; close(socket_fd); free(netlink_buffer); return {}; } // Wrap the read socket to support multi-netlink messages size_t size = 0; if (!readNetlink(socket_fd, 1, (char*)netlink_msg, &size).ok()) { TLOG << "Cannot read NETLINK response from socket"; close(socket_fd); free(netlink_buffer); return {}; } // Treat the netlink response as route information while (NLMSG_OK(netlink_msg, size)) { genNetlinkRoutes(netlink_msg, results); netlink_msg = NLMSG_NEXT(netlink_msg, size); } close(socket_fd); free(netlink_buffer); return results; } } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/options/password_manager_handler.h" #include "base/callback.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "ui/base/l10n/l10n_util.h" PasswordManagerHandler::PasswordManagerHandler() : ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) { } PasswordManagerHandler::~PasswordManagerHandler() { } void PasswordManagerHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString("passwordsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE)); localized_strings->SetString("savedPasswordsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE)); localized_strings->SetString("passwordExceptionsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE)); localized_strings->SetString("passwordShowButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON)); localized_strings->SetString("passwordHideButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON)); localized_strings->SetString("passwordsSiteColumn", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN)); localized_strings->SetString("passwordsUsernameColumn", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN)); localized_strings->SetString("passwordsRemoveButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON)); localized_strings->SetString("passwordsRemoveAllButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON)); localized_strings->SetString("passwordsRemoveAllTitle", l10n_util::GetStringUTF16( IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS)); localized_strings->SetString("passwordsRemoveAllWarning", l10n_util::GetStringUTF16( IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS)); } void PasswordManagerHandler::Initialize() { // We should not cache dom_ui_->GetProfile(). See crosbug.com/6304. } void PasswordManagerHandler::RegisterMessages() { DCHECK(dom_ui_); dom_ui_->RegisterMessageCallback("updatePasswordLists", NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists)); dom_ui_->RegisterMessageCallback("removeSavedPassword", NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword)); dom_ui_->RegisterMessageCallback("removePasswordException", NewCallback(this, &PasswordManagerHandler::RemovePasswordException)); dom_ui_->RegisterMessageCallback("removeAllSavedPasswords", NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords)); dom_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback( this, &PasswordManagerHandler::RemoveAllPasswordExceptions)); } PasswordStore* PasswordManagerHandler::GetPasswordStore() { return dom_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS); } void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) { languages_ = dom_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages); populater_.Populate(); exception_populater_.Populate(); } void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) { std::string string_value = WideToUTF8(ExtractStringValue(args)); int index; base::StringToInt(string_value, &index); GetPasswordStore()->RemoveLogin(*password_list_[index]); delete password_list_[index]; password_list_.erase(password_list_.begin() + index); SetPasswordList(); } void PasswordManagerHandler::RemovePasswordException( const ListValue* args) { std::string string_value = WideToUTF8(ExtractStringValue(args)); int index; base::StringToInt(string_value, &index); GetPasswordStore()->RemoveLogin(*password_exception_list_[index]); delete password_exception_list_[index]; password_exception_list_.erase(password_exception_list_.begin() + index); SetPasswordExceptionList(); } void PasswordManagerHandler::RemoveAllSavedPasswords( const ListValue* args) { PasswordStore* store = GetPasswordStore(); for (size_t i = 0; i < password_list_.size(); ++i) store->RemoveLogin(*password_list_[i]); STLDeleteElements(&password_list_); SetPasswordList(); } void PasswordManagerHandler::RemoveAllPasswordExceptions( const ListValue* args) { PasswordStore* store = GetPasswordStore(); for (size_t i = 0; i < password_exception_list_.size(); ++i) store->RemoveLogin(*password_exception_list_[i]); STLDeleteElements(&password_exception_list_); SetPasswordExceptionList(); } void PasswordManagerHandler::SetPasswordList() { ListValue entries; for (size_t i = 0; i < password_list_.size(); ++i) { ListValue* entry = new ListValue(); entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin, languages_))); entry->Append(new StringValue(password_list_[i]->username_value)); entry->Append(new StringValue(password_list_[i]->password_value)); entries.Append(entry); } dom_ui_->CallJavascriptFunction( L"PasswordManager.setSavedPasswordsList", entries); } void PasswordManagerHandler::SetPasswordExceptionList() { ListValue entries; for (size_t i = 0; i < password_exception_list_.size(); ++i) { entries.Append(new StringValue( net::FormatUrl(password_exception_list_[i]->origin, languages_))); } dom_ui_->CallJavascriptFunction( L"PasswordManager.setPasswordExceptionsList", entries); } PasswordManagerHandler::ListPopulater::ListPopulater( PasswordManagerHandler* page) : page_(page), pending_login_query_(0) { } PasswordManagerHandler::ListPopulater::~ListPopulater() { page_->GetPasswordStore()->CancelLoginsQuery(pending_login_query_); } PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater( PasswordManagerHandler* page) : ListPopulater(page) { } void PasswordManagerHandler::PasswordListPopulater::Populate() { DCHECK(!pending_login_query_); PasswordStore* store = page_->GetPasswordStore(); if (store != NULL) pending_login_query_ = store->GetAutofillableLogins(this); else LOG(ERROR) << "No password store! Cannot display passwords."; } void PasswordManagerHandler::PasswordListPopulater:: OnPasswordStoreRequestDone(int handle, const std::vector<webkit_glue::PasswordForm*>& result) { DCHECK_EQ(pending_login_query_, handle); pending_login_query_ = 0; page_->password_list_ = result; page_->SetPasswordList(); } PasswordManagerHandler::PasswordExceptionListPopulater:: PasswordExceptionListPopulater(PasswordManagerHandler* page) : ListPopulater(page) { } void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() { DCHECK(!pending_login_query_); PasswordStore* store = page_->GetPasswordStore(); if (store != NULL) pending_login_query_ = store->GetBlacklistLogins(this); else LOG(ERROR) << "No password store! Cannot display exceptions."; } void PasswordManagerHandler::PasswordExceptionListPopulater:: OnPasswordStoreRequestDone(int handle, const std::vector<webkit_glue::PasswordForm*>& result) { DCHECK_EQ(pending_login_query_, handle); pending_login_query_ = 0; page_->password_exception_list_ = result; page_->SetPasswordExceptionList(); } <commit_msg>DOMUI: Check for a NULL PasswordStore, as the PasswordStore may be gone by the time ListPopulater is destroyed.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/dom_ui/options/password_manager_handler.h" #include "base/callback.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "ui/base/l10n/l10n_util.h" PasswordManagerHandler::PasswordManagerHandler() : ALLOW_THIS_IN_INITIALIZER_LIST(populater_(this)), ALLOW_THIS_IN_INITIALIZER_LIST(exception_populater_(this)) { } PasswordManagerHandler::~PasswordManagerHandler() { } void PasswordManagerHandler::GetLocalizedValues( DictionaryValue* localized_strings) { DCHECK(localized_strings); localized_strings->SetString("passwordsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE)); localized_strings->SetString("savedPasswordsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE)); localized_strings->SetString("passwordExceptionsTitle", l10n_util::GetStringUTF16(IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE)); localized_strings->SetString("passwordShowButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON)); localized_strings->SetString("passwordHideButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON)); localized_strings->SetString("passwordsSiteColumn", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_SITE_COLUMN)); localized_strings->SetString("passwordsUsernameColumn", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_USERNAME_COLUMN)); localized_strings->SetString("passwordsRemoveButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_REMOVE_BUTTON)); localized_strings->SetString("passwordsRemoveAllButton", l10n_util::GetStringUTF16(IDS_PASSWORDS_PAGE_VIEW_REMOVE_ALL_BUTTON)); localized_strings->SetString("passwordsRemoveAllTitle", l10n_util::GetStringUTF16( IDS_PASSWORDS_PAGE_VIEW_CAPTION_DELETE_ALL_PASSWORDS)); localized_strings->SetString("passwordsRemoveAllWarning", l10n_util::GetStringUTF16( IDS_PASSWORDS_PAGE_VIEW_TEXT_DELETE_ALL_PASSWORDS)); } void PasswordManagerHandler::Initialize() { // We should not cache dom_ui_->GetProfile(). See crosbug.com/6304. } void PasswordManagerHandler::RegisterMessages() { DCHECK(dom_ui_); dom_ui_->RegisterMessageCallback("updatePasswordLists", NewCallback(this, &PasswordManagerHandler::UpdatePasswordLists)); dom_ui_->RegisterMessageCallback("removeSavedPassword", NewCallback(this, &PasswordManagerHandler::RemoveSavedPassword)); dom_ui_->RegisterMessageCallback("removePasswordException", NewCallback(this, &PasswordManagerHandler::RemovePasswordException)); dom_ui_->RegisterMessageCallback("removeAllSavedPasswords", NewCallback(this, &PasswordManagerHandler::RemoveAllSavedPasswords)); dom_ui_->RegisterMessageCallback("removeAllPasswordExceptions", NewCallback( this, &PasswordManagerHandler::RemoveAllPasswordExceptions)); } PasswordStore* PasswordManagerHandler::GetPasswordStore() { return dom_ui_->GetProfile()->GetPasswordStore(Profile::EXPLICIT_ACCESS); } void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) { languages_ = dom_ui_->GetProfile()->GetPrefs()->GetString(prefs::kAcceptLanguages); populater_.Populate(); exception_populater_.Populate(); } void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) { std::string string_value = WideToUTF8(ExtractStringValue(args)); int index; base::StringToInt(string_value, &index); GetPasswordStore()->RemoveLogin(*password_list_[index]); delete password_list_[index]; password_list_.erase(password_list_.begin() + index); SetPasswordList(); } void PasswordManagerHandler::RemovePasswordException( const ListValue* args) { std::string string_value = WideToUTF8(ExtractStringValue(args)); int index; base::StringToInt(string_value, &index); GetPasswordStore()->RemoveLogin(*password_exception_list_[index]); delete password_exception_list_[index]; password_exception_list_.erase(password_exception_list_.begin() + index); SetPasswordExceptionList(); } void PasswordManagerHandler::RemoveAllSavedPasswords( const ListValue* args) { PasswordStore* store = GetPasswordStore(); for (size_t i = 0; i < password_list_.size(); ++i) store->RemoveLogin(*password_list_[i]); STLDeleteElements(&password_list_); SetPasswordList(); } void PasswordManagerHandler::RemoveAllPasswordExceptions( const ListValue* args) { PasswordStore* store = GetPasswordStore(); for (size_t i = 0; i < password_exception_list_.size(); ++i) store->RemoveLogin(*password_exception_list_[i]); STLDeleteElements(&password_exception_list_); SetPasswordExceptionList(); } void PasswordManagerHandler::SetPasswordList() { ListValue entries; for (size_t i = 0; i < password_list_.size(); ++i) { ListValue* entry = new ListValue(); entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin, languages_))); entry->Append(new StringValue(password_list_[i]->username_value)); entry->Append(new StringValue(password_list_[i]->password_value)); entries.Append(entry); } dom_ui_->CallJavascriptFunction( L"PasswordManager.setSavedPasswordsList", entries); } void PasswordManagerHandler::SetPasswordExceptionList() { ListValue entries; for (size_t i = 0; i < password_exception_list_.size(); ++i) { entries.Append(new StringValue( net::FormatUrl(password_exception_list_[i]->origin, languages_))); } dom_ui_->CallJavascriptFunction( L"PasswordManager.setPasswordExceptionsList", entries); } PasswordManagerHandler::ListPopulater::ListPopulater( PasswordManagerHandler* page) : page_(page), pending_login_query_(0) { } PasswordManagerHandler::ListPopulater::~ListPopulater() { PasswordStore* store = page_->GetPasswordStore(); if (store) store->CancelLoginsQuery(pending_login_query_); } PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater( PasswordManagerHandler* page) : ListPopulater(page) { } void PasswordManagerHandler::PasswordListPopulater::Populate() { DCHECK(!pending_login_query_); PasswordStore* store = page_->GetPasswordStore(); if (store != NULL) pending_login_query_ = store->GetAutofillableLogins(this); else LOG(ERROR) << "No password store! Cannot display passwords."; } void PasswordManagerHandler::PasswordListPopulater:: OnPasswordStoreRequestDone(int handle, const std::vector<webkit_glue::PasswordForm*>& result) { DCHECK_EQ(pending_login_query_, handle); pending_login_query_ = 0; page_->password_list_ = result; page_->SetPasswordList(); } PasswordManagerHandler::PasswordExceptionListPopulater:: PasswordExceptionListPopulater(PasswordManagerHandler* page) : ListPopulater(page) { } void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() { DCHECK(!pending_login_query_); PasswordStore* store = page_->GetPasswordStore(); if (store != NULL) pending_login_query_ = store->GetBlacklistLogins(this); else LOG(ERROR) << "No password store! Cannot display exceptions."; } void PasswordManagerHandler::PasswordExceptionListPopulater:: OnPasswordStoreRequestDone(int handle, const std::vector<webkit_glue::PasswordForm*>& result) { DCHECK_EQ(pending_login_query_, handle); pending_login_query_ = 0; page_->password_exception_list_ = result; page_->SetPasswordExceptionList(); } <|endoftext|>
<commit_before>/// /// @file popcnt.hpp /// @brief Functions to count the number of 1 bits inside /// an array or a 64-bit word. /// /// Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POPCNT_HPP #define POPCNT_HPP #include <stdint.h> #if defined(__has_include) #define HAS_INCLUDE(header) __has_include(header) #else // If the __has_include() macro does not exist // we assume that the header file exists. #define HAS_INCLUDE(header) 1 #endif #if defined(ENABLE_POPCNT) #if !defined(__has_builtin) #define __has_builtin(x) 0 #endif // GCC & Clang #if defined(__GNUC__) || \ __has_builtin(__builtin_popcountll) namespace { inline uint64_t popcnt64(uint64_t x) { return __builtin_popcountll(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN64) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u64(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN32) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u32((uint32_t) x) + _mm_popcnt_u32((uint32_t)(x >> 32)); } } // namespace #else // Since hardware popcount support is very important for // performance in primecount we want the compilation to fail in // case the compiler does not select any of the implementations // above (which use compiler intrinsics to enable hardware // popcount support). This way we can be relatively sure that // when primecount has been compiled successfully, primecount // will have hardware popcount support. #error "No fast popcount function implemented for this compiler!" #endif #endif namespace { #if !defined(ENABLE_POPCNT) /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// inline uint64_t popcnt64(uint64_t x) { uint64_t m1 = 0x5555555555555555ull; uint64_t m2 = 0x3333333333333333ull; uint64_t m4 = 0x0F0F0F0F0F0F0F0Full; uint64_t h01 = 0x0101010101010101ull; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } #endif } // namespace #endif // POPCNT_HPP <commit_msg>Fallback to std::popcount<commit_after>/// /// @file popcnt.hpp /// @brief Functions to count the number of 1 bits inside /// an array or a 64-bit word. /// /// Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef POPCNT_HPP #define POPCNT_HPP #include <stdint.h> #if defined(__has_include) #define HAS_INCLUDE(header) __has_include(header) #else // If the __has_include() macro does not exist // we assume that the header file exists. #define HAS_INCLUDE(header) 1 #endif #if defined(ENABLE_POPCNT) #if !defined(__has_builtin) #define __has_builtin(x) 0 #endif // GCC & Clang #if defined(__GNUC__) || \ __has_builtin(__builtin_popcountll) namespace { inline uint64_t popcnt64(uint64_t x) { return __builtin_popcountll(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN64) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u64(x); } } // namespace #elif defined(_MSC_VER) && \ defined(_WIN32) && \ HAS_INCLUDE(<nmmintrin.h>) #include <nmmintrin.h> namespace { inline uint64_t popcnt64(uint64_t x) { return _mm_popcnt_u32((uint32_t) x) + _mm_popcnt_u32((uint32_t)(x >> 32)); } } // namespace #else #include <bit> namespace { /// Ideally we would like to std::popcount instead of the /// intrinsics above. However std::popcount is from C++20 and /// not yet widely supported. Also the assembly generated by /// std::popcount is not as good as __builtin_popcountll on /// x64 with the Clang compiler. This will likely be fixed in /// a few years. /// inline uint64_t popcnt64(uint64_t x) { return std::popcount(x); } } // namespace #endif #endif namespace { #if !defined(ENABLE_POPCNT) /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// inline uint64_t popcnt64(uint64_t x) { uint64_t m1 = 0x5555555555555555ull; uint64_t m2 = 0x3333333333333333ull; uint64_t m4 = 0x0F0F0F0F0F0F0F0Full; uint64_t h01 = 0x0101010101010101ull; x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } #endif } // namespace #endif // POPCNT_HPP <|endoftext|>
<commit_before>/// /// @file ptypes.hpp /// @brief Convenience functions and typedefs for the non standard /// __int128_t integer type. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PTYPES_HPP #define PTYPES_HPP #if defined(HAVE_INT128_T) #include <stdint.h> namespace primecount { typedef int128_t maxint_t; } #elif defined(HAVE___INT128_T) // int128_t is a typedef for __int128_t #define HAVE_INT128_T #include <ostream> #include <string> namespace primecount { typedef __int128_t maxint_t; typedef __int128_t int128_t; inline std::ostream& operator<<(std::ostream& stream, int128_t n) { std::string str; while (n > 0) { str += '0' + n % 10; n /= 10; } stream << std::string(str.rbegin(), str.rend()); return stream; } } // namespace #else /* int128_t not supported */ namespace primecount { typedef int64_t maxint_t; } #endif #endif /* PTYPES_HPP */ <commit_msg>Fix int64_t undefined type<commit_after>/// /// @file ptypes.hpp /// @brief Convenience functions and typedefs for the non standard /// __int128_t integer type. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PTYPES_HPP #define PTYPES_HPP #include <stdint.h> #if defined(HAVE_INT128_T) namespace primecount { typedef int128_t maxint_t; } #elif defined(HAVE___INT128_T) // int128_t is a typedef for __int128_t #define HAVE_INT128_T #include <ostream> #include <string> namespace primecount { typedef __int128_t maxint_t; typedef __int128_t int128_t; inline std::ostream& operator<<(std::ostream& stream, int128_t n) { std::string str; while (n > 0) { str += '0' + n % 10; n /= 10; } stream << std::string(str.rbegin(), str.rend()); return stream; } } // namespace #else /* int128_t not supported */ namespace primecount { typedef int64_t maxint_t; } #endif #endif /* PTYPES_HPP */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 <memory> #include <string> #include <thread> #include "cyber/cyber.h" #include "modules/drivers/velodyne/parser/velodyne_convert_component.h" namespace apollo { namespace drivers { namespace velodyne { bool VelodyneConvertComponent::Init() { Config velodyne_config; if (!GetProtoConfig(&velodyne_config)) { AWARN << "Load config failed, config file" << config_file_path_; return false; } conv_.reset(new Convert()); conv_->init(velodyne_config); writer_ = node_->CreateWriter<PointCloud>(velodyne_config.convert_channel_name()); point_cloud_pool_.reset(new CCObjectPool<PointCloud>(pool_size_)); point_cloud_pool_->ConstructAll(); for (int i = 0; i < pool_size_; i++) { auto point_cloud = point_cloud_pool_->GetObject(); if (point_cloud == nullptr) { AERROR << "fail to getobject, i: " << i; return false; } point_cloud->mutable_point()->Reserve(140000); } AINFO << "Point cloud comp convert init success"; return true; } bool VelodyneConvertComponent::Proc( const std::shared_ptr<VelodyneScan>& scan_msg) { std::shared_ptr<PointCloud> point_cloud_out = point_cloud_pool_->GetObject(); if (point_cloud_out == nullptr) { AWARN << "poin cloud pool return nullptr, will be create new."; point_cloud_out = std::make_shared<PointCloud>(); point_cloud_out->mutable_point()->Reserve(140000); } if (point_cloud_out == nullptr) { AWARN << "point cloud out is nullptr"; return false; } AINFO << "Clear before bytes:" << point_cloud_out->ByteSize(); point_cloud_out->Clear(); AINFO << "Clear after bytes:" << point_cloud_out->ByteSize(); AINFO << "SpaceUsedExcludingSelf: " << point_cloud_out->mutable_point()->SpaceUsedExcludingSelf() << ", ClearedCount:" << point_cloud_out->mutable_point()->ClearedCount(); conv_->ConvertPacketsToPointcloud(scan_msg, point_cloud_out); if (point_cloud_out == nullptr || point_cloud_out->point_size() == 0) { AWARN << "point_cloud_out convert is empty."; return false; } writer_->Write(point_cloud_out); return true; } } // namespace velodyne } // namespace drivers } // namespace apollo <commit_msg>Drivers: clear velodyne debug log<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 <memory> #include <string> #include <thread> #include "cyber/cyber.h" #include "modules/drivers/velodyne/parser/velodyne_convert_component.h" namespace apollo { namespace drivers { namespace velodyne { bool VelodyneConvertComponent::Init() { Config velodyne_config; if (!GetProtoConfig(&velodyne_config)) { AWARN << "Load config failed, config file" << config_file_path_; return false; } conv_.reset(new Convert()); conv_->init(velodyne_config); writer_ = node_->CreateWriter<PointCloud>(velodyne_config.convert_channel_name()); point_cloud_pool_.reset(new CCObjectPool<PointCloud>(pool_size_)); point_cloud_pool_->ConstructAll(); for (int i = 0; i < pool_size_; i++) { auto point_cloud = point_cloud_pool_->GetObject(); if (point_cloud == nullptr) { AERROR << "fail to getobject, i: " << i; return false; } point_cloud->mutable_point()->Reserve(140000); } AINFO << "Point cloud comp convert init success"; return true; } bool VelodyneConvertComponent::Proc( const std::shared_ptr<VelodyneScan>& scan_msg) { std::shared_ptr<PointCloud> point_cloud_out = point_cloud_pool_->GetObject(); if (point_cloud_out == nullptr) { AWARN << "poin cloud pool return nullptr, will be create new."; point_cloud_out = std::make_shared<PointCloud>(); point_cloud_out->mutable_point()->Reserve(140000); } if (point_cloud_out == nullptr) { AWARN << "point cloud out is nullptr"; return false; } point_cloud_out->Clear(); conv_->ConvertPacketsToPointcloud(scan_msg, point_cloud_out); if (point_cloud_out == nullptr || point_cloud_out->point_size() == 0) { AWARN << "point_cloud_out convert is empty."; return false; } writer_->Write(point_cloud_out); return true; } } // namespace velodyne } // namespace drivers } // namespace apollo <|endoftext|>
<commit_before><commit_msg>Prediction: also SetNearbyObstacles for ego_vehicle<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1==a+b&& k1>0 && i>=k1){ printf("%d %d\n",i,k1); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0 && i>=k2){ printf("%d %d\n",i,k2); } int k3=sqrt(b-a); if(k3*k3+a==b&& k3>0 && i>=k3){ printf("%d %d\n",i,k3); } } if(t>=1) printf("\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<commit_msg>update uoj1079<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); void Init(){ return ; } void Solve(int t){ int n; scanf("%d",&n); int a=n*n; REPD(i,2051,3){ int b=i*i; int k1=sqrt(a+b); if(k1*k1==a+b&& k1>0 && i>=k1){ printf("%d %d\n",i,k1); } int k2=sqrt(a-b); if(k2*k2+b==a&& k2>0 && i>=k2){ printf("%d %d\n",i,k2); } int k3=sqrt(b-a); if(k3*k3+a==b&& k3>0 && i>=k3){ printf("%d %d\n",i,k3); } } if(t>=1) printf("1\n"); return ; } int main(){ freopen("uoj1079.in","r",stdin); int t; scanf("%d",&t); while(t--) Init(),Solve(t); return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/engine/post_commit_message_command.h" #include <vector> #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/util/sync_types.h" using std::vector; namespace browser_sync { PostCommitMessageCommand::PostCommitMessageCommand() {} PostCommitMessageCommand::~PostCommitMessageCommand() {} void PostCommitMessageCommand::ExecuteImpl(sessions::SyncSession* session) { if (session->status_controller()->commit_ids().empty()) return; // Nothing to commit. ClientToServerResponse response; syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) return; sessions::StatusController* status = session->status_controller(); if (!SyncerProtoUtil::PostClientToServerMessage( status->mutable_commit_message(), &response, session)) { // None of our changes got through, let's clear sync flags and wait for // another list update. status->increment_num_consecutive_problem_commits(); status->increment_num_consecutive_errors(); syncable::WriteTransaction trans(dir, syncable::SYNCER, __FILE__, __LINE__); // TODO(sync): why set this flag, it seems like a bad side-effect? const vector<syncable::Id>& commit_ids = status->commit_ids(); for (size_t i = 0; i < commit_ids.size(); i++) { syncable::MutableEntry entry(&trans, syncable::GET_BY_ID, commit_ids[i]); entry.Put(syncable::SYNCING, false); } return; } else { status->set_items_committed(true); } status->mutable_commit_response()->CopyFrom(response); } } // namespace browser_sync <commit_msg>Remove a TODO in post_commit_command.cc. Clarify what's going on.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/engine/post_commit_message_command.h" #include <vector> #include "chrome/browser/sync/engine/syncer_proto_util.h" #include "chrome/browser/sync/engine/syncproto.h" #include "chrome/browser/sync/sessions/sync_session.h" #include "chrome/browser/sync/syncable/directory_manager.h" #include "chrome/browser/sync/util/sync_types.h" using std::vector; namespace browser_sync { PostCommitMessageCommand::PostCommitMessageCommand() {} PostCommitMessageCommand::~PostCommitMessageCommand() {} void PostCommitMessageCommand::ExecuteImpl(sessions::SyncSession* session) { if (session->status_controller()->commit_ids().empty()) return; // Nothing to commit. ClientToServerResponse response; syncable::ScopedDirLookup dir(session->context()->directory_manager(), session->context()->account_name()); if (!dir.good()) return; sessions::StatusController* status = session->status_controller(); if (!SyncerProtoUtil::PostClientToServerMessage( status->mutable_commit_message(), &response, session)) { // None of our changes got through. Clear the SYNCING bit which was // set to true during BuildCommitCommand, and which may still be true. // Not to be confused with IS_UNSYNCED. This bit is used to detect local // changes to items that happen during the server Commit operation. status->increment_num_consecutive_problem_commits(); status->increment_num_consecutive_errors(); syncable::WriteTransaction trans(dir, syncable::SYNCER, __FILE__, __LINE__); const vector<syncable::Id>& commit_ids = status->commit_ids(); for (size_t i = 0; i < commit_ids.size(); i++) { syncable::MutableEntry entry(&trans, syncable::GET_BY_ID, commit_ids[i]); entry.Put(syncable::SYNCING, false); } return; } else { status->set_items_committed(true); } status->mutable_commit_response()->CopyFrom(response); } } // namespace browser_sync <|endoftext|>
<commit_before>// Copyright 2017 Google LLC // // 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 "riegeli/bytes/message_parse.h" #include <stddef.h> #include <limits> #include <tuple> #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/message_lite.h" #include "riegeli/base/base.h" #include "riegeli/base/canonical_errors.h" #include "riegeli/base/chain.h" #include "riegeli/base/status.h" #include "riegeli/bytes/chain_reader.h" #include "riegeli/bytes/reader.h" namespace riegeli { namespace { // ReaderInputStream adapts a Reader to a ZeroCopyInputStream. class ReaderInputStream : public google::protobuf::io::ZeroCopyInputStream { public: explicit ReaderInputStream(Reader* src) : src_(RIEGELI_ASSERT_NOTNULL(src)), initial_pos_(src_->pos()) {} bool Next(const void** data, int* size) override; void BackUp(int length) override; bool Skip(int length) override; google::protobuf::int64 ByteCount() const override; private: Position relative_pos() const; Reader* src_; // Invariants: // src_->pos() >= initial_pos_ // src_->pos() - initial_pos_ <= // numeric_limits<google::protobuf::int64>::max() Position initial_pos_; }; inline Position ReaderInputStream::relative_pos() const { RIEGELI_ASSERT_GE(src_->pos(), initial_pos_) << "Failed invariant of ReaderInputStream: " "current position smaller than initial position"; const Position pos = src_->pos() - initial_pos_; RIEGELI_ASSERT_LE( pos, Position{std::numeric_limits<google::protobuf::int64>::max()}) << "Failed invariant of ReaderInputStream: " "relative position overflow"; return pos; } bool ReaderInputStream::Next(const void** data, int* size) { const Position pos = relative_pos(); if (ABSL_PREDICT_FALSE( pos == Position{std::numeric_limits<google::protobuf::int64>::max()})) { return false; } if (ABSL_PREDICT_FALSE(!src_->Pull())) return false; *data = src_->cursor(); *size = IntCast<int>(UnsignedMin( src_->available(), size_t{std::numeric_limits<int>::max()}, Position{std::numeric_limits<google::protobuf::int64>::max()} - pos)); src_->set_cursor(src_->cursor() + *size); return true; } void ReaderInputStream::BackUp(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "negative length"; RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->read_from_buffer()) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "length larger than the amount of buffered data"; src_->set_cursor(src_->cursor() - length); } bool ReaderInputStream::Skip(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::Skip(): negative length"; const Position max_length = Position{std::numeric_limits<google::protobuf::int64>::max()} - relative_pos(); if (ABSL_PREDICT_FALSE(IntCast<size_t>(length) > max_length)) { src_->Skip(max_length); return false; } return src_->Skip(IntCast<size_t>(length)); } google::protobuf::int64 ReaderInputStream::ByteCount() const { return IntCast<google::protobuf::int64>(relative_pos()); } } // namespace namespace internal { Status ParseFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderImpl(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { ReaderInputStream input_stream(src); if (ABSL_PREDICT_FALSE( !dest->ParsePartialFromZeroCopyStream(&input_stream))) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } // namespace internal Status ParseFromChain(google::protobuf::MessageLite* dest, const Chain& src) { return ParseFromReader<ChainReader<>>(dest, std::forward_as_tuple(&src)); } Status ParsePartialFromChain(google::protobuf::MessageLite* dest, const Chain& src) { return ParsePartialFromReader<ChainReader<>>(dest, std::forward_as_tuple(&src)); } } // namespace riegeli <commit_msg>Speed up Parse{,Partial}From{Reader,Chain}() for small inputs: if the input is flat, use ParsePartialFromArray() instead of ParsePartialFromZeroCopyStream().<commit_after>// Copyright 2017 Google LLC // // 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 "riegeli/bytes/message_parse.h" #include <stddef.h> #include <limits> #include <tuple> #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/message_lite.h" #include "riegeli/base/base.h" #include "riegeli/base/canonical_errors.h" #include "riegeli/base/chain.h" #include "riegeli/base/status.h" #include "riegeli/bytes/chain_reader.h" #include "riegeli/bytes/reader.h" namespace riegeli { namespace { // ReaderInputStream adapts a Reader to a ZeroCopyInputStream. class ReaderInputStream : public google::protobuf::io::ZeroCopyInputStream { public: explicit ReaderInputStream(Reader* src) : src_(RIEGELI_ASSERT_NOTNULL(src)), initial_pos_(src_->pos()) {} bool Next(const void** data, int* size) override; void BackUp(int length) override; bool Skip(int length) override; google::protobuf::int64 ByteCount() const override; private: Position relative_pos() const; Reader* src_; // Invariants: // src_->pos() >= initial_pos_ // src_->pos() - initial_pos_ <= // numeric_limits<google::protobuf::int64>::max() Position initial_pos_; }; inline Position ReaderInputStream::relative_pos() const { RIEGELI_ASSERT_GE(src_->pos(), initial_pos_) << "Failed invariant of ReaderInputStream: " "current position smaller than initial position"; const Position pos = src_->pos() - initial_pos_; RIEGELI_ASSERT_LE( pos, Position{std::numeric_limits<google::protobuf::int64>::max()}) << "Failed invariant of ReaderInputStream: " "relative position overflow"; return pos; } bool ReaderInputStream::Next(const void** data, int* size) { const Position pos = relative_pos(); if (ABSL_PREDICT_FALSE( pos == Position{std::numeric_limits<google::protobuf::int64>::max()})) { return false; } if (ABSL_PREDICT_FALSE(!src_->Pull())) return false; *data = src_->cursor(); *size = IntCast<int>(UnsignedMin( src_->available(), size_t{std::numeric_limits<int>::max()}, Position{std::numeric_limits<google::protobuf::int64>::max()} - pos)); src_->set_cursor(src_->cursor() + *size); return true; } void ReaderInputStream::BackUp(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "negative length"; RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->read_from_buffer()) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "length larger than the amount of buffered data"; src_->set_cursor(src_->cursor() - length); } bool ReaderInputStream::Skip(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::Skip(): negative length"; const Position max_length = Position{std::numeric_limits<google::protobuf::int64>::max()} - relative_pos(); if (ABSL_PREDICT_FALSE(IntCast<size_t>(length) > max_length)) { src_->Skip(max_length); return false; } return src_->Skip(IntCast<size_t>(length)); } google::protobuf::int64 ReaderInputStream::ByteCount() const { return IntCast<google::protobuf::int64>(relative_pos()); } } // namespace namespace internal { Status ParseFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderImpl(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { if (src->SupportsRandomAccess()) { Position size; if (ABSL_PREDICT_FALSE(!src->Size(&size))) return src->status(); src->Pull(); if (src->pos() + src->available() == size && ABSL_PREDICT_TRUE(src->available() <= size_t{std::numeric_limits<int>::max()})) { // The data are flat. ParsePartialFromArray() is faster than // ParsePartialFromZeroCopyStream(). bool ok = dest->ParsePartialFromArray(src->cursor(), IntCast<int>(src->available())); src->set_cursor(src->cursor() + src->available()); if (ABSL_PREDICT_FALSE(!ok)) { return DataLossError(absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } ReaderInputStream input_stream(src); if (ABSL_PREDICT_FALSE( !dest->ParsePartialFromZeroCopyStream(&input_stream))) { if (ABSL_PREDICT_FALSE(!src->healthy())) return src->status(); return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } // namespace internal Status ParseFromChain(google::protobuf::MessageLite* dest, const Chain& src) { return ParseFromReader<ChainReader<>>(dest, std::forward_as_tuple(&src)); } Status ParsePartialFromChain(google::protobuf::MessageLite* dest, const Chain& src) { return ParsePartialFromReader<ChainReader<>>(dest, std::forward_as_tuple(&src)); } } // namespace riegeli <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////// // File: fullyconnected.cpp // Description: Simple feed-forward layer with various non-linearities. // Author: Ray Smith // Created: Wed Feb 26 14:49:15 PST 2014 // // (C) Copyright 2014, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////// #include "fullyconnected.h" #ifdef _OPENMP #include <omp.h> #endif #include <stdio.h> #include <stdlib.h> #include "functions.h" #include "networkscratch.h" // Number of threads to use for parallel calculation of Forward and Backward. const int kNumThreads = 4; namespace tesseract { FullyConnected::FullyConnected(const STRING& name, int ni, int no, NetworkType type) : Network(type, name, ni, no), external_source_(NULL), int_mode_(false) { } FullyConnected::~FullyConnected() { } // Returns the shape output from the network given an input shape (which may // be partially unknown ie zero). StaticShape FullyConnected::OutputShape(const StaticShape& input_shape) const { LossType loss_type = LT_NONE; if (type_ == NT_SOFTMAX) loss_type = LT_CTC; else if (type_ == NT_SOFTMAX_NO_CTC) loss_type = LT_SOFTMAX; else if (type_ == NT_LOGISTIC) loss_type = LT_LOGISTIC; StaticShape result(input_shape); result.set_depth(no_); result.set_loss_type(loss_type); return result; } // Suspends/Enables training by setting the training_ flag. void FullyConnected::SetEnableTraining(TrainingState state) { if (state == TS_RE_ENABLE) { // Enable only from temp disabled. if (training_ == TS_TEMP_DISABLE) training_ = TS_ENABLED; } else if (state == TS_TEMP_DISABLE) { // Temp disable only from enabled. if (training_ == TS_ENABLED) training_ = state; } else { if (state == TS_ENABLED && training_ != TS_ENABLED) weights_.InitBackward(); training_ = state; } } // Sets up the network for training. Initializes weights using weights of // scale `range` picked according to the random number generator `randomizer`. int FullyConnected::InitWeights(float range, TRand* randomizer) { Network::SetRandomizer(randomizer); num_weights_ = weights_.InitWeightsFloat(no_, ni_ + 1, TestFlag(NF_ADA_GRAD), range, randomizer); return num_weights_; } // Converts a float network to an int network. void FullyConnected::ConvertToInt() { weights_.ConvertToInt(); } // Provides debug output on the weights. void FullyConnected::DebugWeights() { weights_.Debug2D(name_.string()); } // Writes to the given file. Returns false in case of error. bool FullyConnected::Serialize(TFile* fp) const { if (!Network::Serialize(fp)) return false; if (!weights_.Serialize(IsTraining(), fp)) return false; return true; } // Reads from the given file. Returns false in case of error. bool FullyConnected::DeSerialize(TFile* fp) { return weights_.DeSerialize(IsTraining(), fp); } // Runs forward propagation of activations on the input line. // See NetworkCpp for a detailed discussion of the arguments. void FullyConnected::Forward(bool debug, const NetworkIO& input, const TransposedArray* input_transpose, NetworkScratch* scratch, NetworkIO* output) { int width = input.Width(); if (type_ == NT_SOFTMAX) output->ResizeFloat(input, no_); else output->Resize(input, no_); SetupForward(input, input_transpose); GenericVector<NetworkScratch::FloatVec> temp_lines; temp_lines.init_to_size(kNumThreads, NetworkScratch::FloatVec()); GenericVector<NetworkScratch::FloatVec> curr_input; curr_input.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < temp_lines.size(); ++i) { temp_lines[i].Init(no_, scratch); curr_input[i].Init(ni_, scratch); } #ifdef _OPENMP #pragma omp parallel for num_threads(kNumThreads) for (int t = 0; t < width; ++t) { // Thread-local pointer to temporary storage. int thread_id = omp_get_thread_num(); #else for (int t = 0; t < width; ++t) { // Thread-local pointer to temporary storage. int thread_id = 0; #endif double* temp_line = temp_lines[thread_id]; const double* d_input = NULL; const inT8* i_input = NULL; if (input.int_mode()) { i_input = input.i(t); } else { input.ReadTimeStep(t, curr_input[thread_id]); d_input = curr_input[thread_id]; } ForwardTimeStep(d_input, i_input, t, temp_line); output->WriteTimeStep(t, temp_line); if (IsTraining() && type_ != NT_SOFTMAX) { acts_.CopyTimeStepFrom(t, *output, t); } } // Zero all the elements that are in the padding around images that allows // multiple different-sized images to exist in a single array. // acts_ is only used if this is not a softmax op. if (IsTraining() && type_ != NT_SOFTMAX) { acts_.ZeroInvalidElements(); } output->ZeroInvalidElements(); #if DEBUG_DETAIL > 0 tprintf("F Output:%s\n", name_.string()); output->Print(10); #endif if (debug) DisplayForward(*output); } // Components of Forward so FullyConnected can be reused inside LSTM. void FullyConnected::SetupForward(const NetworkIO& input, const TransposedArray* input_transpose) { // Softmax output is always float, so save the input type. int_mode_ = input.int_mode(); if (IsTraining()) { acts_.Resize(input, no_); // Source_ is a transposed copy of input. It isn't needed if provided. external_source_ = input_transpose; if (external_source_ == NULL) source_t_.ResizeNoInit(ni_, input.Width()); } } void FullyConnected::ForwardTimeStep(const double* d_input, const inT8* i_input, int t, double* output_line) { // input is copied to source_ line-by-line for cache coherency. if (IsTraining() && external_source_ == NULL && d_input != NULL) source_t_.WriteStrided(t, d_input); if (d_input != NULL) weights_.MatrixDotVector(d_input, output_line); else weights_.MatrixDotVector(i_input, output_line); if (type_ == NT_TANH) { FuncInplace<GFunc>(no_, output_line); } else if (type_ == NT_LOGISTIC) { FuncInplace<FFunc>(no_, output_line); } else if (type_ == NT_POSCLIP) { FuncInplace<ClipFFunc>(no_, output_line); } else if (type_ == NT_SYMCLIP) { FuncInplace<ClipGFunc>(no_, output_line); } else if (type_ == NT_RELU) { FuncInplace<Relu>(no_, output_line); } else if (type_ == NT_SOFTMAX || type_ == NT_SOFTMAX_NO_CTC) { SoftmaxInPlace(no_, output_line); } else if (type_ != NT_LINEAR) { ASSERT_HOST("Invalid fully-connected type!" == NULL); } } // Runs backward propagation of errors on the deltas line. // See NetworkCpp for a detailed discussion of the arguments. bool FullyConnected::Backward(bool debug, const NetworkIO& fwd_deltas, NetworkScratch* scratch, NetworkIO* back_deltas) { if (debug) DisplayBackward(fwd_deltas); back_deltas->Resize(fwd_deltas, ni_); GenericVector<NetworkScratch::FloatVec> errors; errors.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < errors.size(); ++i) errors[i].Init(no_, scratch); GenericVector<NetworkScratch::FloatVec> temp_backprops; if (needs_to_backprop_) { temp_backprops.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < kNumThreads; ++i) temp_backprops[i].Init(ni_, scratch); } int width = fwd_deltas.Width(); NetworkScratch::GradientStore errors_t; errors_t.Init(no_, width, scratch); #ifdef _OPENMP #pragma omp parallel for num_threads(kNumThreads) for (int t = 0; t < width; ++t) { int thread_id = omp_get_thread_num(); #else for (int t = 0; t < width; ++t) { int thread_id = 0; #endif double* backprop = NULL; if (needs_to_backprop_) backprop = temp_backprops[thread_id]; double* curr_errors = errors[thread_id]; BackwardTimeStep(fwd_deltas, t, curr_errors, errors_t.get(), backprop); if (backprop != NULL) { back_deltas->WriteTimeStep(t, backprop); } } FinishBackward(*errors_t.get()); if (needs_to_backprop_) { back_deltas->ZeroInvalidElements(); back_deltas->CopyWithNormalization(*back_deltas, fwd_deltas); #if DEBUG_DETAIL > 0 tprintf("F Backprop:%s\n", name_.string()); back_deltas->Print(10); #endif return true; } return false; // No point going further back. } void FullyConnected::BackwardTimeStep(const NetworkIO& fwd_deltas, int t, double* curr_errors, TransposedArray* errors_t, double* backprop) { if (type_ == NT_TANH) acts_.FuncMultiply<GPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_LOGISTIC) acts_.FuncMultiply<FPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_POSCLIP) acts_.FuncMultiply<ClipFPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_SYMCLIP) acts_.FuncMultiply<ClipGPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_RELU) acts_.FuncMultiply<ReluPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_SOFTMAX || type_ == NT_SOFTMAX_NO_CTC || type_ == NT_LINEAR) fwd_deltas.ReadTimeStep(t, curr_errors); // fwd_deltas are the errors. else ASSERT_HOST("Invalid fully-connected type!" == NULL); // Generate backprop only if needed by the lower layer. if (backprop != NULL) weights_.VectorDotMatrix(curr_errors, backprop); errors_t->WriteStrided(t, curr_errors); } void FullyConnected::FinishBackward(const TransposedArray& errors_t) { if (external_source_ == NULL) weights_.SumOuterTransposed(errors_t, source_t_, true); else weights_.SumOuterTransposed(errors_t, *external_source_, true); } // Updates the weights using the given learning rate and momentum. // num_samples is the quotient to be used in the adagrad computation iff // use_ada_grad_ is true. void FullyConnected::Update(float learning_rate, float momentum, int num_samples) { weights_.Update(learning_rate, momentum, num_samples); } // Sums the products of weight updates in *this and other, splitting into // positive (same direction) in *same and negative (different direction) in // *changed. void FullyConnected::CountAlternators(const Network& other, double* same, double* changed) const { ASSERT_HOST(other.type() == type_); const FullyConnected* fc = static_cast<const FullyConnected*>(&other); weights_.CountAlternators(fc->weights_, same, changed); } } // namespace tesseract. <commit_msg>Optimize LSTM code for builds without OpenMP<commit_after>/////////////////////////////////////////////////////////////////////// // File: fullyconnected.cpp // Description: Simple feed-forward layer with various non-linearities. // Author: Ray Smith // Created: Wed Feb 26 14:49:15 PST 2014 // // (C) Copyright 2014, Google Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////// #include "fullyconnected.h" #ifdef _OPENMP #include <omp.h> #endif #include <stdio.h> #include <stdlib.h> #include "functions.h" #include "networkscratch.h" // Number of threads to use for parallel calculation of Forward and Backward. #ifdef _OPENMP const int kNumThreads = 4; #else const int kNumThreads = 1; #endif namespace tesseract { FullyConnected::FullyConnected(const STRING& name, int ni, int no, NetworkType type) : Network(type, name, ni, no), external_source_(NULL), int_mode_(false) { } FullyConnected::~FullyConnected() { } // Returns the shape output from the network given an input shape (which may // be partially unknown ie zero). StaticShape FullyConnected::OutputShape(const StaticShape& input_shape) const { LossType loss_type = LT_NONE; if (type_ == NT_SOFTMAX) loss_type = LT_CTC; else if (type_ == NT_SOFTMAX_NO_CTC) loss_type = LT_SOFTMAX; else if (type_ == NT_LOGISTIC) loss_type = LT_LOGISTIC; StaticShape result(input_shape); result.set_depth(no_); result.set_loss_type(loss_type); return result; } // Suspends/Enables training by setting the training_ flag. void FullyConnected::SetEnableTraining(TrainingState state) { if (state == TS_RE_ENABLE) { // Enable only from temp disabled. if (training_ == TS_TEMP_DISABLE) training_ = TS_ENABLED; } else if (state == TS_TEMP_DISABLE) { // Temp disable only from enabled. if (training_ == TS_ENABLED) training_ = state; } else { if (state == TS_ENABLED && training_ != TS_ENABLED) weights_.InitBackward(); training_ = state; } } // Sets up the network for training. Initializes weights using weights of // scale `range` picked according to the random number generator `randomizer`. int FullyConnected::InitWeights(float range, TRand* randomizer) { Network::SetRandomizer(randomizer); num_weights_ = weights_.InitWeightsFloat(no_, ni_ + 1, TestFlag(NF_ADA_GRAD), range, randomizer); return num_weights_; } // Converts a float network to an int network. void FullyConnected::ConvertToInt() { weights_.ConvertToInt(); } // Provides debug output on the weights. void FullyConnected::DebugWeights() { weights_.Debug2D(name_.string()); } // Writes to the given file. Returns false in case of error. bool FullyConnected::Serialize(TFile* fp) const { if (!Network::Serialize(fp)) return false; if (!weights_.Serialize(IsTraining(), fp)) return false; return true; } // Reads from the given file. Returns false in case of error. bool FullyConnected::DeSerialize(TFile* fp) { return weights_.DeSerialize(IsTraining(), fp); } // Runs forward propagation of activations on the input line. // See NetworkCpp for a detailed discussion of the arguments. void FullyConnected::Forward(bool debug, const NetworkIO& input, const TransposedArray* input_transpose, NetworkScratch* scratch, NetworkIO* output) { int width = input.Width(); if (type_ == NT_SOFTMAX) output->ResizeFloat(input, no_); else output->Resize(input, no_); SetupForward(input, input_transpose); GenericVector<NetworkScratch::FloatVec> temp_lines; temp_lines.init_to_size(kNumThreads, NetworkScratch::FloatVec()); GenericVector<NetworkScratch::FloatVec> curr_input; curr_input.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < kNumThreads; ++i) { temp_lines[i].Init(no_, scratch); curr_input[i].Init(ni_, scratch); } #ifdef _OPENMP #pragma omp parallel for num_threads(kNumThreads) for (int t = 0; t < width; ++t) { // Thread-local pointer to temporary storage. int thread_id = omp_get_thread_num(); #else for (int t = 0; t < width; ++t) { // Thread-local pointer to temporary storage. int thread_id = 0; #endif double* temp_line = temp_lines[thread_id]; const double* d_input = NULL; const inT8* i_input = NULL; if (input.int_mode()) { i_input = input.i(t); } else { input.ReadTimeStep(t, curr_input[thread_id]); d_input = curr_input[thread_id]; } ForwardTimeStep(d_input, i_input, t, temp_line); output->WriteTimeStep(t, temp_line); if (IsTraining() && type_ != NT_SOFTMAX) { acts_.CopyTimeStepFrom(t, *output, t); } } // Zero all the elements that are in the padding around images that allows // multiple different-sized images to exist in a single array. // acts_ is only used if this is not a softmax op. if (IsTraining() && type_ != NT_SOFTMAX) { acts_.ZeroInvalidElements(); } output->ZeroInvalidElements(); #if DEBUG_DETAIL > 0 tprintf("F Output:%s\n", name_.string()); output->Print(10); #endif if (debug) DisplayForward(*output); } // Components of Forward so FullyConnected can be reused inside LSTM. void FullyConnected::SetupForward(const NetworkIO& input, const TransposedArray* input_transpose) { // Softmax output is always float, so save the input type. int_mode_ = input.int_mode(); if (IsTraining()) { acts_.Resize(input, no_); // Source_ is a transposed copy of input. It isn't needed if provided. external_source_ = input_transpose; if (external_source_ == NULL) source_t_.ResizeNoInit(ni_, input.Width()); } } void FullyConnected::ForwardTimeStep(const double* d_input, const inT8* i_input, int t, double* output_line) { // input is copied to source_ line-by-line for cache coherency. if (IsTraining() && external_source_ == NULL && d_input != NULL) source_t_.WriteStrided(t, d_input); if (d_input != NULL) weights_.MatrixDotVector(d_input, output_line); else weights_.MatrixDotVector(i_input, output_line); if (type_ == NT_TANH) { FuncInplace<GFunc>(no_, output_line); } else if (type_ == NT_LOGISTIC) { FuncInplace<FFunc>(no_, output_line); } else if (type_ == NT_POSCLIP) { FuncInplace<ClipFFunc>(no_, output_line); } else if (type_ == NT_SYMCLIP) { FuncInplace<ClipGFunc>(no_, output_line); } else if (type_ == NT_RELU) { FuncInplace<Relu>(no_, output_line); } else if (type_ == NT_SOFTMAX || type_ == NT_SOFTMAX_NO_CTC) { SoftmaxInPlace(no_, output_line); } else if (type_ != NT_LINEAR) { ASSERT_HOST("Invalid fully-connected type!" == NULL); } } // Runs backward propagation of errors on the deltas line. // See NetworkCpp for a detailed discussion of the arguments. bool FullyConnected::Backward(bool debug, const NetworkIO& fwd_deltas, NetworkScratch* scratch, NetworkIO* back_deltas) { if (debug) DisplayBackward(fwd_deltas); back_deltas->Resize(fwd_deltas, ni_); GenericVector<NetworkScratch::FloatVec> errors; errors.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < kNumThreads; ++i) errors[i].Init(no_, scratch); GenericVector<NetworkScratch::FloatVec> temp_backprops; if (needs_to_backprop_) { temp_backprops.init_to_size(kNumThreads, NetworkScratch::FloatVec()); for (int i = 0; i < kNumThreads; ++i) temp_backprops[i].Init(ni_, scratch); } int width = fwd_deltas.Width(); NetworkScratch::GradientStore errors_t; errors_t.Init(no_, width, scratch); #ifdef _OPENMP #pragma omp parallel for num_threads(kNumThreads) for (int t = 0; t < width; ++t) { int thread_id = omp_get_thread_num(); #else for (int t = 0; t < width; ++t) { int thread_id = 0; #endif double* backprop = NULL; if (needs_to_backprop_) backprop = temp_backprops[thread_id]; double* curr_errors = errors[thread_id]; BackwardTimeStep(fwd_deltas, t, curr_errors, errors_t.get(), backprop); if (backprop != NULL) { back_deltas->WriteTimeStep(t, backprop); } } FinishBackward(*errors_t.get()); if (needs_to_backprop_) { back_deltas->ZeroInvalidElements(); back_deltas->CopyWithNormalization(*back_deltas, fwd_deltas); #if DEBUG_DETAIL > 0 tprintf("F Backprop:%s\n", name_.string()); back_deltas->Print(10); #endif return true; } return false; // No point going further back. } void FullyConnected::BackwardTimeStep(const NetworkIO& fwd_deltas, int t, double* curr_errors, TransposedArray* errors_t, double* backprop) { if (type_ == NT_TANH) acts_.FuncMultiply<GPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_LOGISTIC) acts_.FuncMultiply<FPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_POSCLIP) acts_.FuncMultiply<ClipFPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_SYMCLIP) acts_.FuncMultiply<ClipGPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_RELU) acts_.FuncMultiply<ReluPrime>(fwd_deltas, t, curr_errors); else if (type_ == NT_SOFTMAX || type_ == NT_SOFTMAX_NO_CTC || type_ == NT_LINEAR) fwd_deltas.ReadTimeStep(t, curr_errors); // fwd_deltas are the errors. else ASSERT_HOST("Invalid fully-connected type!" == NULL); // Generate backprop only if needed by the lower layer. if (backprop != NULL) weights_.VectorDotMatrix(curr_errors, backprop); errors_t->WriteStrided(t, curr_errors); } void FullyConnected::FinishBackward(const TransposedArray& errors_t) { if (external_source_ == NULL) weights_.SumOuterTransposed(errors_t, source_t_, true); else weights_.SumOuterTransposed(errors_t, *external_source_, true); } // Updates the weights using the given learning rate and momentum. // num_samples is the quotient to be used in the adagrad computation iff // use_ada_grad_ is true. void FullyConnected::Update(float learning_rate, float momentum, int num_samples) { weights_.Update(learning_rate, momentum, num_samples); } // Sums the products of weight updates in *this and other, splitting into // positive (same direction) in *same and negative (different direction) in // *changed. void FullyConnected::CountAlternators(const Network& other, double* same, double* changed) const { ASSERT_HOST(other.type() == type_); const FullyConnected* fc = static_cast<const FullyConnected*>(&other); weights_.CountAlternators(fc->weights_, same, changed); } } // namespace tesseract. <|endoftext|>
<commit_before>// Copyright (c) 2011 Cloudera, Inc. All rights reserved. #include <boost/thread/thread.hpp> #include <protocol/TBinaryProtocol.h> #include <transport/TServerSocket.h> #include <transport/TTransportUtils.h> #include <gtest/gtest.h> #include "common/logging.h" #include "codegen/llvm-codegen.h" #include "runtime/row-batch.h" #include "runtime/data-stream-mgr.h" #include "runtime/data-stream-sender.h" #include "runtime/data-stream-recvr.h" #include "runtime/descriptors.h" #include "testutil/in-process-query-executor.h" #include "testutil/test-exec-env.h" #include "util/cpu-info.h" #include "util/disk-info.h" #include "util/debug-util.h" #include "util/thrift-server.h" #include "gen-cpp/ImpalaInternalService.h" #include "gen-cpp/Types_types.h" #include "gen-cpp/Descriptors_types.h" using namespace std; using namespace tr1; using namespace boost; using namespace apache::thrift; using namespace apache::thrift::protocol; DECLARE_int32(port); namespace impala { class ImpalaTestBackend : public ImpalaInternalServiceIf { public: ImpalaTestBackend(DataStreamMgr* stream_mgr): mgr_(stream_mgr) {} virtual ~ImpalaTestBackend() {} virtual void ExecPlanFragment( TExecPlanFragmentResult& return_val, const TExecPlanFragmentParams& params) {} virtual void ReportExecStatus( TReportExecStatusResult& return_val, const TReportExecStatusParams& params) {} virtual void CancelPlanFragment( TCancelPlanFragmentResult& return_val, const TCancelPlanFragmentParams& params) {} virtual void TransmitData( TTransmitDataResult& return_val, const TTransmitDataParams& params) { if (!params.eos) { mgr_->AddData(params.dest_fragment_id, params.dest_node_id, params.row_batch) .SetTStatus(&return_val); } else { mgr_->CloseSender(params.dest_fragment_id, params.dest_node_id) .SetTStatus(&return_val); } } private: DataStreamMgr* mgr_; }; class DataStreamTest : public testing::Test { protected: DataStreamTest(): next_val_(0) {} virtual void SetUp() { fragment_id_.lo = 0; fragment_id_.hi = 0; stream_mgr_ = new DataStreamMgr(); sink_.destNodeId = DEST_NODE_ID; dest_.push_back(THostPort()); dest_.back().ipaddress = "127.0.0.1"; // Need a unique port since backend servers are never stopped dest_.back().port = FLAGS_port++; CreateRowDesc(); CreateRowBatch(); StartBackend(); } static const PlanNodeId DEST_NODE_ID = 1; static const int BATCH_CAPACITY = 100; // rows static const int PER_ROW_DATA = 8; static const int TOTAL_DATA_SIZE = 8 * 1024; static const int NUM_BATCHES = TOTAL_DATA_SIZE / BATCH_CAPACITY / PER_ROW_DATA; ObjectPool obj_pool_; DescriptorTbl* desc_tbl_; const RowDescriptor* row_desc_; TUniqueId fragment_id_; string stmt_; // RowBatch generation scoped_ptr<RowBatch> batch_; int next_val_; int64_t* tuple_mem_; // receiving node DataStreamMgr* stream_mgr_; DataStreamRecvr* stream_recvr_; thread recvr_thread_; Status recvr_status_; ThriftServer* server_; // sending node(s) TDataStreamSink sink_; vector<THostPort> dest_; struct SenderInfo { thread* thread_handle; Status status; int num_bytes_sent; SenderInfo(): thread_handle(NULL), num_bytes_sent(0) {} }; vector<SenderInfo> sender_info_; // RowDescriptor to mimic "select bigint_col from alltypesagg", except the slot // isn't nullable void CreateRowDesc() { // create DescriptorTbl TTupleDescriptor tuple_desc; tuple_desc.__set_id(0); tuple_desc.__set_byteSize(8); tuple_desc.__set_numNullBytes(0); TDescriptorTable thrift_desc_tbl; thrift_desc_tbl.tupleDescriptors.push_back(tuple_desc); TSlotDescriptor slot_desc; slot_desc.__set_id(0); slot_desc.__set_parent(0); slot_desc.__set_slotType(TPrimitiveType::BIGINT); slot_desc.__set_columnPos(0); slot_desc.__set_byteOffset(0); slot_desc.__set_nullIndicatorByte(-1); slot_desc.__set_nullIndicatorBit(-1); slot_desc.__set_slotIdx(0); slot_desc.__set_isMaterialized(true); thrift_desc_tbl.slotDescriptors.push_back(slot_desc); EXPECT_TRUE(DescriptorTbl::Create(&obj_pool_, thrift_desc_tbl, &desc_tbl_).ok()); vector<TTupleId> row_tids; row_tids.push_back(0); vector<bool> nullable_tuples; nullable_tuples.push_back(false); row_desc_ = obj_pool_.Add(new RowDescriptor(*desc_tbl_, row_tids, nullable_tuples)); } // Create batch_, but don't fill it with data yet. Assumes we created row_desc_. RowBatch* CreateRowBatch() { RowBatch* batch = new RowBatch(*row_desc_, BATCH_CAPACITY); int64_t* tuple_mem = reinterpret_cast<int64_t*>( batch->tuple_data_pool()->Allocate(BATCH_CAPACITY * 8)); bzero(tuple_mem, BATCH_CAPACITY * 8); for (int i = 0; i < BATCH_CAPACITY; ++i) { int idx = batch->AddRow(); TupleRow* row = batch->GetRow(idx); row->SetTuple(0, reinterpret_cast<Tuple*>(&tuple_mem[i])); batch->CommitLastRow(); } return batch; } void GetNextBatch(RowBatch* batch, int* next_val) { for (int i = 0; i < BATCH_CAPACITY; ++i) { TupleRow* row = batch->GetRow(i); int64_t* val = reinterpret_cast<int64_t*>(row->GetTuple(0)->GetSlot(0)); *val = (*next_val)++; } } // Start receiver (expecting given number of senders) in separate thread. void StartReceiver(int num_senders, int buffer_size) { stream_recvr_ = stream_mgr_->CreateRecvr(*row_desc_, fragment_id_, DEST_NODE_ID, num_senders, buffer_size); recvr_thread_ = thread(&DataStreamTest::ReadStream, this, num_senders); } void JoinReceiver() { recvr_thread_.join(); } // Deplete stream and print batches void ReadStream(int num_senders) { RowBatch* batch; VLOG_QUERY << "start reading"; bool is_cancelled; multiset<int64_t> data_values; while ((batch = stream_recvr_->GetBatch(&is_cancelled)) != NULL && !is_cancelled) { VLOG_QUERY << "read batch #rows=" << (batch != NULL ? batch->num_rows() : 0); for (int i = 0; i < batch->num_rows(); ++i) { TupleRow* row = batch->GetRow(i); data_values.insert(*static_cast<int64_t*>(row->GetTuple(0)->GetSlot(0))); } usleep(100000); // slow down receiver to exercise buffering logic } if (is_cancelled) VLOG_QUERY << "reader is cancelled"; recvr_status_ = (is_cancelled ? Status::CANCELLED : Status::OK); if (!is_cancelled) { // check contents of batches int64_t expected_val; EXPECT_EQ(data_values.size(), NUM_BATCHES * BATCH_CAPACITY * num_senders); int j = 0; for (multiset<int64_t>::iterator i = data_values.begin(); i != data_values.end(); ++i, ++j) { expected_val = j / num_senders; EXPECT_EQ(expected_val, *i); } } VLOG_QUERY << "done reading"; } // Start backend in separate thread. void StartBackend() { shared_ptr<ImpalaTestBackend> handler(new ImpalaTestBackend(stream_mgr_)); shared_ptr<TProcessor> processor(new ImpalaInternalServiceProcessor(handler)); server_ = new ThriftServer("DataStreamTest backend", processor, dest_.back().port); server_->Start(); } void StopBackend() { delete server_; } void StartSender(int channel_buffer_size = 1024) { int num_senders = sender_info_.size(); sender_info_.push_back(SenderInfo()); SenderInfo& info = sender_info_.back(); info.thread_handle = new thread(&DataStreamTest::Sender, this, num_senders, channel_buffer_size); } void JoinSenders() { for (int i = 0; i < sender_info_.size(); ++i) { sender_info_[i].thread_handle->join(); } } void Sender(int sender_num, int channel_buffer_size) { VLOG_QUERY << "create sender " << sender_num; DataStreamSender sender( *row_desc_, fragment_id_, sink_, dest_, channel_buffer_size); EXPECT_TRUE(sender.Init(NULL).ok()); scoped_ptr<RowBatch> batch(CreateRowBatch()); SenderInfo& info = sender_info_[sender_num]; int next_val = 0; for (int i = 0; i < NUM_BATCHES; ++i) { GetNextBatch(batch.get(), &next_val); VLOG_QUERY << "sender " << sender_num << ": #rows=" << batch->num_rows(); info.status = sender.Send(NULL, batch.get()); if (!info.status.ok()) break; } VLOG_QUERY << "closing sender" << sender_num; info.status = sender.Close(NULL); info.num_bytes_sent = sender.GetNumDataBytesSent(); } }; TEST_F(DataStreamTest, SingleSenderSmallBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(1, 1024); VLOG_QUERY << "start sender\n"; StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, SingleSenderLargeBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(1, 1024 * 1024); VLOG_QUERY << "start sender\n"; StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, MultipleSendersSmallBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(4, 4 * 1024); VLOG_QUERY << "start senders\n"; StartSender(); StartSender(); StartSender(); StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[1].status.ok()); EXPECT_GT(sender_info_[1].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[2].status.ok()); EXPECT_GT(sender_info_[2].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[3].status.ok()); EXPECT_GT(sender_info_[3].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, MultipleSendersLargeBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(4, 4 * 1024 * 1024); VLOG_QUERY << "start senders\n"; StartSender(); StartSender(); StartSender(); StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[1].status.ok()); EXPECT_GT(sender_info_[1].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[2].status.ok()); EXPECT_GT(sender_info_[2].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[3].status.ok()); EXPECT_GT(sender_info_[3].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, UnknownSenderSmallResult) { // starting a sender w/o a corresponding receiver should result in an error // on the sending side // case 1: entire query result fits in single buffer, close() returns error status StartSender(TOTAL_DATA_SIZE + 1024); JoinSenders(); EXPECT_FALSE(sender_info_[0].status.ok()); EXPECT_EQ(sender_info_[0].num_bytes_sent, 0); } TEST_F(DataStreamTest, UnknownSenderLargeResult) { // case 2: query result requires multiple buffers, send() returns error status StartSender(); JoinSenders(); EXPECT_FALSE(sender_info_[0].status.ok()); EXPECT_EQ(sender_info_[0].num_bytes_sent, 0); } TEST_F(DataStreamTest, Cancel) { StartReceiver(1, 1024); stream_mgr_->Cancel(fragment_id_); JoinReceiver(); EXPECT_TRUE(recvr_status_.IsCancelled()); } // TODO: more tests: // - TEST_F(DataStreamTest, SingleSenderMultipleReceivers) // - TEST_F(DataStreamTest, MultipleSendersMultipleReceivers) // - test case for transmission error in last batch // - receivers getting created concurrently } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::CpuInfo::Init(); impala::DiskInfo::Init(); impala::LlvmCodeGen::InitializeLlvm(); return RUN_ALL_TESTS(); } <commit_msg>Fix data-stream-test bug<commit_after>// Copyright (c) 2011 Cloudera, Inc. All rights reserved. #include <boost/thread/thread.hpp> #include <protocol/TBinaryProtocol.h> #include <transport/TServerSocket.h> #include <transport/TTransportUtils.h> #include <gtest/gtest.h> #include "common/logging.h" #include "codegen/llvm-codegen.h" #include "runtime/row-batch.h" #include "runtime/data-stream-mgr.h" #include "runtime/data-stream-sender.h" #include "runtime/data-stream-recvr.h" #include "runtime/descriptors.h" #include "testutil/in-process-query-executor.h" #include "testutil/test-exec-env.h" #include "util/cpu-info.h" #include "util/disk-info.h" #include "util/debug-util.h" #include "util/thrift-server.h" #include "gen-cpp/ImpalaInternalService.h" #include "gen-cpp/Types_types.h" #include "gen-cpp/Descriptors_types.h" using namespace std; using namespace tr1; using namespace boost; using namespace apache::thrift; using namespace apache::thrift::protocol; DECLARE_int32(port); namespace impala { class ImpalaTestBackend : public ImpalaInternalServiceIf { public: ImpalaTestBackend(DataStreamMgr* stream_mgr): mgr_(stream_mgr) {} virtual ~ImpalaTestBackend() {} virtual void ExecPlanFragment( TExecPlanFragmentResult& return_val, const TExecPlanFragmentParams& params) {} virtual void ReportExecStatus( TReportExecStatusResult& return_val, const TReportExecStatusParams& params) {} virtual void CancelPlanFragment( TCancelPlanFragmentResult& return_val, const TCancelPlanFragmentParams& params) {} virtual void TransmitData( TTransmitDataResult& return_val, const TTransmitDataParams& params) { if (!params.eos) { mgr_->AddData(params.dest_fragment_id, params.dest_node_id, params.row_batch) .SetTStatus(&return_val); } else { mgr_->CloseSender(params.dest_fragment_id, params.dest_node_id) .SetTStatus(&return_val); } } private: DataStreamMgr* mgr_; }; class DataStreamTest : public testing::Test { protected: DataStreamTest(): next_val_(0) {} virtual void SetUp() { fragment_id_.lo = 0; fragment_id_.hi = 0; stream_mgr_ = new DataStreamMgr(); sink_.destNodeId = DEST_NODE_ID; dest_.push_back(THostPort()); dest_.back().ipaddress = "127.0.0.1"; // Need a unique port since backend servers are never stopped dest_.back().port = FLAGS_port++; // Ensure that individual sender info addresses don't change sender_info_.reserve(MAX_SENDERS); CreateRowDesc(); CreateRowBatch(); StartBackend(); } // We reserve contiguous memory for senders in SetUp. If a test uses more // senders, a DCHECK will fail and you should increase this value. static const int MAX_SENDERS = 16; static const PlanNodeId DEST_NODE_ID = 1; static const int BATCH_CAPACITY = 100; // rows static const int PER_ROW_DATA = 8; static const int TOTAL_DATA_SIZE = 8 * 1024; static const int NUM_BATCHES = TOTAL_DATA_SIZE / BATCH_CAPACITY / PER_ROW_DATA; ObjectPool obj_pool_; DescriptorTbl* desc_tbl_; const RowDescriptor* row_desc_; TUniqueId fragment_id_; string stmt_; // RowBatch generation scoped_ptr<RowBatch> batch_; int next_val_; int64_t* tuple_mem_; // receiving node DataStreamMgr* stream_mgr_; DataStreamRecvr* stream_recvr_; thread recvr_thread_; Status recvr_status_; ThriftServer* server_; // sending node(s) TDataStreamSink sink_; vector<THostPort> dest_; struct SenderInfo { thread* thread_handle; Status status; int num_bytes_sent; SenderInfo(): thread_handle(NULL), num_bytes_sent(0) {} }; vector<SenderInfo> sender_info_; // RowDescriptor to mimic "select bigint_col from alltypesagg", except the slot // isn't nullable void CreateRowDesc() { // create DescriptorTbl TTupleDescriptor tuple_desc; tuple_desc.__set_id(0); tuple_desc.__set_byteSize(8); tuple_desc.__set_numNullBytes(0); TDescriptorTable thrift_desc_tbl; thrift_desc_tbl.tupleDescriptors.push_back(tuple_desc); TSlotDescriptor slot_desc; slot_desc.__set_id(0); slot_desc.__set_parent(0); slot_desc.__set_slotType(TPrimitiveType::BIGINT); slot_desc.__set_columnPos(0); slot_desc.__set_byteOffset(0); slot_desc.__set_nullIndicatorByte(-1); slot_desc.__set_nullIndicatorBit(-1); slot_desc.__set_slotIdx(0); slot_desc.__set_isMaterialized(true); thrift_desc_tbl.slotDescriptors.push_back(slot_desc); EXPECT_TRUE(DescriptorTbl::Create(&obj_pool_, thrift_desc_tbl, &desc_tbl_).ok()); vector<TTupleId> row_tids; row_tids.push_back(0); vector<bool> nullable_tuples; nullable_tuples.push_back(false); row_desc_ = obj_pool_.Add(new RowDescriptor(*desc_tbl_, row_tids, nullable_tuples)); } // Create batch_, but don't fill it with data yet. Assumes we created row_desc_. RowBatch* CreateRowBatch() { RowBatch* batch = new RowBatch(*row_desc_, BATCH_CAPACITY); int64_t* tuple_mem = reinterpret_cast<int64_t*>( batch->tuple_data_pool()->Allocate(BATCH_CAPACITY * 8)); bzero(tuple_mem, BATCH_CAPACITY * 8); for (int i = 0; i < BATCH_CAPACITY; ++i) { int idx = batch->AddRow(); TupleRow* row = batch->GetRow(idx); row->SetTuple(0, reinterpret_cast<Tuple*>(&tuple_mem[i])); batch->CommitLastRow(); } return batch; } void GetNextBatch(RowBatch* batch, int* next_val) { for (int i = 0; i < BATCH_CAPACITY; ++i) { TupleRow* row = batch->GetRow(i); int64_t* val = reinterpret_cast<int64_t*>(row->GetTuple(0)->GetSlot(0)); *val = (*next_val)++; } } // Start receiver (expecting given number of senders) in separate thread. void StartReceiver(int num_senders, int buffer_size) { stream_recvr_ = stream_mgr_->CreateRecvr(*row_desc_, fragment_id_, DEST_NODE_ID, num_senders, buffer_size); recvr_thread_ = thread(&DataStreamTest::ReadStream, this, num_senders); } void JoinReceiver() { recvr_thread_.join(); } // Deplete stream and print batches void ReadStream(int num_senders) { RowBatch* batch; VLOG_QUERY << "start reading"; bool is_cancelled; multiset<int64_t> data_values; while ((batch = stream_recvr_->GetBatch(&is_cancelled)) != NULL && !is_cancelled) { VLOG_QUERY << "read batch #rows=" << (batch != NULL ? batch->num_rows() : 0); for (int i = 0; i < batch->num_rows(); ++i) { TupleRow* row = batch->GetRow(i); data_values.insert(*static_cast<int64_t*>(row->GetTuple(0)->GetSlot(0))); } usleep(100000); // slow down receiver to exercise buffering logic } if (is_cancelled) VLOG_QUERY << "reader is cancelled"; recvr_status_ = (is_cancelled ? Status::CANCELLED : Status::OK); if (!is_cancelled) { // check contents of batches int64_t expected_val; EXPECT_EQ(data_values.size(), NUM_BATCHES * BATCH_CAPACITY * num_senders); int j = 0; for (multiset<int64_t>::iterator i = data_values.begin(); i != data_values.end(); ++i, ++j) { expected_val = j / num_senders; EXPECT_EQ(expected_val, *i); } } VLOG_QUERY << "done reading"; } // Start backend in separate thread. void StartBackend() { shared_ptr<ImpalaTestBackend> handler(new ImpalaTestBackend(stream_mgr_)); shared_ptr<TProcessor> processor(new ImpalaInternalServiceProcessor(handler)); server_ = new ThriftServer("DataStreamTest backend", processor, dest_.back().port); server_->Start(); } void StopBackend() { delete server_; } void StartSender(int channel_buffer_size = 1024) { int num_senders = sender_info_.size(); DCHECK_LT(num_senders, MAX_SENDERS); sender_info_.push_back(SenderInfo()); SenderInfo& info = sender_info_.back(); info.thread_handle = new thread(&DataStreamTest::Sender, this, num_senders, channel_buffer_size); } void JoinSenders() { for (int i = 0; i < sender_info_.size(); ++i) { sender_info_[i].thread_handle->join(); } } void Sender(int sender_num, int channel_buffer_size) { VLOG_QUERY << "create sender " << sender_num; DataStreamSender sender( *row_desc_, fragment_id_, sink_, dest_, channel_buffer_size); EXPECT_TRUE(sender.Init(NULL).ok()); scoped_ptr<RowBatch> batch(CreateRowBatch()); SenderInfo& info = sender_info_[sender_num]; int next_val = 0; for (int i = 0; i < NUM_BATCHES; ++i) { GetNextBatch(batch.get(), &next_val); VLOG_QUERY << "sender " << sender_num << ": #rows=" << batch->num_rows(); info.status = sender.Send(NULL, batch.get()); if (!info.status.ok()) break; } VLOG_QUERY << "closing sender" << sender_num; info.status = sender.Close(NULL); info.num_bytes_sent = sender.GetNumDataBytesSent(); } }; TEST_F(DataStreamTest, SingleSenderSmallBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(1, 1024); VLOG_QUERY << "start sender\n"; StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, SingleSenderLargeBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(1, 1024 * 1024); VLOG_QUERY << "start sender\n"; StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, MultipleSendersSmallBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(4, 4 * 1024); VLOG_QUERY << "start senders\n"; StartSender(); StartSender(); StartSender(); StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[1].status.ok()); EXPECT_GT(sender_info_[1].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[2].status.ok()); EXPECT_GT(sender_info_[2].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[3].status.ok()); EXPECT_GT(sender_info_[3].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, MultipleSendersLargeBuffer) { VLOG_QUERY << "start receiver\n"; StartReceiver(4, 4 * 1024 * 1024); VLOG_QUERY << "start senders\n"; StartSender(); StartSender(); StartSender(); StartSender(); VLOG_QUERY << "join senders\n"; JoinSenders(); EXPECT_TRUE(sender_info_[0].status.ok()); EXPECT_GT(sender_info_[0].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[1].status.ok()); EXPECT_GT(sender_info_[1].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[2].status.ok()); EXPECT_GT(sender_info_[2].num_bytes_sent, 0); EXPECT_TRUE(sender_info_[3].status.ok()); EXPECT_GT(sender_info_[3].num_bytes_sent, 0); VLOG_QUERY << "join receiver\n"; JoinReceiver(); VLOG_QUERY << "stop backend\n"; StopBackend(); } TEST_F(DataStreamTest, UnknownSenderSmallResult) { // starting a sender w/o a corresponding receiver should result in an error // on the sending side // case 1: entire query result fits in single buffer, close() returns error status StartSender(TOTAL_DATA_SIZE + 1024); JoinSenders(); EXPECT_FALSE(sender_info_[0].status.ok()); EXPECT_EQ(sender_info_[0].num_bytes_sent, 0); } TEST_F(DataStreamTest, UnknownSenderLargeResult) { // case 2: query result requires multiple buffers, send() returns error status StartSender(); JoinSenders(); EXPECT_FALSE(sender_info_[0].status.ok()); EXPECT_EQ(sender_info_[0].num_bytes_sent, 0); } TEST_F(DataStreamTest, Cancel) { StartReceiver(1, 1024); stream_mgr_->Cancel(fragment_id_); JoinReceiver(); EXPECT_TRUE(recvr_status_.IsCancelled()); } // TODO: more tests: // - TEST_F(DataStreamTest, SingleSenderMultipleReceivers) // - TEST_F(DataStreamTest, MultipleSendersMultipleReceivers) // - test case for transmission error in last batch // - receivers getting created concurrently } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::CpuInfo::Init(); impala::DiskInfo::Init(); impala::LlvmCodeGen::InitializeLlvm(); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "context.h" #include <QAbstractEventDispatcher> #include <QDebug> #warning todo this needs to be a singleton as multiple contexts dont make sense and it makes it eaier to use from qml static void sink_cb(pa_context *context, const pa_sink_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->sinkCallback(context, info, eol); } static void sink_input_callback(pa_context *context, const pa_sink_input_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->sinkInputCallback(context, info, eol); } static void client_cb(pa_context *context, const pa_client_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->clientCallback(context, info, eol); } static void context_state_callback(pa_context *context, void *data) { Q_ASSERT(data); ((Context *)data)->contextStateCallback(context); } #warning fix varnames static void subscribe_cb(pa_context *context, pa_subscription_event_type_t type, uint32_t index, void *data) { Q_ASSERT(data); ((Context *)data)->subscribeCallback(context, type, index); } // -------------------------- Context::Context(QObject *parent) : QObject(parent) , m_context(nullptr) , m_mainloop(nullptr) { // We require a glib event loop if (!QByteArray(QAbstractEventDispatcher::instance()->metaObject()->className()).contains("EventDispatcherGlib")) { qDebug() << "Disabling PulseAudio integration for lack of GLib event loop"; } connectToDaemon(); } Context::~Context() { pa_context_unref(m_context); pa_glib_mainloop_free(m_mainloop); } void Context::subscribeCallback(pa_context *context, pa_subscription_event_type_t type, uint32_t index) { #warning fixme // Q_ASSERT(c == s_context); switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { #warning fixme case PA_SUBSCRIPTION_EVENT_SINK: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { m_sinks.take(index)->deleteLater(); emit sinkRemoved(index); } else { pa_operation *o; if (!(o = pa_context_get_sink_info_by_index(context, index, sink_cb, this))) { qWarning() << "pa_context_get_sink_info_by_index() failed"; return; } pa_operation_unref(o); } break; // case PA_SUBSCRIPTION_EVENT_SOURCE: // if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // if (s_mixers.contains(KMIXPA_CAPTURE)) // s_mixers[KMIXPA_CAPTURE]->removeWidget(index); // } else { // pa_operation *o; // if (!(o = pa_context_get_source_info_by_index(c, index, source_cb, NULL))) { // qWarning() << "pa_context_get_source_info_by_index() failed"; // return; // } // pa_operation_unref(o); // } // break; case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { int listIndex = -1; QList<quint32> list = m_sinkInputs.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); m_sinkInputs.take(index)->deleteLater(); emit sinkInputRemoved(listIndex); } else { qDebug() << "sub sink input info"; pa_operation *o; if (!(o = pa_context_get_sink_input_info(context, index, sink_input_callback, this))) { qWarning() << "pa_context_get_sink_input_info() failed"; return; } pa_operation_unref(o); } break; // case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: // if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // if (s_mixers.contains(KMIXPA_APP_CAPTURE)) // s_mixers[KMIXPA_APP_CAPTURE]->removeWidget(index); // } else { // pa_operation *o; // if (!(o = pa_context_get_source_output_info(c, index, source_output_cb, NULL))) { // qWarning() << "pa_context_get_sink_input_info() failed"; // return; // } // pa_operation_unref(o); // } // break; case PA_SUBSCRIPTION_EVENT_CLIENT: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { m_clients.take(index)->deleteLater(); emit clientsChanged(); } else { pa_operation *o; if (!(o = pa_context_get_client_info(context, index, client_cb, this))) { qWarning() << "pa_context_get_client_info() failed"; return; } pa_operation_unref(o); } break; } qDebug() << "return !!!!!"; } void Context::contextStateCallback(pa_context *c) { qDebug() << "state callback"; pa_context_state_t state = pa_context_get_state(c); if (state == PA_CONTEXT_READY) { qDebug() << "ready"; // Attempt to load things up pa_operation *o = nullptr; // 1. Register for the stream changes (except during probe) if (m_context == c) { #warning fixme pa_context_set_subscribe_callback(c, subscribe_cb, this); if (!(o = pa_context_subscribe(c, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK| PA_SUBSCRIPTION_MASK_SOURCE| PA_SUBSCRIPTION_MASK_CLIENT| PA_SUBSCRIPTION_MASK_SINK_INPUT| PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT), NULL, NULL))) { qWarning() << "pa_context_subscribe() failed"; return; } pa_operation_unref(o); } #warning fixme if (!(o = pa_context_get_sink_info_list(c, sink_cb, this))) { qWarning() << "pa_context_get_sink_info_list() failed"; return; } pa_operation_unref(o); // if (!(o = pa_context_get_source_info_list(c, source_cb, NULL))) { // qWarning() << "pa_context_get_source_info_list() failed"; // return; // } // pa_operation_unref(o); // s_outstandingRequests++; if (!(o = pa_context_get_client_info_list(c, client_cb, this))) { qWarning() << "pa_context_client_info_list() failed"; return; } pa_operation_unref(o); // s_outstandingRequests++; if (!(o = pa_context_get_sink_input_info_list(c, sink_input_callback, this))) { qWarning() << "pa_context_get_sink_input_info_list() failed"; return; } pa_operation_unref(o); // s_outstandingRequests++; // if (!(o = pa_context_get_source_output_info_list(c, source_output_cb, NULL))) { // qWarning() << "pa_context_get_source_output_info_list() failed"; // return; // } // pa_operation_unref(o); // s_outstandingRequests++; /* These calls are not always supported */ // if ((o = pa_ext_stream_restore_read(c, ext_stream_restore_read_cb, NULL))) { // pa_operation_unref(o); // s_outstandingRequests++; // pa_ext_stream_restore_set_subscribe_cb(c, ext_stream_restore_subscribe_cb, NULL); // if ((o = pa_ext_stream_restore_subscribe(c, 1, NULL, NULL))) // pa_operation_unref(o); // } else { // qWarning() << "Failed to initialize stream_restore extension: " << pa_strerror(pa_context_errno(m_context)); // } } else if (!PA_CONTEXT_IS_GOOD(state)) { qDebug() << "context kaput"; // If this is our probe phase, exit our context immediately if (m_context != c) { pa_context_disconnect(c); } else { // If we're not probing, it means we've been disconnected from our // glib context pa_context_unref(m_context); m_context = nullptr; #warning fixme // This one is not handled above. // clients.clear(); } } } #warning data changed should possibly only be emitted once eol is >0 to avoid pointless redraws void Context::sinkCallback(pa_context *context, const pa_sink_info *info, int eol) { if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); bool isNew = false; Sink *obj = m_sinks.value(info->index, nullptr); if (!obj) { obj = new Sink; isNew = true; } obj->setInfo(info); m_sinks.insert(info->index, obj); #warning this is bullshit and removal by this method is even more shit int listIndex = -1; QList<quint32> list = m_sinks.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == info->index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); if (isNew) { emit sinkAdded(listIndex); } else { emit sinkUpdated(listIndex); } } void Context::clientCallback(pa_context *context, const pa_client_info *info, int eol) { Q_ASSERT(context); if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); Client *obj = m_clients.value(info->index, nullptr); if (!obj) obj = new Client; obj->setInfo(info); m_clients.insert(info->index, obj); emit clientsChanged(); } void Context::sinkInputCallback(pa_context *context, const pa_sink_input_info *info, int eol) { qDebug() << "sink_input_cb"; Q_ASSERT(context); if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); bool isNew = false; SinkInput *obj = m_sinkInputs.value(info->index, nullptr); if (!obj) { obj = new SinkInput; isNew = true; } obj->setInfo(info); m_sinkInputs.insert(info->index, obj); int listIndex = -1; QList<quint32> list = m_sinkInputs.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == info->index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); qDebug() << Q_FUNC_INFO << isNew << listIndex; if (isNew) { emit sinkInputAdded(listIndex); } else { emit sinkInputUpdated(listIndex); } } void Context::setSinkVolume(quint32 index, quint32 volume) { qDebug() << Q_FUNC_INFO << index << volume; pa_operation *o; Sink *sink = m_sinks.value(index, nullptr); if (!sink) return; pa_cvolume newVolume = sink->volume(); for (int i = 0; i < newVolume.channels; ++i) { newVolume.values[i] = volume; } if (!(o = pa_context_set_sink_volume_by_index(m_context, index, &newVolume, NULL, NULL))) { qWarning() << "pa_context_set_sink_volume_by_index() failed"; return; } pa_operation_unref(o); } void Context::setSinkPort(quint32 portIndex) { pa_operation *o; if (!(o = pa_context_set_sink_port_by_index(m_context, portIndex, nullptr, nullptr, nullptr))) { qWarning() << "pa_context_set_sink_port_by_index failed"; return; } } void Context::setSinkInputVolume(quint32 index, quint32 volume) { qDebug() << Q_FUNC_INFO << index << volume; pa_operation *o; SinkInput *obj = m_sinkInputs.value(index, nullptr); if (!obj) return; pa_cvolume newVolume = obj->volume(); for (int i = 0; i < newVolume.channels; ++i) { newVolume.values[i] = volume; } if (!(o = pa_context_set_sink_input_volume(m_context, index, &newVolume, NULL, NULL))) { qWarning() << "pa_context_set_sink_volume_by_index() failed"; return; } pa_operation_unref(o); } void Context::connectToDaemon() { Q_ASSERT(m_context == nullptr); Q_ASSERT(m_mainloop == nullptr); qDebug() << "Attempting connection to PulseAudio sound daemon"; m_mainloop = pa_glib_mainloop_new(nullptr); pa_mainloop_api *api = pa_glib_mainloop_get_api(m_mainloop); Q_ASSERT(api); m_context = pa_context_new(api, "QPulse"); Q_ASSERT(m_context); if (pa_context_connect(m_context, NULL, PA_CONTEXT_NOFAIL, 0) < 0) { pa_context_unref(m_context); m_context = nullptr; return; } pa_context_set_state_callback(m_context, &context_state_callback, this); } <commit_msg>do not connect the context when there is no glib event loop<commit_after>#include "context.h" #include <QAbstractEventDispatcher> #include <QDebug> #warning todo this needs to be a singleton as multiple contexts dont make sense and it makes it eaier to use from qml static void sink_cb(pa_context *context, const pa_sink_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->sinkCallback(context, info, eol); } static void sink_input_callback(pa_context *context, const pa_sink_input_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->sinkInputCallback(context, info, eol); } static void client_cb(pa_context *context, const pa_client_info *info, int eol, void *data) { Q_ASSERT(data); ((Context *)data)->clientCallback(context, info, eol); } static void context_state_callback(pa_context *context, void *data) { Q_ASSERT(data); ((Context *)data)->contextStateCallback(context); } #warning fix varnames static void subscribe_cb(pa_context *context, pa_subscription_event_type_t type, uint32_t index, void *data) { Q_ASSERT(data); ((Context *)data)->subscribeCallback(context, type, index); } // -------------------------- Context::Context(QObject *parent) : QObject(parent) , m_context(nullptr) , m_mainloop(nullptr) { // We require a glib event loop if (!QByteArray(QAbstractEventDispatcher::instance()->metaObject()->className()).contains("EventDispatcherGlib")) { qDebug() << "Disabling PulseAudio integration for lack of GLib event loop"; return; } connectToDaemon(); } Context::~Context() { pa_context_unref(m_context); pa_glib_mainloop_free(m_mainloop); } void Context::subscribeCallback(pa_context *context, pa_subscription_event_type_t type, uint32_t index) { #warning fixme // Q_ASSERT(c == s_context); switch (type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { #warning fixme case PA_SUBSCRIPTION_EVENT_SINK: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { m_sinks.take(index)->deleteLater(); emit sinkRemoved(index); } else { pa_operation *o; if (!(o = pa_context_get_sink_info_by_index(context, index, sink_cb, this))) { qWarning() << "pa_context_get_sink_info_by_index() failed"; return; } pa_operation_unref(o); } break; // case PA_SUBSCRIPTION_EVENT_SOURCE: // if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // if (s_mixers.contains(KMIXPA_CAPTURE)) // s_mixers[KMIXPA_CAPTURE]->removeWidget(index); // } else { // pa_operation *o; // if (!(o = pa_context_get_source_info_by_index(c, index, source_cb, NULL))) { // qWarning() << "pa_context_get_source_info_by_index() failed"; // return; // } // pa_operation_unref(o); // } // break; case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { int listIndex = -1; QList<quint32> list = m_sinkInputs.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); m_sinkInputs.take(index)->deleteLater(); emit sinkInputRemoved(listIndex); } else { qDebug() << "sub sink input info"; pa_operation *o; if (!(o = pa_context_get_sink_input_info(context, index, sink_input_callback, this))) { qWarning() << "pa_context_get_sink_input_info() failed"; return; } pa_operation_unref(o); } break; // case PA_SUBSCRIPTION_EVENT_SOURCE_OUTPUT: // if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { // if (s_mixers.contains(KMIXPA_APP_CAPTURE)) // s_mixers[KMIXPA_APP_CAPTURE]->removeWidget(index); // } else { // pa_operation *o; // if (!(o = pa_context_get_source_output_info(c, index, source_output_cb, NULL))) { // qWarning() << "pa_context_get_sink_input_info() failed"; // return; // } // pa_operation_unref(o); // } // break; case PA_SUBSCRIPTION_EVENT_CLIENT: if ((type & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { m_clients.take(index)->deleteLater(); emit clientsChanged(); } else { pa_operation *o; if (!(o = pa_context_get_client_info(context, index, client_cb, this))) { qWarning() << "pa_context_get_client_info() failed"; return; } pa_operation_unref(o); } break; } qDebug() << "return !!!!!"; } void Context::contextStateCallback(pa_context *c) { qDebug() << "state callback"; pa_context_state_t state = pa_context_get_state(c); if (state == PA_CONTEXT_READY) { qDebug() << "ready"; // Attempt to load things up pa_operation *o = nullptr; // 1. Register for the stream changes (except during probe) if (m_context == c) { #warning fixme pa_context_set_subscribe_callback(c, subscribe_cb, this); if (!(o = pa_context_subscribe(c, (pa_subscription_mask_t) (PA_SUBSCRIPTION_MASK_SINK| PA_SUBSCRIPTION_MASK_SOURCE| PA_SUBSCRIPTION_MASK_CLIENT| PA_SUBSCRIPTION_MASK_SINK_INPUT| PA_SUBSCRIPTION_MASK_SOURCE_OUTPUT), NULL, NULL))) { qWarning() << "pa_context_subscribe() failed"; return; } pa_operation_unref(o); } #warning fixme if (!(o = pa_context_get_sink_info_list(c, sink_cb, this))) { qWarning() << "pa_context_get_sink_info_list() failed"; return; } pa_operation_unref(o); // if (!(o = pa_context_get_source_info_list(c, source_cb, NULL))) { // qWarning() << "pa_context_get_source_info_list() failed"; // return; // } // pa_operation_unref(o); // s_outstandingRequests++; if (!(o = pa_context_get_client_info_list(c, client_cb, this))) { qWarning() << "pa_context_client_info_list() failed"; return; } pa_operation_unref(o); // s_outstandingRequests++; if (!(o = pa_context_get_sink_input_info_list(c, sink_input_callback, this))) { qWarning() << "pa_context_get_sink_input_info_list() failed"; return; } pa_operation_unref(o); // s_outstandingRequests++; // if (!(o = pa_context_get_source_output_info_list(c, source_output_cb, NULL))) { // qWarning() << "pa_context_get_source_output_info_list() failed"; // return; // } // pa_operation_unref(o); // s_outstandingRequests++; /* These calls are not always supported */ // if ((o = pa_ext_stream_restore_read(c, ext_stream_restore_read_cb, NULL))) { // pa_operation_unref(o); // s_outstandingRequests++; // pa_ext_stream_restore_set_subscribe_cb(c, ext_stream_restore_subscribe_cb, NULL); // if ((o = pa_ext_stream_restore_subscribe(c, 1, NULL, NULL))) // pa_operation_unref(o); // } else { // qWarning() << "Failed to initialize stream_restore extension: " << pa_strerror(pa_context_errno(m_context)); // } } else if (!PA_CONTEXT_IS_GOOD(state)) { qDebug() << "context kaput"; // If this is our probe phase, exit our context immediately if (m_context != c) { pa_context_disconnect(c); } else { // If we're not probing, it means we've been disconnected from our // glib context pa_context_unref(m_context); m_context = nullptr; #warning fixme // This one is not handled above. // clients.clear(); } } } #warning data changed should possibly only be emitted once eol is >0 to avoid pointless redraws void Context::sinkCallback(pa_context *context, const pa_sink_info *info, int eol) { if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); bool isNew = false; Sink *obj = m_sinks.value(info->index, nullptr); if (!obj) { obj = new Sink; isNew = true; } obj->setInfo(info); m_sinks.insert(info->index, obj); #warning this is bullshit and removal by this method is even more shit int listIndex = -1; QList<quint32> list = m_sinks.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == info->index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); if (isNew) { emit sinkAdded(listIndex); } else { emit sinkUpdated(listIndex); } } void Context::clientCallback(pa_context *context, const pa_client_info *info, int eol) { Q_ASSERT(context); if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); Client *obj = m_clients.value(info->index, nullptr); if (!obj) obj = new Client; obj->setInfo(info); m_clients.insert(info->index, obj); emit clientsChanged(); } void Context::sinkInputCallback(pa_context *context, const pa_sink_input_info *info, int eol) { qDebug() << "sink_input_cb"; Q_ASSERT(context); if (eol < 0) { if (pa_context_errno(context) == PA_ERR_NOENTITY) { return; } return; } if (eol > 0) { return; } Q_ASSERT(info); bool isNew = false; SinkInput *obj = m_sinkInputs.value(info->index, nullptr); if (!obj) { obj = new SinkInput; isNew = true; } obj->setInfo(info); m_sinkInputs.insert(info->index, obj); int listIndex = -1; QList<quint32> list = m_sinkInputs.keys(); for (int i = 0; i < list.size(); ++i) { if (list.at(i) == info->index) { listIndex = i; break; } } Q_ASSERT(listIndex >= 0); qDebug() << Q_FUNC_INFO << isNew << listIndex; if (isNew) { emit sinkInputAdded(listIndex); } else { emit sinkInputUpdated(listIndex); } } void Context::setSinkVolume(quint32 index, quint32 volume) { qDebug() << Q_FUNC_INFO << index << volume; pa_operation *o; Sink *sink = m_sinks.value(index, nullptr); if (!sink) return; pa_cvolume newVolume = sink->volume(); for (int i = 0; i < newVolume.channels; ++i) { newVolume.values[i] = volume; } if (!(o = pa_context_set_sink_volume_by_index(m_context, index, &newVolume, NULL, NULL))) { qWarning() << "pa_context_set_sink_volume_by_index() failed"; return; } pa_operation_unref(o); } void Context::setSinkPort(quint32 portIndex) { pa_operation *o; if (!(o = pa_context_set_sink_port_by_index(m_context, portIndex, nullptr, nullptr, nullptr))) { qWarning() << "pa_context_set_sink_port_by_index failed"; return; } } void Context::setSinkInputVolume(quint32 index, quint32 volume) { qDebug() << Q_FUNC_INFO << index << volume; pa_operation *o; SinkInput *obj = m_sinkInputs.value(index, nullptr); if (!obj) return; pa_cvolume newVolume = obj->volume(); for (int i = 0; i < newVolume.channels; ++i) { newVolume.values[i] = volume; } if (!(o = pa_context_set_sink_input_volume(m_context, index, &newVolume, NULL, NULL))) { qWarning() << "pa_context_set_sink_volume_by_index() failed"; return; } pa_operation_unref(o); } void Context::connectToDaemon() { Q_ASSERT(m_context == nullptr); Q_ASSERT(m_mainloop == nullptr); qDebug() << "Attempting connection to PulseAudio sound daemon"; m_mainloop = pa_glib_mainloop_new(nullptr); pa_mainloop_api *api = pa_glib_mainloop_get_api(m_mainloop); Q_ASSERT(api); m_context = pa_context_new(api, "QPulse"); Q_ASSERT(m_context); if (pa_context_connect(m_context, NULL, PA_CONTEXT_NOFAIL, 0) < 0) { pa_context_unref(m_context); m_context = nullptr; return; } pa_context_set_state_callback(m_context, &context_state_callback, this); } <|endoftext|>
<commit_before>//===-- DynamicLoaderLinux.h ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes #include "lldb/Core/PluginManager.h" #include "lldb/Core/Log.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanRunToAddress.h" #include "AuxVector.h" #include "DynamicLoaderLinuxDYLD.h" using namespace lldb; using namespace lldb_private; void DynamicLoaderLinuxDYLD::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); } void DynamicLoaderLinuxDYLD::Terminate() { } const char * DynamicLoaderLinuxDYLD::GetPluginName() { return "DynamicLoaderLinuxDYLD"; } const char * DynamicLoaderLinuxDYLD::GetShortPluginName() { return "linux-dyld"; } const char * DynamicLoaderLinuxDYLD::GetPluginNameStatic() { return "dynamic-loader.linux-dyld"; } const char * DynamicLoaderLinuxDYLD::GetPluginDescriptionStatic() { return "Dynamic loader plug-in that watches for shared library " "loads/unloads in Linux processes."; } void DynamicLoaderLinuxDYLD::GetPluginCommandHelp(const char *command, Stream *strm) { } uint32_t DynamicLoaderLinuxDYLD::GetPluginVersion() { return 1; } DynamicLoader * DynamicLoaderLinuxDYLD::CreateInstance(Process *process, bool force) { bool create = force; if (!create) { const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple(); if (triple_ref.getOS() == llvm::Triple::Linux) create = true; } if (create) return new DynamicLoaderLinuxDYLD (process); return NULL; } DynamicLoaderLinuxDYLD::DynamicLoaderLinuxDYLD(Process *process) : DynamicLoader(process), m_rendezvous(process), m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS), m_auxv(NULL) { } DynamicLoaderLinuxDYLD::~DynamicLoaderLinuxDYLD() { } void DynamicLoaderLinuxDYLD::DidAttach() { ModuleSP executable; addr_t load_offset; m_auxv.reset(new AuxVector(m_process)); executable = m_process->GetTarget().GetExecutableModule(); load_offset = ComputeLoadOffset(); if (!executable.empty() && load_offset != LLDB_INVALID_ADDRESS) { ModuleList module_list; module_list.Append(executable); UpdateLoadedSections(executable, load_offset); m_process->GetTarget().ModulesDidLoad(module_list); } } void DynamicLoaderLinuxDYLD::DidLaunch() { ModuleSP executable; addr_t load_offset; m_auxv.reset(new AuxVector(m_process)); executable = m_process->GetTarget().GetExecutableModule(); load_offset = ComputeLoadOffset(); if (!executable.empty() && load_offset != LLDB_INVALID_ADDRESS) { ModuleList module_list; module_list.Append(executable); UpdateLoadedSections(executable, load_offset); ProbeEntry(); m_process->GetTarget().ModulesDidLoad(module_list); } } Error DynamicLoaderLinuxDYLD::ExecutePluginCommand(Args &command, Stream *strm) { return Error(); } Log * DynamicLoaderLinuxDYLD::EnablePluginLogging(Stream *strm, Args &command) { return NULL; } Error DynamicLoaderLinuxDYLD::CanLoadImage() { return Error(); } void DynamicLoaderLinuxDYLD::UpdateLoadedSections(ModuleSP module, addr_t base_addr) { ObjectFile *obj_file = module->GetObjectFile(); SectionList *sections = obj_file->GetSectionList(); SectionLoadList &load_list = m_process->GetTarget().GetSectionLoadList(); const size_t num_sections = sections->GetSize(); for (unsigned i = 0; i < num_sections; ++i) { Section *section = sections->GetSectionAtIndex(i).get(); lldb::addr_t new_load_addr = section->GetFileAddress() + base_addr; lldb::addr_t old_load_addr = load_list.GetSectionLoadAddress(section); // If the file address of the section is zero then this is not an // allocatable/loadable section (property of ELF sh_addr). Skip it. if (new_load_addr == base_addr) continue; if (old_load_addr == LLDB_INVALID_ADDRESS || old_load_addr != new_load_addr) load_list.SetSectionLoadAddress(section, new_load_addr); } } void DynamicLoaderLinuxDYLD::ProbeEntry() { Breakpoint *entry_break; addr_t entry; if ((entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS) return; entry_break = m_process->GetTarget().CreateBreakpoint(entry, true).get(); entry_break->SetCallback(EntryBreakpointHit, this, true); } // The runtime linker has run and initialized the rendezvous structure once the // process has hit its entry point. When we hit the corresponding breakpoint we // interrogate the rendezvous structure to get the load addresses of all // dependent modules for the process. Similarly, we can discover the runtime // linker function and setup a breakpoint to notify us of any dynamically loaded // modules (via dlopen). bool DynamicLoaderLinuxDYLD::EntryBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { DynamicLoaderLinuxDYLD* dyld_instance; dyld_instance = static_cast<DynamicLoaderLinuxDYLD*>(baton); dyld_instance->LoadAllCurrentModules(); dyld_instance->SetRendezvousBreakpoint(); return false; // Continue running. } void DynamicLoaderLinuxDYLD::SetRendezvousBreakpoint() { Breakpoint *dyld_break; addr_t break_addr; break_addr = m_rendezvous.GetBreakAddress(); dyld_break = m_process->GetTarget().CreateBreakpoint(break_addr, true).get(); dyld_break->SetCallback(RendezvousBreakpointHit, this, true); } bool DynamicLoaderLinuxDYLD::RendezvousBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { DynamicLoaderLinuxDYLD* dyld_instance; dyld_instance = static_cast<DynamicLoaderLinuxDYLD*>(baton); dyld_instance->RefreshModules(); // Return true to stop the target, false to just let the target run. return dyld_instance->GetStopWhenImagesChange(); } void DynamicLoaderLinuxDYLD::RefreshModules() { if (!m_rendezvous.Resolve()) return; DYLDRendezvous::iterator I; DYLDRendezvous::iterator E; ModuleList &loaded_modules = m_process->GetTarget().GetImages(); if (m_rendezvous.ModulesDidLoad()) { ModuleList new_modules; E = m_rendezvous.loaded_end(); for (I = m_rendezvous.loaded_begin(); I != E; ++I) { FileSpec file(I->path.c_str(), true); ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr); if (!module_sp.empty()) new_modules.Append(module_sp); } m_process->GetTarget().ModulesDidLoad(new_modules); } if (m_rendezvous.ModulesDidUnload()) { ModuleList old_modules; E = m_rendezvous.unloaded_end(); for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { FileSpec file(I->path.c_str(), true); ModuleSP module_sp = loaded_modules.FindFirstModuleForFileSpec(file); if (!module_sp.empty()) old_modules.Append(module_sp); } m_process->GetTarget().ModulesDidUnload(old_modules); } } ThreadPlanSP DynamicLoaderLinuxDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop) { LogSP log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); ThreadPlanSP thread_plan_sp; StackFrame *frame = thread.GetStackFrameAtIndex(0).get(); const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); Symbol *sym = context.symbol; if (sym == NULL || !sym->IsTrampoline()) return thread_plan_sp; const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled); if (!sym_name) return thread_plan_sp; SymbolContextList target_symbols; Target &target = thread.GetProcess().GetTarget(); ModuleList &images = target.GetImages(); images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols); size_t num_targets = target_symbols.GetSize(); if (!num_targets) return thread_plan_sp; typedef std::vector<lldb::addr_t> AddressVector; AddressVector addrs; for (size_t i = 0; i < num_targets; ++i) { SymbolContext context; AddressRange range; if (target_symbols.GetContextAtIndex(i, context)) { context.GetAddressRange(eSymbolContextEverything, range); lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target); if (addr != LLDB_INVALID_ADDRESS) addrs.push_back(addr); } } if (addrs.size() > 0) { AddressVector::iterator start = addrs.begin(); AddressVector::iterator end = addrs.end(); std::sort(start, end); addrs.erase(std::unique(start, end), end); thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); } return thread_plan_sp; } void DynamicLoaderLinuxDYLD::LoadAllCurrentModules() { DYLDRendezvous::iterator I; DYLDRendezvous::iterator E; ModuleList module_list; if (!m_rendezvous.Resolve()) return; for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { FileSpec file(I->path.c_str(), false); ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr); if (!module_sp.empty()) module_list.Append(module_sp); } m_process->GetTarget().ModulesDidLoad(module_list); } ModuleSP DynamicLoaderLinuxDYLD::LoadModuleAtAddress(const FileSpec &file, addr_t base_addr) { Target &target = m_process->GetTarget(); ModuleList &modules = target.GetImages(); ModuleSP module_sp; if ((module_sp = modules.FindFirstModuleForFileSpec(file))) { UpdateLoadedSections(module_sp, base_addr); } else if ((module_sp = target.GetSharedModule(file, target.GetArchitecture()))) { UpdateLoadedSections(module_sp, base_addr); modules.Append(module_sp); } return module_sp; } addr_t DynamicLoaderLinuxDYLD::ComputeLoadOffset() { addr_t virt_entry; if (m_load_offset != LLDB_INVALID_ADDRESS) return m_load_offset; if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS) return LLDB_INVALID_ADDRESS; ModuleSP module = m_process->GetTarget().GetExecutableModule(); ObjectFile *exe = module->GetObjectFile(); Address file_entry = exe->GetEntryPointAddress(); if (!file_entry.IsValid()) return LLDB_INVALID_ADDRESS; m_load_offset = virt_entry - file_entry.GetFileAddress(); return m_load_offset; } addr_t DynamicLoaderLinuxDYLD::GetEntryPoint() { if (m_entry_point != LLDB_INVALID_ADDRESS) return m_entry_point; if (m_auxv.get() == NULL) return LLDB_INVALID_ADDRESS; AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY); if (I == m_auxv->end()) return LLDB_INVALID_ADDRESS; m_entry_point = static_cast<addr_t>(I->value); return m_entry_point; } <commit_msg>linux: add missing arguments to FindFirstModuleForFileSpec<commit_after>//===-- DynamicLoaderLinux.h ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes #include "lldb/Core/PluginManager.h" #include "lldb/Core/Log.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Target/ThreadPlanRunToAddress.h" #include "AuxVector.h" #include "DynamicLoaderLinuxDYLD.h" using namespace lldb; using namespace lldb_private; void DynamicLoaderLinuxDYLD::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance); } void DynamicLoaderLinuxDYLD::Terminate() { } const char * DynamicLoaderLinuxDYLD::GetPluginName() { return "DynamicLoaderLinuxDYLD"; } const char * DynamicLoaderLinuxDYLD::GetShortPluginName() { return "linux-dyld"; } const char * DynamicLoaderLinuxDYLD::GetPluginNameStatic() { return "dynamic-loader.linux-dyld"; } const char * DynamicLoaderLinuxDYLD::GetPluginDescriptionStatic() { return "Dynamic loader plug-in that watches for shared library " "loads/unloads in Linux processes."; } void DynamicLoaderLinuxDYLD::GetPluginCommandHelp(const char *command, Stream *strm) { } uint32_t DynamicLoaderLinuxDYLD::GetPluginVersion() { return 1; } DynamicLoader * DynamicLoaderLinuxDYLD::CreateInstance(Process *process, bool force) { bool create = force; if (!create) { const llvm::Triple &triple_ref = process->GetTarget().GetArchitecture().GetTriple(); if (triple_ref.getOS() == llvm::Triple::Linux) create = true; } if (create) return new DynamicLoaderLinuxDYLD (process); return NULL; } DynamicLoaderLinuxDYLD::DynamicLoaderLinuxDYLD(Process *process) : DynamicLoader(process), m_rendezvous(process), m_load_offset(LLDB_INVALID_ADDRESS), m_entry_point(LLDB_INVALID_ADDRESS), m_auxv(NULL) { } DynamicLoaderLinuxDYLD::~DynamicLoaderLinuxDYLD() { } void DynamicLoaderLinuxDYLD::DidAttach() { ModuleSP executable; addr_t load_offset; m_auxv.reset(new AuxVector(m_process)); executable = m_process->GetTarget().GetExecutableModule(); load_offset = ComputeLoadOffset(); if (!executable.empty() && load_offset != LLDB_INVALID_ADDRESS) { ModuleList module_list; module_list.Append(executable); UpdateLoadedSections(executable, load_offset); m_process->GetTarget().ModulesDidLoad(module_list); } } void DynamicLoaderLinuxDYLD::DidLaunch() { ModuleSP executable; addr_t load_offset; m_auxv.reset(new AuxVector(m_process)); executable = m_process->GetTarget().GetExecutableModule(); load_offset = ComputeLoadOffset(); if (!executable.empty() && load_offset != LLDB_INVALID_ADDRESS) { ModuleList module_list; module_list.Append(executable); UpdateLoadedSections(executable, load_offset); ProbeEntry(); m_process->GetTarget().ModulesDidLoad(module_list); } } Error DynamicLoaderLinuxDYLD::ExecutePluginCommand(Args &command, Stream *strm) { return Error(); } Log * DynamicLoaderLinuxDYLD::EnablePluginLogging(Stream *strm, Args &command) { return NULL; } Error DynamicLoaderLinuxDYLD::CanLoadImage() { return Error(); } void DynamicLoaderLinuxDYLD::UpdateLoadedSections(ModuleSP module, addr_t base_addr) { ObjectFile *obj_file = module->GetObjectFile(); SectionList *sections = obj_file->GetSectionList(); SectionLoadList &load_list = m_process->GetTarget().GetSectionLoadList(); const size_t num_sections = sections->GetSize(); for (unsigned i = 0; i < num_sections; ++i) { Section *section = sections->GetSectionAtIndex(i).get(); lldb::addr_t new_load_addr = section->GetFileAddress() + base_addr; lldb::addr_t old_load_addr = load_list.GetSectionLoadAddress(section); // If the file address of the section is zero then this is not an // allocatable/loadable section (property of ELF sh_addr). Skip it. if (new_load_addr == base_addr) continue; if (old_load_addr == LLDB_INVALID_ADDRESS || old_load_addr != new_load_addr) load_list.SetSectionLoadAddress(section, new_load_addr); } } void DynamicLoaderLinuxDYLD::ProbeEntry() { Breakpoint *entry_break; addr_t entry; if ((entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS) return; entry_break = m_process->GetTarget().CreateBreakpoint(entry, true).get(); entry_break->SetCallback(EntryBreakpointHit, this, true); } // The runtime linker has run and initialized the rendezvous structure once the // process has hit its entry point. When we hit the corresponding breakpoint we // interrogate the rendezvous structure to get the load addresses of all // dependent modules for the process. Similarly, we can discover the runtime // linker function and setup a breakpoint to notify us of any dynamically loaded // modules (via dlopen). bool DynamicLoaderLinuxDYLD::EntryBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { DynamicLoaderLinuxDYLD* dyld_instance; dyld_instance = static_cast<DynamicLoaderLinuxDYLD*>(baton); dyld_instance->LoadAllCurrentModules(); dyld_instance->SetRendezvousBreakpoint(); return false; // Continue running. } void DynamicLoaderLinuxDYLD::SetRendezvousBreakpoint() { Breakpoint *dyld_break; addr_t break_addr; break_addr = m_rendezvous.GetBreakAddress(); dyld_break = m_process->GetTarget().CreateBreakpoint(break_addr, true).get(); dyld_break->SetCallback(RendezvousBreakpointHit, this, true); } bool DynamicLoaderLinuxDYLD::RendezvousBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { DynamicLoaderLinuxDYLD* dyld_instance; dyld_instance = static_cast<DynamicLoaderLinuxDYLD*>(baton); dyld_instance->RefreshModules(); // Return true to stop the target, false to just let the target run. return dyld_instance->GetStopWhenImagesChange(); } void DynamicLoaderLinuxDYLD::RefreshModules() { if (!m_rendezvous.Resolve()) return; DYLDRendezvous::iterator I; DYLDRendezvous::iterator E; ModuleList &loaded_modules = m_process->GetTarget().GetImages(); if (m_rendezvous.ModulesDidLoad()) { ModuleList new_modules; E = m_rendezvous.loaded_end(); for (I = m_rendezvous.loaded_begin(); I != E; ++I) { FileSpec file(I->path.c_str(), true); ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr); if (!module_sp.empty()) new_modules.Append(module_sp); } m_process->GetTarget().ModulesDidLoad(new_modules); } if (m_rendezvous.ModulesDidUnload()) { ModuleList old_modules; E = m_rendezvous.unloaded_end(); for (I = m_rendezvous.unloaded_begin(); I != E; ++I) { FileSpec file(I->path.c_str(), true); ModuleSP module_sp = loaded_modules.FindFirstModuleForFileSpec(file, NULL, NULL); if (!module_sp.empty()) old_modules.Append(module_sp); } m_process->GetTarget().ModulesDidUnload(old_modules); } } ThreadPlanSP DynamicLoaderLinuxDYLD::GetStepThroughTrampolinePlan(Thread &thread, bool stop) { LogSP log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); ThreadPlanSP thread_plan_sp; StackFrame *frame = thread.GetStackFrameAtIndex(0).get(); const SymbolContext &context = frame->GetSymbolContext(eSymbolContextSymbol); Symbol *sym = context.symbol; if (sym == NULL || !sym->IsTrampoline()) return thread_plan_sp; const ConstString &sym_name = sym->GetMangled().GetName(Mangled::ePreferMangled); if (!sym_name) return thread_plan_sp; SymbolContextList target_symbols; Target &target = thread.GetProcess().GetTarget(); ModuleList &images = target.GetImages(); images.FindSymbolsWithNameAndType(sym_name, eSymbolTypeCode, target_symbols); size_t num_targets = target_symbols.GetSize(); if (!num_targets) return thread_plan_sp; typedef std::vector<lldb::addr_t> AddressVector; AddressVector addrs; for (size_t i = 0; i < num_targets; ++i) { SymbolContext context; AddressRange range; if (target_symbols.GetContextAtIndex(i, context)) { context.GetAddressRange(eSymbolContextEverything, range); lldb::addr_t addr = range.GetBaseAddress().GetLoadAddress(&target); if (addr != LLDB_INVALID_ADDRESS) addrs.push_back(addr); } } if (addrs.size() > 0) { AddressVector::iterator start = addrs.begin(); AddressVector::iterator end = addrs.end(); std::sort(start, end); addrs.erase(std::unique(start, end), end); thread_plan_sp.reset(new ThreadPlanRunToAddress(thread, addrs, stop)); } return thread_plan_sp; } void DynamicLoaderLinuxDYLD::LoadAllCurrentModules() { DYLDRendezvous::iterator I; DYLDRendezvous::iterator E; ModuleList module_list; if (!m_rendezvous.Resolve()) return; for (I = m_rendezvous.begin(), E = m_rendezvous.end(); I != E; ++I) { FileSpec file(I->path.c_str(), false); ModuleSP module_sp = LoadModuleAtAddress(file, I->base_addr); if (!module_sp.empty()) module_list.Append(module_sp); } m_process->GetTarget().ModulesDidLoad(module_list); } ModuleSP DynamicLoaderLinuxDYLD::LoadModuleAtAddress(const FileSpec &file, addr_t base_addr) { Target &target = m_process->GetTarget(); ModuleList &modules = target.GetImages(); ModuleSP module_sp; if ((module_sp = modules.FindFirstModuleForFileSpec(file, NULL, NULL))) { UpdateLoadedSections(module_sp, base_addr); } else if ((module_sp = target.GetSharedModule(file, target.GetArchitecture()))) { UpdateLoadedSections(module_sp, base_addr); modules.Append(module_sp); } return module_sp; } addr_t DynamicLoaderLinuxDYLD::ComputeLoadOffset() { addr_t virt_entry; if (m_load_offset != LLDB_INVALID_ADDRESS) return m_load_offset; if ((virt_entry = GetEntryPoint()) == LLDB_INVALID_ADDRESS) return LLDB_INVALID_ADDRESS; ModuleSP module = m_process->GetTarget().GetExecutableModule(); ObjectFile *exe = module->GetObjectFile(); Address file_entry = exe->GetEntryPointAddress(); if (!file_entry.IsValid()) return LLDB_INVALID_ADDRESS; m_load_offset = virt_entry - file_entry.GetFileAddress(); return m_load_offset; } addr_t DynamicLoaderLinuxDYLD::GetEntryPoint() { if (m_entry_point != LLDB_INVALID_ADDRESS) return m_entry_point; if (m_auxv.get() == NULL) return LLDB_INVALID_ADDRESS; AuxVector::iterator I = m_auxv->FindEntry(AuxVector::AT_ENTRY); if (I == m_auxv->end()) return LLDB_INVALID_ADDRESS; m_entry_point = static_cast<addr_t>(I->value); return m_entry_point; } <|endoftext|>
<commit_before>/* * SinglePlayer.cpp * OpenLieroX * * Created by Albert Zeyer on 15.01.10. * code under LGPL * */ #include <boost/bind.hpp> #include "SinglePlayer.h" #include "Options.h" #include "ConfigHandler.h" #include "game/Mod.h" #include "game/Level.h" #include "GfxPrimitives.h" #include "DeprecatedGUI/Menu.h" #include "CClient.h" #include "CServer.h" #include "ProfileSystem.h" #include "CWormHuman.h" #include "OLXCommand.h" #include "util/macros.h" #include "game/Settings.h" #include "game/Game.h" #include "client/ClientConnectionRequestInfo.h" SinglePlayerGame singlePlayerGame; static bool gameLevelExists(const std::string& game, int levelNr) { std::string dir; if(!ReadString("games/" + game + "/game.cfg", "Level" + itoa(levelNr), "Dir", dir, "") || Trimmed(dir) == "") return false; else return true; } static bool gameExists(const std::string& game) { return gameLevelExists(game, 1); } int SinglePlayerGame::maxSelectableLevelForCurrentGame() { int level = 1; std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame); if(f != tLXOptions->localplayLevels.end()) // this is the max allowed level level = MAX(f->second, 1); // check the last existing level while(level > 1 && !gameLevelExists(currentGame, level)) --level; return level; } void SinglePlayerGame::setGame(const std::string& game) { if(!stringcaseequal(currentGame, game)) { currentGame = game; setLevel(maxSelectableLevelForCurrentGame()); } } bool SinglePlayerGame::setLevel(int levelNr) { currentGameValid = false; image = NULL; levelInfo = LevelInfo(); modInfo = ModInfo(); description = ""; if(!gameExists(currentGame)) { description = "<font color=red>Game <b>" + currentGame + "</b> is invalid</font>"; errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl; return false; } currentLevel = levelNr; if(currentLevel <= 0) currentLevel = 1; if(!gameLevelExists(currentGame, currentLevel)) { warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl; do { currentLevel--; } while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel)); if(currentLevel <= 0) { errors << "SinglePlayerGame::setLevel: woot" << endl; return false; } } std::string level, mod, img; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Dir", level, ""); TrimSpaces(level); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Mod", mod, "Classic"); TrimSpaces(mod); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Image", img, ""); TrimSpaces(img); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Desc", description, ""); TrimSpaces(description); level = "../games/" + currentGame + "/" + level; // it's relative to levels levelInfo = infoForLevel(level); if(!levelInfo.valid) { description = "<font color=red>Problem while loading level " + level + "</font>"; errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl; return false; } levelInfo.path = level; // to force this uncommon filename modInfo = infoForMod(mod); if(!modInfo.valid) { description = "<font color=red>Problem while loading mod " + mod + "</font>"; errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl; return false; } if(description == "") description = "Undescribed level <b>" + itoa(currentLevel) + "</b> of game <b>" + currentGame + "</b>"; image = LoadGameImage("games/" + currentGame + "/" + img); if(image.get() == NULL) { warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl; image = gfxCreateSurfaceAlpha(200, 50); DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0)); } currentGameValid = true; return true; } static bool addPlayerToClient() { // this is the current way to tell CClient to create a local worm later on with that profile // that is done in CClientNetEngine::ParseConnected or updateAddedWorms cClient->connectInfo = new ClientConnectionRequestInfo; cClient->connectInfo->worms.push_back(MainHumanProfile()); return true; } struct SinglePlayerSettingsScope : FeatureSettingsLayer { Settings::Layers oldLayers; SinglePlayerSettingsScope() : FeatureSettingsLayer("Single player game settings") { oldLayers.swap(gameSettings.layers); gameSettings.layersInitStandard(false); gameSettings.layers.push_back(this); } ~SinglePlayerSettingsScope() { oldLayers.swap(gameSettings.layers); } }; static SmartPointer<SinglePlayerSettingsScope> singlePlayerSettings; static void SinglePlayer_CleanupAfterGameloopEnd() { singlePlayerSettings = NULL; } bool SinglePlayerGame::startGame() { levelSucceeded = false; if(!currentGameValid) { errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl; return false; } if(bDedicated) { errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl; // actually, we could but I really dont see a reason why we would want return false; } if(singlePlayerSettings.get()) singlePlayerSettings = NULL; // just to be sure singlePlayerSettings = new SinglePlayerSettingsScope(); if(! cClient->Initialize() ) { errors << "Could not initialize client" << endl; return false; } if(!addPlayerToClient()) { errors << "SinglePlayerGame::startGame: didn't found human worm" << endl; return false; } if(!cServer->StartServer()) { errors << "Could not start server" << endl; return false; } // standardGameMode is the lower level game mode - can be set by custom config file standardGameMode = NULL; // don't have any wpn restrictions cServer->setWeaponRestFile(""); gameSettings.overwrite[FT_Map].as<LevelInfo>()->path = levelInfo.path; gameSettings.overwrite[FT_Map].as<LevelInfo>()->name = levelInfo.name; gameSettings.overwrite[FT_Mod].as<ModInfo>()->path = modInfo.path; gameSettings.overwrite[FT_Mod].as<ModInfo>()->name = modInfo.name; gameSettings.overwrite[FT_NewNetEngine] = false; gameSettings.overwrite[FT_Lives] = -2; gameSettings.overwrite[FT_KillLimit] = -1; gameSettings.overwrite[FT_TimeLimit] = -1.0f; gameSettings.overwrite[FT_GameMode].as<GameModeInfo>()->mode = this; { std::string extraConfig; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Config", extraConfig, ""); TrimSpaces(extraConfig); if(extraConfig != "") { notes << "SinglePlayerGame: config: " << extraConfig << endl; singlePlayerSettings->loadFromConfig("games/" + currentGame + "/" + extraConfig, false); } } { std::string extraCmdStr; std::vector<std::string> extraCmds; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Exec", extraCmdStr, ""); TrimSpaces(extraCmdStr); extraCmds = explode(extraCmdStr, ";"); foreach(c, extraCmds) { notes << "SinglePlayerGame: exec: " << *c << endl; game.prepareCallbacks.connect(boost::bind(Execute, &stdoutCLI(), *c)); } } // this can happen if the config has overwritten it if(gameSettings[FT_GameMode].as<GameModeInfo>()->mode != this) { // we set the fallback gamemode standardGameMode = gameSettings[FT_GameMode].as<GameModeInfo>()->mode; gameSettings.overwrite[FT_GameMode].as<GameModeInfo>()->mode = this; } game.cleanupCallbacks.connect(boost::bind(&SinglePlayer_CleanupAfterGameloopEnd)); return true; } void SinglePlayerGame::setLevelSucceeded() { if(levelSucceeded) return; notes << "SinglePlayerGame: level was succeeded" << endl; levelSucceeded = true; game.gameOver = true; tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel + 1); if(gameLevelExists(currentGame, currentLevel + 1)) setLevel(currentLevel + 1); } void SinglePlayerGame::Simulate() { if(standardGameMode) standardGameMode->Simulate(); if(levelSucceeded) cServer->RecheckGame(); } bool SinglePlayerGame::CheckGameOver() { if(standardGameMode && standardGameMode->CheckGameOver()) { notes << "SinglePlayer game gameOver, winner is " << standardGameMode->Winner() << ", winner team is " << standardGameMode->WinnerTeam() << endl; CWorm* w = game.firstLocalHumanWorm(); if(w && standardGameMode->Winner() == w->getID()) setLevelSucceeded(); else if(w && standardGameMode->isTeamGame() && standardGameMode->WinnerTeam() == w->getTeam()) setLevelSucceeded(); return true; } return levelSucceeded; } int SinglePlayerGame::Winner() { if(!levelSucceeded) { if(standardGameMode) return standardGameMode->Winner(); return -1; } CWorm* w = game.firstLocalHumanWorm(); if(w) return w->getID(); return -1; } void SinglePlayerGame::GameOver() { if(standardGameMode) standardGameMode->GameOver(); } <commit_msg>small dbg out<commit_after>/* * SinglePlayer.cpp * OpenLieroX * * Created by Albert Zeyer on 15.01.10. * code under LGPL * */ #include <boost/bind.hpp> #include "SinglePlayer.h" #include "Options.h" #include "ConfigHandler.h" #include "game/Mod.h" #include "game/Level.h" #include "GfxPrimitives.h" #include "DeprecatedGUI/Menu.h" #include "CClient.h" #include "CServer.h" #include "ProfileSystem.h" #include "CWormHuman.h" #include "OLXCommand.h" #include "util/macros.h" #include "game/Settings.h" #include "game/Game.h" #include "client/ClientConnectionRequestInfo.h" SinglePlayerGame singlePlayerGame; static bool gameLevelExists(const std::string& game, int levelNr) { std::string dir; if(!ReadString("games/" + game + "/game.cfg", "Level" + itoa(levelNr), "Dir", dir, "") || Trimmed(dir) == "") return false; else return true; } static bool gameExists(const std::string& game) { return gameLevelExists(game, 1); } int SinglePlayerGame::maxSelectableLevelForCurrentGame() { int level = 1; std::map<std::string,int>::iterator f = tLXOptions->localplayLevels.find(currentGame); if(f != tLXOptions->localplayLevels.end()) // this is the max allowed level level = MAX(f->second, 1); // check the last existing level while(level > 1 && !gameLevelExists(currentGame, level)) --level; return level; } void SinglePlayerGame::setGame(const std::string& game) { if(!stringcaseequal(currentGame, game)) { currentGame = game; setLevel(maxSelectableLevelForCurrentGame()); } } bool SinglePlayerGame::setLevel(int levelNr) { currentGameValid = false; image = NULL; levelInfo = LevelInfo(); modInfo = ModInfo(); description = ""; if(!gameExists(currentGame)) { description = "<font color=red>Game <b>" + currentGame + "</b> is invalid</font>"; errors << "SinglePlayerGame::setLevel: game " << currentGame << " unknown" << endl; return false; } currentLevel = levelNr; if(currentLevel <= 0) currentLevel = 1; if(!gameLevelExists(currentGame, currentLevel)) { warnings << "SinglePlayerGame::setLevel: game " << currentGame << " doesnt have level " << currentLevel << endl; do { currentLevel--; } while(currentLevel > 0 && !gameLevelExists(currentGame, currentLevel)); if(currentLevel <= 0) { errors << "SinglePlayerGame::setLevel: woot" << endl; return false; } } std::string level, mod, img; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Dir", level, ""); TrimSpaces(level); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Mod", mod, "Classic"); TrimSpaces(mod); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Image", img, ""); TrimSpaces(img); ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Desc", description, ""); TrimSpaces(description); level = "../games/" + currentGame + "/" + level; // it's relative to levels levelInfo = infoForLevel(level); if(!levelInfo.valid) { description = "<font color=red>Problem while loading level " + level + "</font>"; errors << "SinglePlayerGame::setLevel: cannot find map " << level << " for game " << currentGame << ":" << currentLevel << endl; return false; } levelInfo.path = level; // to force this uncommon filename modInfo = infoForMod(mod); if(!modInfo.valid) { description = "<font color=red>Problem while loading mod " + mod + "</font>"; errors << "SinglePlayerGame::setLevel: cannot find mod " << mod << " for game " << currentGame << ":" << currentLevel << endl; return false; } if(description == "") description = "Undescribed level <b>" + itoa(currentLevel) + "</b> of game <b>" + currentGame + "</b>"; image = LoadGameImage("games/" + currentGame + "/" + img); if(image.get() == NULL) { warnings << "SinglePlayerGame::setLevel: cannot load preview image '" << img << "' for game " << currentGame << ":" << currentLevel << endl; image = gfxCreateSurfaceAlpha(200, 50); DrawCross(image.get(), 0, 0, 200, 50, Color(255,0,0)); } currentGameValid = true; return true; } static bool addPlayerToClient() { // this is the current way to tell CClient to create a local worm later on with that profile // that is done in CClientNetEngine::ParseConnected or updateAddedWorms cClient->connectInfo = new ClientConnectionRequestInfo; cClient->connectInfo->worms.push_back(MainHumanProfile()); return true; } struct SinglePlayerSettingsScope : FeatureSettingsLayer { Settings::Layers oldLayers; SinglePlayerSettingsScope() : FeatureSettingsLayer("Single player game settings") { oldLayers.swap(gameSettings.layers); gameSettings.layersInitStandard(false); gameSettings.layers.push_back(this); } ~SinglePlayerSettingsScope() { oldLayers.swap(gameSettings.layers); } }; static SmartPointer<SinglePlayerSettingsScope> singlePlayerSettings; static void SinglePlayer_CleanupAfterGameloopEnd() { singlePlayerSettings = NULL; } bool SinglePlayerGame::startGame() { levelSucceeded = false; if(!currentGameValid) { errors << "SinglePlayerGame::startGame: cannot start game: current game/level is invalid" << endl; return false; } if(bDedicated) { errors << "SinglePlayerGame::startGame: cannot do that in dedicated mode" << endl; // actually, we could but I really dont see a reason why we would want return false; } if(singlePlayerSettings.get()) singlePlayerSettings = NULL; // just to be sure singlePlayerSettings = new SinglePlayerSettingsScope(); if(! cClient->Initialize() ) { errors << "Could not initialize client" << endl; return false; } if(!addPlayerToClient()) { errors << "SinglePlayerGame::startGame: didn't found human worm" << endl; return false; } if(!cServer->StartServer()) { errors << "Could not start server" << endl; return false; } // standardGameMode is the lower level game mode - can be set by custom config file standardGameMode = NULL; // don't have any wpn restrictions cServer->setWeaponRestFile(""); gameSettings.overwrite[FT_Map].as<LevelInfo>()->path = levelInfo.path; gameSettings.overwrite[FT_Map].as<LevelInfo>()->name = levelInfo.name; gameSettings.overwrite[FT_Mod].as<ModInfo>()->path = modInfo.path; gameSettings.overwrite[FT_Mod].as<ModInfo>()->name = modInfo.name; gameSettings.overwrite[FT_NewNetEngine] = false; gameSettings.overwrite[FT_Lives] = -2; gameSettings.overwrite[FT_KillLimit] = -1; gameSettings.overwrite[FT_TimeLimit] = -1.0f; gameSettings.overwrite[FT_GameMode].as<GameModeInfo>()->mode = this; { std::string extraConfig; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Config", extraConfig, ""); TrimSpaces(extraConfig); if(extraConfig != "") { notes << "SinglePlayerGame: config: " << extraConfig << endl; singlePlayerSettings->loadFromConfig("games/" + currentGame + "/" + extraConfig, false); } } { std::string extraCmdStr; std::vector<std::string> extraCmds; ReadString("games/" + currentGame + "/game.cfg", "Level" + itoa(currentLevel), "Exec", extraCmdStr, ""); TrimSpaces(extraCmdStr); extraCmds = explode(extraCmdStr, ";"); foreach(c, extraCmds) { notes << "SinglePlayerGame: exec: " << *c << endl; game.prepareCallbacks.connect(boost::bind(Execute, &stdoutCLI(), *c)); } } // this can happen if the config has overwritten it if(gameSettings[FT_GameMode].as<GameModeInfo>()->mode != this) { // we set the fallback gamemode standardGameMode = gameSettings[FT_GameMode].as<GameModeInfo>()->mode; gameSettings.overwrite[FT_GameMode].as<GameModeInfo>()->mode = this; notes << "singlePlayer: special game mode " << standardGameMode->Name() << endl; } game.cleanupCallbacks.connect(boost::bind(&SinglePlayer_CleanupAfterGameloopEnd)); return true; } void SinglePlayerGame::setLevelSucceeded() { if(levelSucceeded) return; notes << "SinglePlayerGame: level was succeeded" << endl; levelSucceeded = true; game.gameOver = true; tLXOptions->localplayLevels[currentGame] = MAX((int)tLXOptions->localplayLevels[currentGame], (int)currentLevel + 1); if(gameLevelExists(currentGame, currentLevel + 1)) setLevel(currentLevel + 1); } void SinglePlayerGame::Simulate() { if(standardGameMode) standardGameMode->Simulate(); if(levelSucceeded) cServer->RecheckGame(); } bool SinglePlayerGame::CheckGameOver() { if(standardGameMode && standardGameMode->CheckGameOver()) { notes << "SinglePlayer game gameOver, winner is " << standardGameMode->Winner() << ", winner team is " << standardGameMode->WinnerTeam() << endl; CWorm* w = game.firstLocalHumanWorm(); if(w && standardGameMode->Winner() == w->getID()) setLevelSucceeded(); else if(w && standardGameMode->isTeamGame() && standardGameMode->WinnerTeam() == w->getTeam()) setLevelSucceeded(); return true; } return levelSucceeded; } int SinglePlayerGame::Winner() { if(!levelSucceeded) { if(standardGameMode) return standardGameMode->Winner(); return -1; } CWorm* w = game.firstLocalHumanWorm(); if(w) return w->getID(); return -1; } void SinglePlayerGame::GameOver() { if(standardGameMode) standardGameMode->GameOver(); } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_LINEAR_BVH_DECL_HPP #define DTK_LINEAR_BVH_DECL_HPP #include <DTK_Box.hpp> #include <DTK_DetailsBoundingVolumeHierarchyImpl.hpp> #include <DTK_DetailsNode.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy { public: using bounding_volume_type = Box; using size_type = typename Kokkos::View<int *, DeviceType>::size_type; BoundingVolumeHierarchy() = default; // build an empty tree BoundingVolumeHierarchy( Kokkos::View<Box const *, DeviceType> bounding_boxes ); KOKKOS_INLINE_FUNCTION size_type size() const { return _leaf_nodes.extent( 0 ); } KOKKOS_INLINE_FUNCTION bool empty() const { return size() == 0; } KOKKOS_INLINE_FUNCTION bounding_volume_type bounds() const { // NOTE should default constructor initialize to an invalid geometry? if ( empty() ) return bounding_volume_type(); return ( size() > 1 ? _internal_nodes : _leaf_nodes )[0].bounding_box; } template <typename Query, typename... Args> inline void query( Kokkos::View<Query *, DeviceType> queries, Args &&... args ) const { using Tag = typename Query::Tag; Details::BoundingVolumeHierarchyImpl<DeviceType>::queryDispatch( Tag{}, *this, queries, std::forward<Args>( args )... ); } private: friend struct Details::TreeTraversal<DeviceType>; Kokkos::View<Node *, DeviceType> _leaf_nodes; Kokkos::View<Node *, DeviceType> _internal_nodes; }; template <typename DeviceType> using BVH = BoundingVolumeHierarchy<DeviceType>; } // namespace DataTransferKit #endif <commit_msg>Pointless s/int/Node/ in BoundingVolumeHierarchy::size_type declaration<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_LINEAR_BVH_DECL_HPP #define DTK_LINEAR_BVH_DECL_HPP #include <DTK_Box.hpp> #include <DTK_DetailsBoundingVolumeHierarchyImpl.hpp> #include <DTK_DetailsNode.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy { public: using bounding_volume_type = Box; using size_type = typename Kokkos::View<Node *, DeviceType>::size_type; BoundingVolumeHierarchy() = default; // build an empty tree BoundingVolumeHierarchy( Kokkos::View<Box const *, DeviceType> bounding_boxes ); KOKKOS_INLINE_FUNCTION size_type size() const { return _leaf_nodes.extent( 0 ); } KOKKOS_INLINE_FUNCTION bool empty() const { return size() == 0; } KOKKOS_INLINE_FUNCTION bounding_volume_type bounds() const { // NOTE should default constructor initialize to an invalid geometry? if ( empty() ) return bounding_volume_type(); return ( size() > 1 ? _internal_nodes : _leaf_nodes )[0].bounding_box; } template <typename Query, typename... Args> inline void query( Kokkos::View<Query *, DeviceType> queries, Args &&... args ) const { using Tag = typename Query::Tag; Details::BoundingVolumeHierarchyImpl<DeviceType>::queryDispatch( Tag{}, *this, queries, std::forward<Args>( args )... ); } private: friend struct Details::TreeTraversal<DeviceType>; Kokkos::View<Node *, DeviceType> _leaf_nodes; Kokkos::View<Node *, DeviceType> _internal_nodes; }; template <typename DeviceType> using BVH = BoundingVolumeHierarchy<DeviceType>; } // namespace DataTransferKit #endif <|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 "BulkMessageTest.h" #include <activemq/util/CMSListener.h> #include <activemq/exceptions/ActiveMQException.h> #include <decaf/lang/Thread.h> #include <decaf/util/UUID.h> #include <decaf/lang/Pointer.h> using namespace std; using namespace cms; using namespace activemq; using namespace activemq::test; using namespace activemq::util; using namespace activemq::exceptions; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; //////////////////////////////////////////////////////////////////////////////// namespace { class ProducerThread : public Thread { private: std::auto_ptr<activemq::util::CMSProvider> cmsProducerProvider; int num; int size; private: ProducerThread(const ProducerThread&); ProducerThread& operator= (const ProducerThread&); public: ProducerThread(const std::string& brokerURL, const std::string& destinationName, const std::string& subscription, int num, int size) : cmsProducerProvider(new activemq::util::CMSProvider(brokerURL, destinationName, subscription)), num(num), size(size) { } virtual ~ProducerThread() {} virtual void run() { cms::Session* session( cmsProducerProvider->getSession() ); Destination* destination = cmsProducerProvider->getDestination(); Pointer<MessageProducer> producer( session->createProducer( destination ) ); producer->setDeliveryMode( cms::DeliveryMode::NON_PERSISTENT ); std::string DATA = "abcdefghijklmnopqrstuvwxyz"; std::string body = ""; for( int i=0; i < size; i ++) { body += DATA.at(i % DATA.length()); } Pointer<BytesMessage> message; for( int i = 0; i < num; ++i ) { message.reset( session->createBytesMessage( (const unsigned char*) body.c_str(), body.length() ) ); producer->send( message.get() ); } } }; } //////////////////////////////////////////////////////////////////////////////// BulkMessageTest::BulkMessageTest() { } //////////////////////////////////////////////////////////////////////////////// BulkMessageTest::~BulkMessageTest() { } //////////////////////////////////////////////////////////////////////////////// void BulkMessageTest::testBulkMessageSendReceive() { static const int MSG_COUNT = 5000; static const int MSG_SIZE = 8192; // Create CMS Object for consumer Comms cms::Session* session( cmsProvider->getSession() ); cms::MessageConsumer* consumer = cmsProvider->getConsumer(); Destination* destination = cmsProvider->getDestination(); ProducerThread thread( this->getBrokerURL(), cmsProvider->getDestinationName(), cmsProvider->getSubscription(), MSG_COUNT, MSG_SIZE ); thread.start(); Pointer<cms::Message> message; for( int i = 0; i < MSG_COUNT ; ++i ) { CPPUNIT_ASSERT_NO_THROW( message.reset( consumer->receive( 2000 ) ) ); CPPUNIT_ASSERT( message.get() != NULL ); } } <commit_msg>Fix some warnings <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 "BulkMessageTest.h" #include <activemq/util/CMSListener.h> #include <activemq/exceptions/ActiveMQException.h> #include <decaf/lang/Thread.h> #include <decaf/util/UUID.h> #include <decaf/lang/Pointer.h> using namespace std; using namespace cms; using namespace activemq; using namespace activemq::test; using namespace activemq::util; using namespace activemq::exceptions; using namespace decaf; using namespace decaf::lang; using namespace decaf::util; //////////////////////////////////////////////////////////////////////////////// namespace { class ProducerThread : public Thread { private: std::auto_ptr<activemq::util::CMSProvider> cmsProducerProvider; int num; int size; private: ProducerThread(const ProducerThread&); ProducerThread& operator= (const ProducerThread&); public: ProducerThread(const std::string& brokerURL, const std::string& destinationName, const std::string& subscription, int num, int size) : cmsProducerProvider(new activemq::util::CMSProvider(brokerURL, destinationName, subscription)), num(num), size(size) { } virtual ~ProducerThread() {} virtual void run() { cms::Session* session( cmsProducerProvider->getSession() ); Destination* destination = cmsProducerProvider->getDestination(); Pointer<MessageProducer> producer( session->createProducer( destination ) ); producer->setDeliveryMode( cms::DeliveryMode::NON_PERSISTENT ); std::string DATA = "abcdefghijklmnopqrstuvwxyz"; std::string body = ""; for( int i=0; i < size; i ++) { body += DATA.at(i % DATA.length()); } Pointer<BytesMessage> message; for( int i = 0; i < num; ++i ) { message.reset( session->createBytesMessage( (const unsigned char*) body.c_str(), (int) body.length() ) ); producer->send( message.get() ); } } }; } //////////////////////////////////////////////////////////////////////////////// BulkMessageTest::BulkMessageTest() { } //////////////////////////////////////////////////////////////////////////////// BulkMessageTest::~BulkMessageTest() { } //////////////////////////////////////////////////////////////////////////////// void BulkMessageTest::testBulkMessageSendReceive() { static const int MSG_COUNT = 5000; static const int MSG_SIZE = 8192; // Create CMS Object for consumer Comms cms::MessageConsumer* consumer = cmsProvider->getConsumer(); ProducerThread thread(this->getBrokerURL(), cmsProvider->getDestinationName(), cmsProvider->getSubscription(), MSG_COUNT, MSG_SIZE); thread.start(); Pointer<cms::Message> message; for (int i = 0; i < MSG_COUNT; ++i) { CPPUNIT_ASSERT_NO_THROW(message.reset(consumer->receive(2000))); CPPUNIT_ASSERT(message.get() != NULL); } } <|endoftext|>
<commit_before>#include "classui.h" #include "listworker.h" #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; classUI::classUI() { } void classUI::run() { bool runOn = true; string choice; do { cout << "List of things: " << endl; cout << "-----------------------------------------------------------" << endl; cout << "add - Add to the list" << endl; cout << "remove - Remove from the list" << endl; cout << "view - View the entire list" << endl; cout << "save - save the file" << endl; cout << "search - Search the list" << endl; cout << "sort - Sort the list by name/yearofbirth" << endl; cout << "exit - Exit" << endl; cin >> choice; if (choice != "exit"){ select(choice); } else{ runOn = false; } }while(runOn == true); } void classUI::select(string ch) { if(ch == "add" || ch == "ADD" || ch == "Add" ){ addPerson(); } else if(ch == "view" || ch == "View" || ch == "VIEW") { viewAll(); } else if(ch == "sort") { string sortcho; cout << "Enter 'name' or 'year' and then re-enter the 'view' command." << endl; cin >> sortcho; if(sortcho == "name") { list.sortNames(); } else if(sortcho == "year") { list.sortBirth(); } } else if(ch == "search" || ch == "Search" || ch == "SEARCH"){ searching(); } else if(ch == "remove" || ch == "Remove" || ch == "REMOVE"){ remove(); } else if(ch == "save" || ch == "Save" || ch == "SAVE"){ save(); } else { cout << "Invalid input" << endl; } } void classUI::view(int i) { int nameSize = list.getNameSize(i); cout << endl; cout << "--------------------------------------------------------------" << endl; cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl; cout << "--------------------------------|-------|-------|-------------" << endl; cout << list.getName(i); if(nameSize > 0 && nameSize <= 7) { cout << "\t" << "\t" << "\t" << "\t"; } else if(nameSize > 7 && nameSize <= 15) { cout << "\t" << "\t" << "\t"; } else if(nameSize > 15 && nameSize <= 23) { cout << "\t" << "\t"; } else if(nameSize > 23 && nameSize <= 31) { cout << "\t"; } if(list.getGender(i) == 'M' || list.getGender(i) == 'm') { cout << "|Male" << "\t"; } else { cout << "|Female" << "\t"; } cout << "|" << list.getBirth(i); if(list.getDeath(i) == 0) { cout << "\t" << "|Still kickin'" << endl; } else { cout << "\t" << "|" << list.getDeath(i) << endl; } cout << list.getComment(i) << endl; cout << "--------------------------------------------------------------" << endl; cout << endl; } void classUI::searching() { cout << "----------Select any of the following options----------" << endl; cout << "What do you want to search for? " << endl; cout << "Name -- Searches for a name" << endl; cout << "Gender -- Searches for a Gender" << endl; cout << "Year -- Searches for a year born" << endl; search(); } void classUI::addPerson() { string name; char gender; int yearOfBirth = 0; int yearOfDeath = 0; string comment; cout << "Input Name: "; cin.ignore(); std::getline(std::cin,name); cout << "Input gender (M/F): "; cin >> gender; if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { cout << "Input year of birth: "; cin >> yearOfBirth; cout << "Input year of death: "; cin >> yearOfDeath; cout << "Input a comment: "; cin >> comment; } else { cout << "Invalid gender! Try again." << endl; addPerson(); } list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment); } void classUI::search() { string searchChoice; cin >> searchChoice; if (searchChoice == "Name" || searchChoice == "name" || searchChoice == "NAME") { string namesearch; cout << "Enter a name you want to search for: "; cin >> namesearch; for(int i = 0; i < list.getPersonsSize();++i) { if(namesearch == list.getName(i)) { namesearch = list.getName(i); view(i); } } /*if ( eitthvad dot) { cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else if (searchChoice == "Gender" || searchChoice == "GENDER" || searchChoice == "gender") { char gendersearch; cout << "Enter a Gender you want to search for: "; cin >> gendersearch; for(int i = 0; i < list.getPersonsSize();++i) { if(gendersearch == list.getGender(i)) { gendersearch = gendersearch + list.getGender(i); view(i); } } /* if (eitthvad dot) { cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else if (searchChoice == "year" || searchChoice == "YEAR" || searchChoice == "Year") { int yearsearch; cout << "Enter a Year you want to search for: "; cin >> yearsearch; for(int i = 0; i < list.getPersonsSize();++i) { if(yearsearch == list.getBirth(i)) { yearsearch = yearsearch + list.getBirth(i); view(i); } }/* if (eitthvad dot) { cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else { cout << "Error reading input" << endl; } } void classUI::remove() { string name; cout << "Enter a name of person that you want to remove: "; cin >> name; if (list.removePerson(name) == true) { cout << "Person removed!" << endl; } else { cout << "Person not found!" << endl; } } void classUI::save() { list.saveFile(); } void classUI::viewAll() { for(int i = 0; i < list.getPersonsSize(); i++) { view(i); } } <commit_msg>sma lagfaeringar<commit_after>#include "classui.h" #include "listworker.h" #include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; classUI::classUI() { } void classUI::run() { bool runOn = true; string choice; do { cout << "List of things: " << endl; cout << "-----------------------------------------------------------" << endl; cout << "add - Add to the list" << endl; cout << "remove - Remove from the list" << endl; cout << "view - View the entire list" << endl; cout << "save - save the file" << endl; cout << "search - Search the list" << endl; cout << "sort - Sort the list by name/yearofbirth" << endl; cout << "exit - Exit" << endl; cin >> choice; if (choice != "exit"){ select(choice); } else{ runOn = false; } }while(runOn == true); } void classUI::select(string ch) { if(ch == "add" || ch == "ADD" || ch == "Add" ){ addPerson(); } else if(ch == "view" || ch == "View" || ch == "VIEW") { viewAll(); } else if(ch == "sort") { string sortcho; cout << "Enter 'name' or 'year' and then re-enter the 'view' command." << endl; cin >> sortcho; if(sortcho == "name") { list.sortNames(); } else if(sortcho == "year") { list.sortBirth(); } } else if(ch == "search" || ch == "Search" || ch == "SEARCH"){ searching(); } else if(ch == "remove" || ch == "Remove" || ch == "REMOVE"){ remove(); } else if(ch == "save" || ch == "Save" || ch == "SAVE"){ save(); } else { cout << "Invalid input" << endl; } } void classUI::view(int i) { int nameSize = list.getNameSize(i); cout << endl; cout << "--------------------------------------------------------------" << endl; cout << "Name" << "\t" << "\t" << "\t" << "\t" << "|Gender " << "|Born " << "\t" << "|Death" << endl; cout << "--------------------------------|-------|-------|-------------" << endl; cout << list.getName(i); if(nameSize > 0 && nameSize <= 7) { cout << "\t" << "\t" << "\t" << "\t"; } else if(nameSize > 7 && nameSize <= 15) { cout << "\t" << "\t" << "\t"; } else if(nameSize > 15 && nameSize <= 23) { cout << "\t" << "\t"; } else if(nameSize > 23 && nameSize <= 31) { cout << "\t"; } if(list.getGender(i) == 'M' || list.getGender(i) == 'm') { cout << "|Male" << "\t"; } else { cout << "|Female" << "\t"; } cout << "|" << list.getBirth(i); if(list.getDeath(i) == 0) { cout << "\t" << "|Still kickin'" << endl; } else { cout << "\t" << "|" << list.getDeath(i) << endl; } cout << list.getComment(i) << endl; cout << "--------------------------------------------------------------" << endl; cout << endl; } void classUI::searching() { cout << "----------Select any of the following options----------" << endl; cout << "What do you want to search for? " << endl; cout << "Name -- Searches for a name" << endl; cout << "Gender -- Searches for a Gender" << endl; cout << "Year -- Searches for a year born" << endl; search(); } void classUI::addPerson() { string name; char gender; int yearOfBirth = 0; int yearOfDeath = 0; string comment; cout << "Input Name: "; cin.ignore(); std::getline(std::cin,name); cout << "Input gender (M/F): "; cin >> gender; if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { cout << "Input year of birth: "; cin >> yearOfBirth; cout << "Input year of death: "; cin >> yearOfDeath; cout << "Input a comment: "; cin >> comment; } else { cout << "Invalid gender! Try again." << endl; addPerson(); } list.addNewPerson(name, gender, yearOfBirth, yearOfDeath, comment); } void classUI::search() { string searchChoice; cin >> searchChoice; if (searchChoice == "Name" || searchChoice == "name" || searchChoice == "NAME") { string namesearch; cout << "Enter a name you want to search for: "; cin >> namesearch; for(int i = 0; i < list.getPersonsSize();++i) { if(namesearch == list.getName(i)) { namesearch = list.getName(i); view(i); } } /*if ( eitthvad dot) { cout << "Sorry that name is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else if (searchChoice == "Gender" || searchChoice == "GENDER" || searchChoice == "gender") { char gendersearch; cout << "Enter a Gender you want to search for: (m/f)"; cin >> gendersearch; for(int i = 0; i < list.getPersonsSize();++i) { if(gendersearch == list.getGender(i)) { gendersearch = list.getGender(i); view(i); cout << "blabla" << endl; } } /* if (eitthvad dot) { cout << "Sorry that gender is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else if (searchChoice == "year" || searchChoice == "YEAR" || searchChoice == "Year") { int yearsearch; cout << "Enter a Year you want to search for: "; cin >> yearsearch; for(int i = 0; i < list.getPersonsSize();++i) { if(yearsearch == list.getBirth(i)) { yearsearch = list.getBirth(i); view(i); } }/* if (eitthvad dot) { cout << "Sorry that year is not in our database, but you can add a new instance in the 'Add' section in the main menu" << endl; }*/ } else { cout << "Error reading input" << endl; } } void classUI::remove() { string name; cout << "Enter a name of person that you want to remove: "; cin >> name; if (list.removePerson(name) == true) { cout << "Person removed!" << endl; } else { cout << "Person not found!" << endl; } } void classUI::save() { list.saveFile(); } void classUI::viewAll() { for(int i = 0; i < list.getPersonsSize(); i++) { view(i); } } <|endoftext|>
<commit_before>// BubbleSort.cpp // by Xiaoguang Zhu (id est smdsbz) of the Backstage Group #include <iostream> #include <vector> using namespace std; int main() { // get the numbers from user input vector<int> array; cout << "Enter at least two numbers to start the bubble sort." << endl; for (int p = 0, input = 0; cin >> input; ++p) { array.push_back(input); cout << "I get that! Give me some more OR Enter \'eof\' to start sorting!" << endl; } // print out the input numbers cout << "\nThe array you\'ve entered was: "; for (int p = 0; p < array.size(); ++p) cout << array [p] << " "; cout << "\n\nNow sorting..." << endl; // start bubble sorting int i = 1, exch = 0; while (i < array.size()) { if (array [i - 1] <= array [i]) ++i; else { // block of code to move the bigger number to the end of the line like a bubble! for (int p = i; p < array.size(); ++p) { exch = array [p - 1]; array [p - 1] = array [p]; array [p] = exch; // debug output // for (int p = 0; p < array.size(); ++p) // cout << array [p] << " "; // cout << endl; } // roll back to the first number if there is number moved i = 1; } } // giving the final output - the sorted array cout << "\nThe moment of truth!" << endl; for (int p = 0; p < array.size(); ++p) cout << array [p] << " "; cout << endl; return 0; } <commit_msg>deleted cpp<commit_after><|endoftext|>
<commit_before>/* Definition of member functions of class ErrorReporter */ #include "../headers/ErrorReporter.hpp" #include <iomanip> #include <sstream> #include <string> using namespace std; ErrorReporter::ErrorReporter() : m_errorOut(), m_outFileName("errores.out"), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { } ErrorReporter::ErrorReporter(const string& outFileName) : m_errorOut(), m_outFileName(outFileName), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { } // Singleton, so this should not be used. Written for removing EffC++ warnings. ErrorReporter::ErrorReporter(const ErrorReporter& source) : m_errorOut(), m_outFileName(), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { m_instance = source.m_instance; } ErrorReporter::~ErrorReporter() { delete m_instance; } ErrorReporter* ErrorReporter::getInstance() { if (m_instance == nullptr) { m_instance = new ErrorReporter(); return m_instance; } return m_instance; } ErrorReporter* ErrorReporter::getInstance(const string& outFileName) { if (m_instance == nullptr) { m_instance = new ErrorReporter(outFileName); return m_instance; } return m_instance; } void ErrorReporter::writeError(const string& message) { writeErrorsFileHeader(); m_errorOut << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_LEXEME) << ' ' << setw(WIDTH_MESSAGE) << message << setw(WIDTH_LINE) << ' ' << endl; } void ErrorReporter::writeLexicalError(int state, char currentChar, const string& line, const string& lexeme, int lineNo, int columnNo) { writeErrorsFileHeader(); ostringstream messageBuilder; switch (state) { case 0 : messageBuilder << "simbolo ilegal: '" << currentChar << "'"; break; case 3 : messageBuilder << "constante hexadecimal incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 6 : case 10 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 9 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito o signo"; break; case 17 : messageBuilder << "comentario multilinea sin cerrar"; break; case 20 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '|'"; break; case 21 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '&'"; break; case 30 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '\\' o letra"; break; case 31 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba letra"; break; case 32 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '''"; break; case 34 : messageBuilder << "comentario multilinea sin cerrar"; break; default : messageBuilder << "error desconocido"; break; } string errorMessage = messageBuilder.str(); m_errorOut << setw(WIDTH_NUMBER) << lineNo << setw(WIDTH_NUMBER) << columnNo << setw(WIDTH_LEXEME) << lexeme << setw(WIDTH_MESSAGE) << errorMessage << setw(WIDTH_LINE) << line; } void ErrorReporter::writeErrorsFileHeader() { if (!m_errorOut.is_open()) { m_errorOut.open(m_outFileName, ios::app); for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; m_errorOut << setw(WIDTH_NUMBER) << "Linea" << setw(WIDTH_NUMBER) << "Columna" << setw(WIDTH_LEXEME) << "Lexema" << setw(WIDTH_MESSAGE) << "Mensaje de error" << setw(WIDTH_LINE) << "Linea" << endl; for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; } } ErrorReporter& ErrorReporter::operator=(const ErrorReporter& rhs) { m_instance = rhs.m_instance; return *this; } void ErrorReporter::setMaxErrors(int maxErrors) { m_maxErrors = maxErrors; } int ErrorReporter::getMaxErrors() const { return m_maxErrors; } int ErrorReporter::getErrors() const { return m_errors; } int ErrorReporter::getWarnings() const { return m_warnings; } <commit_msg>added increments to error counter in error functions<commit_after>/* Definition of member functions of class ErrorReporter */ #include "../headers/ErrorReporter.hpp" #include <iomanip> #include <sstream> #include <string> using namespace std; ErrorReporter::ErrorReporter() : m_errorOut(), m_outFileName("errores.out"), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { } ErrorReporter::ErrorReporter(const string& outFileName) : m_errorOut(), m_outFileName(outFileName), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { } // Singleton, so this should not be used. Written for removing EffC++ warnings. ErrorReporter::ErrorReporter(const ErrorReporter& source) : m_errorOut(), m_outFileName(), m_warnings(0), m_errors(0), m_maxErrors(5), m_instance(nullptr) { m_instance = source.m_instance; } ErrorReporter::~ErrorReporter() { delete m_instance; } ErrorReporter* ErrorReporter::getInstance() { if (m_instance == nullptr) { m_instance = new ErrorReporter(); return m_instance; } return m_instance; } ErrorReporter* ErrorReporter::getInstance(const string& outFileName) { if (m_instance == nullptr) { m_instance = new ErrorReporter(outFileName); return m_instance; } return m_instance; } void ErrorReporter::writeError(const string& message) { writeErrorsFileHeader(); m_errorOut << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_LEXEME) << ' ' << setw(WIDTH_MESSAGE) << message << setw(WIDTH_LINE) << ' ' << endl; ++m_errors; } void ErrorReporter::writeLexicalError(int state, char currentChar, const string& line, const string& lexeme, int lineNo, int columnNo) { writeErrorsFileHeader(); ostringstream messageBuilder; switch (state) { case 0 : messageBuilder << "simbolo ilegal: '" << currentChar << "'"; break; case 3 : messageBuilder << "constante hexadecimal incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 6 : case 10 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 9 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito o signo"; break; case 17 : messageBuilder << "comentario multilinea sin cerrar"; break; case 20 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '|'"; break; case 21 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '&'"; break; case 30 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '\\' o letra"; break; case 31 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba letra"; break; case 32 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '''"; break; case 34 : messageBuilder << "comentario multilinea sin cerrar"; break; default : messageBuilder << "error desconocido"; break; } string errorMessage = messageBuilder.str(); m_errorOut << setw(WIDTH_NUMBER) << lineNo << setw(WIDTH_NUMBER) << columnNo << setw(WIDTH_LEXEME) << lexeme << setw(WIDTH_MESSAGE) << errorMessage << setw(WIDTH_LINE) << line; ++m_errors; } void ErrorReporter::writeErrorsFileHeader() { if (!m_errorOut.is_open()) { m_errorOut.open(m_outFileName, ios::app); for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; m_errorOut << setw(WIDTH_NUMBER) << "Linea" << setw(WIDTH_NUMBER) << "Columna" << setw(WIDTH_LEXEME) << "Lexema" << setw(WIDTH_MESSAGE) << "Mensaje de error" << setw(WIDTH_LINE) << "Linea" << endl; for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; } } ErrorReporter& ErrorReporter::operator=(const ErrorReporter& rhs) { m_instance = rhs.m_instance; return *this; } void ErrorReporter::setMaxErrors(int maxErrors) { m_maxErrors = maxErrors; } int ErrorReporter::getMaxErrors() const { return m_maxErrors; } int ErrorReporter::getErrors() const { return m_errors; } int ErrorReporter::getWarnings() const { return m_warnings; } <|endoftext|>
<commit_before>/* Definition of member functions of class ErrorReporter */ #include "../headers/ErrorReporter.hpp" #include <iomanip> #include <sstream> #include <string> #ifdef DEBUG # include <iostream> #endif using namespace std; ErrorReporter::ErrorReporter() : m_errorOut(), m_outFileName("errores.out"), m_warnings(0), m_errors(0), m_maxErrors(5), m_fileReader(nullptr) { } ErrorReporter::ErrorReporter(const string& outFileName) : m_errorOut(), m_outFileName(outFileName), m_warnings(0), m_errors(0), m_maxErrors(5), m_fileReader(nullptr) { } ErrorReporter* ErrorReporter::m_instance = nullptr; ErrorReporter::~ErrorReporter() { delete m_instance; } ErrorReporter* ErrorReporter::getInstance() { if (m_instance == nullptr) { m_instance = new ErrorReporter(); return m_instance; } return m_instance; } ErrorReporter* ErrorReporter::getInstance(const string& outFileName) { if (m_instance == nullptr) { m_instance = new ErrorReporter(outFileName); return m_instance; } return m_instance; } void ErrorReporter::writeError(const string& message) { writeErrorsFileHeader(); m_errorOut << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_LEXEME) << ' ' << setw(WIDTH_MESSAGE) << message << setw(WIDTH_LINE) << ' ' << endl; ++m_errors; } void ErrorReporter::writeLexicalError(int state, char currentChar, const string& lexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; switch (state) { case 0 : messageBuilder << "simbolo ilegal: '" << currentChar << "'"; break; case 3 : messageBuilder << "constante hexadecimal incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 6 : case 10 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 9 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito o signo"; break; case 17 : messageBuilder << "comentario multilinea sin cerrar"; break; case 20 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '|'"; break; case 21 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '&'"; break; case 30 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '\\' o letra"; break; case 31 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba letra"; break; case 32 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '''"; break; case 34 : messageBuilder << "comentario multilinea sin cerrar"; break; default : messageBuilder << "error desconocido"; break; } m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << lexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); ++m_errors; } void ErrorReporter::writeSyntaxError(const std::string& expectedLexeme, const std::string& actualLexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; messageBuilder << "se esperaba lexema: \"" << expectedLexeme << "\", se recibio: \"" << actualLexeme << "\""; m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << actualLexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); ++m_errors; } void ErrorReporter::writeSyntaxError(TokenType_t expectedToken, TokenType_t actualToken, const string& actualLexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; messageBuilder << "se esperaba token: \"" << TokenLexeme::getTokenString(expectedToken) << "\", se recibio: \"" << TokenLexeme::getTokenString(actualToken) << "\""; m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << actualLexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); ++m_errors; } void ErrorReporter::writeErrorsFileHeader() { if (!m_errorOut.is_open()) { m_errorOut.open(m_outFileName, ios::trunc); for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; m_errorOut << setw(WIDTH_NUMBER) << "Linea" << setw(WIDTH_NUMBER) << "Columna" << setw(WIDTH_LEXEME) << "Lexema" << setw(WIDTH_MESSAGE) << "Mensaje de error" << setw(WIDTH_LINE) << "Linea" << endl; for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; } } void ErrorReporter::setFileReader(FileReader* fileReader) { m_fileReader = fileReader; } void ErrorReporter::setMaxErrors(int maxErrors) { m_maxErrors = maxErrors; } int ErrorReporter::getMaxErrors() const { return m_maxErrors; } int ErrorReporter::getErrors() const { return m_errors; } int ErrorReporter::getWarnings() const { return m_warnings; } <commit_msg>added conditions for writing no more than maxErrors to errors.out file<commit_after>/* Definition of member functions of class ErrorReporter */ #include "../headers/ErrorReporter.hpp" #include <iomanip> #include <sstream> #include <string> #ifdef DEBUG # include <iostream> #endif using namespace std; ErrorReporter::ErrorReporter() : m_errorOut(), m_outFileName("errores.out"), m_warnings(0), m_errors(0), m_maxErrors(5), m_fileReader(nullptr) { } ErrorReporter::ErrorReporter(const string& outFileName) : m_errorOut(), m_outFileName(outFileName), m_warnings(0), m_errors(0), m_maxErrors(5), m_fileReader(nullptr) { } ErrorReporter* ErrorReporter::m_instance = nullptr; ErrorReporter::~ErrorReporter() { delete m_instance; } ErrorReporter* ErrorReporter::getInstance() { if (m_instance == nullptr) { m_instance = new ErrorReporter(); return m_instance; } return m_instance; } ErrorReporter* ErrorReporter::getInstance(const string& outFileName) { if (m_instance == nullptr) { m_instance = new ErrorReporter(outFileName); return m_instance; } return m_instance; } void ErrorReporter::writeError(const string& message) { writeErrorsFileHeader(); if (m_errors < m_maxErrors) { m_errorOut << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_NUMBER) << ' ' << setw(WIDTH_LEXEME) << ' ' << setw(WIDTH_MESSAGE) << message << setw(WIDTH_LINE) << ' ' << endl; } ++m_errors; } void ErrorReporter::writeLexicalError(int state, char currentChar, const string& lexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; switch (state) { case 0 : messageBuilder << "simbolo ilegal: '" << currentChar << "'"; break; case 3 : messageBuilder << "constante hexadecimal incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 6 : case 10 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito"; break; case 9 : messageBuilder << "constante flotante incompleta, se encontro : '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba digito o signo"; break; case 17 : messageBuilder << "comentario multilinea sin cerrar"; break; case 20 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '|'"; break; case 21 : messageBuilder << "operador logico incompleto, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '&'"; break; case 30 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '\\' o letra"; break; case 31 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba letra"; break; case 32 : messageBuilder << "constante caracter incompleta, se encontro: '"; if (!isspace(currentChar)) messageBuilder << currentChar; else messageBuilder << ' '; messageBuilder << "', se esperaba '''"; break; case 34 : messageBuilder << "comentario multilinea sin cerrar"; break; default : messageBuilder << "error desconocido"; break; } if (m_errors < m_maxErrors) { m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << lexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); } ++m_errors; } void ErrorReporter::writeSyntaxError(const std::string& expectedLexeme, const std::string& actualLexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; messageBuilder << "se esperaba lexema: \"" << expectedLexeme << "\", se recibio: \"" << actualLexeme << "\""; if (m_errors < m_maxErrors) { m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << actualLexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); } ++m_errors; } void ErrorReporter::writeSyntaxError(TokenType_t expectedToken, TokenType_t actualToken, const string& actualLexeme, int line, int column) { writeErrorsFileHeader(); ostringstream messageBuilder; messageBuilder << "se esperaba token: \"" << TokenLexeme::getTokenString(expectedToken) << "\", se recibio: \"" << TokenLexeme::getTokenString(actualToken) << "\""; if (m_errors < m_maxErrors) { m_errorOut << setw(WIDTH_NUMBER) << line << setw(WIDTH_NUMBER) << column << setw(WIDTH_LEXEME) << actualLexeme << setw(WIDTH_MESSAGE) << messageBuilder.str() << setw(WIDTH_LINE) << m_fileReader->getTextAtLine(line - 1); m_errorOut.flush(); } ++m_errors; } void ErrorReporter::writeErrorsFileHeader() { if (!m_errorOut.is_open()) { m_errorOut.open(m_outFileName, ios::trunc); for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; m_errorOut << setw(WIDTH_NUMBER) << "Linea" << setw(WIDTH_NUMBER) << "Columna" << setw(WIDTH_LEXEME) << "Lexema" << setw(WIDTH_MESSAGE) << "Mensaje de error" << setw(WIDTH_LINE) << "Linea" << endl; for (int i = 0; i < (WIDTH_NUMBER * 2 + WIDTH_LEXEME + WIDTH_MESSAGE + WIDTH_LINE); ++i) m_errorOut << '-'; m_errorOut << endl; } } void ErrorReporter::setFileReader(FileReader* fileReader) { m_fileReader = fileReader; } void ErrorReporter::setMaxErrors(int maxErrors) { m_maxErrors = maxErrors; } int ErrorReporter::getMaxErrors() const { return m_maxErrors; } int ErrorReporter::getErrors() const { return m_errors; } int ErrorReporter::getWarnings() const { return m_warnings; } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(k) // KMP Algorithm class Solution { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { string src(source), tgt(target); if (tgt.empty()) { return 0; } return KMP(src, tgt); } return -1; } int KMP(const string& text, const string& pattern) { vector<int> prefix = getPrefix(pattern); int j = -1; for (int i = 0; i < text.length(); ++i) { while (j > -1 && pattern[j + 1] != text[i]) { j = prefix[j]; } if (pattern[j + 1] == text[i]) { ++j; } if (j == pattern.length() - 1) { return i - j; } } return -1; } vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(k * n) // Space: O(k) class Solution2 { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { string src(source), tgt(target); for (int i = 0; i < src.length() - tgt.length() + 1; ++i) { if(src.substr(i, tgt.length()) == tgt) { return i; } } } return -1; } }; <commit_msg>update<commit_after>// Time: O(n) // Space: O(k) // KMP Algorithm class Solution { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { string src(source), tgt(target); if (tgt.empty()) { return 0; } return KMP(src, tgt); } return -1; } int KMP(const string& text, const string& pattern) { vector<int> prefix = getPrefix(pattern); int j = -1; for (int i = 0; i < text.length(); ++i) { while (j > -1 && pattern[j + 1] != text[i]) { j = prefix[j]; } if (pattern[j + 1] == text[i]) { ++j; } if (j == pattern.length() - 1) { return i - j; } } return -1; } vector<int> getPrefix(const string& pattern) { vector<int> prefix(pattern.length(), -1); int j = -1; for (int i = 1; i < pattern.length(); ++i) { while (j > -1 && pattern[j + 1] != pattern[i]) { j = prefix[j]; } if (pattern[j + 1] == pattern[i]) { ++j; } prefix[i] = j; } return prefix; } }; // Time: O(k * n) // Space: O(k) class Solution2 { public: /** * Returns a index to the first occurrence of target in source, * or -1 if target is not part of source. * @param source string to be scanned. * @param target string containing the sequence of characters to match. */ int strStr(const char *source, const char *target) { if (source != nullptr && target != nullptr) { string src(source), tgt(target); for (int i = 0; i < src.length() - tgt.length() + 1; ++i) { if (src.substr(i, tgt.length()) == tgt) { return i; } } } return -1; } }; <|endoftext|>
<commit_before>#include "stdsneezy.h" #include "db.h" #include "database.h" #define UNIQUE_TROPHY_FAERIE 33313 #define PERMA_DEATH_FAERIE 33314 #define FAERIE_CASTER_LEVEL 50 #define MAX_TIME 5 // max idle time // only important that higher is better // rate players by number of unique creatures killed int getUniqueTrophyRank(TBeing *targ) { TDatabase db(DB_SNEEZY); if (!targ) { vlogf(LOG_BUG, "getUniqueTrophyRank entered with null targ"); return 0; } db.query("select t.count from trophyplayer t where t.player_id=%i", targ->getPlayerID()); if (!db.isResults()) return 0; if (db.fetchRow()) { return convertTo<int>(db["count"]); } else return 0; } void uniqueTrophyIntro(TBeing *faerie, TBeing *targ) { if (!targ) { vlogf(LOG_BUG, "uniqueTrophyIntro entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "uniqueTrophyIntro entered with null faerie"); return; } faerie->doTell(targ->getName(), "You are greatly respected amongst my people for the breadth of your travels."); faerie->doTell(targ->getName(), "I have been sent to help you in your endeavors!"); } // feral wrath, but only the stat part (no AC penalty), stat part is halved void addUniqueTrophyEffects(TBeing *faerie, TBeing *targ) { affectedData aff2; if (!targ) { vlogf(LOG_BUG, "addUniqueTrophyEffects entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "addUniqueTrophyEffects entered with null faerie"); return; } int modifier = FAERIE_CASTER_LEVEL/2 * ::number(80,125)/100; int which = ::number(1,3); switch (which) { case 1: aff2.location = APPLY_STR; aff2.modifier = modifier; break; case 2: aff2.location = APPLY_DEX; aff2.modifier = modifier; break; case 3: aff2.location = APPLY_SPE; aff2.modifier = modifier; break; } aff2.type = SPELL_FERAL_WRATH; aff2.duration = 2*UPDATES_PER_MUDHOUR; aff2.bitvector = 0; if (!targ->affectJoin(targ, &aff2, AVG_DUR_NO, AVG_EFF_YES)) { vlogf(LOG_BUG, "Failed to join aff2 in addUniqueTrophyEffects"); targ->sendTo("The faerie's magic fails."); } else { if (aff2.location == APPLY_STR) { act("The misty shape of a large bear settles on you.\n\rYou feel stronger.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a large bear settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } else if (aff2.location == APPLY_DEX) { act("The misty shape of a great cat settles on you.\n\rYou feel your reflexes quicken.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a great cat settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } else if (aff2.location == APPLY_SPE) { act("The misty shape of a snake settles on you.\n\rYou feel you can strike with great speed.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a snake settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } } } int clearUniqueTrophyEffects(TBeing *faerie, TBeing *targ) { int rc; if (!targ) { vlogf(LOG_BUG, "Missing target in clearUniqueTrophyEffects."); return FALSE; } if (!faerie) { vlogf(LOG_BUG, "Missing faerie in clearUniqueTrophyEffects."); return FALSE; } rc = targ->spellWearOff(SPELL_FERAL_WRATH, SAFE_YES); if (IS_SET_DELETE(rc, DELETE_THIS)) return DELETE_VICT; targ->affectFrom(SPELL_FERAL_WRATH); return TRUE; } // only important that higher is better int getPermaDeathRank(TBeing *targ) { if (!targ) { vlogf(LOG_BUG, "getPermaDeathRank entered with null target"); return 0; } if (!targ->hasQuestBit(TOG_PERMA_DEATH_CHAR)) return 0; else return (int) max(1.,(targ->getExp()/100)); // don't want to overflow int } void permaDeathIntro(TBeing *faerie, TBeing *targ) { if (!faerie) { vlogf(LOG_BUG, "permaDeathIntro entered with null faerie"); return; } if (!targ) { vlogf(LOG_BUG, "permaDeathIntro entered with null targ"); return; } faerie->doTell(targ->getName(), "You are greatly respected amongst my people for your great bravery."); faerie->doTell(targ->getName(), "I have been sent to help you in your endeavors!"); } // barkskin void addPermaDeathEffects(TBeing *faerie, TBeing *targ) { affectedData aff; if (!targ) { vlogf(LOG_BUG, "addPermaDeathEffects entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "addPermaDeathEffects entered with null faerie"); return; } aff.type = SKILL_BARKSKIN; aff.location = APPLY_ARMOR; aff.duration = 2*UPDATES_PER_MUDHOUR; aff.bitvector = 0; aff.modifier = -90; if (!targ->affectJoin(targ, &aff, AVG_DUR_NO, AVG_EFF_YES)) { vlogf(LOG_BUG, "Failed to join aff in addPermaDeathEffects"); targ->sendTo("The faerie's magic fails."); } else { act("Your skin turns into an extremely hard, oak-like bark.", FALSE, targ, NULL, NULL, TO_CHAR); act("$n's skin turns into an extremely hard, oak-like bark.", TRUE, targ, NULL, NULL, TO_ROOM); } } int clearPermaDeathEffects(TBeing *faerie, TBeing *targ) { int rc; if (!targ) { vlogf(LOG_BUG, "Missing target in clearPermaDeathEffects."); return FALSE; } if (!faerie) { vlogf(LOG_BUG, "Missing faerie in clearPermaDeathEffects."); return FALSE; } rc = targ->spellWearOff(SKILL_BARKSKIN, SAFE_YES); if (IS_SET_DELETE(rc, DELETE_THIS)) return DELETE_VICT; targ->affectFrom(SKILL_BARKSKIN); return TRUE; } // wrapper function int heroFaerie(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *) { return heroFaerie(ch, cmd, arg, myself, NULL, FALSE); } int heroFaerie(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *, bool login) { TBeing *newMaster = NULL; int rc = FALSE; if (!ch || !cmd || !myself) return FALSE; if (cmd == CMD_RENT) { myself->stopFollower(FALSE); act("$n disappears. *pop*" , TRUE, myself, 0, NULL, TO_ROOM); --(*myself); // reinsert at birth room *real_roomp(myself->brtRoom) += *myself; return FALSE; } if (!login && cmd != CMD_GENERIC_PULSE) return FALSE; if (myself->master && ::number(0,119)) // on most of the time but !spammy return FALSE; if (login) vlogf(LOG_MAROR, "Calling heroFaerie on login."); if (!myself->awake()) myself->doWake(""); myself->doFly(); // put faerie and master in the same room if (myself->master && myself->roomp != myself->master->roomp) { act("$N left without you! Can't have that!. *pop*", FALSE, myself, 0, myself->master, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *myself->master->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop*", TRUE, myself, 0, NULL, TO_ROOM); act("$n tells you, <1>\"<c>Hey! Why'd you leave me behind?<1>\"", TRUE, myself, 0, myself->master, TO_VICT); myself->master->addFollower(myself); } // erase effects on current target if (myself->master && myself->roomp == myself->master->roomp) { act("Time for something new! You point at $N, then touch your nose and wiggle your bottom.", FALSE, myself, 0, myself->master, TO_CHAR); act("$n points at you, then touches $s nose and wiggles $s bottom.", FALSE, myself, 0, myself->master, TO_VICT); act("$n points at $N, then touches $s nose and wiggles $s bottom.", FALSE, myself, 0, myself->master, TO_NOTVICT); switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: rc = clearUniqueTrophyEffects(myself, myself->master); break; case PERMA_DEATH_FAERIE: rc = clearPermaDeathEffects(myself, myself->master); break; default: break; } } if (IS_SET_DELETE(rc, DELETE_THIS)) { myself->master->reformGroup(); delete myself->master; myself->master = NULL; } if (myself->master && myself->master->getTimer() > MAX_TIME) { myself->doSay("I'm bored."); myself->stopFollower(FALSE); } // identify new master Descriptor *d; for (d = descriptor_list; d; d = d->next) { if (d->connected != CON_PLYNG) continue; TBeing *targ = d->character; if (!targ || targ->GetMaxLevel() > MAX_MORT) continue; if (targ->getTimer() > MAX_TIME) continue; if (targ->roomp == real_roomp(ROOM_VOID)) continue; switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: if ( !newMaster || getUniqueTrophyRank(targ) > getUniqueTrophyRank(newMaster)) { newMaster = targ; } break; case PERMA_DEATH_FAERIE: if ( (getPermaDeathRank(targ) > 0 && !newMaster) || ( newMaster && getPermaDeathRank(targ) > getPermaDeathRank(newMaster))) { newMaster = targ; } break; default: vlogf(LOG_BUG, fmt("defaulting with myself->mobVnum()=%d") % myself->mobVnum()); break; } } // check for new target, if no target return DELETE_THIS // if target is new, move there and give intro message if (!newMaster) { act("You can't find a master, so you go on your way. *pop*", FALSE, myself, 0, NULL, TO_CHAR); act("$n disappears. *pop*" , TRUE, myself, 0, NULL, TO_ROOM); --(*myself); // reinsert at birth room *real_roomp(myself->brtRoom) += *myself; return TRUE; } else if (myself->master != newMaster) { if (myself->master) act("$n tells you, <1>\"<c>Sorry, gotta go. Someone more interesting has arrived.<1>\"", TRUE, myself, 0, myself->master, TO_VICT); act("You go to $N, your new master. *pop*", FALSE, myself, 0, newMaster, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *newMaster->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop*", TRUE, myself, 0, NULL, TO_ROOM); switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: uniqueTrophyIntro(myself, newMaster); break; case PERMA_DEATH_FAERIE: permaDeathIntro(myself, newMaster); break; default: break; } myself->stopFollower(FALSE); newMaster->addFollower(myself); } else if (myself->roomp != myself->master->roomp) { vlogf(LOG_BUG, "Master and heroFaerie in different rooms - this should not happen at this point."); act("$N left without you! Can't have that!. *pop*", FALSE, myself, 0, myself->master, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *myself->master->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop", TRUE, myself, 0, NULL, TO_ROOM); act("$n tells you, <1>\"<c>Hey! Why'd you leave me behind?<1>\"", TRUE, myself, 0, myself->master, TO_VICT); myself->master->addFollower(myself); } act("$n claps $s hands twice and sprinkles you with glittery dust.", TRUE, myself, 0, myself->master, TO_VICT); act("$n claps $s hands twice and sprinkles $N with glittery dust.", TRUE, myself, 0, myself->master, TO_NOTVICT); // spell up target switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: addUniqueTrophyEffects(myself, newMaster); break; case PERMA_DEATH_FAERIE: addPermaDeathEffects(myself, newMaster); break; default: break; } return TRUE; } <commit_msg>changed room moved to thing_to_room to handle bad rooms<commit_after>#include "stdsneezy.h" #include "db.h" #include "database.h" #define UNIQUE_TROPHY_FAERIE 33313 #define PERMA_DEATH_FAERIE 33314 #define FAERIE_CASTER_LEVEL 50 #define MAX_TIME 5 // max idle time // only important that higher is better // rate players by number of unique creatures killed int getUniqueTrophyRank(TBeing *targ) { TDatabase db(DB_SNEEZY); if (!targ) { vlogf(LOG_BUG, "getUniqueTrophyRank entered with null targ"); return 0; } db.query("select t.count from trophyplayer t where t.player_id=%i", targ->getPlayerID()); if (!db.isResults()) return 0; if (db.fetchRow()) { return convertTo<int>(db["count"]); } else return 0; } void uniqueTrophyIntro(TBeing *faerie, TBeing *targ) { if (!targ) { vlogf(LOG_BUG, "uniqueTrophyIntro entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "uniqueTrophyIntro entered with null faerie"); return; } faerie->doTell(targ->getName(), "You are greatly respected amongst my people for the breadth of your travels."); faerie->doTell(targ->getName(), "I have been sent to help you in your endeavors!"); } // feral wrath, but only the stat part (no AC penalty), stat part is halved void addUniqueTrophyEffects(TBeing *faerie, TBeing *targ) { affectedData aff2; if (!targ) { vlogf(LOG_BUG, "addUniqueTrophyEffects entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "addUniqueTrophyEffects entered with null faerie"); return; } int modifier = FAERIE_CASTER_LEVEL/2 * ::number(80,125)/100; int which = ::number(1,3); switch (which) { case 1: aff2.location = APPLY_STR; aff2.modifier = modifier; break; case 2: aff2.location = APPLY_DEX; aff2.modifier = modifier; break; case 3: aff2.location = APPLY_SPE; aff2.modifier = modifier; break; } aff2.type = SPELL_FERAL_WRATH; aff2.duration = 2*UPDATES_PER_MUDHOUR; aff2.bitvector = 0; if (!targ->affectJoin(targ, &aff2, AVG_DUR_NO, AVG_EFF_YES)) { vlogf(LOG_BUG, "Failed to join aff2 in addUniqueTrophyEffects"); targ->sendTo("The faerie's magic fails."); } else { if (aff2.location == APPLY_STR) { act("The misty shape of a large bear settles on you.\n\rYou feel stronger.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a large bear settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } else if (aff2.location == APPLY_DEX) { act("The misty shape of a great cat settles on you.\n\rYou feel your reflexes quicken.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a great cat settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } else if (aff2.location == APPLY_SPE) { act("The misty shape of a snake settles on you.\n\rYou feel you can strike with great speed.", FALSE, targ, NULL, NULL, TO_CHAR); act("A light mist in the shape of a snake settles on $n.", FALSE, targ, NULL, NULL, TO_ROOM); } } } int clearUniqueTrophyEffects(TBeing *faerie, TBeing *targ) { int rc; if (!targ) { vlogf(LOG_BUG, "Missing target in clearUniqueTrophyEffects."); return FALSE; } if (!faerie) { vlogf(LOG_BUG, "Missing faerie in clearUniqueTrophyEffects."); return FALSE; } rc = targ->spellWearOff(SPELL_FERAL_WRATH, SAFE_YES); if (IS_SET_DELETE(rc, DELETE_THIS)) return DELETE_VICT; targ->affectFrom(SPELL_FERAL_WRATH); return TRUE; } // only important that higher is better int getPermaDeathRank(TBeing *targ) { if (!targ) { vlogf(LOG_BUG, "getPermaDeathRank entered with null target"); return 0; } if (!targ->hasQuestBit(TOG_PERMA_DEATH_CHAR)) return 0; else return (int) max(1.,(targ->getExp()/100)); // don't want to overflow int } void permaDeathIntro(TBeing *faerie, TBeing *targ) { if (!faerie) { vlogf(LOG_BUG, "permaDeathIntro entered with null faerie"); return; } if (!targ) { vlogf(LOG_BUG, "permaDeathIntro entered with null targ"); return; } faerie->doTell(targ->getName(), "You are greatly respected amongst my people for your great bravery."); faerie->doTell(targ->getName(), "I have been sent to help you in your endeavors!"); } // barkskin void addPermaDeathEffects(TBeing *faerie, TBeing *targ) { affectedData aff; if (!targ) { vlogf(LOG_BUG, "addPermaDeathEffects entered with null targ"); return; } if (!faerie) { vlogf(LOG_BUG, "addPermaDeathEffects entered with null faerie"); return; } aff.type = SKILL_BARKSKIN; aff.location = APPLY_ARMOR; aff.duration = 2*UPDATES_PER_MUDHOUR; aff.bitvector = 0; aff.modifier = -90; if (!targ->affectJoin(targ, &aff, AVG_DUR_NO, AVG_EFF_YES)) { vlogf(LOG_BUG, "Failed to join aff in addPermaDeathEffects"); targ->sendTo("The faerie's magic fails."); } else { act("Your skin turns into an extremely hard, oak-like bark.", FALSE, targ, NULL, NULL, TO_CHAR); act("$n's skin turns into an extremely hard, oak-like bark.", TRUE, targ, NULL, NULL, TO_ROOM); } } int clearPermaDeathEffects(TBeing *faerie, TBeing *targ) { int rc; if (!targ) { vlogf(LOG_BUG, "Missing target in clearPermaDeathEffects."); return FALSE; } if (!faerie) { vlogf(LOG_BUG, "Missing faerie in clearPermaDeathEffects."); return FALSE; } rc = targ->spellWearOff(SKILL_BARKSKIN, SAFE_YES); if (IS_SET_DELETE(rc, DELETE_THIS)) return DELETE_VICT; targ->affectFrom(SKILL_BARKSKIN); return TRUE; } // wrapper function int heroFaerie(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *) { return heroFaerie(ch, cmd, arg, myself, NULL, FALSE); } int heroFaerie(TBeing *ch, cmdTypeT cmd, const char *arg, TMonster *myself, TObj *, bool login) { TBeing *newMaster = NULL; int rc = FALSE; if (!ch || !cmd || !myself) return FALSE; if (cmd == CMD_RENT) { myself->stopFollower(FALSE); act("$n disappears. *pop*" , TRUE, myself, 0, NULL, TO_ROOM); --(*myself); // reinsert at birth room thing_to_room(myself, myself->brtRoom); return FALSE; } if (!login && cmd != CMD_GENERIC_PULSE) return FALSE; if (myself->master && ::number(0,119)) // on most of the time but !spammy return FALSE; if (login) vlogf(LOG_MAROR, "Calling heroFaerie on login."); if (!myself->awake()) myself->doWake(""); myself->doFly(); // put faerie and master in the same room if (myself->master && myself->roomp != myself->master->roomp) { act("$N left without you! Can't have that!. *pop*", FALSE, myself, 0, myself->master, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *myself->master->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop*", TRUE, myself, 0, NULL, TO_ROOM); act("$n tells you, <1>\"<c>Hey! Why'd you leave me behind?<1>\"", TRUE, myself, 0, myself->master, TO_VICT); myself->master->addFollower(myself); } // erase effects on current target if (myself->master && myself->roomp == myself->master->roomp) { act("Time for something new! You point at $N, then touch your nose and wiggle your bottom.", FALSE, myself, 0, myself->master, TO_CHAR); act("$n points at you, then touches $s nose and wiggles $s bottom.", FALSE, myself, 0, myself->master, TO_VICT); act("$n points at $N, then touches $s nose and wiggles $s bottom.", FALSE, myself, 0, myself->master, TO_NOTVICT); switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: rc = clearUniqueTrophyEffects(myself, myself->master); break; case PERMA_DEATH_FAERIE: rc = clearPermaDeathEffects(myself, myself->master); break; default: break; } } if (IS_SET_DELETE(rc, DELETE_THIS)) { myself->master->reformGroup(); delete myself->master; myself->master = NULL; } if (myself->master && myself->master->getTimer() > MAX_TIME) { myself->doSay("I'm bored."); myself->stopFollower(FALSE); } // identify new master Descriptor *d; for (d = descriptor_list; d; d = d->next) { if (d->connected != CON_PLYNG) continue; TBeing *targ = d->character; if (!targ || targ->GetMaxLevel() > MAX_MORT) continue; if (targ->getTimer() > MAX_TIME) continue; if (targ->roomp == real_roomp(ROOM_VOID)) continue; switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: if ( !newMaster || getUniqueTrophyRank(targ) > getUniqueTrophyRank(newMaster)) { newMaster = targ; } break; case PERMA_DEATH_FAERIE: if ( (getPermaDeathRank(targ) > 0 && !newMaster) || ( newMaster && getPermaDeathRank(targ) > getPermaDeathRank(newMaster))) { newMaster = targ; } break; default: vlogf(LOG_BUG, fmt("defaulting with myself->mobVnum()=%d") % myself->mobVnum()); break; } } // check for new target, if no target return DELETE_THIS // if target is new, move there and give intro message if (!newMaster) { act("You can't find a master, so you go on your way. *pop*", FALSE, myself, 0, NULL, TO_CHAR); act("$n disappears. *pop*" , TRUE, myself, 0, NULL, TO_ROOM); --(*myself); // reinsert at birth room thing_to_room(myself, myself->brtRoom); return TRUE; } else if (myself->master != newMaster) { if (myself->master) act("$n tells you, <1>\"<c>Sorry, gotta go. Someone more interesting has arrived.<1>\"", TRUE, myself, 0, myself->master, TO_VICT); act("You go to $N, your new master. *pop*", FALSE, myself, 0, newMaster, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *newMaster->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop*", TRUE, myself, 0, NULL, TO_ROOM); switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: uniqueTrophyIntro(myself, newMaster); break; case PERMA_DEATH_FAERIE: permaDeathIntro(myself, newMaster); break; default: break; } myself->stopFollower(FALSE); newMaster->addFollower(myself); } else if (myself->roomp != myself->master->roomp) { vlogf(LOG_BUG, "Master and heroFaerie in different rooms - this should not happen at this point."); act("$N left without you! Can't have that!. *pop*", FALSE, myself, 0, myself->master, TO_CHAR); act("$n disappears. *pop*", TRUE, myself, 0, NULL, TO_ROOM); --(*myself); *myself->master->roomp += *myself; myself->doLook("",CMD_LOOK); act("$n appears in the room. *pop", TRUE, myself, 0, NULL, TO_ROOM); act("$n tells you, <1>\"<c>Hey! Why'd you leave me behind?<1>\"", TRUE, myself, 0, myself->master, TO_VICT); myself->master->addFollower(myself); } act("$n claps $s hands twice and sprinkles you with glittery dust.", TRUE, myself, 0, myself->master, TO_VICT); act("$n claps $s hands twice and sprinkles $N with glittery dust.", TRUE, myself, 0, myself->master, TO_NOTVICT); // spell up target switch(myself->mobVnum()) { case UNIQUE_TROPHY_FAERIE: addUniqueTrophyEffects(myself, newMaster); break; case PERMA_DEATH_FAERIE: addPermaDeathEffects(myself, newMaster); break; default: break; } return TRUE; } <|endoftext|>
<commit_before>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "matrix_algs.h" #include "combined_matrix_store.h" namespace fm { namespace alg { static size_t get_nnz(sparse_matrix::ptr mat) { int num_nodes = matrix_conf.get_num_nodes(); detail::matrix_store::ptr out_store = detail::matrix_store::create( mat->get_num_rows(), 1, matrix_layout_t::L_ROW, get_scalar_type<size_t>(), num_nodes, true); dense_matrix::ptr one = dense_matrix::create_const<size_t>(1, mat->get_num_cols(), 1, matrix_layout_t::L_ROW, num_nodes, true); mat->multiply<size_t, size_t>(one->get_raw_store(), out_store); dense_matrix::ptr out_deg = dense_matrix::create(out_store); scalar_variable::ptr v = out_deg->sum(); return scalar_variable::get_val<size_t>(*v); } // trace of W %*% H static double trace_MM(dense_matrix::ptr W, dense_matrix::ptr H) { dense_matrix::ptr tH = H->transpose(); dense_matrix::ptr tmp = W->multiply_ele(*tH); scalar_variable::ptr res = tmp->sum(); return scalar_variable::get_val<double>(*res); } static dense_matrix::ptr multiply(sparse_matrix::ptr S, dense_matrix::ptr D, size_t num_in_mem) { size_t k = D->get_num_cols(); if (num_in_mem >= k * 2) { detail::mem_matrix_store::ptr res = detail::mem_matrix_store::create( S->get_num_rows(), D->get_num_cols(), matrix_layout_t::L_ROW, D->get_type(), D->get_raw_store()->get_num_nodes()); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); } else if (num_in_mem > k) { return dense_matrix::ptr(); #if 0 detail::matrix_store::ptr res = detail::cached_col_matrix_store::create( S->get_num_rows(), D->get_num_cols(), D->get_type(), D->get_raw_store()->get_num_nodes(), num_in_mem - k); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); #endif } else if (num_in_mem == k) { detail::matrix_store::ptr res = detail::matrix_store::create( S->get_num_rows(), D->get_num_cols(), matrix_layout_t::L_ROW, D->get_type(), -1, false); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); } else { std::vector<detail::matrix_store::const_ptr> res_mats; for (size_t i = 0; i < k; i += num_in_mem) { size_t sub_ncol = std::min(num_in_mem, k - i); std::vector<off_t> col_idxs(sub_ncol); for (size_t j = 0; j < sub_ncol; j++) col_idxs[j] = i + j; dense_matrix::ptr sub_in = D->get_cols(col_idxs); detail::matrix_store::ptr out = detail::matrix_store::create( S->get_num_rows(), sub_in->get_num_cols(), matrix_layout_t::L_COL, D->get_type(), -1, false); S->multiply<double, double>(sub_in->get_raw_store(), out); res_mats.push_back(out); } return dense_matrix::create( detail::combined_matrix_store::create(res_mats, matrix_layout_t::L_COL)); } } // ||A - W %*% H||^2 static double Fnorm(sparse_matrix::ptr A, size_t Annz, dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW, size_t num_in_mem) { // tAW <- t(A) %*% W sparse_matrix::ptr tA = A->transpose(); dense_matrix::ptr tAW = multiply(tA, W, num_in_mem); // tHtWW <- t(H) %*% (t(W) %*% W) dense_matrix::ptr tH = H->transpose(); dense_matrix::ptr tHtWW = tH->multiply(*tWW); // sumA2 - 2 * trace.MM(tAW, H) + trace.MM(tHtWW, H) // TODO H is read twice in this implementation. // TODO tAW doesn't need to be materialized. return Annz - 2 * trace_MM(tAW, H) + trace_MM(tHtWW, H); } struct nmf_state { dense_matrix::ptr W; dense_matrix::ptr H; dense_matrix::ptr tWW; nmf_state(dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW) { this->W = W; this->H = H; this->tWW = tWW; } }; static nmf_state update_lee(sparse_matrix::ptr mat, dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW, size_t num_in_mem) { double eps = 10e-9; // den <- (t(W) %*% W) %*% H dense_matrix::ptr D; { // t(H) dense_matrix::ptr tH = H->transpose(); // t(H) %*% (t(W) %*% W) dense_matrix::ptr tD = tH->multiply(*tWW); D = tD->transpose(); } // H <- fm.pmax2(H * t(tA %*% W), eps) / (den + eps) { sparse_matrix::ptr tmat = mat->transpose(); // tA %*% W dense_matrix::ptr tmp1 = multiply(tmat, W, num_in_mem); // t(tA %*% W) tmp1 = tmp1->transpose(); // H * t(tA %*% W) assert(tmp1->store_layout() == H->store_layout()); tmp1 = tmp1->multiply_ele(*H); // fm.pmax2(H * t(tA %*% W), eps) tmp1 = tmp1->pmax_scalar(eps); // den + eps dense_matrix::ptr tmp3 = D->add_scalar(eps); assert(tmp1->store_layout() == tmp3->store_layout()); H = tmp1->div(*tmp3); H->set_materialize_level(materialize_level::MATER_FULL); } // den <- W %*% (H %*% t(H)) { // t(H) dense_matrix::ptr tH = H->transpose(); // H %*% t(H) dense_matrix::ptr tmp1 = H->multiply(*tH); D = W->multiply(*tmp1); } // W <- fm.pmax2(W * (A %*% t(H)), eps) / (den + eps) { // t(H) dense_matrix::ptr tH = H->transpose(); // A %*% t(H) dense_matrix::ptr tmp1 = multiply(mat, tH, num_in_mem); // W * (A %*% t(H)) assert(W->store_layout() == tmp1->store_layout()); tmp1 = W->multiply_ele(*tmp1); // fm.pmax2(W * (A %*% t(H)), eps) tmp1 = tmp1->pmax_scalar(eps); // den + eps dense_matrix::ptr tmp2 = D->add_scalar(eps); assert(tmp1->store_layout() == tmp2->store_layout()); W = tmp1->div(*tmp2); W->set_materialize_level(materialize_level::MATER_FULL); } dense_matrix::ptr tW = W->transpose(); tWW = tW->multiply(*W); // TODO We have to materialize these matrices here. // Otherwise, we'll get segmentation fault. Why? W->materialize_self(); H->materialize_self(); return nmf_state(W, H, tWW); } std::pair<dense_matrix::ptr, dense_matrix::ptr> NMF(sparse_matrix::ptr mat, size_t k, size_t max_niters, size_t num_in_mem) { if (mat->get_entry_size() > 0) { BOOST_LOG_TRIVIAL(error) << "can only handle binary sparse matrix"; return std::pair<dense_matrix::ptr, dense_matrix::ptr>(); } size_t n = mat->get_num_rows(); size_t m = mat->get_num_cols(); size_t nnz = get_nnz(mat); int num_nodes = matrix_conf.get_num_nodes(); dense_matrix::ptr W, H; if (num_in_mem >= 2 * k) { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_ROW, num_nodes, true); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_COL, num_nodes, true); } else if (num_in_mem > k && num_in_mem < 2 * k) { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_ROW, num_nodes, true); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_ROW, num_nodes, false); } else { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_COL, num_nodes, false); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_ROW, num_nodes, false); } dense_matrix::ptr tWW; { dense_matrix::ptr tW = W->transpose(); tWW = tW->multiply(*W); } nmf_state state(W, H, tWW); for (size_t i = 0; i < max_niters; i++) { struct timeval start, end; gettimeofday(&start, NULL); state = update_lee(mat, state.W, state.H, state.tWW, num_in_mem); gettimeofday(&end, NULL); double update_time = time_diff(start, end); start = end; double dist = Fnorm(mat, nnz, state.W, state.H, state.tWW, num_in_mem); gettimeofday(&end, NULL); printf("iteration %ld: distance: %f, update time: %.3fs, Fnorm: %.3f\n", i, dist, update_time, time_diff(start, end)); } return std::pair<dense_matrix::ptr, dense_matrix::ptr>(state.W, state.H); } } } <commit_msg>[Matrix]: fix a bug in NMF.<commit_after>/* * Copyright 2015 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "matrix_algs.h" #include "combined_matrix_store.h" namespace fm { namespace alg { static size_t get_nnz(sparse_matrix::ptr mat) { int num_nodes = matrix_conf.get_num_nodes(); detail::matrix_store::ptr out_store = detail::matrix_store::create( mat->get_num_rows(), 1, matrix_layout_t::L_ROW, get_scalar_type<size_t>(), num_nodes, true); dense_matrix::ptr one = dense_matrix::create_const<size_t>(1, mat->get_num_cols(), 1, matrix_layout_t::L_ROW, num_nodes, true); mat->multiply<size_t, size_t>(one->get_raw_store(), out_store); dense_matrix::ptr out_deg = dense_matrix::create(out_store); scalar_variable::ptr v = out_deg->sum(); return scalar_variable::get_val<size_t>(*v); } // trace of W %*% H static double trace_MM(dense_matrix::ptr W, dense_matrix::ptr H) { dense_matrix::ptr tH = H->transpose(); dense_matrix::ptr tmp = W->multiply_ele(*tH); scalar_variable::ptr res = tmp->sum(); return scalar_variable::get_val<double>(*res); } static dense_matrix::ptr multiply(sparse_matrix::ptr S, dense_matrix::ptr D, size_t num_in_mem) { size_t k = D->get_num_cols(); if (num_in_mem >= k * 2) { detail::mem_matrix_store::ptr res = detail::mem_matrix_store::create( S->get_num_rows(), D->get_num_cols(), matrix_layout_t::L_ROW, D->get_type(), D->get_raw_store()->get_num_nodes()); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); } else if (num_in_mem > k) { return dense_matrix::ptr(); #if 0 detail::matrix_store::ptr res = detail::cached_col_matrix_store::create( S->get_num_rows(), D->get_num_cols(), D->get_type(), D->get_raw_store()->get_num_nodes(), num_in_mem - k); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); #endif } else if (num_in_mem == k) { detail::matrix_store::ptr res = detail::matrix_store::create( S->get_num_rows(), D->get_num_cols(), matrix_layout_t::L_ROW, D->get_type(), -1, false); S->multiply<double, double>(D->get_raw_store(), res); return dense_matrix::create(res); } else { std::vector<detail::matrix_store::const_ptr> res_mats; for (size_t i = 0; i < k; i += num_in_mem) { size_t sub_ncol = std::min(num_in_mem, k - i); std::vector<off_t> col_idxs(sub_ncol); for (size_t j = 0; j < sub_ncol; j++) col_idxs[j] = i + j; dense_matrix::ptr sub_in = D->get_cols(col_idxs); detail::matrix_store::ptr out = detail::matrix_store::create( S->get_num_rows(), sub_in->get_num_cols(), matrix_layout_t::L_COL, D->get_type(), -1, false); S->multiply<double, double>(sub_in->get_raw_store(), out); res_mats.push_back(out); } return dense_matrix::create( detail::combined_matrix_store::create(res_mats, matrix_layout_t::L_COL)); } } // ||A - W %*% H||^2 static double Fnorm(sparse_matrix::ptr A, size_t Annz, dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW, size_t num_in_mem) { // tAW <- t(A) %*% W sparse_matrix::ptr tA = A->transpose(); dense_matrix::ptr tAW = multiply(tA, W, num_in_mem); // tHtWW <- t(H) %*% (t(W) %*% W) dense_matrix::ptr tH = H->transpose(); dense_matrix::ptr tHtWW = tH->multiply(*tWW); // sumA2 - 2 * trace.MM(tAW, H) + trace.MM(tHtWW, H) // TODO H is read twice in this implementation. // TODO tAW doesn't need to be materialized. return Annz - 2 * trace_MM(tAW, H) + trace_MM(tHtWW, H); } struct nmf_state { dense_matrix::ptr W; dense_matrix::ptr H; dense_matrix::ptr tWW; nmf_state(dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW) { this->W = W; this->H = H; this->tWW = tWW; } }; static nmf_state update_lee(sparse_matrix::ptr mat, dense_matrix::ptr W, dense_matrix::ptr H, dense_matrix::ptr tWW, size_t num_in_mem) { double eps = 10e-9; // den <- (t(W) %*% W) %*% H dense_matrix::ptr D; { // t(H) dense_matrix::ptr tH = H->transpose(); // t(H) %*% (t(W) %*% W) dense_matrix::ptr tD = tH->multiply(*tWW); D = tD->transpose(); } // H <- fm.pmax2(H * t(tA %*% W), eps) / (den + eps) { sparse_matrix::ptr tmat = mat->transpose(); // tA %*% W dense_matrix::ptr tmp1 = multiply(tmat, W, num_in_mem); // t(tA %*% W) tmp1 = tmp1->transpose(); // H * t(tA %*% W) assert(tmp1->store_layout() == H->store_layout()); tmp1 = tmp1->multiply_ele(*H); // fm.pmax2(H * t(tA %*% W), eps) tmp1 = tmp1->pmax_scalar(eps); // den + eps dense_matrix::ptr tmp3 = D->add_scalar(eps); assert(tmp1->store_layout() == tmp3->store_layout()); H = tmp1->div(*tmp3); H->set_materialize_level(materialize_level::MATER_FULL); } // den <- W %*% (H %*% t(H)) { // t(H) dense_matrix::ptr tH = H->transpose(); // H %*% t(H) dense_matrix::ptr tmp1 = H->multiply(*tH); D = W->multiply(*tmp1); } // W <- fm.pmax2(W * (A %*% t(H)), eps) / (den + eps) { // t(H) dense_matrix::ptr tH = H->transpose(); // A %*% t(H) dense_matrix::ptr tmp1 = multiply(mat, tH, num_in_mem); // W * (A %*% t(H)) assert(W->store_layout() == tmp1->store_layout()); tmp1 = W->multiply_ele(*tmp1); // fm.pmax2(W * (A %*% t(H)), eps) tmp1 = tmp1->pmax_scalar(eps); // den + eps dense_matrix::ptr tmp2 = D->add_scalar(eps); assert(tmp1->store_layout() == tmp2->store_layout()); W = tmp1->div(*tmp2); W->set_materialize_level(materialize_level::MATER_FULL); } dense_matrix::ptr tW = W->transpose(); tWW = tW->multiply(*W); // TODO We have to materialize these matrices here. // Otherwise, we'll get segmentation fault. Why? W->materialize_self(); H->materialize_self(); return nmf_state(W, H, tWW); } std::pair<dense_matrix::ptr, dense_matrix::ptr> NMF(sparse_matrix::ptr mat, size_t k, size_t max_niters, size_t num_in_mem) { if (mat->get_entry_size() > 0) { BOOST_LOG_TRIVIAL(error) << "can only handle binary sparse matrix"; return std::pair<dense_matrix::ptr, dense_matrix::ptr>(); } size_t n = mat->get_num_rows(); size_t m = mat->get_num_cols(); size_t nnz = get_nnz(mat); int num_nodes = matrix_conf.get_num_nodes(); dense_matrix::ptr W, H; if (num_in_mem >= 2 * k) { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_ROW, num_nodes, true); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_COL, num_nodes, true); } else if (num_in_mem > k && num_in_mem < 2 * k) { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_ROW, num_nodes, true); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_ROW, num_nodes, false); } else if (num_in_mem == k) { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_ROW, num_nodes, true); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_COL, num_nodes, false); } else { W = dense_matrix::create_randu<double>(0, 1, n, k, matrix_layout_t::L_COL, num_nodes, false); H = dense_matrix::create_randu<double>(0, 1, k, m, matrix_layout_t::L_ROW, num_nodes, false); } dense_matrix::ptr tWW; { dense_matrix::ptr tW = W->transpose(); tWW = tW->multiply(*W); } nmf_state state(W, H, tWW); for (size_t i = 0; i < max_niters; i++) { struct timeval start, end; gettimeofday(&start, NULL); state = update_lee(mat, state.W, state.H, state.tWW, num_in_mem); gettimeofday(&end, NULL); double update_time = time_diff(start, end); start = end; double dist = Fnorm(mat, nnz, state.W, state.H, state.tWW, num_in_mem); gettimeofday(&end, NULL); printf("iteration %ld: distance: %f, update time: %.3fs, Fnorm: %.3f\n", i, dist, update_time, time_diff(start, end)); } return std::pair<dense_matrix::ptr, dense_matrix::ptr>(state.W, state.H); } } } <|endoftext|>
<commit_before>/* * Project: moba-common * * Copyright (C) 2016 Stefan Paproth <pappi-@gmx.de> * * 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/agpl.txt>. * */ #include "version.h" #include <sstream> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> namespace moba { Version::Version(const std::string &version) { std::string str = version; if(str.length() == 0) { throw VersionException( "version-string is empty or not set" ); } try { size_t p = version.rfind('-'); if(p != std::string::npos) { this->ver[3] = boost::lexical_cast<int>(version.substr(p + 1)); } size_t f; --p; for(int i = 2; i >= 0; --i) { f = version.rfind('.', p); if(f == std::string::npos) { f = -1; } this->ver[i] = boost::lexical_cast<int>(version.substr(f + 1, p - f)); p = f - 1; } } catch(...) { throw VersionException("converting failed"); } } std::string Version::getJsonString() const { if(this->ver[MAJOR] == -1) { return "\"0.0.0.0\""; } std::stringstream ss; ss << '"' << this->ver[MAJOR] << '.' << this->ver[MINOR] << '.' << this->ver[BUILD] << '.' << this->ver[PATCH] << '"'; return ss.str(); } std::string Version::getString() const { if(ver[Version::MAJOR] == -1) { return "0.0.0-0000"; } std::stringstream o; o << ver[Version::MAJOR] << "." << ver[Version::MINOR] << "." << ver[Version::BUILD] << "-" << std::setw(4) << std::setfill('0') << ver[Version::PATCH]; return o.str(); } int Version::compareMajor(const Version &v) const { if(this->ver[MAJOR] < v.ver[MAJOR]) { return -1; } if(this->ver[MAJOR] > v.ver[MAJOR]) { return 1; } return 0; } int Version::compareMinor(const Version &v) const { if(this->ver[MINOR] < v.ver[MINOR]) { return -1; } else if(this->ver[MINOR] > v.ver[MINOR]) { return 1; } return 0; } bool Version::operator <(const Version &v) const { if(this->ver[MAJOR] < v.ver[MAJOR]) { return true; } if(this->ver[MAJOR] > v.ver[MAJOR]) { return false; } if(this->ver[MINOR] < v.ver[MINOR]) { return true; } if(this->ver[MINOR] > v.ver[MINOR]) { return false; } if(this->ver[BUILD] < v.ver[BUILD]) { return true; } if(this->ver[BUILD] > v.ver[BUILD]) { return false; } if(this->ver[PATCH] < v.ver[PATCH]) { return true; } if(this->ver[PATCH] > v.ver[PATCH]) { return false; } return false; } bool Version::operator >(const Version &v) const { return !this->operator <(v); } bool Version::operator <=(const Version &v) const { return this->operator <(v) || this->operator ==(v); } bool Version::operator >=(const Version &v) const { return this->operator >(v) || this->operator ==(v); } std::ostream& operator<<(std::ostream &out, const Version &v) { out << v.getString(); return out; } } <commit_msg>bugfix: version accepts now .<commit_after>/* * Project: moba-common * * Copyright (C) 2016 Stefan Paproth <pappi-@gmx.de> * * 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/agpl.txt>. * */ #include "version.h" #include <sstream> #include <vector> #include <iomanip> #include <boost/lexical_cast.hpp> namespace moba { Version::Version(const std::string &version) { std::string str = version; if(str.length() == 0) { throw VersionException("version-string is empty or not set"); } try { size_t p = version.rfind('-'); if(p == std::string::npos) { p = version.rfind('.'); } if(p == std::string::npos) { throw VersionException("invalid version-string given"); } this->ver[3] = boost::lexical_cast<int>(version.substr(p + 1)); size_t f; --p; for(int i = 2; i >= 0; --i) { f = version.rfind('.', p); if(f == std::string::npos) { f = -1; } this->ver[i] = boost::lexical_cast<int>(version.substr(f + 1, p - f)); p = f - 1; } } catch(...) { throw VersionException("converting failed"); } } std::string Version::getJsonString() const { if(this->ver[MAJOR] == -1) { return "\"0.0.0.0\""; } std::stringstream ss; ss << '"' << this->ver[MAJOR] << '.' << this->ver[MINOR] << '.' << this->ver[BUILD] << '.' << this->ver[PATCH] << '"'; return ss.str(); } std::string Version::getString() const { if(ver[Version::MAJOR] == -1) { return "0.0.0-0000"; } std::stringstream o; o << ver[Version::MAJOR] << "." << ver[Version::MINOR] << "." << ver[Version::BUILD] << "-" << std::setw(4) << std::setfill('0') << ver[Version::PATCH]; return o.str(); } int Version::compareMajor(const Version &v) const { if(this->ver[MAJOR] < v.ver[MAJOR]) { return -1; } if(this->ver[MAJOR] > v.ver[MAJOR]) { return 1; } return 0; } int Version::compareMinor(const Version &v) const { if(this->ver[MINOR] < v.ver[MINOR]) { return -1; } if(this->ver[MINOR] > v.ver[MINOR]) { return 1; } return 0; } bool Version::operator <(const Version &v) const { if(this->ver[MAJOR] < v.ver[MAJOR]) { return true; } if(this->ver[MAJOR] > v.ver[MAJOR]) { return false; } if(this->ver[MINOR] < v.ver[MINOR]) { return true; } if(this->ver[MINOR] > v.ver[MINOR]) { return false; } if(this->ver[BUILD] < v.ver[BUILD]) { return true; } if(this->ver[BUILD] > v.ver[BUILD]) { return false; } if(this->ver[PATCH] < v.ver[PATCH]) { return true; } if(this->ver[PATCH] > v.ver[PATCH]) { return false; } return false; } bool Version::operator >(const Version &v) const { return !this->operator <(v); } bool Version::operator <=(const Version &v) const { return this->operator <(v) || this->operator ==(v); } bool Version::operator >=(const Version &v) const { return this->operator >(v) || this->operator ==(v); } std::ostream& operator<<(std::ostream &out, const Version &v) { out << v.getString(); return out; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com) * * Distributed under 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 <cetty/service/builder/ServerBuilder.h> #include <cetty/channel/ChannelPipeline.h> #include <cetty/channel/asio/AsioServicePool.h> #include <cetty/bootstrap/ServerUtil.h> #include <cetty/bootstrap/ServerBootstrap.h> #include <cetty/config/ConfigCenter.h> #include <cetty/logging/Logger.h> #include <cetty/logging/LoggerHelper.h> namespace cetty { namespace service { namespace builder { using namespace cetty::channel; using namespace cetty::channel::asio; using namespace cetty::bootstrap; using namespace cetty::service; using namespace cetty::config; using namespace cetty::logging; ServerBuilder::ServerBuilder() { ConfigCenter::instance().configure(&config_); init(); } ServerBuilder::ServerBuilder(int parentThreadCnt, int childThreadCnt) { ConfigCenter::instance().configure(&config_); config_.parentThreadCount = parentThreadCnt; config_.childThreadCount = childThreadCnt; init(); } ServerBuilder::~ServerBuilder() { } ServerBuilder& ServerBuilder::registerServer(const std::string& name, const ChildInitializer& childInitializer) { ChannelOptions empty; return registerServer(name, empty, empty, childInitializer); } ServerBuilder& ServerBuilder::registerServer(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer) { if (name.empty()) { LOG_WARN << "name is empty, can not register the server."; return *this; } if (!childInitializer) { LOG_WARN << "childInitializer is empty, can not register the server."; return *this; } ServerBootstrapPtr bootstrap = new ServerBootstrap( parentEventLoopPool_, childEventLoopPool_); bootstrap->setChildInitializer(childInitializer); if (!options.empty()) { bootstrap->setChannelOptions(options); } if (!childOptions.empty()) { bootstrap->setChildOptions(childOptions); } bootstraps_.insert(std::make_pair(name, bootstrap)); return *this; } ServerBuilder& ServerBuilder::setOptions(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions) { ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr != bootstraps_.end()) { itr->second->setChannelOptions(options); itr->second->setChildOptions(childOptions); } else { LOG_WARN << "can not find the server: " << name << ", do nothing."; } return *this; } cetty::channel::ChannelPtr ServerBuilder::build(const std::string& name, int port) { return build(name, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const std::string& host, int port) { ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr == bootstraps_.end()) { LOG_WARN << "has not found such server: " << name << " in builder registers, should registerServer first."; return ChannelPtr(); } return build(itr->second, host, port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChildInitializer& initializer, int port) { return build(name, ChannelOptions(), ChannelOptions(), initializer, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChildInitializer& initializer, const std::string& host, int port) { return build(name, ChannelOptions(), ChannelOptions(), initializer, host, port); } cetty::channel::ChannelPtr ServerBuilder::build(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer, int port) { return build(name, options, childOptions, childInitializer, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer, const std::string& host, int port) { if (name.empty()) { LOG_WARN << "parameter error, empty name or invalid address."; return ChannelPtr(); } ServerBootstrap* bootstrap = new ServerBootstrap( parentEventLoopPool_, childEventLoopPool_); bootstraps_.insert(std::make_pair(name, bootstrap)); if (childOptions.empty()) { //bootstrap->setChildOption(ChannelOption::CO_TCP_NODELAY, true); } if (options.empty()) { //bootstrap->setChannelOption(ChannelOption::CO_SO_LINGER, 0); //bootstrap->setChannelOption(ChannelOption::CO_SO_REUSEADDR, true); bootstrap->setChannelOption(ChannelOption::CO_TCP_NODELAY, true); bootstrap->setChannelOption(ChannelOption::CO_SO_BACKLOG, 4096); bootstrap->setChannelOption(ChannelOption::CO_SO_REUSEADDR, true); } if (childInitializer) { bootstrap->setChildInitializer(childInitializer); } else { LOG_WARN << "childInitializer is empty, channel will not work fine."; } bootstrap->setDaemonize(config_.deamonize); return build(bootstrap, host, port); } ChannelPtr ServerBuilder::build(const ServerBootstrapPtr& bootstrap, const std::string& host, int port) { ChannelFuturePtr future; if (host.empty()) { future = bootstrap->bind(port); } else { future = bootstrap->bind(host, port); } if (future->await()->isSuccess()) { return future->channel(); } else { return ChannelPtr(); } } int ServerBuilder::init() { if (config_.deamonize) { ServerUtil::daemonize(); } if (!parentEventLoopPool_) { parentEventLoopPool_ = new AsioServicePool(config_.parentThreadCount); } if (!childEventLoopPool_) { if (config_.childThreadCount > 0) { childEventLoopPool_ = new AsioServicePool(config_.childThreadCount); } else { childEventLoopPool_ = parentEventLoopPool_; } } if (config_.logger) { Logger::logLevel(LogLevel::parseFrom(config_.logger->level)); } return 0; } void ServerBuilder::shutdown() { ServerBootstraps::iterator itr; for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { itr->second->shutdown(); } } void ServerBuilder::waitingForExit() { ServerBootstraps::iterator itr; if (config_.deamonize) { ServerUtil::createPidFile(config_.pidfile.c_str()); for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { ServerBootstrap::Channels& channels = itr->second->channels(); ServerBootstrap::Channels::iterator channelItr = channels.begin(); for (; channelItr != channels.end(); ++channelItr) { channelItr->second->closeFuture()->awaitUninterruptibly(); } } } else { printf("Servers: \n"); for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { ServerBootstrap::Channels& channels = itr->second->channels(); ServerBootstrap::Channels::const_iterator itr = channels.begin(); for (; itr != channels.end(); ++itr) { printf(" Channel ID: %d has bind to %s\n", itr->first, itr->second->localAddress().toString().c_str()); } } printf("To quit server, press 'q'.\n"); char input; do { input = getchar(); if (input == 'q') { shutdown(); break; } } while (true); } } ServerBuilder& ServerBuilder::buildAll() { std::map<std::string, ServerBuilderConfig::Server*>::const_iterator itr = config_.servers.begin(); for (; itr != config_.servers.end(); ++itr) { const std::string& name = itr->first; const ServerBuilderConfig::Server* server = itr->second; if (name.empty()) { LOG_WARN << "has not config the server name, will not start the server."; continue; } if (!server) { LOG_WARN << "config the server: " << name << " has no config item, will skip it."; } if (server->port <= 0) { LOG_WARN << "config the server: " << name << " , which port is not great than 0, will skip it."; continue; } ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr == bootstraps_.end()) { LOG_WARN << "the server: " << name << "has not register to the builder, should register first."; continue; } //TODO setting the options build(itr->second, server->host, server->port); } return *this; } } } } <commit_msg>daemonize改名<commit_after>/* * Copyright (c) 2010-2012 frankee zhou (frankee.zhou at gmail dot com) * * Distributed under 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 <cetty/service/builder/ServerBuilder.h> #include <cetty/channel/ChannelPipeline.h> #include <cetty/channel/asio/AsioServicePool.h> #include <cetty/bootstrap/ServerUtil.h> #include <cetty/bootstrap/ServerBootstrap.h> #include <cetty/config/ConfigCenter.h> #include <cetty/logging/Logger.h> #include <cetty/logging/LoggerHelper.h> namespace cetty { namespace service { namespace builder { using namespace cetty::channel; using namespace cetty::channel::asio; using namespace cetty::bootstrap; using namespace cetty::service; using namespace cetty::config; using namespace cetty::logging; ServerBuilder::ServerBuilder() { ConfigCenter::instance().configure(&config_); init(); } ServerBuilder::ServerBuilder(int parentThreadCnt, int childThreadCnt) { ConfigCenter::instance().configure(&config_); config_.parentThreadCount = parentThreadCnt; config_.childThreadCount = childThreadCnt; init(); } ServerBuilder::~ServerBuilder() { } ServerBuilder& ServerBuilder::registerServer(const std::string& name, const ChildInitializer& childInitializer) { ChannelOptions empty; return registerServer(name, empty, empty, childInitializer); } ServerBuilder& ServerBuilder::registerServer(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer) { if (name.empty()) { LOG_WARN << "name is empty, can not register the server."; return *this; } if (!childInitializer) { LOG_WARN << "childInitializer is empty, can not register the server."; return *this; } ServerBootstrapPtr bootstrap = new ServerBootstrap( parentEventLoopPool_, childEventLoopPool_); bootstrap->setChildInitializer(childInitializer); if (!options.empty()) { bootstrap->setChannelOptions(options); } if (!childOptions.empty()) { bootstrap->setChildOptions(childOptions); } bootstraps_.insert(std::make_pair(name, bootstrap)); return *this; } ServerBuilder& ServerBuilder::setOptions(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions) { ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr != bootstraps_.end()) { itr->second->setChannelOptions(options); itr->second->setChildOptions(childOptions); } else { LOG_WARN << "can not find the server: " << name << ", do nothing."; } return *this; } cetty::channel::ChannelPtr ServerBuilder::build(const std::string& name, int port) { return build(name, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const std::string& host, int port) { ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr == bootstraps_.end()) { LOG_WARN << "has not found such server: " << name << " in builder registers, should registerServer first."; return ChannelPtr(); } return build(itr->second, host, port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChildInitializer& initializer, int port) { return build(name, ChannelOptions(), ChannelOptions(), initializer, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChildInitializer& initializer, const std::string& host, int port) { return build(name, ChannelOptions(), ChannelOptions(), initializer, host, port); } cetty::channel::ChannelPtr ServerBuilder::build(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer, int port) { return build(name, options, childOptions, childInitializer, std::string(), port); } ChannelPtr ServerBuilder::build(const std::string& name, const ChannelOptions& options, const ChannelOptions& childOptions, const ChildInitializer& childInitializer, const std::string& host, int port) { if (name.empty()) { LOG_WARN << "parameter error, empty name or invalid address."; return ChannelPtr(); } ServerBootstrap* bootstrap = new ServerBootstrap( parentEventLoopPool_, childEventLoopPool_); bootstraps_.insert(std::make_pair(name, bootstrap)); if (childOptions.empty()) { //bootstrap->setChildOption(ChannelOption::CO_TCP_NODELAY, true); } if (options.empty()) { //bootstrap->setChannelOption(ChannelOption::CO_SO_LINGER, 0); //bootstrap->setChannelOption(ChannelOption::CO_SO_REUSEADDR, true); bootstrap->setChannelOption(ChannelOption::CO_TCP_NODELAY, true); bootstrap->setChannelOption(ChannelOption::CO_SO_BACKLOG, 4096); bootstrap->setChannelOption(ChannelOption::CO_SO_REUSEADDR, true); } if (childInitializer) { bootstrap->setChildInitializer(childInitializer); } else { LOG_WARN << "childInitializer is empty, channel will not work fine."; } bootstrap->setDaemonize(config_.daemonize); return build(bootstrap, host, port); } ChannelPtr ServerBuilder::build(const ServerBootstrapPtr& bootstrap, const std::string& host, int port) { ChannelFuturePtr future; if (host.empty()) { future = bootstrap->bind(port); } else { future = bootstrap->bind(host, port); } if (future->await()->isSuccess()) { return future->channel(); } else { return ChannelPtr(); } } int ServerBuilder::init() { if (config_.daemonize) { ServerUtil::daemonize(); } if (!parentEventLoopPool_) { parentEventLoopPool_ = new AsioServicePool(config_.parentThreadCount); } if (!childEventLoopPool_) { if (config_.childThreadCount > 0) { childEventLoopPool_ = new AsioServicePool(config_.childThreadCount); } else { childEventLoopPool_ = parentEventLoopPool_; } } if (config_.logger) { Logger::logLevel(LogLevel::parseFrom(config_.logger->level)); } return 0; } void ServerBuilder::shutdown() { ServerBootstraps::iterator itr; for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { itr->second->shutdown(); } } void ServerBuilder::waitingForExit() { ServerBootstraps::iterator itr; if (config_.daemonize) { ServerUtil::createPidFile(config_.pidfile.c_str()); for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { ServerBootstrap::Channels& channels = itr->second->channels(); ServerBootstrap::Channels::iterator channelItr = channels.begin(); for (; channelItr != channels.end(); ++channelItr) { channelItr->second->closeFuture()->awaitUninterruptibly(); } } } else { printf("Servers: \n"); for (itr = bootstraps_.begin(); itr != bootstraps_.end(); ++itr) { ServerBootstrap::Channels& channels = itr->second->channels(); ServerBootstrap::Channels::const_iterator itr = channels.begin(); for (; itr != channels.end(); ++itr) { printf(" Channel ID: %d has bind to %s\n", itr->first, itr->second->localAddress().toString().c_str()); } } printf("To quit server, press 'q'.\n"); char input; do { input = getchar(); if (input == 'q') { shutdown(); break; } } while (true); } } ServerBuilder& ServerBuilder::buildAll() { std::map<std::string, ServerBuilderConfig::Server*>::const_iterator itr = config_.servers.begin(); for (; itr != config_.servers.end(); ++itr) { const std::string& name = itr->first; const ServerBuilderConfig::Server* server = itr->second; if (name.empty()) { LOG_WARN << "has not config the server name, will not start the server."; continue; } if (!server) { LOG_WARN << "config the server: " << name << " has no config item, will skip it."; } if (server->port <= 0) { LOG_WARN << "config the server: " << name << " , which port is not great than 0, will skip it."; continue; } ServerBootstraps::const_iterator itr = bootstraps_.find(name); if (itr == bootstraps_.end()) { LOG_WARN << "the server: " << name << "has not register to the builder, should register first."; continue; } //TODO setting the options build(itr->second, server->host, server->port); } return *this; } } } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The tekcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both tekcoind and tekcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("tekcoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-TEK" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "f96a5a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE "May 7, 2014" # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Change version suffix<commit_after>// Copyright (c) 2012 The tekcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both tekcoind and tekcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("tekcoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-noise23" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "f96a5a" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE "May 7, 2014" # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>//===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetAsmBackend.h" #include "ARM.h" #include "ARMFixupKinds.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCObjectFormat.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/Object/MachOFormat.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; namespace { class ARMAsmBackend : public TargetAsmBackend { public: ARMAsmBackend(const Target &T) : TargetAsmBackend() {} bool MayNeedRelaxation(const MCInst &Inst) const; void RelaxInstruction(const MCInst &Inst, MCInst &Res) const; bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const; unsigned getPointerSize() const { return 4; } protected: static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) { switch (Kind) { default: llvm_unreachable("Unknown fixup kind!"); case FK_Data_4: case ARM::fixup_arm_movt_hi16: case ARM::fixup_arm_movw_lo16: return Value; case ARM::fixup_arm_pcrel_12: { bool isAdd = true; // ARM PC-relative values are offset by 8. Value -= 8; if ((int64_t)Value < 0) { Value = -Value; isAdd = false; } assert ((Value < 4096) && "Out of range pc-relative fixup value!"); Value |= isAdd << 23; return Value; } case ARM::fixup_arm_branch: // These values don't encode the low two bits since they're always zero. // Offset by 8 just as above. return (Value - 8) >> 2; case ARM::fixup_arm_vfp_pcrel_10: { // Offset by 8 just as above. Value = Value - 8; bool isAdd = true; if ((int64_t)Value < 0) { Value = -Value; isAdd = false; } // These values don't encode the low two bits since they're always zero. Value >>= 2; assert ((Value < 256) && "Out of range pc-relative fixup value!"); Value |= isAdd << 23; return Value; } } } }; } // end anonymous namespace bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const { // FIXME: Thumb targets, different move constant targets.. return false; } void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const { assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented"); return; } bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const { // FIXME: Zero fill for now. That's not right, but at least will get the // section size right. for (uint64_t i = 0; i != Count; ++i) OW->Write8(0); return true; } namespace { // FIXME: This should be in a separate file. // ELF is an ELF of course... class ELFARMAsmBackend : public ARMAsmBackend { MCELFObjectFormat Format; public: Triple::OSType OSType; ELFARMAsmBackend(const Target &T, Triple::OSType _OSType) : ARMAsmBackend(T), OSType(_OSType) { HasScatteredSymbols = true; } virtual const MCObjectFormat &getObjectFormat() const { return Format; } void ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const; MCObjectWriter *createObjectWriter(raw_ostream &OS) const { return createELFObjectWriter(OS, /*Is64Bit=*/false, OSType, ELF::EM_ARM, /*IsLittleEndian=*/true, /*HasRelocationAddend=*/false); } }; // Fixme: can we raise this to share code between Darwin and ELF? void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const { uint32_t Mask = 0; // Fixme: 2 for Thumb unsigned NumBytes = 4; Value = adjustFixupValue(Fixup.getKind(), Value); switch (Fixup.getKind()) { default: assert(0 && "Unsupported Fixup kind"); break; case ARM::fixup_arm_branch: { unsigned Lo24 = Value & 0xFFFFFF; Mask = ~(0xFFFFFF); Value = Lo24; }; break; case ARM::fixup_arm_movt_hi16: case ARM::fixup_arm_movw_lo16: { unsigned Hi4 = (Value & 0xF000) >> 12; unsigned Lo12 = Value & 0x0FFF; // inst{19-16} = Hi4; // inst{11-0} = Lo12; Value = (Hi4 << 16) | (Lo12); Mask = ~(0xF0FFF); }; break; } assert((Fixup.getOffset() % NumBytes == 0) && "Offset mod NumBytes is nonzero!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. // The Value has been "split up" into the appropriate bitfields above. // Fixme: how to share code with the .td generated code? for (unsigned i = 0; i != NumBytes; ++i) { DF.getContents()[Fixup.getOffset() + i] &= uint8_t(Mask >> (i * 8)); DF.getContents()[Fixup.getOffset() + i] |= uint8_t(Value >> (i * 8)); } } namespace { // FIXME: This should be in a separate file. class DarwinARMAsmBackend : public ARMAsmBackend { MCMachOObjectFormat Format; public: DarwinARMAsmBackend(const Target &T) : ARMAsmBackend(T) { HasScatteredSymbols = true; } virtual const MCObjectFormat &getObjectFormat() const { return Format; } void ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const; MCObjectWriter *createObjectWriter(raw_ostream &OS) const { // FIXME: Subtarget info should be derived. Force v7 for now. return createMachObjectWriter(OS, /*Is64Bit=*/false, object::mach::CTM_ARM, object::mach::CSARM_V7, /*IsLittleEndian=*/true); } virtual bool doesSectionRequireSymbols(const MCSection &Section) const { return false; } }; } // end anonymous namespace static unsigned getFixupKindNumBytes(unsigned Kind) { switch (Kind) { default: llvm_unreachable("Unknown fixup kind!"); case FK_Data_4: return 4; case ARM::fixup_arm_pcrel_12: return 3; case ARM::fixup_arm_vfp_pcrel_10: return 3; case ARM::fixup_arm_branch: return 3; } } void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const { unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind()); Value = adjustFixupValue(Fixup.getKind(), Value); assert(Fixup.getOffset() + NumBytes <= DF.getContents().size() && "Invalid fixup offset!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. for (unsigned i = 0; i != NumBytes; ++i) DF.getContents()[Fixup.getOffset() + i] |= uint8_t(Value >> (i * 8)); } } // end anonymous namespace TargetAsmBackend *llvm::createARMAsmBackend(const Target &T, const std::string &TT) { switch (Triple(TT).getOS()) { case Triple::Darwin: return new DarwinARMAsmBackend(T); case Triple::MinGW32: case Triple::Cygwin: case Triple::Win32: assert(0 && "Windows not supported on ARM"); default: return new ELFARMAsmBackend(T, Triple(TT).getOS()); } } <commit_msg>kill trailing space<commit_after>//===-- ARMAsmBackend.cpp - ARM Assembler Backend -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Target/TargetAsmBackend.h" #include "ARM.h" #include "ARMFixupKinds.h" #include "llvm/ADT/Twine.h" #include "llvm/MC/MCAssembler.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCObjectFormat.h" #include "llvm/MC/MCObjectWriter.h" #include "llvm/MC/MCSectionELF.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/Object/MachOFormat.h" #include "llvm/Support/ELF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetRegistry.h" using namespace llvm; namespace { class ARMAsmBackend : public TargetAsmBackend { public: ARMAsmBackend(const Target &T) : TargetAsmBackend() {} bool MayNeedRelaxation(const MCInst &Inst) const; void RelaxInstruction(const MCInst &Inst, MCInst &Res) const; bool WriteNopData(uint64_t Count, MCObjectWriter *OW) const; unsigned getPointerSize() const { return 4; } protected: static unsigned adjustFixupValue(unsigned Kind, uint64_t Value) { switch (Kind) { default: llvm_unreachable("Unknown fixup kind!"); case FK_Data_4: case ARM::fixup_arm_movt_hi16: case ARM::fixup_arm_movw_lo16: return Value; case ARM::fixup_arm_pcrel_12: { bool isAdd = true; // ARM PC-relative values are offset by 8. Value -= 8; if ((int64_t)Value < 0) { Value = -Value; isAdd = false; } assert ((Value < 4096) && "Out of range pc-relative fixup value!"); Value |= isAdd << 23; return Value; } case ARM::fixup_arm_branch: // These values don't encode the low two bits since they're always zero. // Offset by 8 just as above. return (Value - 8) >> 2; case ARM::fixup_arm_vfp_pcrel_10: { // Offset by 8 just as above. Value = Value - 8; bool isAdd = true; if ((int64_t)Value < 0) { Value = -Value; isAdd = false; } // These values don't encode the low two bits since they're always zero. Value >>= 2; assert ((Value < 256) && "Out of range pc-relative fixup value!"); Value |= isAdd << 23; return Value; } } } }; } // end anonymous namespace bool ARMAsmBackend::MayNeedRelaxation(const MCInst &Inst) const { // FIXME: Thumb targets, different move constant targets.. return false; } void ARMAsmBackend::RelaxInstruction(const MCInst &Inst, MCInst &Res) const { assert(0 && "ARMAsmBackend::RelaxInstruction() unimplemented"); return; } bool ARMAsmBackend::WriteNopData(uint64_t Count, MCObjectWriter *OW) const { // FIXME: Zero fill for now. That's not right, but at least will get the // section size right. for (uint64_t i = 0; i != Count; ++i) OW->Write8(0); return true; } namespace { // FIXME: This should be in a separate file. // ELF is an ELF of course... class ELFARMAsmBackend : public ARMAsmBackend { MCELFObjectFormat Format; public: Triple::OSType OSType; ELFARMAsmBackend(const Target &T, Triple::OSType _OSType) : ARMAsmBackend(T), OSType(_OSType) { HasScatteredSymbols = true; } virtual const MCObjectFormat &getObjectFormat() const { return Format; } void ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const; MCObjectWriter *createObjectWriter(raw_ostream &OS) const { return createELFObjectWriter(OS, /*Is64Bit=*/false, OSType, ELF::EM_ARM, /*IsLittleEndian=*/true, /*HasRelocationAddend=*/false); } }; // Fixme: can we raise this to share code between Darwin and ELF? void ELFARMAsmBackend::ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const { uint32_t Mask = 0; // Fixme: 2 for Thumb unsigned NumBytes = 4; Value = adjustFixupValue(Fixup.getKind(), Value); switch (Fixup.getKind()) { default: assert(0 && "Unsupported Fixup kind"); break; case ARM::fixup_arm_branch: { unsigned Lo24 = Value & 0xFFFFFF; Mask = ~(0xFFFFFF); Value = Lo24; }; break; case ARM::fixup_arm_movt_hi16: case ARM::fixup_arm_movw_lo16: { unsigned Hi4 = (Value & 0xF000) >> 12; unsigned Lo12 = Value & 0x0FFF; // inst{19-16} = Hi4; // inst{11-0} = Lo12; Value = (Hi4 << 16) | (Lo12); Mask = ~(0xF0FFF); }; break; } assert((Fixup.getOffset() % NumBytes == 0) && "Offset mod NumBytes is nonzero!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. // The Value has been "split up" into the appropriate bitfields above. // Fixme: how to share code with the .td generated code? for (unsigned i = 0; i != NumBytes; ++i) { DF.getContents()[Fixup.getOffset() + i] &= uint8_t(Mask >> (i * 8)); DF.getContents()[Fixup.getOffset() + i] |= uint8_t(Value >> (i * 8)); } } namespace { // FIXME: This should be in a separate file. class DarwinARMAsmBackend : public ARMAsmBackend { MCMachOObjectFormat Format; public: DarwinARMAsmBackend(const Target &T) : ARMAsmBackend(T) { HasScatteredSymbols = true; } virtual const MCObjectFormat &getObjectFormat() const { return Format; } void ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const; MCObjectWriter *createObjectWriter(raw_ostream &OS) const { // FIXME: Subtarget info should be derived. Force v7 for now. return createMachObjectWriter(OS, /*Is64Bit=*/false, object::mach::CTM_ARM, object::mach::CSARM_V7, /*IsLittleEndian=*/true); } virtual bool doesSectionRequireSymbols(const MCSection &Section) const { return false; } }; } // end anonymous namespace static unsigned getFixupKindNumBytes(unsigned Kind) { switch (Kind) { default: llvm_unreachable("Unknown fixup kind!"); case FK_Data_4: return 4; case ARM::fixup_arm_pcrel_12: return 3; case ARM::fixup_arm_vfp_pcrel_10: return 3; case ARM::fixup_arm_branch: return 3; } } void DarwinARMAsmBackend::ApplyFixup(const MCFixup &Fixup, MCDataFragment &DF, uint64_t Value) const { unsigned NumBytes = getFixupKindNumBytes(Fixup.getKind()); Value = adjustFixupValue(Fixup.getKind(), Value); assert(Fixup.getOffset() + NumBytes <= DF.getContents().size() && "Invalid fixup offset!"); // For each byte of the fragment that the fixup touches, mask in the // bits from the fixup value. for (unsigned i = 0; i != NumBytes; ++i) DF.getContents()[Fixup.getOffset() + i] |= uint8_t(Value >> (i * 8)); } } // end anonymous namespace TargetAsmBackend *llvm::createARMAsmBackend(const Target &T, const std::string &TT) { switch (Triple(TT).getOS()) { case Triple::Darwin: return new DarwinARMAsmBackend(T); case Triple::MinGW32: case Triple::Cygwin: case Triple::Win32: assert(0 && "Windows not supported on ARM"); default: return new ELFARMAsmBackend(T, Triple(TT).getOS()); } } <|endoftext|>
<commit_before>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===// // // This transform is designed to eliminate unreachable internal globals // FIXME: GlobalDCE should update the callgraph, not destroy it! // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Module.h" #include "llvm/Function.h" #include "llvm/GlobalVariable.h" #include "llvm/Analysis/CallGraph.h" #include "Support/DepthFirstIterator.h" #include "Support/StatisticReporter.h" static Statistic<> NumFunctions("globaldce\t- Number of functions removed"); static Statistic<> NumVariables("globaldce\t- Number of global variables removed"); static bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) { // Calculate which functions are reachable from the external functions in the // call graph. // std::set<CallGraphNode*> ReachableNodes(df_begin(&CallGraph), df_end(&CallGraph)); // Loop over the functions in the module twice. The first time is used to // drop references that functions have to each other before they are deleted. // The second pass removes the functions that need to be removed. // std::vector<CallGraphNode*> FunctionsToDelete; // Track unused functions for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { CallGraphNode *N = CallGraph[I]; if (!ReachableNodes.count(N)) { // Not reachable?? I->dropAllReferences(); N->removeAllCalledFunctions(); FunctionsToDelete.push_back(N); ++NumFunctions; } } // Nothing to do if no unreachable functions have been found... if (FunctionsToDelete.empty()) return false; // Unreachables functions have been found and should have no references to // them, delete them now. // for (std::vector<CallGraphNode*>::iterator I = FunctionsToDelete.begin(), E = FunctionsToDelete.end(); I != E; ++I) delete CallGraph.removeFunctionFromModule(*I); return true; } static bool RemoveUnreachableGlobalVariables(Module &M) { bool Changed = false; // Eliminate all global variables that are unused, and that are internal, or // do not have an initializer. // for (Module::giterator I = M.gbegin(); I != M.gend(); ) if (!I->use_empty() || (I->hasExternalLinkage() && I->hasInitializer())) ++I; // Cannot eliminate global variable else { I = M.getGlobalList().erase(I); ++NumVariables; Changed = true; } return Changed; } namespace { struct GlobalDCE : public Pass { // run - Do the GlobalDCE pass on the specified module, optionally updating // the specified callgraph to reflect the changes. // bool run(Module &M) { return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) | RemoveUnreachableGlobalVariables(M); } // getAnalysisUsage - This function works on the call graph of a module. // It is capable of updating the call graph to reflect the new state of the // module. // virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<CallGraph>(); } }; RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination"); } Pass *createGlobalDCEPass() { return new GlobalDCE(); } <commit_msg> - Made GlobalDCE worklist driven, making it more successful. Now can handle cases like: test/Regression/Transforms/GlobalDCE/2002-08-17-WorkListTest.ll<commit_after>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===// // // This transform is designed to eliminate unreachable internal globals // FIXME: GlobalDCE should update the callgraph, not destroy it! // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Module.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/GlobalVariable.h" #include "llvm/Analysis/CallGraph.h" #include "Support/DepthFirstIterator.h" #include "Support/StatisticReporter.h" #include <algorithm> static Statistic<> NumFunctions("globaldce\t- Number of functions removed"); static Statistic<> NumVariables("globaldce\t- Number of global variables removed"); static Statistic<> NumCPRs("globaldce\t- Number of const pointer refs removed"); static Statistic<> NumConsts("globaldce\t- Number of init constants removed"); static bool RemoveUnreachableFunctions(Module &M, CallGraph &CallGraph) { // Calculate which functions are reachable from the external functions in the // call graph. // std::set<CallGraphNode*> ReachableNodes(df_begin(&CallGraph), df_end(&CallGraph)); // Loop over the functions in the module twice. The first time is used to // drop references that functions have to each other before they are deleted. // The second pass removes the functions that need to be removed. // std::vector<CallGraphNode*> FunctionsToDelete; // Track unused functions for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { CallGraphNode *N = CallGraph[I]; if (!ReachableNodes.count(N)) { // Not reachable?? I->dropAllReferences(); N->removeAllCalledFunctions(); FunctionsToDelete.push_back(N); ++NumFunctions; } } // Nothing to do if no unreachable functions have been found... if (FunctionsToDelete.empty()) return false; // Unreachables functions have been found and should have no references to // them, delete them now. // for (std::vector<CallGraphNode*>::iterator I = FunctionsToDelete.begin(), E = FunctionsToDelete.end(); I != E; ++I) delete CallGraph.removeFunctionFromModule(*I); return true; } namespace { struct GlobalDCE : public Pass { // run - Do the GlobalDCE pass on the specified module, optionally updating // the specified callgraph to reflect the changes. // bool run(Module &M) { return RemoveUnreachableFunctions(M, getAnalysis<CallGraph>()) | RemoveUnreachableGlobalVariables(M); } // getAnalysisUsage - This function works on the call graph of a module. // It is capable of updating the call graph to reflect the new state of the // module. // virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<CallGraph>(); } private: std::vector<GlobalValue*> WorkList; inline bool RemoveIfDead(GlobalValue *GV); void DestroyInitializer(Constant *C); bool RemoveUnreachableGlobalVariables(Module &M); bool RemoveUnusedConstantPointerRef(GlobalValue &GV); bool SafeToDestroyConstant(Constant *C); }; RegisterOpt<GlobalDCE> X("globaldce", "Dead Global Elimination"); } Pass *createGlobalDCEPass() { return new GlobalDCE(); } // RemoveIfDead - If this global value is dead, remove it from the current // module and return true. // bool GlobalDCE::RemoveIfDead(GlobalValue *GV) { // If there is only one use of the global value, it might be a // ConstantPointerRef... which means that this global might actually be // dead. if (GV->use_size() == 1) RemoveUnusedConstantPointerRef(*GV); if (!GV->use_empty()) return false; if (GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) { // Eliminate all global variables that are unused, and that are internal, or // do not have an initializer. // if (!GVar->hasExternalLinkage() || !GVar->hasInitializer()) { Constant *Init = GVar->hasInitializer() ? GVar->getInitializer() : 0; GV->getParent()->getGlobalList().erase(GVar); ++NumVariables; // If there was an initializer for the global variable, try to destroy it // now. if (Init) DestroyInitializer(Init); // If the global variable is still on the worklist, remove it now. std::vector<GlobalValue*>::iterator I = std::find(WorkList.begin(), WorkList.end(), GV); while (I != WorkList.end()) I = std::find(WorkList.erase(I), WorkList.end(), GV); return true; } } else { Function *F = cast<Function>(GV); // FIXME: TODO } return false; } // DestroyInitializer - A global variable was just destroyed and C is its // initializer. If we can, destroy C and all of the constants it refers to. // void GlobalDCE::DestroyInitializer(Constant *C) { // Cannot destroy constants still being used, and cannot destroy primitive // types. if (!C->use_empty() || C->getType()->isPrimitiveType()) return; // If this is a CPR, the global value referred to may be dead now! Add it to // the worklist. // if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C)) { WorkList.push_back(CPR->getValue()); C->destroyConstant(); ++NumCPRs; } else { bool DestroyContents = true; // As an optimization to the GlobalDCE algorithm, do attempt to destroy the // contents of an array of primitive types, because we know that this will // never succeed, and there could be a lot of them. // if (ConstantArray *CA = dyn_cast<ConstantArray>(C)) if (CA->getType()->getElementType()->isPrimitiveType()) DestroyContents = false; // Nothing we can do with the subcontents // All other constants refer to other constants. Destroy them if possible // as well. // std::vector<Value*> SubConstants; if (DestroyContents) SubConstants.insert(SubConstants.end(), C->op_begin(), C->op_end()); // Destroy the actual constant... C->destroyConstant(); ++NumConsts; if (DestroyContents) { // Remove duplicates from SubConstants, so that we do not call // DestroyInitializer on the same constant twice (the first call might // delete it, so this would be bad) // std::sort(SubConstants.begin(), SubConstants.end()); SubConstants.erase(std::unique(SubConstants.begin(), SubConstants.end()), SubConstants.end()); // Loop over the subconstants, destroying them as well. for (unsigned i = 0, e = SubConstants.size(); i != e; ++i) DestroyInitializer(cast<Constant>(SubConstants[i])); } } } bool GlobalDCE::RemoveUnreachableGlobalVariables(Module &M) { bool Changed = false; WorkList.reserve(M.gsize()); // Insert all of the globals into the WorkList, making sure to run // RemoveUnusedConstantPointerRef at least once on all globals... // for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { Changed |= RemoveUnusedConstantPointerRef(*I); WorkList.push_back(I); } for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I) { Changed |= RemoveUnusedConstantPointerRef(*I); WorkList.push_back(I); } // Loop over the worklist, deleting global objects that we can. Whenever we // delete something that might make something else dead, it gets added to the // worklist. // while (!WorkList.empty()) { GlobalValue *GV = WorkList.back(); WorkList.pop_back(); Changed |= RemoveIfDead(GV); } // Make sure that all memory is free'd from the worklist... std::vector<GlobalValue*>().swap(WorkList); return Changed; } // RemoveUnusedConstantPointerRef - Loop over all of the uses of the specified // GlobalValue, looking for the constant pointer ref that may be pointing to it. // If found, check to see if the constant pointer ref is safe to destroy, and if // so, nuke it. This will reduce the reference count on the global value, which // might make it deader. // bool GlobalDCE::RemoveUnusedConstantPointerRef(GlobalValue &GV) { for (Value::use_iterator I = GV.use_begin(), E = GV.use_end(); I != E; ++I) if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(*I)) if (SafeToDestroyConstant(CPR)) { // Only if unreferenced... CPR->destroyConstant(); ++NumCPRs; return true; } return false; } // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used // by constants itself. Note that constants cannot be cyclic, so this test is // pretty easy to implement recursively. // bool GlobalDCE::SafeToDestroyConstant(Constant *C) { for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I) if (Constant *User = dyn_cast<Constant>(*I)) { if (!SafeToDestroyConstant(User)) return false; } else { return false; } return true; } <|endoftext|>
<commit_before>#ifndef resplunk_util_Cloneable_HeaderPlusPlus #define resplunk_util_Cloneable_HeaderPlusPlus #include <memory> #include <type_traits> namespace resplunk { namespace util { struct Cloneable { Cloneable() = default; Cloneable(Cloneable const &) = default; Cloneable &operator=(Cloneable const &) = delete; Cloneable(Cloneable &&) = default; Cloneable &operator=(Cloneable &&) = delete; virtual ~Cloneable() = default; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable const &c) noexcept -> Wrapper<Cloneable, Args...> { return Wrapper<Cloneable, Args...>{c.clone()}; } private: template<typename DerivedT> friend struct CloneImplementor; virtual Cloneable *clone() const noexcept = 0; }; template<typename DerivedT> struct CloneImplementor : virtual Cloneable { using Cloneable_t = DerivedT; using CloneImplementor_t = CloneImplementor; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable_t const &ct) noexcept -> Wrapper<Cloneable_t, Args...> { Cloneable const &c = ct; return Wrapper<Cloneable_t, Args...>{dynamic_cast<Cloneable_t *>(c.clone())}; } private: CloneImplementor() = default; friend Cloneable_t; }; } } #endif <commit_msg>More serialization work<commit_after>#ifndef resplunk_util_Cloneable_HeaderPlusPlus #define resplunk_util_Cloneable_HeaderPlusPlus #include <memory> #include <type_traits> namespace resplunk { namespace util { struct Cloneable { Cloneable() = default; Cloneable(Cloneable const &) = default; Cloneable &operator=(Cloneable const &) = delete; Cloneable(Cloneable &&) = default; Cloneable &operator=(Cloneable &&) = delete; virtual ~Cloneable() = default; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable const &c) noexcept -> Wrapper<Cloneable, Args...> { return Wrapper<Cloneable, Args...>{c.clone()}; } private: template<typename DerivedT> friend struct CloneImplementor; virtual Cloneable *clone() const noexcept = 0; }; template<typename DerivedT> struct CloneImplementor : virtual Cloneable { using Cloneable_t = DerivedT; using CloneImplementor_t = CloneImplementor; template<template<typename...> typename Wrapper = std::unique_ptr, typename... Args> static auto Clone(Cloneable_t const &ct) noexcept -> Wrapper<Cloneable_t, Args...> { Cloneable const &c = ct; return Wrapper<Cloneable_t, Args...>{dynamic_cast<Cloneable_t *>(c.clone())}; } private: CloneImplementor() = default; friend Cloneable_t; }; template<typename CloneableT, template<typename...> typename Wrapper = std::unique_ptr, typename... Args> struct ClonePtr final : Wrapper<CloneableT, Args...> { static_assert(std::is_base_of<Cloneable, CloneableT>::value); using Cloneable_t = CloneableT; using ClonePtr_t = ClonePtr; using Wrapper_t = Wrapper<CloneableT, Args...>; using Wrapper_t::Wrapper_t; ClonePtr(ClonePtr const &from) noexcept : Wrapper_t{std::move(Cloneable_t::Clone<Wrapper, Args...>(*from))} { } ClonePtr &operator=(ClonePtr const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(*from))); } ClonePtr(Cloneable_t const &from) noexcept : Wrapper_t{std::move(Cloneable_t::Clone<Wrapper, Args...>(from))} { } ClonePtr &operator=(Cloneable_t const &from) noexcept { return Wrapper_t::operator=(std::move(Cloneable_t::Clone<Wrapper, Args...>(from))); } }; } } #endif <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // const charT* data() const; // charT* data(); // C++17 #include <string> #include <cassert> #include "test_macros.h" #include "min_allocator.h" template <class S> void test_const(const S& s) { typedef typename S::traits_type T; const typename S::value_type* str = s.data(); if (s.size() > 0) { assert(T::compare(str, &s[0], s.size()) == 0); assert(T::eq(str[s.size()], typename S::value_type())); } else assert(T::eq(str[0], typename S::value_type())); } template <class S> void test_nonconst(S& s) { typedef typename S::traits_type T; typename S::value_type* str = s.data(); if (s.size() > 0) { assert(T::compare(str, &s[0], s.size()) == 0); assert(T::eq(str[s.size()], typename S::value_type())); } else assert(T::eq(str[0], typename S::value_type())); } int main() { { typedef std::string S; test_const(S("")); test_const(S("abcde")); test_const(S("abcdefghij")); test_const(S("abcdefghijklmnopqrst")); } #if TEST_STD_VER >= 11 { typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S; test_const(S("")); test_const(S("abcde")); test_const(S("abcdefghij")); test_const(S("abcdefghijklmnopqrst")); } #endif #if TEST_STD_VER > 14 { typedef std::string S; S s1(""); test_nonconst(s1); S s2("abcde"); test_nonconst(s2); S s3("abcdefghij"); test_nonconst(s3); S s4("abcdefghijklmnopqrst"); test_nonconst(s4); } #endif } <commit_msg>Remove a couple tabs that crept in<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // const charT* data() const; // charT* data(); // C++17 #include <string> #include <cassert> #include "test_macros.h" #include "min_allocator.h" template <class S> void test_const(const S& s) { typedef typename S::traits_type T; const typename S::value_type* str = s.data(); if (s.size() > 0) { assert(T::compare(str, &s[0], s.size()) == 0); assert(T::eq(str[s.size()], typename S::value_type())); } else assert(T::eq(str[0], typename S::value_type())); } template <class S> void test_nonconst(S& s) { typedef typename S::traits_type T; typename S::value_type* str = s.data(); if (s.size() > 0) { assert(T::compare(str, &s[0], s.size()) == 0); assert(T::eq(str[s.size()], typename S::value_type())); } else assert(T::eq(str[0], typename S::value_type())); } int main() { { typedef std::string S; test_const(S("")); test_const(S("abcde")); test_const(S("abcdefghij")); test_const(S("abcdefghijklmnopqrst")); } #if TEST_STD_VER >= 11 { typedef std::basic_string<char, std::char_traits<char>, min_allocator<char>> S; test_const(S("")); test_const(S("abcde")); test_const(S("abcdefghij")); test_const(S("abcdefghijklmnopqrst")); } #endif #if TEST_STD_VER > 14 { typedef std::string S; S s1(""); test_nonconst(s1); S s2("abcde"); test_nonconst(s2); S s3("abcdefghij"); test_nonconst(s3); S s4("abcdefghijklmnopqrst"); test_nonconst(s4); } #endif } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "cpp_utils/data.hpp" #include "dataset.hpp" #include "detector.hpp" #include "image_utils.hpp" //Real constants used to divide the dataset if necessary constexpr const std::size_t test_divide = 5; constexpr const std::size_t subset_divide = 10; void preprocess(std::vector<double>& image, const config& conf){ if(conf.gray){ for(auto& pixel : image){ pixel = 255 - pixel; } cpp::normalize(image); } } dataset get_oracle_dataset(const config& conf){ dataset ds; for(auto& image_source_path : conf.files){ if(!conf.quiet){ std::cout << "Load and detect "<< image_source_path << std::endl; } auto source_image = open_image(image_source_path); auto original_image = open_image(image_source_path, false); if (!source_image.data || !original_image.data){ std::cout << "Invalid source_image" << std::endl; return ds; } cv::Mat source; sudoku_binarize(source_image, source); //Detect if image was resized //bool resized = source_image.size() != original_image.size(); //auto w_ratio = static_cast<double>(source_image.size().width) / original_image.size().width; //auto h_ratio = static_cast<double>(source_image.size().height) / original_image.size().height; //Read metadata auto data = read_data(image_source_path); auto pure_data = read_data_pure(image_source_path); cv::Mat dest_image; auto grid = detect(source_image, dest_image, conf.mixed); grid.source_image_path = image_source_path; for(size_t i = 0; i < 9; ++i){ for(size_t j = 0; j < 9; ++j){ auto& cell = grid(j, i); //This is a handwritten digit if(!pure_data.results[i][j]){ const auto& bounding_rect = cell.bounding; auto width = 28 + 4; auto height = 28 + 4; auto x_start = -2 + bounding_rect.x + (bounding_rect.width - 28) / 2; auto y_start = -2 + bounding_rect.y + (bounding_rect.height - 28) / 2; //Apply reverse ratio //if(resized){ //x_start *= (1.0 / w_ratio); //y_start *= (1.0 / h_ratio); //width *= (1.0 / h_ratio); //height *= (1.0 / h_ratio); //} cell.digit_bounding.x = x_start; cell.digit_bounding.y = y_start; cell.digit_bounding.width = width; cell.digit_bounding.height = height; cell.color_mat = cv::Mat(source_image, cell.digit_bounding); //cv::resize(color_final_square, cell.color_mat, cell.color_mat.size(), 0, 0, cv::INTER_CUBIC); cv::cvtColor(cell.color_mat, cell.gray_mat, CV_RGB2GRAY); //cv::Mat binary_final_square(source, cell.digit_bounding); //cv::Mat binary_big_square(cv::Size(CELL_SIZE, CELL_SIZE), source.type()); //cv::resize(binary_final_square, binary_big_square, binary_big_square.size(), 0, 0, cv::INTER_CUBIC); cell_binarize(cell.gray_mat, cell.binary_mat, conf.mixed); } //show_regrid(grid, 0); //cv::waitKey(0); cell.correct() = data.results[i][j]; if(data.results[i][j]){ ds.all_labels.push_back(data.results[i][j]-1); ds.all_images.emplace_back(cell.image(conf)); } } } ds.source_grids.push_back(grid); } for(auto& image : ds.all_images){ preprocess(image, conf); } if(conf.subset){ std::size_t count = 0; auto filter_lambda = [&count](auto&){ return count++ % subset_divide > 0; }; ds.all_labels.erase(std::remove_if(ds.all_labels.begin(), ds.all_labels.end(), filter_lambda), ds.all_labels.end()); count = 0; ds.all_images.erase(std::remove_if(ds.all_images.begin(), ds.all_images.end(), filter_lambda), ds.all_images.end()); } if(conf.test){ for(std::size_t i = 0; i < ds.all_images.size(); ++i){ if(i % test_divide == 0){ ds.test_labels.push_back(ds.all_labels[i]); ds.test_images.push_back(ds.all_images[i]); } else { ds.training_labels.push_back(ds.all_labels[i]); ds.training_images.push_back(ds.all_images[i]); } } } else { ds.training_labels = ds.all_labels; ds.training_images = ds.all_images; } assert(ds.all_images.size() == ds.all_labels.size()); assert(ds.training_images.size() == ds.training_labels.size()); assert(ds.test_images.size() == ds.test_labels.size()); std::cout << "...dataset loaded" << std::endl; return ds; } dataset get_dataset(const config& conf){ if(conf.oracle){ std::cout << "Start loading oracle dataset..." << std::endl; return get_oracle_dataset(conf); } std::cout << "Start loading dataset..." << std::endl; dataset ds; for(auto& image_source_path : conf.files){ if(!conf.quiet){ std::cout << "Load and detect "<< image_source_path << std::endl; } auto source_image = open_image(image_source_path); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; continue; } auto data = read_data(image_source_path); cv::Mat dest_image; auto grid = detect(source_image, dest_image, conf.mixed); grid.source_image_path = image_source_path; for(size_t i = 0; i < 9; ++i){ for(size_t j = 0; j < 9; ++j){ auto& cell = grid(j, i); cell.correct() = data.results[i][j]; if(data.results[i][j]){ ds.all_labels.push_back(data.results[i][j]-1); ds.all_images.emplace_back(cell.image(conf)); } } } ds.source_grids.push_back(grid); } for(auto& image : ds.all_images){ preprocess(image, conf); } if(conf.subset){ std::size_t count = 0; auto filter_lambda = [&count](auto&){ return count++ % subset_divide > 0; }; ds.all_labels.erase(std::remove_if(ds.all_labels.begin(), ds.all_labels.end(), filter_lambda), ds.all_labels.end()); count = 0; ds.all_images.erase(std::remove_if(ds.all_images.begin(), ds.all_images.end(), filter_lambda), ds.all_images.end()); } if(conf.test){ for(std::size_t i = 0; i < ds.all_images.size(); ++i){ if(i % test_divide == 0){ ds.test_labels.push_back(ds.all_labels[i]); ds.test_images.push_back(ds.all_images[i]); } else { ds.training_labels.push_back(ds.all_labels[i]); ds.training_images.push_back(ds.all_images[i]); } } } else { ds.training_labels = ds.all_labels; ds.training_images = ds.all_images; } assert(ds.all_images.size() == ds.all_labels.size()); assert(ds.training_images.size() == ds.training_labels.size()); assert(ds.test_images.size() == ds.test_labels.size()); std::cout << "...dataset loaded" << std::endl; return ds; } <commit_msg>Cleanup<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "cpp_utils/data.hpp" #include "dataset.hpp" #include "detector.hpp" #include "image_utils.hpp" //Real constants used to divide the dataset if necessary constexpr const std::size_t test_divide = 5; constexpr const std::size_t subset_divide = 10; void preprocess(std::vector<double>& image, const config& conf){ if(conf.gray){ for(auto& pixel : image){ pixel = 255 - pixel; } cpp::normalize(image); } } dataset get_dataset(const config& conf){ if(conf.oracle){ std::cout << "Start loading oracle dataset..." << std::endl; } else { std::cout << "Start loading dataset..." << std::endl; } dataset ds; for(auto& image_source_path : conf.files){ if(!conf.quiet){ std::cout << "Load and detect "<< image_source_path << std::endl; } auto source_image = open_image(image_source_path); if (!source_image.data){ std::cout << "Invalid source_image" << std::endl; continue; } cv::Mat source; if(conf.oracle){ sudoku_binarize(source_image, source); } //Read metadata auto data = read_data(image_source_path); auto pure_data = read_data_pure(image_source_path); cv::Mat dest_image; auto grid = detect(source_image, dest_image, conf.mixed); grid.source_image_path = image_source_path; for(size_t i = 0; i < 9; ++i){ for(size_t j = 0; j < 9; ++j){ auto& cell = grid(j, i); //This is a handwritten digit if(conf.oracle && !pure_data.results[i][j]){ const auto& bounding_rect = cell.bounding; static_assert(CELL_SIZE == 32, "Oracle algorith is out of sync with CELL_SIZE"); auto width = 28 + 4; auto height = 28 + 4; auto x_start = -2 + bounding_rect.x + (bounding_rect.width - 28) / 2; auto y_start = -2 + bounding_rect.y + (bounding_rect.height - 28) / 2; cell.digit_bounding.x = x_start; cell.digit_bounding.y = y_start; cell.digit_bounding.width = width; cell.digit_bounding.height = height; cell.color_mat = cv::Mat(source_image, cell.digit_bounding); //cv::resize(color_final_square, cell.color_mat, cell.color_mat.size(), 0, 0, cv::INTER_CUBIC); cv::cvtColor(cell.color_mat, cell.gray_mat, CV_RGB2GRAY); //cv::Mat binary_final_square(source, cell.digit_bounding); //cv::Mat binary_big_square(cv::Size(CELL_SIZE, CELL_SIZE), source.type()); //cv::resize(binary_final_square, binary_big_square, binary_big_square.size(), 0, 0, cv::INTER_CUBIC); cell_binarize(cell.gray_mat, cell.binary_mat, conf.mixed); } cell.correct() = data.results[i][j]; if(data.results[i][j]){ ds.all_labels.push_back(data.results[i][j]-1); ds.all_images.emplace_back(cell.image(conf)); } } } ds.source_grids.push_back(grid); } for(auto& image : ds.all_images){ preprocess(image, conf); } if(conf.subset){ std::size_t count = 0; auto filter_lambda = [&count](auto&){ return count++ % subset_divide > 0; }; ds.all_labels.erase(std::remove_if(ds.all_labels.begin(), ds.all_labels.end(), filter_lambda), ds.all_labels.end()); count = 0; ds.all_images.erase(std::remove_if(ds.all_images.begin(), ds.all_images.end(), filter_lambda), ds.all_images.end()); } if(conf.test){ for(std::size_t i = 0; i < ds.all_images.size(); ++i){ if(i % test_divide == 0){ ds.test_labels.push_back(ds.all_labels[i]); ds.test_images.push_back(ds.all_images[i]); } else { ds.training_labels.push_back(ds.all_labels[i]); ds.training_images.push_back(ds.all_images[i]); } } } else { ds.training_labels = ds.all_labels; ds.training_images = ds.all_images; } assert(ds.all_images.size() == ds.all_labels.size()); assert(ds.training_images.size() == ds.training_labels.size()); assert(ds.test_images.size() == ds.test_labels.size()); std::cout << "...dataset loaded" << std::endl; return ds; } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2015-2017. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <fstream> #include <sstream> #include <dirent.h> #include "dataset.hpp" #include "config.hpp" #include "utils.hpp" namespace { void read_word_labels(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string token; while (std::getline(ss, token, '-')) { dataset.word_labels[image_name].push_back(token); } } } void read_word_labels_ak(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } // Get rid of AK crap if (label == "N/A" || label == "." || label == "," || label == "\"" || label == "-") { continue; } std::transform(label.begin(), label.end(), label.begin(), ::tolower); for(char c : label){ dataset.word_labels[image_name].push_back(std::string() + c); } } } void read_line_transcriptions(spot_dataset& dataset, const std::string& path) { std::ifstream line_transcriptions_stream(path + "/ground_truth/transcription.txt"); while (!line_transcriptions_stream.eof()) { std::string image_name; line_transcriptions_stream >> image_name; std::string label; line_transcriptions_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string word_token; while (std::getline(ss, word_token, '|')) { std::vector<std::string> word_labels; std::istringstream ss2(word_token); std::string token; while (std::getline(ss2, token, '-')) { word_labels.push_back(token); } dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels)); } } } void read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) { std::cout << "Read images from '" << file_path << "'" << std::endl; struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(file_path + "/" + file_name); map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); if (!map[file_name].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_images_ak(const config& conf, std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path, const std::string& sub) { std::cout << "Read images from '" << file_path << "/" << sub << "'" << std::endl; auto full_path = file_path + "/" + sub; struct dirent* entry; auto dir = opendir(full_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(full_path + "/" + file_name); auto key = sub + "/" + file_name; cv::Mat base_image = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); if (conf.method == Method::Patches) { if (base_image.size().height == HEIGHT) { map[key] = base_image; } else { float ratio = float(HEIGHT) / base_image.size().height; cv::Mat scaled_normalized( cv::Size(static_cast<size_t>(base_image.size().width * ratio), HEIGHT), CV_8U); cv::resize(base_image, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, map[key], 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); } } else { map[key] = base_image; } if (!map[key].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_line_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.line_images, path + "/data/line_images_normalized/"); } void read_word_images(const config& /*conf*/, spot_dataset& dataset, const std::string& path) { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } void read_word_images_gw(const config& conf, spot_dataset& dataset, const std::string& path) { if(conf.gray){ read_images(dataset.word_images, path + "/data/word_gray/"); } else if(conf.binary){ read_images(dataset.word_images, path + "/data/word_binary/"); } else { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } } void read_word_images_ak(const config& conf, spot_dataset& dataset, const std::string& path) { read_images_ak(conf, dataset.word_images, path + "/data/word_images_normalized", "test"); read_images_ak(conf, dataset.word_images, path + "/data/word_images_normalized", "train"); } void read_list(std::vector<std::string>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string image_name; stream >> image_name; if (!image_name.empty()) { list.push_back(image_name); } } } void read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string keywords; stream >> keywords; if (!keywords.empty()) { list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } } void read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string line_keywords; std::getline(stream, line_keywords); if(line_keywords.empty()){ continue; } std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' ')); if(keywords.empty()){ continue; } list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } void load_sets_washington(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } void load_sets_ak(spot_dataset& dataset, const std::string& path) { std::string set_name = "cv1"; auto& test_set = dataset.sets[set_name].test_set; auto& train_set = dataset.sets[set_name].train_set; auto& valid_set = dataset.sets[set_name].validation_set; for(auto& image : dataset.word_images){ if(image.first.substr(0, 5) == "train"){ train_set.push_back(image.first); } else if(image.first.substr(0, 4) == "test"){ test_set.push_back(image.first); } } valid_set.clear(); // Nothing } void load_sets_parzival(spot_dataset& dataset, const std::string& path) { std::string full_name(path + "/sets1/"); read_list(dataset.sets["cv1"].test_set, full_name + "/test.txt"); read_list(dataset.sets["cv1"].train_set, full_name + "/train.txt"); read_list(dataset.sets["cv1"].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets["cv1"].keywords, full_name + "/keywords.txt"); } void load_sets_iam(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords_iam(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } } //end of anonymous namespace spot_dataset read_washington(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images_gw(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_washington(dataset, path); return dataset; } spot_dataset read_ak(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels_ak(dataset, path); read_word_images_ak(conf, dataset, path); // Now we need to filter the crap out of the data set auto it = dataset.word_images.begin(); while (it != dataset.word_images.end()) { if (!dataset.word_labels.count({it->first.begin(), it->first.end() - 4})) { it = dataset.word_images.erase(it); } else { ++it; } } load_sets_ak(dataset, path); return dataset; } spot_dataset read_botany(const config& conf, const std::string& path) { // Seems the same crap return read_ak(conf, path); } spot_dataset read_manmatha(const config& conf, const std::string& path) { spot_dataset dataset; read_word_images(conf, dataset, path); load_sets_washington(dataset, path); return dataset; } spot_dataset read_parzival(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_parzival(dataset, path); return dataset; } spot_dataset read_iam(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_iam(dataset, path); return dataset; } std::vector<std::vector<std::string>> select_keywords(const config& conf, const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names, bool verbose) { std::vector<std::vector<std::string>> keywords; if(conf.ak || conf.botany){ std::set<std::vector<std::string>> base_keywords; for (auto& labels : dataset.word_labels) { base_keywords.insert(labels.second); } for (auto& keyword : base_keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { std::string key{i.begin(), i.end() - 4}; return dataset.word_labels.at(key) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } } else { for (auto& keyword : set.keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } } if(verbose){ std::cout << "Selected " << keywords.size() << " keyword out of " << set.keywords.size() << std::endl; } return keywords; } <commit_msg>More resizing<commit_after>//======================================================================= // Copyright Baptiste Wicht 2015-2017. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <fstream> #include <sstream> #include <dirent.h> #include "dataset.hpp" #include "config.hpp" #include "utils.hpp" namespace { void read_word_labels(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string token; while (std::getline(ss, token, '-')) { dataset.word_labels[image_name].push_back(token); } } } void read_word_labels_ak(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } // Get rid of AK crap if (label == "N/A" || label == "." || label == "," || label == "\"" || label == "-") { continue; } std::transform(label.begin(), label.end(), label.begin(), ::tolower); for(char c : label){ dataset.word_labels[image_name].push_back(std::string() + c); } } } void read_line_transcriptions(spot_dataset& dataset, const std::string& path) { std::ifstream line_transcriptions_stream(path + "/ground_truth/transcription.txt"); while (!line_transcriptions_stream.eof()) { std::string image_name; line_transcriptions_stream >> image_name; std::string label; line_transcriptions_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string word_token; while (std::getline(ss, word_token, '|')) { std::vector<std::string> word_labels; std::istringstream ss2(word_token); std::string token; while (std::getline(ss2, token, '-')) { word_labels.push_back(token); } dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels)); } } } void read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) { std::cout << "Read images from '" << file_path << "'" << std::endl; struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(file_path + "/" + file_name); map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); if (!map[file_name].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_images_ak(const config& conf, std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path, const std::string& sub) { std::cout << "Read images from '" << file_path << "/" << sub << "'" << std::endl; auto full_path = file_path + "/" + sub; struct dirent* entry; auto dir = opendir(full_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(full_path + "/" + file_name); auto key = sub + "/" + file_name; cv::Mat base_image = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); // Some methods need resizing if (conf.method == Method::Patches || conf.method == Method::Terasawa2009 || conf.method == Method::Rodriguez2008) { if (base_image.size().height == HEIGHT) { map[key] = base_image; } else { float ratio = float(HEIGHT) / base_image.size().height; cv::Mat scaled_normalized( cv::Size(static_cast<size_t>(base_image.size().width * ratio), HEIGHT), CV_8U); cv::resize(base_image, scaled_normalized, scaled_normalized.size(), cv::INTER_AREA); cv::adaptiveThreshold(scaled_normalized, map[key], 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 7, 2); } } else { map[key] = base_image; } if (!map[key].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_line_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.line_images, path + "/data/line_images_normalized/"); } void read_word_images(const config& /*conf*/, spot_dataset& dataset, const std::string& path) { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } void read_word_images_gw(const config& conf, spot_dataset& dataset, const std::string& path) { if(conf.gray){ read_images(dataset.word_images, path + "/data/word_gray/"); } else if(conf.binary){ read_images(dataset.word_images, path + "/data/word_binary/"); } else { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } } void read_word_images_ak(const config& conf, spot_dataset& dataset, const std::string& path) { read_images_ak(conf, dataset.word_images, path + "/data/word_images_normalized", "test"); read_images_ak(conf, dataset.word_images, path + "/data/word_images_normalized", "train"); } void read_list(std::vector<std::string>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string image_name; stream >> image_name; if (!image_name.empty()) { list.push_back(image_name); } } } void read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string keywords; stream >> keywords; if (!keywords.empty()) { list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } } void read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string line_keywords; std::getline(stream, line_keywords); if(line_keywords.empty()){ continue; } std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' ')); if(keywords.empty()){ continue; } list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } void load_sets_washington(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } void load_sets_ak(spot_dataset& dataset, const std::string& path) { std::string set_name = "cv1"; auto& test_set = dataset.sets[set_name].test_set; auto& train_set = dataset.sets[set_name].train_set; auto& valid_set = dataset.sets[set_name].validation_set; for(auto& image : dataset.word_images){ if(image.first.substr(0, 5) == "train"){ train_set.push_back(image.first); } else if(image.first.substr(0, 4) == "test"){ test_set.push_back(image.first); } } valid_set.clear(); // Nothing } void load_sets_parzival(spot_dataset& dataset, const std::string& path) { std::string full_name(path + "/sets1/"); read_list(dataset.sets["cv1"].test_set, full_name + "/test.txt"); read_list(dataset.sets["cv1"].train_set, full_name + "/train.txt"); read_list(dataset.sets["cv1"].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets["cv1"].keywords, full_name + "/keywords.txt"); } void load_sets_iam(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords_iam(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } } //end of anonymous namespace spot_dataset read_washington(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images_gw(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_washington(dataset, path); return dataset; } spot_dataset read_ak(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels_ak(dataset, path); read_word_images_ak(conf, dataset, path); // Now we need to filter the crap out of the data set auto it = dataset.word_images.begin(); while (it != dataset.word_images.end()) { if (!dataset.word_labels.count({it->first.begin(), it->first.end() - 4})) { it = dataset.word_images.erase(it); } else { ++it; } } load_sets_ak(dataset, path); return dataset; } spot_dataset read_botany(const config& conf, const std::string& path) { // Seems the same crap return read_ak(conf, path); } spot_dataset read_manmatha(const config& conf, const std::string& path) { spot_dataset dataset; read_word_images(conf, dataset, path); load_sets_washington(dataset, path); return dataset; } spot_dataset read_parzival(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_parzival(dataset, path); return dataset; } spot_dataset read_iam(const config& conf, const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(conf, dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_iam(dataset, path); return dataset; } std::vector<std::vector<std::string>> select_keywords(const config& conf, const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names, bool verbose) { std::vector<std::vector<std::string>> keywords; if(conf.ak || conf.botany){ std::set<std::vector<std::string>> base_keywords; for (auto& labels : dataset.word_labels) { base_keywords.insert(labels.second); } for (auto& keyword : base_keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { std::string key{i.begin(), i.end() - 4}; return dataset.word_labels.at(key) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } } else { for (auto& keyword : set.keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } } if(verbose){ std::cout << "Selected " << keywords.size() << " keyword out of " << set.keywords.size() << std::endl; } return keywords; } <|endoftext|>
<commit_before>#include "Kdtree.h" #include <cstdio> #include <algorithm> #include <numeric> #include <cmath> namespace P_RVD{ // Eww global. Need this for the sort function // A pointer to the class itself, allows the sort function to determine the splitting axis to sort by static KDtree *myself = NULL; KDtree::KDtree() { myself = this; m_id = 0; } KDtree::~KDtree() { // Delete all the ndoes std::vector <KDNode*> to_visit; to_visit.push_back(m_root); while (to_visit.size()) { std::vector <KDNode*> next_search; while (to_visit.size()) { KDNode *cur = to_visit.back(); to_visit.pop_back(); if (cur->left) next_search.push_back(cur->left); if (cur->right) next_search.push_back(cur->right); delete cur; } to_visit = next_search; } m_root = NULL; } void KDtree::Create_kdtree(std::vector<Kd_tree_point> &pts, int max_levels) { m_pts = &pts; m_levels = max_levels; m_root = new KDNode(); m_root->id = m_id++; m_root->index.resize(pts.size()); //init the index for (unsigned int i = 0; i < pts.size(); ++i) { m_root->index[i] = i; } std::vector<KDNode*> to_visit; to_visit.push_back(m_root); while (to_visit.size()) { std::vector<KDNode*> next_search; while (to_visit.size()) { KDNode *node = to_visit.back(); to_visit.pop_back();; if (node->level < max_levels) { //if current node's index size > 1 //it has more than 1 point in this space //So split it if (node->index.size() > 1) { KDNode *left = new KDNode(); KDNode *right = new KDNode(); left->id = m_id++; right->id = m_id++; Split(node, left, right); //Claer current index { std::vector<int> dummy; node->index.swap(dummy); } node->left = left; node->right = right; node->_left = left->id; node->_right = right->id; if (left->index.size()) next_search.push_back(left); if (right->index.size()) next_search.push_back(right); } } } to_visit = next_search; } } /* compare the data of 2 points with the index */ bool KDtree::SortPoints(const int a, const int b) { std::vector<Kd_tree_point> &pts = *myself->m_pts; return pts[a].coords[myself->m_current_axis] < pts[b].coords[myself->m_current_axis]; } /* Split the current node into 2 part: left and right we assume that the left and right nodes are already created */ void KDtree::Split(KDNode *cur, KDNode *left, KDNode *right) { std::vector<Kd_tree_point> &pts = *m_pts; m_current_axis = cur->level % KDTREE_DIM; //sort the points by the axis value std::sort(cur->index.begin(), cur->index.end(), KDtree::SortPoints); int mid = cur->index[cur->index.size() / 2]; cur->split_value = pts[mid].coords[m_current_axis]; left->parent = cur; right->parent = cur; left->level = cur->level + 1; right->level = cur->level + 1; left->_parent = cur->id; right->_parent = cur->id; for (unsigned int i = 0; i < cur->index.size(); ++i) { int idx = cur->index[i]; if (pts[idx].coords[m_current_axis] < cur->split_value) left->index.push_back(idx); else right->index.push_back(idx); } } /* search the best node return the index and distance square of the closed point in this node */ void KDtree::SearchAtNode(KDNode *cur, const Kd_tree_point &query, int *ret_index, double *ret_dist, KDNode **ret_node) { int best_idx = 0; // if the range the coords is larger than 100,best_dist should be adjusted double best_dist_Squa = 100.0; std::vector<Kd_tree_point> &pts = *m_pts; //First pass while (true) { int split_axis = cur->level % KDTREE_DIM; m_cmps++; if (cur->left == NULL) { *ret_node = cur; for (unsigned int i = 0; i < cur->index.size(); ++i) { m_cmps++; int idx = cur->index[i]; double distSqua = DistanceSquare(query, pts[idx]); if (distSqua < best_dist_Squa) { best_dist_Squa = distSqua; best_idx = idx; } } break; } else if (query.coords[split_axis] < cur->split_value) { cur = cur->left; } else { cur = cur->right; } } *ret_index = best_idx; *ret_dist = best_dist_Squa; } void KDtree::SearchAtNodeRange(KDNode *cur, const Kd_tree_point &query, double range, int *ret_index, double *ret_dist) { int best_idx = 0; double best_dist = 100.0; std::vector<Kd_tree_point> &pts = *m_pts; std::vector<KDNode* > to_visit; to_visit.push_back(cur); while (to_visit.size() > 0) { std::vector<KDNode*> next_search; while (to_visit.size()) { cur = to_visit.back(); to_visit.pop_back(); int split_axis = cur->level % KDTREE_DIM; if (cur->left == NULL) { for (unsigned int i = 0; i < cur->index.size(); i++) { m_cmps++; int idx = cur->index[i]; double d = DistanceSquare(query, pts[idx]); if (d < best_dist) { best_dist = d; best_idx = idx; } } } else { double d = query.coords[split_axis] - cur->split_value; // There are 3 possible scenarios // The hypercircle only intersects the left region // The hypercircle only intersects the right region // The hypercricle intersects both m_cmps++; if (fabs(d) > range) { if (d < 0) next_search.push_back(cur->left); else next_search.push_back(cur->right); } else { next_search.push_back(cur->left); next_search.push_back(cur->right); } } } } } void KDtree::Search(const Kd_tree_point &query, int *ret_index, double *ret_dist) { //First pass //Find the first closest node, this will be the upper bound for the next searches std::vector<Kd_tree_point> &pts = *m_pts; KDNode *best_node = NULL; int best_idx = 0; double best_dist = 100.0; double radius = 0.0; m_cmps = 0; SearchAtNode(m_root, query, &best_idx, &best_dist, &best_node); radius = sqrt(best_dist); //Second pss //Find ohter possible candidates KDNode *cur = best_node; while (cur->parent != NULL) { //Go up KDNode *parent = cur->parent; int split_axis = (parent->level) % KDTREE_DIM; //Search the other node int temp_idx; double temp_dist = 100.0; KDNode *temp_node; KDNode *search_node = NULL; if (fabs(parent->split_value - query.coords[split_axis]) <= radius) { //Search opposite node if (parent->left != cur) SearchAtNodeRange(parent->left, query, radius, &temp_idx, &temp_dist); else SearchAtNodeRange(parent->right, query, radius, &temp_idx, &temp_dist); } if (temp_dist < best_dist) { best_idx = temp_idx; best_dist = temp_dist; } cur = parent; } *ret_index = best_idx; *ret_dist = best_dist; } inline double KDtree::DistanceSquare(const Kd_tree_point &a, const Kd_tree_point &b) const { double dist = 0.0; for (int i = 0; i < KDTREE_DIM; ++i) { double d = a.coords[i] - b.coords[i]; dist += d * d; } return dist; } }<commit_msg>modify for knn<commit_after>#include "Kdtree.h" #include <cstdio> #include <algorithm> #include <numeric> #include <cmath> namespace P_RVD{ // Eww global. Need this for the sort function // A pointer to the class itself, allows the sort function to determine the splitting axis to sort by static KDtree *myself = NULL; KDtree::KDtree() { myself = this; m_id = 0; } KDtree::~KDtree() { // Delete all the ndoes std::vector <KDNode*> to_visit; to_visit.push_back(m_root); while (to_visit.size()) { std::vector <KDNode*> next_search; while (to_visit.size()) { KDNode *cur = to_visit.back(); to_visit.pop_back(); if (cur->left) next_search.push_back(cur->left); if (cur->right) next_search.push_back(cur->right); delete cur; } to_visit = next_search; } m_root = NULL; } void KDtree::Create_kdtree(std::vector<Kd_tree_point> &pts, int max_levels) { m_pts = &pts; m_levels = max_levels; m_root = new KDNode(); m_root->id = m_id++; m_root->index.resize(pts.size()); //init the index for (unsigned int i = 0; i < pts.size(); ++i) { m_root->index[i] = i; } std::vector<KDNode*> to_visit; to_visit.push_back(m_root); while (to_visit.size()) { std::vector<KDNode*> next_search; while (to_visit.size()) { KDNode *node = to_visit.back(); to_visit.pop_back();; if (node->level < max_levels) { //if current node's index size > 1 //it has more than 1 point in this space //So split it if (node->index.size() > 1) { KDNode *left = new KDNode(); KDNode *right = new KDNode(); left->id = m_id++; right->id = m_id++; Split(node, left, right); //Claer current index { //std::vector<int> dummy; //node->index.swap(dummy); } node->left = left; node->right = right; node->_left = left->id; node->_right = right->id; if (left->index.size()) next_search.push_back(left); if (right->index.size()) next_search.push_back(right); } } } to_visit = next_search; } } /* compare the data of 2 points with the index */ bool KDtree::SortPoints(const int a, const int b) { std::vector<Kd_tree_point> &pts = *myself->m_pts; return pts[a].coords[myself->m_current_axis] < pts[b].coords[myself->m_current_axis]; } /* Split the current node into 2 part: left and right we assume that the left and right nodes are already created */ void KDtree::Split(KDNode *cur, KDNode *left, KDNode *right) { std::vector<Kd_tree_point> &pts = *m_pts; m_current_axis = cur->level % KDTREE_DIM; //sort the points by the axis value std::sort(cur->index.begin(), cur->index.end(), KDtree::SortPoints); int mid = cur->index[cur->index.size() / 2]; cur->split_value = pts[mid].coords[m_current_axis]; left->parent = cur; right->parent = cur; left->level = cur->level + 1; right->level = cur->level + 1; left->_parent = cur->id; right->_parent = cur->id; for (unsigned int i = 0; i < cur->index.size(); ++i) { int idx = cur->index[i]; if (pts[idx].coords[m_current_axis] < cur->split_value) left->index.push_back(idx); else right->index.push_back(idx); } } /* search the best node return the index and distance square of the closed point in this node */ void KDtree::SearchAtNode(KDNode *cur, const Kd_tree_point &query, int *ret_index, double *ret_dist, KDNode **ret_node) { int best_idx = 0; // if the range the coords is larger than 100,best_dist should be adjusted double best_dist_Squa = 100.0; std::vector<Kd_tree_point> &pts = *m_pts; //First pass while (true) { int split_axis = cur->level % KDTREE_DIM; m_cmps++; if (cur->left == NULL) { *ret_node = cur; for (unsigned int i = 0; i < cur->index.size(); ++i) { m_cmps++; int idx = cur->index[i]; double distSqua = DistanceSquare(query, pts[idx]); if (distSqua < best_dist_Squa) { best_dist_Squa = distSqua; best_idx = idx; } } break; } else if (query.coords[split_axis] < cur->split_value) { cur = cur->left; } else { cur = cur->right; } } *ret_index = best_idx; *ret_dist = best_dist_Squa; } void KDtree::SearchAtNodeRange(KDNode *cur, const Kd_tree_point &query, double range, int *ret_index, double *ret_dist) { int best_idx = 0; double best_dist = 100.0; std::vector<Kd_tree_point> &pts = *m_pts; std::vector<KDNode* > to_visit; to_visit.push_back(cur); while (to_visit.size() > 0) { std::vector<KDNode*> next_search; while (to_visit.size()) { cur = to_visit.back(); to_visit.pop_back(); int split_axis = cur->level % KDTREE_DIM; if (cur->left == NULL) { for (unsigned int i = 0; i < cur->index.size(); i++) { m_cmps++; int idx = cur->index[i]; double d = DistanceSquare(query, pts[idx]); if (d < best_dist) { best_dist = d; best_idx = idx; } } } else { double d = query.coords[split_axis] - cur->split_value; // There are 3 possible scenarios // The hypercircle only intersects the left region // The hypercircle only intersects the right region // The hypercricle intersects both m_cmps++; if (fabs(d) > range) { if (d < 0) next_search.push_back(cur->left); else next_search.push_back(cur->right); } else { next_search.push_back(cur->left); next_search.push_back(cur->right); } } } } } void KDtree::Search(const Kd_tree_point &query, int *ret_index, double *ret_dist) { //First pass //Find the first closest node, this will be the upper bound for the next searches std::vector<Kd_tree_point> &pts = *m_pts; KDNode *best_node = NULL; int best_idx = 0; double best_dist = 100.0; double radius = 0.0; m_cmps = 0; SearchAtNode(m_root, query, &best_idx, &best_dist, &best_node); radius = sqrt(best_dist); //Second pss //Find ohter possible candidates KDNode *cur = best_node; while (cur->parent != NULL) { //Go up KDNode *parent = cur->parent; int split_axis = (parent->level) % KDTREE_DIM; //Search the other node int temp_idx; double temp_dist = 100.0; KDNode *temp_node; KDNode *search_node = NULL; if (fabs(parent->split_value - query.coords[split_axis]) <= radius) { //Search opposite node if (parent->left != cur) SearchAtNodeRange(parent->left, query, radius, &temp_idx, &temp_dist); else SearchAtNodeRange(parent->right, query, radius, &temp_idx, &temp_dist); } if (temp_dist < best_dist) { best_idx = temp_idx; best_dist = temp_dist; } cur = parent; } *ret_index = best_idx; *ret_dist = best_dist; } inline double KDtree::DistanceSquare(const Kd_tree_point &a, const Kd_tree_point &b) const { double dist = 0.0; for (int i = 0; i < KDTREE_DIM; ++i) { double d = a.coords[i] - b.coords[i]; dist += d * d; } return dist; } }<|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <fstream> #include <sstream> #include <dirent.h> #include "dataset.hpp" #include "config.hpp" namespace { void read_word_labels(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string token; while (std::getline(ss, token, '-')) { dataset.word_labels[image_name].push_back(token); } } } void read_line_transcriptions(spot_dataset& dataset, const std::string& path) { std::ifstream line_transcriptions_stream(path + "/ground_truth/transcription.txt"); while (!line_transcriptions_stream.eof()) { std::string image_name; line_transcriptions_stream >> image_name; std::string label; line_transcriptions_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string word_token; while (std::getline(ss, word_token, '|')) { std::vector<std::string> word_labels; std::istringstream ss2(word_token); std::string token; while (std::getline(ss2, token, '-')) { word_labels.push_back(token); } dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels)); } } } void read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) { struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(file_path + "/" + file_name); map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); if (!map[file_name].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_line_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.line_images, path + "/data/line_images_normalized/"); } void read_word_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } void read_list(std::vector<std::string>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string image_name; stream >> image_name; if (!image_name.empty()) { list.push_back(image_name); } } } void read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string keywords; stream >> keywords; if (!keywords.empty()) { list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } } void read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string line_keywords; std::getline(stream, line_keywords); if(line_keywords.empty()){ continue; } std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' ')); if(keywords.empty()){ continue; } list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } void load_sets_washington(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } void load_sets_parzival(spot_dataset& dataset, const std::string& path) { std::string full_name(path + "/sets1/"); read_list(dataset.sets["cv1"].test_set, full_name + "/test.txt"); read_list(dataset.sets["cv1"].train_set, full_name + "/train.txt"); read_list(dataset.sets["cv1"].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets["cv1"].keywords, full_name + "/keywords.txt"); } void load_sets_iam(spot_dataset& dataset, const std::string& path) { std::string full_name(path + "/sets/"); read_list(dataset.sets["cv1"].test_set, full_name + "/test.txt"); read_list(dataset.sets["cv1"].train_set, full_name + "/train.txt"); read_list(dataset.sets["cv1"].validation_set, full_name + "/valid.txt"); read_keywords_iam(dataset.sets["cv1"].keywords, full_name + "/keywords.txt"); } } //end of anonymous namespace spot_dataset read_washington(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_washington(dataset, path); return dataset; } spot_dataset read_parzival(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_parzival(dataset, path); return dataset; } spot_dataset read_iam(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_iam(dataset, path); return dataset; } std::vector<std::vector<std::string>> select_keywords(const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names) { std::vector<std::vector<std::string>> keywords; for (auto& keyword : set.keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } std::cout << "Selected " << keywords.size() << " keyword out of " << set.keywords.size() << std::endl; return keywords; } <commit_msg>Review iam sets<commit_after>//======================================================================= // Copyright Baptiste Wicht 2015. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <fstream> #include <sstream> #include <dirent.h> #include "dataset.hpp" #include "config.hpp" namespace { void read_word_labels(spot_dataset& dataset, const std::string& path) { std::ifstream word_labels_stream(path + "/ground_truth/word_labels.txt"); while (!word_labels_stream.eof()) { std::string image_name; word_labels_stream >> image_name; std::string label; word_labels_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string token; while (std::getline(ss, token, '-')) { dataset.word_labels[image_name].push_back(token); } } } void read_line_transcriptions(spot_dataset& dataset, const std::string& path) { std::ifstream line_transcriptions_stream(path + "/ground_truth/transcription.txt"); while (!line_transcriptions_stream.eof()) { std::string image_name; line_transcriptions_stream >> image_name; std::string label; line_transcriptions_stream >> label; if (image_name.empty() || label.empty()) { continue; } std::istringstream ss(label); std::string word_token; while (std::getline(ss, word_token, '|')) { std::vector<std::string> word_labels; std::istringstream ss2(word_token); std::string token; while (std::getline(ss2, token, '-')) { word_labels.push_back(token); } dataset.line_transcriptions[image_name].emplace_back(std::move(word_labels)); } } } void read_images(std::unordered_map<std::string, cv::Mat>& map, const std::string& file_path) { struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 3 || file_name.find(".png") != file_name.size() - 4) { continue; } std::string full_name(file_path + "/" + file_name); map[file_name] = cv::imread(full_name, CV_LOAD_IMAGE_ANYDEPTH); if (!map[file_name].data) { std::cout << "Impossible to read image " << full_name << std::endl; } } } void read_line_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.line_images, path + "/data/line_images_normalized/"); } void read_word_images(spot_dataset& dataset, const std::string& path) { read_images(dataset.word_images, path + "/data/word_images_normalized/"); } void read_list(std::vector<std::string>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string image_name; stream >> image_name; if (!image_name.empty()) { list.push_back(image_name); } } } void read_keywords(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string keywords; stream >> keywords; if (!keywords.empty()) { list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } } void read_keywords_iam(std::vector<std::vector<std::string>>& list, const std::string& path) { std::ifstream stream(path); while (!stream.eof()) { std::string line_keywords; std::getline(stream, line_keywords); if(line_keywords.empty()){ continue; } std::string keywords(line_keywords.begin(), line_keywords.begin() + line_keywords.find(' ')); if(keywords.empty()){ continue; } list.emplace_back(); std::istringstream ss(keywords); std::string token; while (std::getline(ss, token, '-')) { list.back().push_back(token); } } } void load_sets_washington(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } void load_sets_parzival(spot_dataset& dataset, const std::string& path) { std::string full_name(path + "/sets1/"); read_list(dataset.sets["cv1"].test_set, full_name + "/test.txt"); read_list(dataset.sets["cv1"].train_set, full_name + "/train.txt"); read_list(dataset.sets["cv1"].validation_set, full_name + "/valid.txt"); read_keywords(dataset.sets["cv1"].keywords, full_name + "/keywords.txt"); } void load_sets_iam(spot_dataset& dataset, const std::string& path) { std::string file_path(path + "/sets"); struct dirent* entry; auto dir = opendir(file_path.c_str()); while ((entry = readdir(dir))) { std::string file_name(entry->d_name); if (file_name.size() <= 2) { continue; } std::string full_name(file_path + "/" + file_name); read_list(dataset.sets[file_name].test_set, full_name + "/test.txt"); read_list(dataset.sets[file_name].train_set, full_name + "/train.txt"); read_list(dataset.sets[file_name].validation_set, full_name + "/valid.txt"); read_keywords_iam(dataset.sets[file_name].keywords, full_name + "/keywords.txt"); } } } //end of anonymous namespace spot_dataset read_washington(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_washington(dataset, path); return dataset; } spot_dataset read_parzival(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_parzival(dataset, path); return dataset; } spot_dataset read_iam(const std::string& path) { spot_dataset dataset; read_word_labels(dataset, path); read_word_images(dataset, path); if(dataset_read_lines){ read_line_transcriptions(dataset, path); read_line_images(dataset, path); } load_sets_iam(dataset, path); return dataset; } std::vector<std::vector<std::string>> select_keywords(const spot_dataset& dataset, const spot_dataset_set& set, names train_word_names, names test_image_names) { std::vector<std::vector<std::string>> keywords; for (auto& keyword : set.keywords) { bool found = false; for (auto& labels : dataset.word_labels) { if (keyword == labels.second && std::find(train_word_names.begin(), train_word_names.end(), labels.first) != train_word_names.end()) { found = true; break; } } if (found) { auto total_test = std::count_if(test_image_names.begin(), test_image_names.end(), [&dataset, &keyword](auto& i) { return dataset.word_labels.at({i.begin(), i.end() - 4}) == keyword; }); if (total_test > 0) { keywords.push_back(keyword); } } } std::cout << "Selected " << keywords.size() << " keyword out of " << set.keywords.size() << std::endl; return keywords; } <|endoftext|>
<commit_before>#include <sched.h> #include <linux/unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #include "core_manager.h" #include "core.h" #include "network.h" #include "ocache.h" #include "config.h" #include "packetize.h" #include "message_types.h" #include "log.h" using namespace std; CoreManager::CoreManager() : tid_to_core_map(3*Config::getSingleton()->getNumLocalCores()), tid_to_core_index_map(3*Config::getSingleton()->getNumLocalCores()), simthread_tid_to_core_map(3*Config::getSingleton()->getNumLocalCores()) { LOG_PRINT("Starting CoreManager Constructor."); UInt32 num_local_cores = Config::getSingleton()->getNumLocalCores(); tid_map = new UInt32 [num_local_cores]; core_to_simthread_tid_map = new UInt32 [num_local_cores]; UInt32 proc_id = Config::getSingleton()->getCurrentProcessNum(); const Config::CoreList &local_cores = Config::getSingleton()->getCoreListForProcess(proc_id); for (UInt32 i = 0; i < num_local_cores; i++) { tid_map[i] = UINT_MAX; core_to_simthread_tid_map[i] = UINT_MAX; m_cores.push_back(new Core(local_cores[i])); } LOG_PRINT("Finished CoreManager Constructor."); } CoreManager::~CoreManager() { for (std::vector<Core *>::iterator i = m_cores.begin(); i != m_cores.end(); i++) delete *i; delete [] core_to_simthread_tid_map; delete [] tid_map; } void CoreManager::initializeCommId(SInt32 comm_id) { UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_ERROR(e.first, "initializeCommId: Called without binding thread to a core."); core_id_t core_id = e.second; UnstructuredBuffer send_buff; send_buff << (SInt32)LCP_MESSAGE_COMMID_UPDATE << comm_id << core_id; LOG_PRINT("Initializing comm_id: %d to core_id: %d", comm_id, core_id); // Broadcast this update to other processes e = tid_to_core_index_map.find(tid); LOG_ASSERT_ERROR(e.first, "initializeCommId: tid mapped to core, but not to an index?"); UInt32 idx = (UInt32) e.second; LOG_ASSERT_ERROR(idx < Config::getSingleton()->getNumLocalCores(), "CoreManager got and index [%d] out of range (0-%d).", idx, Config::getSingleton()->getNumLocalCores()); Network *network = m_cores[idx]->getNetwork(); Transport::Node *transport = Transport::getSingleton()->getGlobalNode(); UInt32 num_procs = Config::getSingleton()->getProcessCount(); for (UInt32 i = 0; i < num_procs; i++) { transport->globalSend(i, send_buff.getBuffer(), send_buff.size()); } LOG_PRINT("Waiting for replies from LCPs."); for (UInt32 i = 0; i < num_procs; i++) { network->netRecvType(LCP_COMM_ID_UPDATE_REPLY); LOG_PRINT("Received reply from proc: %d", i); } LOG_PRINT("Finished."); } void CoreManager::initializeThread() { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_WARNING(e.first == false, "Thread: %d already mapped to core: %lld", tid, e.second); const Config::CoreList &core_list = Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum()); for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { if (tid_map[i] == UINT_MAX) { core_id_t core_id = core_list[i]; tid_map[i] = tid; tid_to_core_index_map.insert(tid, i); tid_to_core_map.insert(tid, core_id); LOG_PRINT("Initialize thread : index %d mapped to: thread %d, core_id: %d", i, tid, core_id); return; } else { // LOG_PRINT("%d/%d already mapped to: %d", i, Config::getSingleton()->getNumLocalCores(), tid_map[i]); } } LOG_PRINT_ERROR("initializeThread - No free cores out of %d total.", Config::getSingleton()->getNumLocalCores()); } void CoreManager::initializeThread(core_id_t core_id) { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_ERROR(e.first == false, "Tried to initialize core %d twice.", core_id); const Config::CoreList &core_list = Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum()); for (unsigned int i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { core_id_t local_core_id = core_list[i]; if(local_core_id == core_id) { if (tid_map[i] == UINT_MAX) { tid_map[i] = tid; tid_to_core_index_map.insert(tid, i); tid_to_core_map.insert(tid, core_id); LOG_PRINT("Initialize thread : index %d mapped to: thread %d, core_id: %d", i, tid_map[i], core_id); return; } else { LOG_PRINT_ERROR("initializeThread -- %d/%d already mapped to thread %d", i, Config::getSingleton()->getNumLocalCores(), tid_map[i]); } } } LOG_PRINT_ERROR("initializeThread - Requested core %d does not live on process %d.", core_id, Config::getSingleton()->getCurrentProcessNum()); } void CoreManager::terminateThread() { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); LOG_PRINT("CoreManager::terminating thread: %d", tid); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_WARNING(e.first == true, "Thread: %lld not initialized while terminating.", e.second); // If it's not in the tid_to_core_map, well then we don't need to remove it if(e.first == false) return; for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { if (tid_map[i] == tid) { tid_map[i] = UINT_MAX; tid_to_core_index_map.remove(tid); tid_to_core_map.remove(tid); LOG_PRINT("Terminate thread : removed %lld", e.second); return; } else { // LOG_PRINT("%d/%d already mapped to: %d", i, Config::getSingleton()->getNumLocalCores(), tid_map[i]); } } LOG_PRINT_ERROR("terminateThread - Thread tid: %lld not found in list.", e.second); } core_id_t CoreManager::getCurrentCoreID() { core_id_t core_id; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); core_id = (e.first == false) ? INVALID_CORE_ID : e.second; LOG_ASSERT_ERROR(!e.first || core_id < (SInt32)Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n"); return core_id; } core_id_t CoreManager::getCurrentSimThreadCoreID() { core_id_t core_id; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = simthread_tid_to_core_map.find(tid); core_id = (e.first == false) ? INVALID_CORE_ID : e.second; LOG_ASSERT_ERROR(!e.first || core_id < (SInt32)Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n"); return core_id; } Core *CoreManager::getCurrentCore() { Core *core; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_index_map.find(tid); core = (e.first == false) ? NULL : m_cores[e.second]; LOG_ASSERT_ERROR(!e.first || e.second < Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCore!\n"); return core; } Core *CoreManager::getCoreFromID(core_id_t id) { Core *core = NULL; // Look up the index from the core list // FIXME: make this more cached const Config::CoreList & cores(Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum())); UInt32 idx = 0; for (Config::CLCI i = cores.begin(); i != cores.end(); i++) { if (*i == id) { core = m_cores[idx]; break; } idx++; } LOG_ASSERT_ERROR(!core || idx < Config::getSingleton()->getNumLocalCores(), "Illegal index in getCoreFromID!\n"); return core; } Core *CoreManager::getCoreFromIndex(UInt32 index) { LOG_ASSERT_ERROR(index < Config::getSingleton()->getNumLocalCores(), "getCoreFromIndex -- invalid index %d", index); return m_cores[index]; } void CoreManager::outputSummary() { LOG_PRINT("Starting CoreManager::outputSummary"); ofstream out(Config::getSingleton()->getOutputFileName()); for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { LOG_PRINT("Output summary core %i", i); out << "*** Core[" << i << "] summary ***" << endl; if (Config::getSingleton()->getEnablePerformanceModeling()) { m_cores[i]->getPerfModel()->outputSummary(out); m_cores[i]->getNetwork()->outputSummary(out); } if (Config::getSingleton()->getEnableDCacheModeling() || Config::getSingleton()->getEnableICacheModeling()) m_cores[i]->getOCache()->outputSummary(out); out << endl; } out.close(); } core_id_t CoreManager::registerSimMemThread() { UInt32 tid = getCurrentTID(); ScopedLock sl(m_maps_lock); pair<bool, UInt64> e = simthread_tid_to_core_map.find(tid); // If this thread isn't registered if (e.first == false) { // Search for an unused core to map this simthread thread to // one less to account for the MCP for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { // Unused slots are set to UINT_MAX // FIXME: Use a different constant than UINT_MAX if (core_to_simthread_tid_map[i] == UINT_MAX) { core_to_simthread_tid_map[i] = tid; simthread_tid_to_core_map.insert(tid, i); return Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum())[i]; } } LOG_PRINT("registerSimMemThread - No free cores for thread: %d", tid); for (UInt32 j = 0; j < Config::getSingleton()->getNumLocalCores(); j++) LOG_PRINT("core_to_simthread_tid_map[%d] = %d\n", j, core_to_simthread_tid_map[j]); LOG_PRINT_ERROR(""); } else { LOG_PRINT_WARNING("registerSimMemThread - Initialized thread twice"); // FIXME: I think this is OK return simthread_tid_to_core_map.find(tid).second; } return INVALID_CORE_ID; } UInt32 CoreManager::getCurrentTID() { return syscall(__NR_gettid); } <commit_msg>[core_manager] Add bounds checks, remove dead code.<commit_after>#include <sched.h> #include <linux/unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <unistd.h> #include "core_manager.h" #include "core.h" #include "network.h" #include "ocache.h" #include "config.h" #include "packetize.h" #include "message_types.h" #include "log.h" using namespace std; CoreManager::CoreManager() : tid_to_core_map(3*Config::getSingleton()->getNumLocalCores()), tid_to_core_index_map(3*Config::getSingleton()->getNumLocalCores()), simthread_tid_to_core_map(3*Config::getSingleton()->getNumLocalCores()) { LOG_PRINT("Starting CoreManager Constructor."); UInt32 num_local_cores = Config::getSingleton()->getNumLocalCores(); tid_map = new UInt32 [num_local_cores]; core_to_simthread_tid_map = new UInt32 [num_local_cores]; UInt32 proc_id = Config::getSingleton()->getCurrentProcessNum(); const Config::CoreList &local_cores = Config::getSingleton()->getCoreListForProcess(proc_id); for (UInt32 i = 0; i < num_local_cores; i++) { tid_map[i] = UINT_MAX; core_to_simthread_tid_map[i] = UINT_MAX; m_cores.push_back(new Core(local_cores[i])); } LOG_PRINT("Finished CoreManager Constructor."); } CoreManager::~CoreManager() { for (std::vector<Core *>::iterator i = m_cores.begin(); i != m_cores.end(); i++) delete *i; delete [] core_to_simthread_tid_map; delete [] tid_map; } void CoreManager::initializeCommId(SInt32 comm_id) { UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_ERROR(e.first, "initializeCommId: Called without binding thread to a core."); core_id_t core_id = e.second; UnstructuredBuffer send_buff; send_buff << (SInt32)LCP_MESSAGE_COMMID_UPDATE << comm_id << core_id; LOG_PRINT("Initializing comm_id: %d to core_id: %d", comm_id, core_id); // Broadcast this update to other processes e = tid_to_core_index_map.find(tid); LOG_ASSERT_ERROR(e.first, "initializeCommId: tid mapped to core, but not to an index?"); UInt32 idx = (UInt32) e.second; LOG_ASSERT_ERROR(idx < Config::getSingleton()->getNumLocalCores(), "CoreManager got and index [%d] out of range (0-%d).", idx, Config::getSingleton()->getNumLocalCores()); Network *network = m_cores[idx]->getNetwork(); Transport::Node *transport = Transport::getSingleton()->getGlobalNode(); UInt32 num_procs = Config::getSingleton()->getProcessCount(); for (UInt32 i = 0; i < num_procs; i++) { transport->globalSend(i, send_buff.getBuffer(), send_buff.size()); } LOG_PRINT("Waiting for replies from LCPs."); for (UInt32 i = 0; i < num_procs; i++) { network->netRecvType(LCP_COMM_ID_UPDATE_REPLY); LOG_PRINT("Received reply from proc: %d", i); } LOG_PRINT("Finished."); } void CoreManager::initializeThread() { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_WARNING(e.first == false, "Thread: %d already mapped to core: %lld", tid, e.second); const Config::CoreList &core_list = Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum()); LOG_ASSERT_ERROR(core_list.size() == Config::getSingleton()->getNumLocalCores(), "Core list size different from num local cores? %d != %d", core_list.size(), Config::getSingleton()->getNumLocalCores()); for (UInt32 i = 0; i < core_list.size(); i++) { if (tid_map[i] == UINT_MAX) { core_id_t core_id = core_list[i]; tid_map[i] = tid; tid_to_core_index_map.insert(tid, i); tid_to_core_map.insert(tid, core_id); LOG_PRINT("Initialize thread : index %d mapped to: thread %d, core_id: %d", i, tid, core_id); return; } } LOG_PRINT_ERROR("initializeThread - No free cores out of %d total.", Config::getSingleton()->getNumLocalCores()); } void CoreManager::initializeThread(core_id_t core_id) { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_ERROR(e.first == false, "Tried to initialize core %d twice.", core_id); const Config::CoreList &core_list = Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum()); LOG_ASSERT_ERROR(core_list.size() == Config::getSingleton()->getNumLocalCores(), "Core list size different from num local cores? %d != %d", core_list.size(), Config::getSingleton()->getNumLocalCores()); for (UInt32 i = 0; i < core_list.size(); i++) { core_id_t local_core_id = core_list[i]; if(local_core_id == core_id) { if (tid_map[i] == UINT_MAX) { tid_map[i] = tid; tid_to_core_index_map.insert(tid, i); tid_to_core_map.insert(tid, core_id); LOG_PRINT("Initialize thread : index %d mapped to: thread %d, core_id: %d", i, tid_map[i], core_id); return; } else { LOG_PRINT_ERROR("initializeThread -- %d/%d already mapped to thread %d", i, Config::getSingleton()->getNumLocalCores(), tid_map[i]); } } } LOG_PRINT_ERROR("initializeThread - Requested core %d does not live on process %d.", core_id, Config::getSingleton()->getCurrentProcessNum()); } void CoreManager::terminateThread() { ScopedLock scoped_maps_lock(m_maps_lock); UInt32 tid = getCurrentTID(); LOG_PRINT("CoreManager::terminating thread: %d", tid); pair<bool, UInt64> e = tid_to_core_map.find(tid); LOG_ASSERT_WARNING(e.first == true, "Thread: %lld not initialized while terminating.", e.second); // If it's not in the tid_to_core_map, well then we don't need to remove it if(e.first == false) return; for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { if (tid_map[i] == tid) { tid_map[i] = UINT_MAX; tid_to_core_index_map.remove(tid); tid_to_core_map.remove(tid); LOG_PRINT("Terminate thread : removed %lld", e.second); return; } } LOG_PRINT_ERROR("terminateThread - Thread tid: %lld not found in list.", e.second); } core_id_t CoreManager::getCurrentCoreID() { core_id_t core_id; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_map.find(tid); core_id = (e.first == false) ? INVALID_CORE_ID : e.second; LOG_ASSERT_ERROR(!e.first || core_id < (SInt32)Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n"); return core_id; } core_id_t CoreManager::getCurrentSimThreadCoreID() { core_id_t core_id; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = simthread_tid_to_core_map.find(tid); core_id = (e.first == false) ? INVALID_CORE_ID : e.second; LOG_ASSERT_ERROR(!e.first || core_id < (SInt32)Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCoreID!\n"); return core_id; } Core *CoreManager::getCurrentCore() { Core *core; UInt32 tid = getCurrentTID(); pair<bool, UInt64> e = tid_to_core_index_map.find(tid); core = (e.first == false) ? NULL : m_cores[e.second]; LOG_ASSERT_ERROR(!e.first || e.second < Config::getSingleton()->getTotalCores(), "Illegal core_id value returned by getCurrentCore!\n"); return core; } Core *CoreManager::getCoreFromID(core_id_t id) { Core *core = NULL; // Look up the index from the core list // FIXME: make this more cached const Config::CoreList & cores(Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum())); UInt32 idx = 0; for (Config::CLCI i = cores.begin(); i != cores.end(); i++) { if (*i == id) { core = m_cores[idx]; break; } idx++; } LOG_ASSERT_ERROR(!core || idx < Config::getSingleton()->getNumLocalCores(), "Illegal index in getCoreFromID!\n"); return core; } Core *CoreManager::getCoreFromIndex(UInt32 index) { LOG_ASSERT_ERROR(index < Config::getSingleton()->getNumLocalCores(), "getCoreFromIndex -- invalid index %d", index); return m_cores[index]; } void CoreManager::outputSummary() { LOG_PRINT("Starting CoreManager::outputSummary"); ofstream out(Config::getSingleton()->getOutputFileName()); for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { LOG_PRINT("Output summary core %i", i); out << "*** Core[" << i << "] summary ***" << endl; if (Config::getSingleton()->getEnablePerformanceModeling()) { m_cores[i]->getPerfModel()->outputSummary(out); m_cores[i]->getNetwork()->outputSummary(out); } if (Config::getSingleton()->getEnableDCacheModeling() || Config::getSingleton()->getEnableICacheModeling()) m_cores[i]->getOCache()->outputSummary(out); out << endl; } out.close(); } core_id_t CoreManager::registerSimMemThread() { UInt32 tid = getCurrentTID(); ScopedLock sl(m_maps_lock); pair<bool, UInt64> e = simthread_tid_to_core_map.find(tid); // If this thread isn't registered if (e.first == false) { // Search for an unused core to map this simthread thread to // one less to account for the MCP for (UInt32 i = 0; i < Config::getSingleton()->getNumLocalCores(); i++) { // Unused slots are set to UINT_MAX // FIXME: Use a different constant than UINT_MAX if (core_to_simthread_tid_map[i] == UINT_MAX) { core_to_simthread_tid_map[i] = tid; simthread_tid_to_core_map.insert(tid, i); return Config::getSingleton()->getCoreListForProcess(Config::getSingleton()->getCurrentProcessNum())[i]; } } LOG_PRINT("registerSimMemThread - No free cores for thread: %d", tid); for (UInt32 j = 0; j < Config::getSingleton()->getNumLocalCores(); j++) LOG_PRINT("core_to_simthread_tid_map[%d] = %d\n", j, core_to_simthread_tid_map[j]); LOG_PRINT_ERROR(""); } else { LOG_PRINT_WARNING("registerSimMemThread - Initialized thread twice"); // FIXME: I think this is OK return simthread_tid_to_core_map.find(tid).second; } return INVALID_CORE_ID; } UInt32 CoreManager::getCurrentTID() { return syscall(__NR_gettid); } <|endoftext|>
<commit_before>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* mem_nodes= nullptr; /// for nodes allocation/delocation. operation of new/delete of each node has been overwritten to use this memory pool for speed-up AlignedMemoryPool<ALIGN>* glb_temp_working_mem = nullptr; AlignedMemoryPool<ALIGN>* glb_temp_lookup_gradient_value_mem = nullptr; /// this saves gradient on those sparse lookup table parameters that have non-zero gradiens. these values and gradients are temporary mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; mem_nodes = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20), true); glb_temp_working_mem = new AlignedMemoryPool<ALIGN>(1UL << 16); glb_temp_lookup_gradient_value_mem = new AlignedMemoryPool<ALIGN>(1UL << 26); if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); delete (mem_nodes); delete (glb_temp_working_mem); for (auto p : kSCALAR_ONE_OVER_INT) cnn_mm_free(p); #ifdef HAVE_CUDA Free_GPU(); #endif cerr << "Done.\n"; } } // namespace cnn <commit_msg>smaller space for temp gradient and value space as value is not need to be allocated for non-zero gradients<commit_after>#include "cnn/init.h" #include "cnn/aligned-mem-pool.h" #include "cnn/cnn.h" #include "cnn/model.h" #include <iostream> #include <random> #include <cmath> #if HAVE_CUDA #include "cnn/cuda.h" #include <device_launch_parameters.h> #endif using namespace std; namespace cnn { AlignedMemoryPool<ALIGN>* fxs = nullptr; AlignedMemoryPool<ALIGN>* dEdfs = nullptr; AlignedMemoryPool<ALIGN>* mem_nodes= nullptr; /// for nodes allocation/delocation. operation of new/delete of each node has been overwritten to use this memory pool for speed-up AlignedMemoryPool<ALIGN>* glb_temp_working_mem = nullptr; AlignedMemoryPool<ALIGN>* glb_temp_lookup_gradient_value_mem = nullptr; /// this saves gradient on those sparse lookup table parameters that have non-zero gradiens. these values and gradients are temporary mt19937* rndeng = nullptr; char* getCmdOption(char ** begin, char ** end, const std::string & option) { char ** itr = std::find(begin, end, option); if (itr != end && ++itr != end) { return *itr; } return 0; } static void RemoveArgs(int& argc, char**& argv, int& argi, int n) { for (int i = argi + n; i < argc; ++i) argv[i - n] = argv[i]; argc -= n; assert(argc >= 0); } bool cmdOptionExists(char** begin, char** end, const std::string& option) { return std::find(begin, end, option) != end; } void Initialize(int& argc, char**& argv, unsigned random_seed, bool demo) { cerr << "Initializing...\n"; #if HAVE_CUDA Initialize_GPU(argc, argv); #else kSCALAR_MINUSONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_MINUSONE = -1; kSCALAR_ONE = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ONE = 1; kSCALAR_ZERO = (cnn::real*)cnn_mm_malloc(sizeof(cnn::real), CNN_ALIGN); *kSCALAR_ZERO = 0; #endif if (random_seed == 0) { if (cmdOptionExists(argv, argv + argc, "--seed")) { string seed = getCmdOption(argv, argv + argc, "--seed"); stringstream(seed) >> random_seed; } else { random_device rd; random_seed = rd(); } } rndeng = new mt19937(random_seed); cerr << "Allocating memory...\n"; unsigned long num_mb = 512UL; mem_nodes = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20), true); glb_temp_working_mem = new AlignedMemoryPool<ALIGN>(1UL << 16); glb_temp_lookup_gradient_value_mem = new AlignedMemoryPool<ALIGN>(1UL << 25); if (demo) { fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 20)); } else { #ifdef HAVE_CUDA fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #else fxs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); dEdfs = new AlignedMemoryPool<ALIGN>(512UL * (1UL << 22)); #endif } cerr << "Done.\n"; } void Free() { cerr << "Freeing memory ...\n"; cnn_mm_free(kSCALAR_MINUSONE); cnn_mm_free(kSCALAR_ONE); cnn_mm_free(kSCALAR_ZERO); delete (rndeng); delete (fxs); delete (dEdfs); delete (mem_nodes); delete (glb_temp_working_mem); for (auto p : kSCALAR_ONE_OVER_INT) cnn_mm_free(p); #ifdef HAVE_CUDA Free_GPU(); #endif cerr << "Done.\n"; } } // namespace cnn <|endoftext|>
<commit_before>#include "filename/filename-parser.h" #include <QChar> #include <QList> #include <QStack> #include "filename/ast/filename-node-condition.h" #include "filename/ast/filename-node-condition-ignore.h" #include "filename/ast/filename-node-condition-invert.h" #include "filename/ast/filename-node-condition-javascript.h" #include "filename/ast/filename-node-condition-op.h" #include "filename/ast/filename-node-condition-tag.h" #include "filename/ast/filename-node-condition-token.h" #include "filename/ast/filename-node-conditional.h" #include "filename/ast/filename-node-javascript.h" #include "filename/ast/filename-node-root.h" #include "filename/ast/filename-node-text.h" #include "filename/ast/filename-node-variable.h" #define ESCAPE_CHARACTER '^' FilenameParser::FilenameParser(QString str) : m_str(std::move(str)), m_index(0) {} const QString &FilenameParser::error() const { return m_error; } FilenameNodeRoot *FilenameParser::parseRoot() { try { return parseRootNode(); } catch (const std::runtime_error &e) { m_error = e.what(); return nullptr; } } FilenameNodeCondition *FilenameParser::parseCondition() { try { return parseConditionNode(); } catch (const std::runtime_error &e) { m_error = e.what(); return nullptr; } } QChar FilenameParser::peek() { return m_str[m_index]; } bool FilenameParser::finished() { return m_index >= m_str.count(); } void FilenameParser::skipSpaces() { while (peek().isSpace()) { m_index++; } } int FilenameParser::indexOf(const QList<QChar> &chars, int max) { bool escapeNext = false; int limit = max < 0 ? m_str.count() : qMin(max, m_str.count()); for (int index = m_index; index < limit; ++index) { QChar c = m_str[index]; // Don't return on escaped characters bool isEscape = c == ESCAPE_CHARACTER || ((c == '<' || c == '>') && index < m_str.length() - 1 && c == m_str[index + 1]); if (isEscape && !escapeNext) { escapeNext = true; } else if (chars.contains(c) && !escapeNext) { return index; } // Clear escape character if unused if (!isEscape && escapeNext) { escapeNext = false; } } return -1; } QString FilenameParser::readUntil(const QList<QChar> &chars, bool allowEnd) { QString ret; bool escapeNext = false; while (!finished()) { QChar c = m_str[m_index]; // Don't return on escaped characters bool isEscape = c == ESCAPE_CHARACTER || ((c == '<' || c == '>') && m_index < m_str.length() - 1 && c == m_str[m_index + 1]); if (isEscape && !escapeNext) { escapeNext = true; } else { if (chars.contains(c) && !escapeNext) { return ret; } ret.append(c); } // Clear escape character if unused if (!isEscape && escapeNext) { escapeNext = false; } m_index++; } if (!allowEnd) { throw std::runtime_error("Unexpected EOF"); } return ret; } FilenameNodeRoot *FilenameParser::parseRootNode() { QList<FilenameNode*> exprs; while (!finished()) { exprs.append(parseExpr()); } return new FilenameNodeRoot(exprs); } FilenameNode *FilenameParser::parseExpr(const QList<QChar> &addChars) { if (m_str.mid(m_index, 11) == "javascript:") { return parseJavaScript(); } QList<QChar> until = QList<QChar>{ '<', '%' } + addChars; QString txt = readUntil(until, true); if (txt.isEmpty()) { QChar p = peek(); if (p == '<' && (m_index >= m_str.length() - 1 || m_str[m_index + 1] != '<')) { return parseConditional(); } if (p == '%') { return parseVariable(); } } return new FilenameNodeText(txt); } FilenameNodeJavaScript *FilenameParser::parseJavaScript() { m_index += 11; // javascript: int start = m_index; m_index = m_str.length(); return new FilenameNodeJavaScript(m_str.mid(start)); } FilenameNodeVariable *FilenameParser::parseVariable() { m_index++; // % QString name = readUntil({ ':', '%' }); QMap<QString, QString> opts; while (peek() != '%') { m_index++; // : or , QString opt = readUntil({ '=', ',', '%' }); QString val; if (peek() == '=') { m_index++; // = val = readUntil({ ',', '%' }); } opts.insert(opt, val); } m_index++; // % return new FilenameNodeVariable(name, opts); } FilenameNodeConditional *FilenameParser::parseConditional() { m_index++; // < FilenameNodeCondition *condition = nullptr; FilenameNode *ifTrue = nullptr; FilenameNode *ifFalse = nullptr; // Legacy conditionals int endIndex = indexOf({ '>' }); int sepIndex = indexOf({ '?' }, endIndex); if (sepIndex < 0) { QList<FilenameNode*> exprs; QList<FilenameNodeCondition*> conds; while (peek() != '>') { QList<QChar> stop { '>', '-', '!', '"', '%' }; if (!stop.contains(peek())) { exprs.append(parseExpr(stop)); } if (peek() != '>') { auto cond = parseSingleCondition(true); conds.append(cond); exprs.append(cond); } } if (conds.isEmpty()) { throw std::runtime_error("No condition found in conditional"); } condition = conds.takeFirst(); while (!conds.isEmpty()) { condition = new FilenameNodeConditionOp(FilenameNodeConditionOp::And, condition, conds.takeFirst()); } ifTrue = exprs.count() == 1 ? exprs.first() : new FilenameNodeRoot(exprs); } else { condition = parseConditionNode(); if (peek() != '?') { delete condition; throw std::runtime_error("Expected '?' after condition"); } m_index++; // ? ifTrue = parseExpr({ ':', '>' }); if (peek() == ':') { m_index++; // : ifFalse = parseExpr({ '>' }); } if (peek() != '>') { delete condition; delete ifTrue; delete ifFalse; throw std::runtime_error("Expected '>' at the end of contional"); } } m_index++; // > return new FilenameNodeConditional(condition, ifTrue, ifFalse); } FilenameNodeCondition *FilenameParser::parseConditionNode() { if (m_str.mid(m_index, 11) == "javascript:") { return parseConditionJavaScript(); } skipSpaces(); FilenameNodeCondition *lhs; // Parenthesis QChar p = peek(); if (p == '(') { m_index++; // ( lhs = parseConditionNode(); if (peek() != ')') { delete lhs; throw std::runtime_error("Expected ')' after condition in parenthesis"); } m_index++; // ) } else { lhs = parseSingleCondition(); } QStack<QChar> opsStack; QStack<FilenameNodeCondition*> termStack; while (!finished()) { skipSpaces(); QChar p = peek(); QChar c = p == '"' || p == '%' ? '&' : p; if (c != '&' && c != '|') { break; } termStack.push(lhs); int prec = (c == '&' ? 2 : 1); while (!opsStack.isEmpty()) { QChar stackC = opsStack.top(); int stackPrec = (stackC == '&' ? 2 : 1); if (prec > stackPrec) { break; } FilenameNodeCondition *operand2 = termStack.pop(); FilenameNodeCondition *operand1 = termStack.pop(); QChar opC = opsStack.pop(); auto op = opC == '&' ? FilenameNodeConditionOp::And : FilenameNodeConditionOp::Or; auto expr = new FilenameNodeConditionOp(op, operand1, operand2); termStack.push(expr); } opsStack.push(c); if (p == c) { m_index++; skipSpaces(); } termStack.push(parseSingleCondition()); } while (!opsStack.isEmpty()) { FilenameNodeCondition *operand2 = termStack.pop(); FilenameNodeCondition *operand1 = termStack.pop(); QChar opC = opsStack.pop(); auto op = opC == '&' ? FilenameNodeConditionOp::And : FilenameNodeConditionOp::Or; auto expr = new FilenameNodeConditionOp(op, operand1, operand2); termStack.push(expr); } auto term = lhs; if (!termStack.isEmpty()) { term = termStack.pop(); } skipSpaces(); return term; } FilenameNodeCondition *FilenameParser::parseSingleCondition(bool legacy) { QChar c = peek(); if (legacy && c == '-') { return parseConditionIgnore(); } if (c == '!' || c == '-') { return parseConditionInvert(); } if (c == '%') { return parseConditionToken(); } if (c == '"') { return parseConditionTag(); } if (!legacy) { return parseConditionTag(false); } throw std::runtime_error("Expected '!', '%' or '\"' for condition"); } FilenameNodeConditionIgnore *FilenameParser::parseConditionIgnore() { m_index++; // - auto cond = parseSingleCondition(); return new FilenameNodeConditionIgnore(cond); } FilenameNodeConditionInvert *FilenameParser::parseConditionInvert() { m_index++; // ! or - auto cond = parseSingleCondition(); return new FilenameNodeConditionInvert(cond); } FilenameNodeConditionJavaScript *FilenameParser::parseConditionJavaScript() { m_index += 11; // javascript: int start = m_index; m_index = m_str.length(); return new FilenameNodeConditionJavaScript(m_str.mid(start)); } FilenameNodeConditionTag *FilenameParser::parseConditionTag(bool quotes) { if (quotes) { m_index++; // " } QString tag = quotes ? readUntil({ '"' }) : readUntil({ ' ', '&', '|', '?' }, true); if (quotes) { m_index++; // " } return new FilenameNodeConditionTag(Tag(tag)); } FilenameNodeConditionToken *FilenameParser::parseConditionToken() { m_index++; // % QString token = readUntil({ '%' }); m_index++; // % return new FilenameNodeConditionToken(token); } <commit_msg>Stay in legacy mode when parsing conditional ignores<commit_after>#include "filename/filename-parser.h" #include <QChar> #include <QList> #include <QStack> #include "filename/ast/filename-node-condition.h" #include "filename/ast/filename-node-condition-ignore.h" #include "filename/ast/filename-node-condition-invert.h" #include "filename/ast/filename-node-condition-javascript.h" #include "filename/ast/filename-node-condition-op.h" #include "filename/ast/filename-node-condition-tag.h" #include "filename/ast/filename-node-condition-token.h" #include "filename/ast/filename-node-conditional.h" #include "filename/ast/filename-node-javascript.h" #include "filename/ast/filename-node-root.h" #include "filename/ast/filename-node-text.h" #include "filename/ast/filename-node-variable.h" #define ESCAPE_CHARACTER '^' FilenameParser::FilenameParser(QString str) : m_str(std::move(str)), m_index(0) {} const QString &FilenameParser::error() const { return m_error; } FilenameNodeRoot *FilenameParser::parseRoot() { try { return parseRootNode(); } catch (const std::runtime_error &e) { m_error = e.what(); return nullptr; } } FilenameNodeCondition *FilenameParser::parseCondition() { try { return parseConditionNode(); } catch (const std::runtime_error &e) { m_error = e.what(); return nullptr; } } QChar FilenameParser::peek() { return m_str[m_index]; } bool FilenameParser::finished() { return m_index >= m_str.count(); } void FilenameParser::skipSpaces() { while (peek().isSpace()) { m_index++; } } int FilenameParser::indexOf(const QList<QChar> &chars, int max) { bool escapeNext = false; int limit = max < 0 ? m_str.count() : qMin(max, m_str.count()); for (int index = m_index; index < limit; ++index) { QChar c = m_str[index]; // Don't return on escaped characters bool isEscape = c == ESCAPE_CHARACTER || ((c == '<' || c == '>') && index < m_str.length() - 1 && c == m_str[index + 1]); if (isEscape && !escapeNext) { escapeNext = true; } else if (chars.contains(c) && !escapeNext) { return index; } // Clear escape character if unused if (!isEscape && escapeNext) { escapeNext = false; } } return -1; } QString FilenameParser::readUntil(const QList<QChar> &chars, bool allowEnd) { QString ret; bool escapeNext = false; while (!finished()) { QChar c = m_str[m_index]; // Don't return on escaped characters bool isEscape = c == ESCAPE_CHARACTER || ((c == '<' || c == '>') && m_index < m_str.length() - 1 && c == m_str[m_index + 1]); if (isEscape && !escapeNext) { escapeNext = true; } else { if (chars.contains(c) && !escapeNext) { return ret; } ret.append(c); } // Clear escape character if unused if (!isEscape && escapeNext) { escapeNext = false; } m_index++; } if (!allowEnd) { throw std::runtime_error("Unexpected EOF"); } return ret; } FilenameNodeRoot *FilenameParser::parseRootNode() { QList<FilenameNode*> exprs; while (!finished()) { exprs.append(parseExpr()); } return new FilenameNodeRoot(exprs); } FilenameNode *FilenameParser::parseExpr(const QList<QChar> &addChars) { if (m_str.mid(m_index, 11) == "javascript:") { return parseJavaScript(); } QList<QChar> until = QList<QChar>{ '<', '%' } + addChars; QString txt = readUntil(until, true); if (txt.isEmpty()) { QChar p = peek(); if (p == '<' && (m_index >= m_str.length() - 1 || m_str[m_index + 1] != '<')) { return parseConditional(); } if (p == '%') { return parseVariable(); } } return new FilenameNodeText(txt); } FilenameNodeJavaScript *FilenameParser::parseJavaScript() { m_index += 11; // javascript: int start = m_index; m_index = m_str.length(); return new FilenameNodeJavaScript(m_str.mid(start)); } FilenameNodeVariable *FilenameParser::parseVariable() { m_index++; // % QString name = readUntil({ ':', '%' }); QMap<QString, QString> opts; while (peek() != '%') { m_index++; // : or , QString opt = readUntil({ '=', ',', '%' }); QString val; if (peek() == '=') { m_index++; // = val = readUntil({ ',', '%' }); } opts.insert(opt, val); } m_index++; // % return new FilenameNodeVariable(name, opts); } FilenameNodeConditional *FilenameParser::parseConditional() { m_index++; // < FilenameNodeCondition *condition = nullptr; FilenameNode *ifTrue = nullptr; FilenameNode *ifFalse = nullptr; // Legacy conditionals int endIndex = indexOf({ '>' }); int sepIndex = indexOf({ '?' }, endIndex); if (sepIndex < 0) { QList<FilenameNode*> exprs; QList<FilenameNodeCondition*> conds; while (peek() != '>') { QList<QChar> stop { '>', '-', '!', '"', '%' }; if (!stop.contains(peek())) { exprs.append(parseExpr(stop)); } if (peek() != '>') { auto cond = parseSingleCondition(true); conds.append(cond); exprs.append(cond); } } if (conds.isEmpty()) { throw std::runtime_error("No condition found in conditional"); } condition = conds.takeFirst(); while (!conds.isEmpty()) { condition = new FilenameNodeConditionOp(FilenameNodeConditionOp::And, condition, conds.takeFirst()); } ifTrue = exprs.count() == 1 ? exprs.first() : new FilenameNodeRoot(exprs); } else { condition = parseConditionNode(); if (peek() != '?') { delete condition; throw std::runtime_error("Expected '?' after condition"); } m_index++; // ? ifTrue = parseExpr({ ':', '>' }); if (peek() == ':') { m_index++; // : ifFalse = parseExpr({ '>' }); } if (peek() != '>') { delete condition; delete ifTrue; delete ifFalse; throw std::runtime_error("Expected '>' at the end of contional"); } } m_index++; // > return new FilenameNodeConditional(condition, ifTrue, ifFalse); } FilenameNodeCondition *FilenameParser::parseConditionNode() { if (m_str.mid(m_index, 11) == "javascript:") { return parseConditionJavaScript(); } skipSpaces(); FilenameNodeCondition *lhs; // Parenthesis QChar p = peek(); if (p == '(') { m_index++; // ( lhs = parseConditionNode(); if (peek() != ')') { delete lhs; throw std::runtime_error("Expected ')' after condition in parenthesis"); } m_index++; // ) } else { lhs = parseSingleCondition(); } QStack<QChar> opsStack; QStack<FilenameNodeCondition*> termStack; while (!finished()) { skipSpaces(); QChar p = peek(); QChar c = p == '"' || p == '%' ? '&' : p; if (c != '&' && c != '|') { break; } termStack.push(lhs); int prec = (c == '&' ? 2 : 1); while (!opsStack.isEmpty()) { QChar stackC = opsStack.top(); int stackPrec = (stackC == '&' ? 2 : 1); if (prec > stackPrec) { break; } FilenameNodeCondition *operand2 = termStack.pop(); FilenameNodeCondition *operand1 = termStack.pop(); QChar opC = opsStack.pop(); auto op = opC == '&' ? FilenameNodeConditionOp::And : FilenameNodeConditionOp::Or; auto expr = new FilenameNodeConditionOp(op, operand1, operand2); termStack.push(expr); } opsStack.push(c); if (p == c) { m_index++; skipSpaces(); } termStack.push(parseSingleCondition()); } while (!opsStack.isEmpty()) { FilenameNodeCondition *operand2 = termStack.pop(); FilenameNodeCondition *operand1 = termStack.pop(); QChar opC = opsStack.pop(); auto op = opC == '&' ? FilenameNodeConditionOp::And : FilenameNodeConditionOp::Or; auto expr = new FilenameNodeConditionOp(op, operand1, operand2); termStack.push(expr); } auto term = lhs; if (!termStack.isEmpty()) { term = termStack.pop(); } skipSpaces(); return term; } FilenameNodeCondition *FilenameParser::parseSingleCondition(bool legacy) { QChar c = peek(); if (legacy && c == '-') { return parseConditionIgnore(); } if (c == '!' || c == '-') { return parseConditionInvert(); } if (c == '%') { return parseConditionToken(); } if (c == '"') { return parseConditionTag(); } if (!legacy) { return parseConditionTag(false); } throw std::runtime_error("Expected '!', '%' or '\"' for condition"); } FilenameNodeConditionIgnore *FilenameParser::parseConditionIgnore() { m_index++; // - auto cond = parseSingleCondition(true); return new FilenameNodeConditionIgnore(cond); } FilenameNodeConditionInvert *FilenameParser::parseConditionInvert() { m_index++; // ! or - auto cond = parseSingleCondition(); return new FilenameNodeConditionInvert(cond); } FilenameNodeConditionJavaScript *FilenameParser::parseConditionJavaScript() { m_index += 11; // javascript: int start = m_index; m_index = m_str.length(); return new FilenameNodeConditionJavaScript(m_str.mid(start)); } FilenameNodeConditionTag *FilenameParser::parseConditionTag(bool quotes) { if (quotes) { m_index++; // " } QString tag = quotes ? readUntil({ '"' }) : readUntil({ ' ', '&', '|', '?' }, true); if (quotes) { m_index++; // " } return new FilenameNodeConditionTag(Tag(tag)); } FilenameNodeConditionToken *FilenameParser::parseConditionToken() { m_index++; // % QString token = readUntil({ '%' }); m_index++; // % return new FilenameNodeConditionToken(token); } <|endoftext|>
<commit_before><commit_msg>This should hopefully fix the problem with disappearing dimap folders (backport revision 1.313)<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_MIOPEN_DB_HPP_ #define GUARD_MIOPEN_DB_HPP_ #include <string> #include <ios> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/sync/sharable_lock.hpp> #include <boost/optional.hpp> #include <miopen/db_record.hpp> #include <miopen/lock_file.hpp> namespace miopen { /// No instance of this class should be used from several threads at the same time. class Db { public: inline Db(const std::string& filename_) : filename(filename_), lock_file(LockFileDispatcher::Get((filename_ + ".lock").c_str())) { } /// Searches db for provided key and returns found record or none if key not found in database inline boost::optional<DbRecord> FindRecord(const std::string& key) { shared_lock lock(lock_file); return FindRecordUnsafe(key, nullptr); } template <class T> inline boost::optional<DbRecord> FindRecord(const T& problem_config) { shared_lock lock(lock_file); return FindRecordUnsafe(problem_config); } /// Stores provided record in database. If record with same key is already in database it is /// replaced by provided record. /// /// Returns true if store was successful, false otherwise. inline bool StoreRecord(const DbRecord& record) { exclusive_lock lock(lock_file); return StoreRecordUnsafe(record); } /// Stores provided record in database. If record with same key is already in database it is /// updated with values from provided record. Provided records data is also updated via /// DbRecord::Merge(). /// /// Returns true if update was successful, false otherwise. inline bool UpdateRecord(DbRecord& record) { exclusive_lock lock(lock_file); return UpdateRecordUnsafe(record); } /// Removes record with provided key from db /// /// Returns true if remove was successful, false otherwise. inline bool RemoveRecord(const std::string& key) { exclusive_lock lock(lock_file); return RemoveRecordUnsafe(key); } template <class T> inline bool RemoveRecord(const T& problem_config) { auto key = DbRecord::Serialize(problem_config); return RemoveRecord(key); } /// Updates record under key PROBLEM_CONFIG with data ID:VALUES in database. /// Both T and V classes should have "void Serialize(std::ostream&) const" member function /// available. /// /// Returns updated record or none if update was unsuccessful. template <class T, class V> inline boost::optional<DbRecord> Update(const T& problem_config, const std::string& id, const V& values) { DbRecord record(problem_config); record.SetValues(id, values); bool ok = UpdateRecord(record); if(ok) return record; else return boost::none; } /// Searches for record with key PROBLEM_CONFIG and gets VALUES under the ID from it. /// Class T should have "void Serialize(std::ostream&) const" member function available. /// Class V shall have "bool Deserialize(const std::string& str)" member function available. /// /// Returns false if there is none PROBLEM_CONFIG=ID:VALUES in the database /// or in case of any error, e.g. if VALUES cannot be deserialized due to incorrect format. template <class T, class V> inline bool Load(const T& problem_config, const std::string& id, V& values) { auto record = FindRecord(problem_config); if(!record) return false; return record->GetValues(id, values); } /// Removes ID with associated VALUES from record with key PROBLEM_CONFIG from db. /// If payload of a record becomes empty after that, also removes the entire record /// /// Returns true if remove was successful. Returns false if this PROBLEM_CONFIG or ID was not /// found. template <class T> inline bool Remove(const T& problem_config, const std::string& id) { exclusive_lock lock(lock_file); auto record = FindRecordUnsafe(problem_config); if(!record) return false; bool erased = record->EraseValues(id); if(!erased) return false; return StoreRecordUnsafe(*record); } private: struct RecordPositions { std::streamoff begin = -1; std::streamoff end = -1; }; using exclusive_lock = boost::interprocess::scoped_lock<LockFile>; using shared_lock = boost::interprocess::sharable_lock<LockFile>; std::string filename; LockFile lock_file; boost::optional<DbRecord> FindRecordUnsafe(const std::string& key, RecordPositions* pos); bool FlushUnsafe(const DbRecord& record, const RecordPositions* pos); bool StoreRecordUnsafe(const DbRecord& record); bool UpdateRecordUnsafe(DbRecord& record); bool RemoveRecordUnsafe(const std::string& key); template <class T> inline boost::optional<DbRecord> FindRecordUnsafe(const T& problem_config) { std::string key = DbRecord::Serialize(problem_config); return FindRecordUnsafe(key, nullptr); } }; class MultiFileDb { public: MultiFileDb(const std::string& installed_path, const std::string& user_path) : _installed(installed_path) , _user(user_path) {} boost::optional<DbRecord> FindRecord(const std::string& key) { auto users = _user.FindRecord(key); if (users) return users; return _installed.FindRecord(key); } template <class T> boost::optional<DbRecord> FindRecord(const T& problem_config) { auto users = _user.FindRecord(problem_config); if (users) return users; return _installed.FindRecord(problem_config); } bool StoreRecord(const DbRecord& record) { return _user.StoreRecord(record); } bool UpdateRecord(DbRecord& record) { return _user.UpdateRecord(record); } bool RemoveRecord(const std::string& key) { return _user.RemoveRecord(key); } template <class T> bool RemoveRecord(const T& problem_config) { return _user.RemoveRecord(problem_config); } template <class T, class V> boost::optional<DbRecord> Update(const T& problem_config, const std::string& id, const V& values) { return _user.Update(problem_config, id, values); } template <class T, class V> bool Load(const T& problem_config, const std::string& id, V& values) { if (_user.Load(problem_config, id, values)) return true; return _installed.Load(problem_config, id, values); } template <class T> bool Remove(const T& problem_config, const std::string& id) { return _user.Remove(problem_config, id); } private: Db _installed, _user; }; } // namespace miopen #endif // GUARD_MIOPEN_DB_HPP_ <commit_msg>Fixed minor bug.<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef GUARD_MIOPEN_DB_HPP_ #define GUARD_MIOPEN_DB_HPP_ #include <string> #include <ios> #include <boost/interprocess/sync/scoped_lock.hpp> #include <boost/interprocess/sync/sharable_lock.hpp> #include <boost/optional.hpp> #include <miopen/db_record.hpp> #include <miopen/lock_file.hpp> namespace miopen { /// No instance of this class should be used from several threads at the same time. class Db { public: inline Db(const std::string& filename_) : filename(filename_), lock_file(LockFileDispatcher::Get((filename_ + ".lock").c_str())) { } /// Searches db for provided key and returns found record or none if key not found in database inline boost::optional<DbRecord> FindRecord(const std::string& key) { shared_lock lock(lock_file); return FindRecordUnsafe(key, nullptr); } template <class T> inline boost::optional<DbRecord> FindRecord(const T& problem_config) { shared_lock lock(lock_file); return FindRecordUnsafe(problem_config); } /// Stores provided record in database. If record with same key is already in database it is /// replaced by provided record. /// /// Returns true if store was successful, false otherwise. inline bool StoreRecord(const DbRecord& record) { exclusive_lock lock(lock_file); return StoreRecordUnsafe(record); } /// Stores provided record in database. If record with same key is already in database it is /// updated with values from provided record. Provided records data is also updated via /// DbRecord::Merge(). /// /// Returns true if update was successful, false otherwise. inline bool UpdateRecord(DbRecord& record) { exclusive_lock lock(lock_file); return UpdateRecordUnsafe(record); } /// Removes record with provided key from db /// /// Returns true if remove was successful, false otherwise. inline bool RemoveRecord(const std::string& key) { exclusive_lock lock(lock_file); return RemoveRecordUnsafe(key); } template <class T> inline bool RemoveRecord(const T& problem_config) { auto key = DbRecord::Serialize(problem_config); return RemoveRecord(key); } /// Updates record under key PROBLEM_CONFIG with data ID:VALUES in database. /// Both T and V classes should have "void Serialize(std::ostream&) const" member function /// available. /// /// Returns updated record or none if update was unsuccessful. template <class T, class V> inline boost::optional<DbRecord> Update(const T& problem_config, const std::string& id, const V& values) { DbRecord record(problem_config); record.SetValues(id, values); bool ok = UpdateRecord(record); if(ok) return record; else return boost::none; } /// Searches for record with key PROBLEM_CONFIG and gets VALUES under the ID from it. /// Class T should have "void Serialize(std::ostream&) const" member function available. /// Class V shall have "bool Deserialize(const std::string& str)" member function available. /// /// Returns false if there is none PROBLEM_CONFIG=ID:VALUES in the database /// or in case of any error, e.g. if VALUES cannot be deserialized due to incorrect format. template <class T, class V> inline bool Load(const T& problem_config, const std::string& id, V& values) { auto record = FindRecord(problem_config); if(!record) return false; return record->GetValues(id, values); } /// Removes ID with associated VALUES from record with key PROBLEM_CONFIG from db. /// If payload of a record becomes empty after that, also removes the entire record /// /// Returns true if remove was successful. Returns false if this PROBLEM_CONFIG or ID was not /// found. template <class T> inline bool Remove(const T& problem_config, const std::string& id) { exclusive_lock lock(lock_file); auto record = FindRecordUnsafe(problem_config); if(!record) return false; bool erased = record->EraseValues(id); if(!erased) return false; return StoreRecordUnsafe(*record); } private: struct RecordPositions { std::streamoff begin = -1; std::streamoff end = -1; }; using exclusive_lock = boost::interprocess::scoped_lock<LockFile>; using shared_lock = boost::interprocess::sharable_lock<LockFile>; std::string filename; LockFile lock_file; boost::optional<DbRecord> FindRecordUnsafe(const std::string& key, RecordPositions* pos); bool FlushUnsafe(const DbRecord& record, const RecordPositions* pos); bool StoreRecordUnsafe(const DbRecord& record); bool UpdateRecordUnsafe(DbRecord& record); bool RemoveRecordUnsafe(const std::string& key); template <class T> inline boost::optional<DbRecord> FindRecordUnsafe(const T& problem_config) { std::string key = DbRecord::Serialize(problem_config); return FindRecordUnsafe(key, nullptr); } }; class MultiFileDb { public: MultiFileDb(const std::string& installed_path, const std::string& user_path) : _installed(installed_path) , _user(user_path) {} boost::optional<DbRecord> FindRecord(const std::string& key) { auto users = _user.FindRecord(key); auto installed = _installed.FindRecord(key); if (users && installed) { users->Merge(installed); return users; } if (users) return users; return installed; } template <class T> boost::optional<DbRecord> FindRecord(const T& problem_config) { auto users = _user.FindRecord(problem_config); auto installed = _installed.FindRecord(problem_config); if (users && installed) { users->Merge(installed); return users; } if (users) return users; return installed; } bool StoreRecord(const DbRecord& record) { return _user.StoreRecord(record); } bool UpdateRecord(DbRecord& record) { return _user.UpdateRecord(record); } bool RemoveRecord(const std::string& key) { return _user.RemoveRecord(key); } template <class T> bool RemoveRecord(const T& problem_config) { return _user.RemoveRecord(problem_config); } template <class T, class V> boost::optional<DbRecord> Update(const T& problem_config, const std::string& id, const V& values) { return _user.Update(problem_config, id, values); } template <class T, class V> bool Load(const T& problem_config, const std::string& id, V& values) { if (_user.Load(problem_config, id, values)) return true; return _installed.Load(problem_config, id, values); } template <class T> bool Remove(const T& problem_config, const std::string& id) { return _user.Remove(problem_config, id); } private: Db _installed, _user; }; } // namespace miopen #endif // GUARD_MIOPEN_DB_HPP_ <|endoftext|>
<commit_before> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(EPlatformWindowType eType, bool bCreateContext) { m_eType = eType; m_pContainer = new ImwContainer(this); m_pContext = NULL; m_pPreviousContext = NULL; m_bNeedRender = false; m_bShowContent = true; if ( bCreateContext ) { ImGuiContext* pGlobalContext = ImGui::GetCurrentContext(); IM_ASSERT(pGlobalContext != NULL); m_pContext = ImGui::CreateContext( pGlobalContext->IO.MemAllocFn, pGlobalContext->IO.MemFreeFn ); ImGuiIO& oGlobalIO = pGlobalContext->IO; ImGuiIO& oNewIO = m_pContext->IO; memcpy(&(oNewIO.KeyMap), &(oGlobalIO.KeyMap ), sizeof( pGlobalContext->IO.KeyMap )); oNewIO.RenderDrawListsFn = NULL; oNewIO.GetClipboardTextFn = oGlobalIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oGlobalIO.SetClipboardTextFn; oNewIO.ImeSetInputScreenPosFn = oGlobalIO.ImeSetInputScreenPosFn; oNewIO.IniFilename = NULL; } } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); if (m_pContext != NULL) { m_pContext->IO.Fonts = NULL; SetContext(false); ImGui::Shutdown(); RestoreContext(false); ImGui::DestroyContext(m_pContext); m_pContext = NULL; } } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } EPlatformWindowType ImwPlatformWindow::GetType() const { return m_eType; } bool ImwPlatformWindow::IsMainWindow() const { return m_eType == E_PLATFORM_WINDOW_TYPE_MAIN; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } ImVec2 ImwPlatformWindow::GetNormalPosition() const { return GetPosition(); } ImVec2 ImwPlatformWindow::GetNormalSize() const { return GetSize(); } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } bool ImwPlatformWindow::IsWindowMinimized() const { return false; } void ImwPlatformWindow::Show(bool /*bShow*/) { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetWindowMinimized() { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::PreRender() { } void ImwPlatformWindow::OnOverlay() { } void ImwPlatformWindow::RenderDrawLists(ImDrawData* /*pDrawData */) { } void ImwPlatformWindow::Render() { if( m_bNeedRender ) { m_bNeedRender = false; SetContext(false); ImGui::GetIO().DisplaySize = GetSize(); PreRender(); ImGui::Render(); RenderDrawLists(ImGui::GetDrawData()); RestoreContext(false); } } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } void ImwPlatformWindow::OnDropFiles(int iCount, char** pFiles, const ImVec2& oPos) { ImwWindow* pWindow = GetWindowAtPos(oPos); IM_ASSERT(pWindow != NULL); if (pWindow != NULL) { pWindow->OnDropFiles(iCount, pFiles, oPos); } } bool ImwPlatformWindow::Save(JsonValue& oJson) { ImVec2 oSize = GetNormalSize(); ImVec2 oPos = GetNormalPosition(); oJson["Width"] = (long)oSize.x; oJson["Height"] = (long)oSize.y; oJson["Left"] = (long)oPos.x; oJson["Top"] = (long)oPos.y; oJson["Mode"] = (long)(IsWindowMaximized() ? 1 : (IsWindowMinimized() ? -1 : 0)); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || (!oJson["Mode"].IsNumeric() && !oJson["Maximized"].IsBoolean())) return false; if (!bJustCheck) { SetSize((long)oJson["Width"], (long)oJson["Height"]); SetPosition((long)oJson["Left"], (long)oJson["Top"]); if (oJson["Mode"].IsNumeric()) { long iMode = (long)oJson["Mode"]; if (iMode < 0) { SetWindowMinimized(); } else { SetWindowMaximized(iMode > 0); } } else if (oJson["Maximized"].IsBoolean()) { SetWindowMaximized(oJson["Maximized"]); } } return m_pContainer->Load(oJson["Container"], bJustCheck); } static bool s_bContextPushed = false; bool ImwPlatformWindow::IsContextSet() { return s_bContextPushed; } bool ImwPlatformWindow::HasContext() const { return m_pContext != NULL; } ImGuiContext* ImwPlatformWindow::GetContext() { return m_pContext; } void ImwPlatformWindow::SetContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == false); s_bContextPushed = true; if (m_pContext != NULL) { IM_ASSERT( m_pPreviousContext == NULL ); m_pPreviousContext = ImGui::GetCurrentContext(); ImGui::SetCurrentContext(m_pContext); if (bCopyStyle) { //Copy style from Global context memcpy(&(m_pContext->Style), &(m_pPreviousContext->Style), sizeof(ImGuiStyle)); } } } void ImwPlatformWindow::RestoreContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == true); s_bContextPushed = false; if (m_pContext != NULL) { IM_ASSERT(m_pPreviousContext != NULL); if (bCopyStyle) { //Copy style to Global context memcpy(&(m_pPreviousContext->Style), &(m_pContext->Style), sizeof(ImGuiStyle)); } ImGui::SetCurrentContext(m_pPreviousContext); m_pPreviousContext = NULL; } } void ImwPlatformWindow::OnLoseFocus() { if (NULL != m_pContext) { m_pContext->SetNextWindowPosCond = m_pContext->SetNextWindowSizeCond = m_pContext->SetNextWindowContentSizeCond = m_pContext->SetNextWindowCollapsedCond = m_pContext->SetNextWindowFocus = 0; m_pContext->ActiveId = 0; for (int i = 0; i < 512; ++i) m_pContext->IO.KeysDown[i] = false; for (int i = 0; i < 5; ++i) m_pContext->IO.MouseDown[i] = false; m_pContext->IO.KeyAlt = false; m_pContext->IO.KeyCtrl = false; m_pContext->IO.KeyShift = false; } } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwWindow* ImwPlatformWindow::GetWindowAtPos(const ImVec2& oPos) const { return m_pContainer->GetWindowAtPos(oPos); } const ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::RefreshTitle() { const ImwChar* pMainTitle = ImwWindowManager::GetInstance()->GetMainTitle(); ImwWindow* pActiveWindow = m_pContainer->GetActiveWindow(); const ImwChar* pActiveWindowTitle = NULL; if (pActiveWindow != NULL) { pActiveWindowTitle = pActiveWindow->GetTitle(); } const size_t c_iMaxTitleLen = 512; ImwChar pTitle[c_iMaxTitleLen + 1]; size_t iCurrentIndex = 0; if (pMainTitle != NULL) { size_t iLen = strlen(pMainTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pMainTitle, iLen); iCurrentIndex += iLen; } } if (pActiveWindowTitle != NULL) { if (iCurrentIndex != 0) { const char* const c_pSeparator = " - "; size_t iLen = strlen(c_pSeparator); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, c_pSeparator, iLen); iCurrentIndex += iLen; } } size_t iLen = strlen(pActiveWindowTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pActiveWindowTitle, iLen); iCurrentIndex += iLen; } } pTitle[iCurrentIndex] = 0; SetTitle(pTitle); } //SFF_END }<commit_msg>GetContext() will always return something<commit_after> #include "ImwPlatformWindow.h" #include "ImwWindowManager.h" namespace ImWindow { //SFF_BEGIN ImwPlatformWindow::ImwPlatformWindow(EPlatformWindowType eType, bool bCreateContext) { m_eType = eType; m_pContainer = new ImwContainer(this); m_pContext = NULL; m_pPreviousContext = NULL; m_bNeedRender = false; m_bShowContent = true; if ( bCreateContext ) { ImGuiContext* pGlobalContext = ImGui::GetCurrentContext(); IM_ASSERT(pGlobalContext != NULL); m_pContext = ImGui::CreateContext( pGlobalContext->IO.MemAllocFn, pGlobalContext->IO.MemFreeFn ); ImGuiIO& oGlobalIO = pGlobalContext->IO; ImGuiIO& oNewIO = m_pContext->IO; memcpy(&(oNewIO.KeyMap), &(oGlobalIO.KeyMap ), sizeof( pGlobalContext->IO.KeyMap )); oNewIO.RenderDrawListsFn = NULL; oNewIO.GetClipboardTextFn = oGlobalIO.GetClipboardTextFn; oNewIO.SetClipboardTextFn = oGlobalIO.SetClipboardTextFn; oNewIO.ImeSetInputScreenPosFn = oGlobalIO.ImeSetInputScreenPosFn; oNewIO.IniFilename = NULL; } } ImwPlatformWindow::~ImwPlatformWindow() { ImwSafeDelete(m_pContainer); if (m_pContext != NULL) { m_pContext->IO.Fonts = NULL; SetContext(false); ImGui::Shutdown(); RestoreContext(false); ImGui::DestroyContext(m_pContext); m_pContext = NULL; } } bool ImwPlatformWindow::Init(ImwPlatformWindow* /*pParent*/) { return true; } EPlatformWindowType ImwPlatformWindow::GetType() const { return m_eType; } bool ImwPlatformWindow::IsMainWindow() const { return m_eType == E_PLATFORM_WINDOW_TYPE_MAIN; } const ImVec2 c_oVec2_0 = ImVec2(0,0); ImVec2 ImwPlatformWindow::GetPosition() const { return c_oVec2_0; } ImVec2 ImwPlatformWindow::GetSize() const { return ImGui::GetIO().DisplaySize; } ImVec2 ImwPlatformWindow::GetNormalPosition() const { return GetPosition(); } ImVec2 ImwPlatformWindow::GetNormalSize() const { return GetSize(); } bool ImwPlatformWindow::IsWindowMaximized() const { return false; } bool ImwPlatformWindow::IsWindowMinimized() const { return false; } void ImwPlatformWindow::Show(bool /*bShow*/) { } void ImwPlatformWindow::SetSize(int /*iWidth*/, int /*iHeight*/) { } void ImwPlatformWindow::SetPosition(int /*iX*/, int /*iY*/) { } void ImwPlatformWindow::SetWindowMaximized(bool /*bMaximized*/) { } void ImwPlatformWindow::SetWindowMinimized() { } void ImwPlatformWindow::SetTitle(const char* /*pTtile*/) { } bool ImwPlatformWindow::IsShowContent() const { return m_bShowContent; } void ImwPlatformWindow::SetShowContent(bool bShow) { m_bShowContent = bShow; } void ImwPlatformWindow::PreUpdate() { } void ImwPlatformWindow::PreRender() { } void ImwPlatformWindow::OnOverlay() { } void ImwPlatformWindow::RenderDrawLists(ImDrawData* /*pDrawData */) { } void ImwPlatformWindow::Render() { if( m_bNeedRender ) { m_bNeedRender = false; SetContext(false); ImGui::GetIO().DisplaySize = GetSize(); PreRender(); ImGui::Render(); RenderDrawLists(ImGui::GetDrawData()); RestoreContext(false); } } void ImwPlatformWindow::PaintContainer() { m_pContainer->Paint(); } void ImwPlatformWindow::OnClose() { ImwWindowManager::GetInstance()->OnClosePlatformWindow(this); } void ImwPlatformWindow::OnDropFiles(int iCount, char** pFiles, const ImVec2& oPos) { ImwWindow* pWindow = GetWindowAtPos(oPos); IM_ASSERT(pWindow != NULL); if (pWindow != NULL) { pWindow->OnDropFiles(iCount, pFiles, oPos); } } bool ImwPlatformWindow::Save(JsonValue& oJson) { ImVec2 oSize = GetNormalSize(); ImVec2 oPos = GetNormalPosition(); oJson["Width"] = (long)oSize.x; oJson["Height"] = (long)oSize.y; oJson["Left"] = (long)oPos.x; oJson["Top"] = (long)oPos.y; oJson["Mode"] = (long)(IsWindowMaximized() ? 1 : (IsWindowMinimized() ? -1 : 0)); return m_pContainer->Save(oJson["Container"]); } bool ImwPlatformWindow::Load(const JsonValue& oJson, bool bJustCheck) { if (!oJson["Width"].IsNumeric() || !oJson["Height"].IsNumeric() || !oJson["Left"].IsNumeric() || !oJson["Top"].IsNumeric() || (!oJson["Mode"].IsNumeric() && !oJson["Maximized"].IsBoolean())) return false; if (!bJustCheck) { SetSize((long)oJson["Width"], (long)oJson["Height"]); SetPosition((long)oJson["Left"], (long)oJson["Top"]); if (oJson["Mode"].IsNumeric()) { long iMode = (long)oJson["Mode"]; if (iMode < 0) { SetWindowMinimized(); } else { SetWindowMaximized(iMode > 0); } } else if (oJson["Maximized"].IsBoolean()) { SetWindowMaximized(oJson["Maximized"]); } } return m_pContainer->Load(oJson["Container"], bJustCheck); } static bool s_bContextPushed = false; bool ImwPlatformWindow::IsContextSet() { return s_bContextPushed; } bool ImwPlatformWindow::HasContext() const { return m_pContext != NULL; } ImGuiContext* ImwPlatformWindow::GetContext() { if (m_pContext != NULL) return m_pContext; return ImGui::GetCurrentContext(); } void ImwPlatformWindow::SetContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == false); s_bContextPushed = true; if (m_pContext != NULL) { IM_ASSERT( m_pPreviousContext == NULL ); m_pPreviousContext = ImGui::GetCurrentContext(); ImGui::SetCurrentContext(m_pContext); if (bCopyStyle) { //Copy style from Global context memcpy(&(m_pContext->Style), &(m_pPreviousContext->Style), sizeof(ImGuiStyle)); } } } void ImwPlatformWindow::RestoreContext(bool bCopyStyle) { IM_ASSERT(s_bContextPushed == true); s_bContextPushed = false; if (m_pContext != NULL) { IM_ASSERT(m_pPreviousContext != NULL); if (bCopyStyle) { //Copy style to Global context memcpy(&(m_pPreviousContext->Style), &(m_pContext->Style), sizeof(ImGuiStyle)); } ImGui::SetCurrentContext(m_pPreviousContext); m_pPreviousContext = NULL; } } void ImwPlatformWindow::OnLoseFocus() { if (NULL != m_pContext) { m_pContext->SetNextWindowPosCond = m_pContext->SetNextWindowSizeCond = m_pContext->SetNextWindowContentSizeCond = m_pContext->SetNextWindowCollapsedCond = m_pContext->SetNextWindowFocus = 0; m_pContext->ActiveId = 0; for (int i = 0; i < 512; ++i) m_pContext->IO.KeysDown[i] = false; for (int i = 0; i < 5; ++i) m_pContext->IO.MouseDown[i] = false; m_pContext->IO.KeyAlt = false; m_pContext->IO.KeyCtrl = false; m_pContext->IO.KeyShift = false; } } void ImwPlatformWindow::Dock(ImwWindow* pWindow) { m_pContainer->Dock(pWindow); } bool ImwPlatformWindow::UnDock(ImwWindow* pWindow) { return m_pContainer->UnDock(pWindow); } ImwContainer* ImwPlatformWindow::GetContainer() { return m_pContainer; } ImwWindow* ImwPlatformWindow::GetWindowAtPos(const ImVec2& oPos) const { return m_pContainer->GetWindowAtPos(oPos); } const ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow) { return m_pContainer->HasWindow(pWindow); } bool ImwPlatformWindow::FocusWindow(ImwWindow* pWindow) { return m_pContainer->FocusWindow(pWindow); } void ImwPlatformWindow::RefreshTitle() { const ImwChar* pMainTitle = ImwWindowManager::GetInstance()->GetMainTitle(); ImwWindow* pActiveWindow = m_pContainer->GetActiveWindow(); const ImwChar* pActiveWindowTitle = NULL; if (pActiveWindow != NULL) { pActiveWindowTitle = pActiveWindow->GetTitle(); } const size_t c_iMaxTitleLen = 512; ImwChar pTitle[c_iMaxTitleLen + 1]; size_t iCurrentIndex = 0; if (pMainTitle != NULL) { size_t iLen = strlen(pMainTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pMainTitle, iLen); iCurrentIndex += iLen; } } if (pActiveWindowTitle != NULL) { if (iCurrentIndex != 0) { const char* const c_pSeparator = " - "; size_t iLen = strlen(c_pSeparator); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, c_pSeparator, iLen); iCurrentIndex += iLen; } } size_t iLen = strlen(pActiveWindowTitle); if (iLen > (c_iMaxTitleLen - iCurrentIndex)) iLen = c_iMaxTitleLen - iCurrentIndex; if (iLen > 0) { memcpy(pTitle + iCurrentIndex, pActiveWindowTitle, iLen); iCurrentIndex += iLen; } } pTitle[iCurrentIndex] = 0; SetTitle(pTitle); } //SFF_END }<|endoftext|>
<commit_before>// Difference from running average. #include <vector> #include <sstream> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <opencv2/opencv.hpp> #include "RateTicker.hpp" #include "Config.hpp" #include "util.hpp" int main(int argc, char** argv) { // Parse command-line arguments. int DEVICE, WIDTH, HEIGHT, DURATION; std::istringstream(std::string(argv[1])) >> DEVICE; std::istringstream(std::string(argv[2])) >> WIDTH; std::istringstream(std::string(argv[3])) >> HEIGHT; std::istringstream(std::string(argv[4])) >> DURATION; // Create the OpenCV video capture object. cv::VideoCapture cap(DEVICE); cap.set(3, WIDTH); cap.set(4, HEIGHT); // Create the output window. const char* title = "detect 1"; cv::namedWindow(title, CV_WINDOW_NORMAL); // Initialize the classifiers and their respective colors. Config config ("conf/classifiers.conf"); std::vector< cv::CascadeClassifier* > classifiers; std::vector< cv::Scalar > colors; for(auto fname : config.keys()) { boost::filesystem::path file(fname + ".xml"); for(auto dname : { "/usr/share/OpenCV/haarcascades", "/usr/share/OpenCV/lbpcascades" } ) { boost::filesystem::path dir(dname); boost::filesystem::path full = dir / file; auto cfer = new cv::CascadeClassifier(full.string()); if( cfer->empty() ) continue; classifiers.push_back(cfer); int rr, gg, bb; std::stringstream(config[fname]) >> rr >> gg >> bb; colors.push_back(cv::Scalar(rr, gg, bb)); } } // Keep track of previous iteration's timestamp. boost::posix_time::ptime tstamp_prev; // Monitor framerates for the given seconds past. std::vector<float> periods = { 1, 5, 10 }; RateTicker framerate (periods); // Run the loop for designated amount of time. auto now = boost::posix_time::microsec_clock::universal_time(); auto dur = boost::posix_time::seconds(DURATION); auto end = now + dur; while (end > boost::posix_time::microsec_clock::universal_time()) { // Take a snapshot. cv::Mat frame; cap >> frame; // Collect a list of positive detection rectangles. struct RectColor{ cv::Rect rect; cv::Scalar color; }; std::vector<RectColor> results; for(auto ii=0; ii!= classifiers.size(); ++ii){ std::vector<cv::Rect> rects; classifiers[ii]->detectMultiScale( frame, rects, 1.3, // scale factor. 3, // min neighbors. 0, // flags. {frame.size().width/20, frame.size().height/20}, // min size. {frame.size().width/2, frame.size().height/2} // max size. ); for(auto jj=rects.begin(); jj!= rects.end(); ++jj){ results.push_back({ *jj, colors[ii] }); } } // Draw the rectangles. for(auto ii=results.begin(); ii!=results.end(); ++ii){ auto rect = ii->rect; auto color = ii->color; cv::rectangle( frame, cv::Point(rect.x, rect.y), cv::Point(rect.x + rect.width, rect.y + rect.height), color, 2 // thickness. ); } // Display the snapshot. cv::imshow(title, frame); cv::waitKey(1); } } <commit_msg>Add framerate display.<commit_after>// Difference from running average. #include <vector> #include <sstream> #include <boost/date_time.hpp> #include <boost/filesystem.hpp> #include <opencv2/opencv.hpp> #include "RateTicker.hpp" #include "Config.hpp" #include "util.hpp" int main(int argc, char** argv) { // Parse command-line arguments. int DEVICE, WIDTH, HEIGHT, DURATION; std::istringstream(std::string(argv[1])) >> DEVICE; std::istringstream(std::string(argv[2])) >> WIDTH; std::istringstream(std::string(argv[3])) >> HEIGHT; std::istringstream(std::string(argv[4])) >> DURATION; // Create the OpenCV video capture object. cv::VideoCapture cap(DEVICE); cap.set(3, WIDTH); cap.set(4, HEIGHT); // Create the output window. const char* title = "detect 1"; cv::namedWindow(title, CV_WINDOW_NORMAL); // Initialize the classifiers and their respective colors. Config config ("conf/classifiers.conf"); std::vector< cv::CascadeClassifier* > classifiers; std::vector< cv::Scalar > colors; for(auto fname : config.keys()) { boost::filesystem::path file(fname + ".xml"); for(auto dname : { "/usr/share/OpenCV/haarcascades", "/usr/share/OpenCV/lbpcascades" } ) { boost::filesystem::path dir(dname); boost::filesystem::path full = dir / file; auto cfer = new cv::CascadeClassifier(full.string()); if( cfer->empty() ) continue; classifiers.push_back(cfer); int rr, gg, bb; std::stringstream(config[fname]) >> rr >> gg >> bb; colors.push_back(cv::Scalar(rr, gg, bb)); } } // Monitor framerates for the given seconds past. RateTicker framerate ({ 1, 5, 10 }); // Run the loop for designated amount of time. auto now = boost::posix_time::microsec_clock::universal_time(); auto dur = boost::posix_time::seconds(DURATION); auto end = now + dur; while (end > boost::posix_time::microsec_clock::universal_time()) { // Take a snapshot. cv::Mat frame; cap >> frame; // Collect a list of positive detection rectangles. struct RectColor{ cv::Rect rect; cv::Scalar color; }; std::vector<RectColor> results; for(auto ii=0; ii!= classifiers.size(); ++ii){ std::vector<cv::Rect> rects; classifiers[ii]->detectMultiScale( frame, rects, 1.3, // scale factor. 3, // min neighbors. 0, // flags. {frame.size().width/20, frame.size().height/20}, // min size. {frame.size().width/2, frame.size().height/2} // max size. ); for(auto jj=rects.begin(); jj!= rects.end(); ++jj){ results.push_back({ *jj, colors[ii] }); } } // Draw the rectangles. for(auto ii=results.begin(); ii!=results.end(); ++ii){ auto rect = ii->rect; auto color = ii->color; cv::rectangle( frame, cv::Point(rect.x, rect.y), cv::Point(rect.x + rect.width, rect.y + rect.height), color, 2 // thickness. ); } // Write the display framerate on top of the image. auto fps = framerate.tick(); std::ostringstream line; line << std::fixed << std::setprecision(2); line << fps[0] << ", " << fps[1] << ", " << fps[2]; std::list<std::string> lines; lines.push_back(line.str()); sherlock::writeOSD(frame, lines, 0.04); // Display the snapshot. cv::imshow(title, frame); cv::waitKey(1); } } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "googleurl/src/gurl.h" namespace { typedef InProcessBrowserTest PrintPreviewTabControllerBrowserTest; // Test to verify that when a preview tab navigates, we can create a new print // preview tab for both initiator tab and new preview tab contents. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, NavigateFromPrintPreviewTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); GURL url(chrome::kAboutBlankURL); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(url, preview_tab->tab_contents()->GetURL()); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New preview tab is created. EXPECT_EQ(3, browser()->tab_count()); EXPECT_NE(new_preview_tab, preview_tab); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Newest preview tab is created and the previously created preview tab is not // merely activated. EXPECT_EQ(4, browser()->tab_count()); EXPECT_NE(newest_preview_tab, new_preview_tab); } // Test to verify that when a initiator tab navigates, we can create a new // preview tab for the new tab contents. But we cannot create a preview tab for // the old preview tab. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, NavigateFromInitiatorTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); // Activate initiator tab. browser()->ActivateTabAt(0, true); GURL url(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), url); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New preview tab is created. EXPECT_EQ(3, browser()->tab_count()); EXPECT_NE(new_preview_tab, preview_tab); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Make sure preview tab is not created for |preview_tab|. EXPECT_EQ(3, browser()->tab_count()); EXPECT_EQ(newest_preview_tab, preview_tab); } // Test to verify that even after reloading initiator tab and preview tab, // their association exists. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, ReloadInitiatorTabAndPreviewTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); // Activate initiator tab and reload. browser()->ActivateTabAt(0, true); browser()->Reload(CURRENT_TAB); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // Old preview tab is activated. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(new_preview_tab, preview_tab); // Reload preview tab. browser()->Reload(CURRENT_TAB); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Make sure new preview tab is not created for |preview_tab|. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(newest_preview_tab, preview_tab); } // Test that print preview tabs are placed correctly. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, OpenPreviewTabInCorrectPosition) { const int kTabCount = 4; // Create kTabCount - 1 tabs since we start with 1 tab already. for (int i = 0; i < kTabCount - 1; ++i) { browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_FOREGROUND_TAB; browser::Navigate(&p); } EXPECT_EQ(kTabCount, browser()->tab_count()); // Create a print preview tab. scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); const int kInitiatorTabIndex = 1; TabContentsWrapper* initiator_tab = browser()->GetTabContentsWrapperAt(kInitiatorTabIndex); ASSERT_TRUE(initiator_tab); TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_TRUE(preview_tab); // Check the preview tab's location. EXPECT_EQ(preview_tab, browser()->GetTabContentsWrapperAt(kInitiatorTabIndex + 1)); EXPECT_EQ(preview_tab, browser()->GetSelectedTabContentsWrapper()); } // Test that print preview tabs created by pop-up windows are placed correctly. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, OpenPreviewTabFromPopupInCorrectPosition) { const int kTabCount = 4; // Create kTabCount - 1 tabs since we start with 1 tab already. for (int i = 0; i < kTabCount - 1; ++i) { browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_FOREGROUND_TAB; browser::Navigate(&p); } EXPECT_EQ(kTabCount, browser()->tab_count()); // Create a popup browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_POPUP; ui_test_utils::NavigateToURL(&p); #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Navigate() should have opened a new tab on CrOS. EXPECT_EQ(browser(), p.browser); EXPECT_EQ(Browser::TYPE_TABBED, p.browser->type()); #else // Navigate() should have opened a new popup window. EXPECT_NE(browser(), p.browser); EXPECT_EQ(Browser::TYPE_POPUP, p.browser->type()); #endif ASSERT_TRUE(p.target_contents); // Create a print preview tab. scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(p.target_contents); EXPECT_TRUE(preview_tab); int tab_position = kTabCount; #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Increment position since CrOS opened a new tab instead of a popup. tab_position++; #endif // Check the preview tab's location. EXPECT_EQ(preview_tab, browser()->GetTabContentsWrapperAt(tab_position)); EXPECT_EQ(preview_tab, browser()->GetSelectedTabContentsWrapper()); } } // namespace <commit_msg>Fix OpenPreviewTabFromPopupInCorrectPosition test on Linux Views.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_preview_tab_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/browser/tab_contents/tab_contents.h" #include "googleurl/src/gurl.h" namespace { typedef InProcessBrowserTest PrintPreviewTabControllerBrowserTest; // Test to verify that when a preview tab navigates, we can create a new print // preview tab for both initiator tab and new preview tab contents. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, NavigateFromPrintPreviewTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); GURL url(chrome::kAboutBlankURL); ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(url, preview_tab->tab_contents()->GetURL()); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New preview tab is created. EXPECT_EQ(3, browser()->tab_count()); EXPECT_NE(new_preview_tab, preview_tab); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Newest preview tab is created and the previously created preview tab is not // merely activated. EXPECT_EQ(4, browser()->tab_count()); EXPECT_NE(newest_preview_tab, new_preview_tab); } // Test to verify that when a initiator tab navigates, we can create a new // preview tab for the new tab contents. But we cannot create a preview tab for // the old preview tab. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, NavigateFromInitiatorTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); // Activate initiator tab. browser()->ActivateTabAt(0, true); GURL url(chrome::kChromeUINewTabURL); ui_test_utils::NavigateToURL(browser(), url); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New preview tab is created. EXPECT_EQ(3, browser()->tab_count()); EXPECT_NE(new_preview_tab, preview_tab); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Make sure preview tab is not created for |preview_tab|. EXPECT_EQ(3, browser()->tab_count()); EXPECT_EQ(newest_preview_tab, preview_tab); } // Test to verify that even after reloading initiator tab and preview tab, // their association exists. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, ReloadInitiatorTabAndPreviewTab) { ASSERT_TRUE(browser()); BrowserList::SetLastActive(browser()); ASSERT_TRUE(BrowserList::GetLastActive()); // Lets start with one window with one tab. EXPECT_EQ(1u, BrowserList::size()); EXPECT_EQ(1, browser()->tab_count()); // Create a reference to initiator tab contents. TabContentsWrapper* initiator_tab = browser()->GetSelectedTabContentsWrapper(); ASSERT_TRUE(initiator_tab); scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); // Get the preview tab for initiator tab. TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // New print preview tab is created. Current focus is on preview tab. EXPECT_EQ(2, browser()->tab_count()); EXPECT_NE(initiator_tab, preview_tab); // Activate initiator tab and reload. browser()->ActivateTabAt(0, true); browser()->Reload(CURRENT_TAB); // Get the print preview tab for initiator tab. TabContentsWrapper* new_preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); // Old preview tab is activated. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(new_preview_tab, preview_tab); // Reload preview tab. browser()->Reload(CURRENT_TAB); // Get the print preview tab for old preview tab. TabContentsWrapper* newest_preview_tab = tab_controller->GetOrCreatePreviewTab(preview_tab); // Make sure new preview tab is not created for |preview_tab|. EXPECT_EQ(2, browser()->tab_count()); EXPECT_EQ(newest_preview_tab, preview_tab); } // Test that print preview tabs are placed correctly. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, OpenPreviewTabInCorrectPosition) { const int kTabCount = 4; // Create kTabCount - 1 tabs since we start with 1 tab already. for (int i = 0; i < kTabCount - 1; ++i) { browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_FOREGROUND_TAB; browser::Navigate(&p); } EXPECT_EQ(kTabCount, browser()->tab_count()); // Create a print preview tab. scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); const int kInitiatorTabIndex = 1; TabContentsWrapper* initiator_tab = browser()->GetTabContentsWrapperAt(kInitiatorTabIndex); ASSERT_TRUE(initiator_tab); TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(initiator_tab); EXPECT_TRUE(preview_tab); // Check the preview tab's location. EXPECT_EQ(preview_tab, browser()->GetTabContentsWrapperAt(kInitiatorTabIndex + 1)); EXPECT_EQ(preview_tab, browser()->GetSelectedTabContentsWrapper()); } // Test that print preview tabs created by pop-up windows are placed correctly. IN_PROC_BROWSER_TEST_F(PrintPreviewTabControllerBrowserTest, OpenPreviewTabFromPopupInCorrectPosition) { const int kTabCount = 4; // Create kTabCount - 1 tabs since we start with 1 tab already. for (int i = 0; i < kTabCount - 1; ++i) { browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_FOREGROUND_TAB; browser::Navigate(&p); } EXPECT_EQ(kTabCount, browser()->tab_count()); // Create a popup browser::NavigateParams p(browser(), GURL(), PageTransition::LINK); p.disposition = NEW_POPUP; ui_test_utils::NavigateToURL(&p); #if defined(OS_CHROMEOS) // Navigate() should have opened a new tab on CrOS. EXPECT_EQ(browser(), p.browser); EXPECT_EQ(Browser::TYPE_TABBED, p.browser->type()); #else // Navigate() should have opened a new popup window. EXPECT_NE(browser(), p.browser); EXPECT_EQ(Browser::TYPE_POPUP, p.browser->type()); #endif ASSERT_TRUE(p.target_contents); // Create a print preview tab. scoped_refptr<printing::PrintPreviewTabController> tab_controller(new printing::PrintPreviewTabController()); ASSERT_TRUE(tab_controller); TabContentsWrapper* preview_tab = tab_controller->GetOrCreatePreviewTab(p.target_contents); EXPECT_TRUE(preview_tab); int tab_position = kTabCount; #if defined(OS_CHROMEOS) // Increment position since CrOS opened a new tab instead of a popup. tab_position++; #endif // Check the preview tab's location. EXPECT_EQ(preview_tab, browser()->GetTabContentsWrapperAt(tab_position)); EXPECT_EQ(preview_tab, browser()->GetSelectedTabContentsWrapper()); } } // namespace <|endoftext|>
<commit_before>#include "df_font.h" #include "df_bitmap.h" #include "df_common.h" #if _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include "df_bmp.h" #endif #include <limits.h> #include <memory.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Global variables // **************************************************************************** DfFont *g_defaultFont = NULL; static int GetPixel(char *tmpBitmap, int bmpWidth, int x, int y) { return tmpBitmap[y * bmpWidth + x]; } struct MemBuf { unsigned char *data; int len; int currentPos; int currentByte; int hiNibbleNext; MemBuf(unsigned *_data, int _len) { data = (unsigned char *)_data; len = _len; currentPos = 0; currentByte = 0; hiNibbleNext = 0; } int ReadByte() { if (currentPos >= len) return 0; currentByte = data[currentPos]; currentPos++; return currentByte; } int ReadNibble() { if (hiNibbleNext) { hiNibbleNext = 0; return currentByte >> 4; } ReadByte(); hiNibbleNext = 1; return currentByte & 0xf; } }; // **************************************************************************** // Public Functions // **************************************************************************** DfFont *LoadFontFromMemory(void *_buf, int bufLen) { MemBuf buf((unsigned int *)_buf, bufLen); DfFont *tr = new DfFont; memset(tr, 0, sizeof(DfFont)); tr->maxCharWidth = buf.ReadByte(); tr->charHeight = buf.ReadByte(); tr->fixedWidth = !buf.ReadByte(); char glyphWidths[224]; if (!tr->fixedWidth) { for (int i = 0; i < 224; i++) glyphWidths[i] = buf.ReadByte(); } else { for (int i = 0; i < 224; i++) glyphWidths[i] = tr->maxCharWidth; } // Decode the RLE data into a bitmap with one char per pixel. int bmpWidth = tr->maxCharWidth * 16; int bmpHeight = tr->charHeight * 14; char *tmpBitmap = new char [bmpWidth * bmpHeight]; { int runVal = 1; int tmpBitmapOffset = 0; while (buf.currentPos < buf.len) { int runLeft = buf.ReadNibble(); if (runLeft == 0) // 0 is the escape token. { runLeft = buf.ReadNibble(); runLeft += buf.ReadNibble() << 4; } runVal = 1 - runVal; DebugAssert((tmpBitmapOffset + runLeft) < bmpWidth * bmpHeight); memset(tmpBitmap + tmpBitmapOffset, runVal, runLeft); tmpBitmapOffset += runLeft; } int pixelsLeft = bmpWidth * bmpHeight - tmpBitmapOffset; DebugAssert(pixelsLeft >= 0); memset(tmpBitmap + tmpBitmapOffset, 0, pixelsLeft); } // Undo "up" prediction for (int y = 1; y < bmpHeight; y++) { for (int x = 0; x < bmpWidth; x++) { char up = tmpBitmap[(y - 1) * bmpWidth + x]; tmpBitmap[y * bmpWidth + x] ^= up; } } // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Run-length encode each ASCII character for (int i = 32; i < 256; i++) { // Read back the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; int bmpY = (i - 32) / 16 * tr->charHeight + y; while (x < tr->maxCharWidth) { // Skip blank pixels int bmpX = i % 16 * tr->maxCharWidth + x; while (GetPixel(tmpBitmap, bmpWidth, bmpX, bmpY) == 0) { x++; if (x >= tr->maxCharWidth) break; bmpX++; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixel(tmpBitmap, bmpWidth, bmpX, bmpY) != 0) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; bmpX++; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphWidths[i - 32]); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; delete [] tmpBitmap; return tr; } DfFont *LoadFontFromFile(char const *filename, int pixHeight) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; char buf[5]; fread(buf, 1, 5, f); if (memcmp(buf, "dfbf\0", 5) != 0) return NULL; unsigned char numFonts = 0; fread(&numFonts, 1, 1, f); unsigned int fileOffsets[257]; fread(fileOffsets, 4, numFonts, f); fseek(f, 0, SEEK_END); fileOffsets[numFonts] = ftell(f); for (unsigned i = 0; i < numFonts; i++) { fseek(f, fileOffsets[i], SEEK_SET); int maxWidth = fgetc(f); int thisPixHeight = fgetc(f); if (thisPixHeight == pixHeight) { fseek(f, fileOffsets[i], SEEK_SET); int fontBinSize = fileOffsets[i + 1] - fileOffsets[i]; char *fontBuf = new char[fontBinSize]; fread(fontBuf, 1, fontBinSize, f); DfFont *fnt = LoadFontFromMemory((unsigned int *)fontBuf, fontBinSize); delete[] fontBuf; return fnt; } } return NULL; } static int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; DfColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < bmp->clipTop || y > bmp->clipBottom) return 0; for (int j = 0; text[j] && j < maxChars; j++) { if (x > bmp->clipRight) break; unsigned char c = text[j]; Glyph *glyph = tr->glyphs[c]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= bmp->clipTop && y3 < bmp->clipBottom) { DfColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= bmp->clipLeft && x3 < bmp->clipRight) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; } return x - _x; } int DrawTextSimpleLen(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; int width = bmp->width; if (x < bmp->clipLeft || y < bmp->clipTop || (y + tr->charHeight) > bmp->clipBottom) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text, maxChars); DfColour *startRow = bmp->pixels + y * bmp->width; for (int j = 0; text[j] && j < maxChars; j++) { unsigned char c = text[j]; if (x + (int)tr->glyphs[c]->m_width > bmp->clipRight) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[c]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; rleBuf++; } x += glyph.m_width; } return x - _x; } int DrawTextSimple(DfFont *f, DfColour col, DfBitmap *bmp, int x, int y, char const *text) { return DrawTextSimpleLen(f, col, bmp, x, y, text, 9999); } int DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(DfFont *tr, char const *text, int len) { len = IntMin((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (int i = 0; i < len; i++) width += tr->glyphs[text[i] & 0xff]->m_width; return width; } } <commit_msg>Fix a warning from GCC.<commit_after>#include "df_font.h" #include "df_bitmap.h" #include "df_common.h" #if _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include "df_bmp.h" #endif #include <limits.h> #include <memory.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> // **************************************************************************** // Glyph // **************************************************************************** typedef struct { unsigned startX; unsigned startY; unsigned runLen; } EncodedRun; class Glyph { public: unsigned m_width; int m_numRuns; EncodedRun *m_pixelRuns; Glyph(int w) { m_width = w; } }; // **************************************************************************** // Global variables // **************************************************************************** DfFont *g_defaultFont = NULL; static int GetPixel(char *tmpBitmap, int bmpWidth, int x, int y) { return tmpBitmap[y * bmpWidth + x]; } struct MemBuf { unsigned char *data; int len; int currentPos; int currentByte; int hiNibbleNext; MemBuf(unsigned *_data, int _len) { data = (unsigned char *)_data; len = _len; currentPos = 0; currentByte = 0; hiNibbleNext = 0; } int ReadByte() { if (currentPos >= len) return 0; currentByte = data[currentPos]; currentPos++; return currentByte; } int ReadNibble() { if (hiNibbleNext) { hiNibbleNext = 0; return currentByte >> 4; } ReadByte(); hiNibbleNext = 1; return currentByte & 0xf; } }; // **************************************************************************** // Public Functions // **************************************************************************** DfFont *LoadFontFromMemory(void *_buf, int bufLen) { MemBuf buf((unsigned int *)_buf, bufLen); DfFont *tr = new DfFont; memset(tr, 0, sizeof(DfFont)); tr->maxCharWidth = buf.ReadByte(); tr->charHeight = buf.ReadByte(); tr->fixedWidth = !buf.ReadByte(); char glyphWidths[224]; if (!tr->fixedWidth) { for (int i = 0; i < 224; i++) glyphWidths[i] = buf.ReadByte(); } else { for (int i = 0; i < 224; i++) glyphWidths[i] = tr->maxCharWidth; } // Decode the RLE data into a bitmap with one char per pixel. int bmpWidth = tr->maxCharWidth * 16; int bmpHeight = tr->charHeight * 14; char *tmpBitmap = new char [bmpWidth * bmpHeight]; { int runVal = 1; int tmpBitmapOffset = 0; while (buf.currentPos < buf.len) { int runLeft = buf.ReadNibble(); if (runLeft == 0) // 0 is the escape token. { runLeft = buf.ReadNibble(); runLeft += buf.ReadNibble() << 4; } runVal = 1 - runVal; DebugAssert((tmpBitmapOffset + runLeft) < bmpWidth * bmpHeight); memset(tmpBitmap + tmpBitmapOffset, runVal, runLeft); tmpBitmapOffset += runLeft; } int pixelsLeft = bmpWidth * bmpHeight - tmpBitmapOffset; DebugAssert(pixelsLeft >= 0); memset(tmpBitmap + tmpBitmapOffset, 0, pixelsLeft); } // Undo "up" prediction for (int y = 1; y < bmpHeight; y++) { for (int x = 0; x < bmpWidth; x++) { char up = tmpBitmap[(y - 1) * bmpWidth + x]; tmpBitmap[y * bmpWidth + x] ^= up; } } // Allocate enough EncodedRuns to store the worst case for a glyph of this size. // Worst case is if the whole glyph is encoded as runs of one pixel. There has // to be a gap of one pixel between each run, so there can only be half as many // runs as there are pixels. unsigned tempRunsSize = tr->charHeight * (tr->maxCharWidth / 2 + 1); EncodedRun *tempRuns = new EncodedRun [tempRunsSize]; // Run-length encode each ASCII character for (int i = 32; i < 256; i++) { // Read back the bitmap and construct a run-length encoding memset(tempRuns, 0, tempRunsSize); EncodedRun *run = tempRuns; for (int y = 0; y < tr->charHeight; y++) { int x = 0; int bmpY = (i - 32) / 16 * tr->charHeight + y; while (x < tr->maxCharWidth) { // Skip blank pixels int bmpX = i % 16 * tr->maxCharWidth + x; while (GetPixel(tmpBitmap, bmpWidth, bmpX, bmpY) == 0) { x++; if (x >= tr->maxCharWidth) break; bmpX++; } // Have we got to the end of the line? if (x >= tr->maxCharWidth) continue; run->startX = x; run->startY = y; run->runLen = 0; // Count non-blank pixels while (GetPixel(tmpBitmap, bmpWidth, bmpX, bmpY) != 0) { x++; run->runLen++; if (x >= tr->maxCharWidth) break; bmpX++; } run++; } } // Create the glyph to store the encoded runs we've made Glyph *glyph = new Glyph(glyphWidths[i - 32]); tr->glyphs[i] = glyph; // Copy the runs into the glyph glyph->m_numRuns = run - tempRuns; glyph->m_pixelRuns = new EncodedRun [glyph->m_numRuns]; memcpy(glyph->m_pixelRuns, tempRuns, glyph->m_numRuns * sizeof(EncodedRun)); } delete [] tempRuns; delete [] tmpBitmap; return tr; } DfFont *LoadFontFromFile(char const *filename, int pixHeight) { FILE *f = fopen(filename, "rb"); if (!f) return NULL; char buf[5]; fread(buf, 1, 5, f); if (memcmp(buf, "dfbf\0", 5) != 0) return NULL; unsigned char numFonts = 0; fread(&numFonts, 1, 1, f); unsigned int fileOffsets[257]; fread(fileOffsets, 4, numFonts, f); fseek(f, 0, SEEK_END); fileOffsets[numFonts] = ftell(f); for (unsigned i = 0; i < numFonts; i++) { fseek(f, fileOffsets[i] + 1, SEEK_SET); // +1 skips the max width field. int thisPixHeight = fgetc(f); if (thisPixHeight == pixHeight) { fseek(f, fileOffsets[i], SEEK_SET); int fontBinSize = fileOffsets[i + 1] - fileOffsets[i]; char *fontBuf = new char[fontBinSize]; fread(fontBuf, 1, fontBinSize, f); DfFont *fnt = LoadFontFromMemory((unsigned int *)fontBuf, fontBinSize); delete[] fontBuf; return fnt; } } return NULL; } static int DrawTextSimpleClipped(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; DfColour *startRow = bmp->pixels + y * bmp->width; int width = bmp->width; if (y + tr->charHeight < bmp->clipTop || y > bmp->clipBottom) return 0; for (int j = 0; text[j] && j < maxChars; j++) { if (x > bmp->clipRight) break; unsigned char c = text[j]; Glyph *glyph = tr->glyphs[c]; EncodedRun *rleBuf = glyph->m_pixelRuns; for (int i = 0; i < glyph->m_numRuns; i++) { int y3 = y + rleBuf->startY; if (y3 >= bmp->clipTop && y3 < bmp->clipBottom) { DfColour *thisRow = startRow + rleBuf->startY * width; for (unsigned i = 0; i < rleBuf->runLen; i++) { int x3 = x + rleBuf->startX + i; if (x3 >= bmp->clipLeft && x3 < bmp->clipRight) thisRow[x3] = col; } } rleBuf++; } x += glyph->m_width; } return x - _x; } int DrawTextSimpleLen(DfFont *tr, DfColour col, DfBitmap *bmp, int _x, int y, char const *text, int maxChars) { int x = _x; int width = bmp->width; if (x < bmp->clipLeft || y < bmp->clipTop || (y + tr->charHeight) > bmp->clipBottom) return DrawTextSimpleClipped(tr, col, bmp, _x, y, text, maxChars); DfColour *startRow = bmp->pixels + y * bmp->width; for (int j = 0; text[j] && j < maxChars; j++) { unsigned char c = text[j]; if (x + (int)tr->glyphs[c]->m_width > bmp->clipRight) break; // Copy the glyph onto the stack for better cache performance. This increased the // performance from 13.8 to 14.4 million chars per second. Madness. Glyph glyph = *tr->glyphs[c]; EncodedRun *rleBuf = glyph.m_pixelRuns; for (int i = 0; i < glyph.m_numRuns; i++) { DfColour *startPixel = startRow + rleBuf->startY * width + rleBuf->startX + x; for (unsigned i = 0; i < rleBuf->runLen; i++) startPixel[i] = col; rleBuf++; } x += glyph.m_width; } return x - _x; } int DrawTextSimple(DfFont *f, DfColour col, DfBitmap *bmp, int x, int y, char const *text) { return DrawTextSimpleLen(f, col, bmp, x, y, text, 9999); } int DrawTextLeft(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); return DrawTextSimple(tr, c, bmp, x, y, buf); } int DrawTextRight(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width, y, buf); } int DrawTextCentre(DfFont *tr, DfColour c, DfBitmap *bmp, int x, int y, char const *text, ...) { char buf[512]; va_list ap; va_start(ap, text); vsprintf(buf, text, ap); int width = GetTextWidth(tr, buf); return DrawTextSimple(tr, c, bmp, x - width/2, y, buf); } int GetTextWidth(DfFont *tr, char const *text, int len) { len = IntMin((int)strlen(text), len); if (tr->fixedWidth) { return len * tr->maxCharWidth; } else { int width = 0; for (int i = 0; i < len; i++) width += tr->glyphs[text[i] & 0xff]->m_width; return width; } } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/logging.h" #include "chrome_frame/crash_reporting/vectored_handler-impl.h" #include "chrome_frame/crash_reporting/veh_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; ACTION_P(StackTraceDump, s) { memcpy(arg2, s->stack_, s->count_ * sizeof(s->stack_[0])); return s->count_; } namespace { class MockApi : public Win32VEHTraits, public ModuleOfInterest { public: MockApi() { Win32VEHTraits::InitializeIgnoredBlocks(); } MOCK_METHOD1(WriteDump, void(const EXCEPTION_POINTERS*)); MOCK_METHOD0(RtlpGetExceptionList, const EXCEPTION_REGISTRATION_RECORD*()); MOCK_METHOD4(RtlCaptureStackBackTrace, WORD(DWORD FramesToSkip, DWORD FramesToCapture, void** BackTrace, DWORD* BackTraceHash)); // Helpers void SetSEH(const SEHChain& sehchain) { EXPECT_CALL(*this, RtlpGetExceptionList()) .Times(testing::AnyNumber()) .WillRepeatedly(testing::Return(sehchain.chain_)); } void SetStack(const StackHelper& s) { EXPECT_CALL(*this, RtlCaptureStackBackTrace(_, _, _, _)) .Times(testing::AnyNumber()) .WillRepeatedly(StackTraceDump(&s)); } enum {max_back_trace = 15}; }; }; // namespace typedef VectoredHandlerT<MockApi> VectoredHandlerMock; TEST(ChromeFrame, ExceptionReport) { MockApi api; VectoredHandlerMock veh(&api); // Start address of our module. char* s = reinterpret_cast<char*>(0x30000000); char *e = s + 0x10000; api.SetModule(s, e); SEHChain have_seh(s - 0x1000, s + 0x1000, e + 0x7127, NULL); SEHChain no_seh(s - 0x1000, e + 0x7127, NULL); StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL); StackHelper not_on_stack(s - 0x11283, s - 0x278361, e + 1231, NULL); char* our_code = s + 0x1111; char* not_our_code = s - 0x5555; char* not_our_code2 = e + 0x5555; // Exception in our code, but we have SEH filter => no dump. api.SetSEH(have_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // RPC_E_DISCONNECTED (0x80010108) is "The object invoked has disconnected // from its clients", shall not be caught since it's a warning only. EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(RPC_E_DISCONNECTED, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, not in our code, we do not have SEH and we are not in stack. api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, not in our code, no SEH, but we are on the stack. api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(1); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code2))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in our code, no SEH, not on stack (assume FPO screwed us) api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(1); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_PRIVILEGED_INSTRUCTION, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in IsBadStringPtrA, we are on the stack. api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); char* ignore_address = reinterpret_cast<char*>(GetProcAddress( GetModuleHandleA("kernel32.dll"), "IsBadStringPtrA")) + 10; EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in IsBadStringPtrA, we are not on the stack. api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address))); testing::Mock::VerifyAndClearExpectations(&api); } MATCHER_P(ExceptionCodeIs, code, "") { return (arg->ExceptionRecord->ExceptionCode == code); } void OverflowStack() { char tmp[1024 * 2048]; ZeroMemory(tmp, sizeof(tmp)); } DWORD WINAPI CrashingThread(PVOID tmp) { __try { OverflowStack(); } __except(EXCEPTION_EXECUTE_HANDLER) { } // This will cause STATUS_ACCESS_VIOLATION __try { OverflowStack(); } __except(EXCEPTION_EXECUTE_HANDLER) { } return 0; } static VectoredHandlerMock* g_mock_veh = NULL; static LONG WINAPI VEH(EXCEPTION_POINTERS* exptrs) { return g_mock_veh->Handler(exptrs); } TEST(ChromeFrame, TrickyStackOverflow) { MockApi api; VectoredHandlerMock veh(&api); // Start address of our module. char* s = reinterpret_cast<char*>(0x30000000); char *e = s + 0x10000; api.SetModule(s, e); SEHChain no_seh(s - 0x1000, e + 0x7127, NULL); StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL); api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(ExceptionCodeIs(STATUS_STACK_OVERFLOW))).Times(1); g_mock_veh = &veh; void* id = ::AddVectoredExceptionHandler(FALSE, VEH); DWORD tid; HANDLE h = ::CreateThread(0, 0, CrashingThread, 0, 0, &tid); ::WaitForSingleObject(h, INFINITE); ::CloseHandle(h); EXPECT_EQ(2, veh.get_exceptions_seen()); ::RemoveVectoredExceptionHandler(id); g_mock_veh = NULL; } <commit_msg>Committing for stoyan since we need this now...<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <atlbase.h> #include "base/logging.h" #include "chrome_frame/crash_reporting/vectored_handler-impl.h" #include "chrome_frame/crash_reporting/veh_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; ACTION_P(StackTraceDump, s) { memcpy(arg2, s->stack_, s->count_ * sizeof(s->stack_[0])); return s->count_; } namespace { class MockApi : public Win32VEHTraits, public ModuleOfInterest { public: MockApi() { Win32VEHTraits::InitializeIgnoredBlocks(); } MOCK_METHOD1(WriteDump, void(const EXCEPTION_POINTERS*)); MOCK_METHOD0(RtlpGetExceptionList, const EXCEPTION_REGISTRATION_RECORD*()); MOCK_METHOD4(RtlCaptureStackBackTrace, WORD(DWORD FramesToSkip, DWORD FramesToCapture, void** BackTrace, DWORD* BackTraceHash)); // Helpers void SetSEH(const SEHChain& sehchain) { EXPECT_CALL(*this, RtlpGetExceptionList()) .Times(testing::AnyNumber()) .WillRepeatedly(testing::Return(sehchain.chain_)); } void SetStack(const StackHelper& s) { EXPECT_CALL(*this, RtlCaptureStackBackTrace(_, _, _, _)) .Times(testing::AnyNumber()) .WillRepeatedly(StackTraceDump(&s)); } enum {max_back_trace = 15}; }; }; // namespace typedef VectoredHandlerT<MockApi> VectoredHandlerMock; TEST(ChromeFrame, ExceptionReport) { MockApi api; VectoredHandlerMock veh(&api); // Start address of our module. char* s = reinterpret_cast<char*>(0x30000000); char *e = s + 0x10000; api.SetModule(s, e); SEHChain have_seh(s - 0x1000, s + 0x1000, e + 0x7127, NULL); SEHChain no_seh(s - 0x1000, e + 0x7127, NULL); StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL); StackHelper not_on_stack(s - 0x11283, s - 0x278361, e + 1231, NULL); char* our_code = s + 0x1111; char* not_our_code = s - 0x5555; char* not_our_code2 = e + 0x5555; // Exception in our code, but we have SEH filter => no dump. api.SetSEH(have_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // RPC_E_DISCONNECTED (0x80010108) is "The object invoked has disconnected // from its clients", shall not be caught since it's a warning only. EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(RPC_E_DISCONNECTED, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, not in our code, we do not have SEH and we are not in stack. api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, not in our code, no SEH, but we are on the stack. api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(1); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_INTEGER_DIVIDE_BY_ZERO, not_our_code2))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in our code, no SEH, not on stack (assume FPO screwed us) api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(1); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_PRIVILEGED_INSTRUCTION, our_code))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in IsBadStringPtrA, we are on the stack. api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); char* ignore_address = reinterpret_cast<char*>(GetProcAddress( GetModuleHandleA("kernel32.dll"), "IsBadStringPtrA")) + 10; EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address))); testing::Mock::VerifyAndClearExpectations(&api); // Exception, in IsBadStringPtrA, we are not on the stack. api.SetSEH(no_seh); api.SetStack(not_on_stack); EXPECT_CALL(api, WriteDump(_)).Times(0); EXPECT_EQ(ExceptionContinueSearch, veh.Handler(&ExceptionInfo(STATUS_ACCESS_VIOLATION, ignore_address))); testing::Mock::VerifyAndClearExpectations(&api); } MATCHER_P(ExceptionCodeIs, code, "") { return (arg->ExceptionRecord->ExceptionCode == code); } DECLSPEC_NOINLINE static void OverflowStack() { char tmp[1024 * 2048] = {0}; GetSystemInfo(reinterpret_cast<SYSTEM_INFO*>(&tmp)); } DWORD WINAPI CrashingThread(PVOID tmp) { __try { OverflowStack(); } __except(EXCEPTION_EXECUTE_HANDLER) { } // This will cause STATUS_ACCESS_VIOLATION __try { OverflowStack(); } __except(EXCEPTION_EXECUTE_HANDLER) { } return 0; } static VectoredHandlerMock* g_mock_veh = NULL; static LONG WINAPI VEH(EXCEPTION_POINTERS* exptrs) { return g_mock_veh->Handler(exptrs); } TEST(ChromeFrame, TrickyStackOverflow) { MockApi api; VectoredHandlerMock veh(&api); // Start address of our module. char* s = reinterpret_cast<char*>(0x30000000); char *e = s + 0x10000; api.SetModule(s, e); SEHChain no_seh(s - 0x1000, e + 0x7127, NULL); StackHelper on_stack(s - 0x11283, s - 0x278361, s + 0x9171, e + 1231, NULL); api.SetSEH(no_seh); api.SetStack(on_stack); EXPECT_CALL(api, WriteDump(ExceptionCodeIs(STATUS_STACK_OVERFLOW))).Times(1); g_mock_veh = &veh; void* id = ::AddVectoredExceptionHandler(FALSE, VEH); DWORD tid; HANDLE h = ::CreateThread(0, 0, CrashingThread, 0, 0, &tid); ::WaitForSingleObject(h, INFINITE); ::CloseHandle(h); EXPECT_EQ(2, veh.get_exceptions_seen()); ::RemoveVectoredExceptionHandler(id); g_mock_veh = NULL; } <|endoftext|>
<commit_before>#include"all_defines.hpp" #include"types.hpp" #include"workers.hpp" #include"processes.hpp" #include"mutexes.hpp" #include"lockeds.hpp" #include"symbols.hpp" #include<boost/noncopyable.hpp> #include<iostream> /*----------------------------------------------------------------------------- AllWorkers -----------------------------------------------------------------------------*/ /* * Registration */ void AllWorkers::register_process(Process* P) { AppLock l(U_mtx); U.push_back(P); } void AllWorkers::register_worker(Worker* W) { AppLock l(general_mtx); Ws.push_back(W); total_workers++; } void AllWorkers::unregister_worker(Worker* W) { AppLock lg(general_mtx); size_t l = Ws.size(); for(size_t i = 0; i < l; ++i) { if(Ws[i] == W) { Ws[i] = Ws[l - 1]; Ws.resize(l - 1); --total_workers; /*check if this has changed any of the waiting states */ if(soft_stop_condition) { if(soft_stop_waiting == total_workers) { soft_stop_waiting = 0; soft_stop_cv.broadcast(); } } if(workqueue_waiting > 0) { if(workqueue_waiting == total_workers) { workqueue_waiting = 0; exit_condition = 1; workqueue_cv.broadcast(); } } return; } } } /* * Soft-stop */ void AllWorkers::soft_stop_raise(void) { AppLock l(general_mtx); soft_stop_condition = 1; if(workqueue_waiting != 0) { workqueue_cv.broadcast(); } soft_stop_waiting++; soft_stop_cv.wait(l); } void AllWorkers::soft_stop_lower(void) { AppLock l(general_mtx); soft_stop_condition = 0; soft_stop_cv.broadcast(); } void AllWorkers::soft_stop_check(AppLock& l) { while(soft_stop_condition) { soft_stop_waiting++; if(soft_stop_waiting == total_workers) { soft_stop_waiting = 0; soft_stop_cv.broadcast(); } else { soft_stop_cv.wait(l); } } } /* * Workqueue */ void AllWorkers::workqueue_push(Process* R) { AppLock l(general_mtx); bool sig = workqueue.empty(); workqueue.push(R); if(sig) workqueue_cv.broadcast(); } void AllWorkers::workqueue_push_and_pop(Process*& R) { AppLock l(general_mtx); soft_stop_check(l); /*if workqueue is empty, we'd end up popping what we would have pushed anyway, so just short-circuit it */ if(workqueue.empty()) return; workqueue.push(R); R = workqueue.front(); workqueue.pop(); } bool AllWorkers::workqueue_pop(Process*& R) { AppLock l(general_mtx); start: soft_stop_check(l); if(!workqueue.empty()) { R = workqueue.front(); workqueue.pop(); return 1; } retry: workqueue_waiting++; if(workqueue_waiting == total_workers) { workqueue_waiting = 0; exit_condition = 1; return 0; } workqueue_cv.wait(l); if(exit_condition) return 0; --workqueue_waiting; /*if we exited due to a soft-stop, bar*/ if(soft_stop_condition) goto start; if(workqueue.empty()) goto retry; R = workqueue.front(); workqueue.pop(); return 1; } /*----------------------------------------------------------------------------- Worker -----------------------------------------------------------------------------*/ void Worker::operator()(void) { try { try { parent->register_worker(this); work(); parent->unregister_worker(this); } catch(std::exception& e) { std::cerr << "Unhandled exception:" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "aborting a worker thread..." << std::endl; std::cerr.flush(); parent->unregister_worker(this); return; } } catch(...) { std::cerr << "Unknown exception!" << std::endl; std::cerr << "aborting a worker thread..." << std::endl; std::cerr.flush(); parent->unregister_worker(this); return; } } /* * Helper RAII classes */ class MarkingTraverser : public HeapTraverser { private: std::set<Process*>* pgray_set; public: explicit MarkingTraverser(std::set<Process*>& ngray_set) : pgray_set(&ngray_set) { } virtual void traverse(Generic* gp) { HlPid* pp = dynamic_cast<HlPid*>(gp); if(pp && pp->process->waiting_and_not_black()){ pgray_set->insert(pp->process); } } }; /*Holds the currently-running process. If something throws while we're running that process, just kill the process and drop its references. */ class RunningProcessRef : boost::noncopyable { public: Process* p; RunningProcessRef(void) : p(0) { } RunningProcessRef& operator=(Process* np) { p = np; } ~RunningProcessRef() { /*DON'T delete p, just kill it*/ if(p) p->atomic_kill(); } operator Process*&(void) { return p; } Process* operator->(void) { return p; } Process* operator->(void) const { return p; } Process& operator*(void) { return *p; } Process& operator*(void) const { return *p; } }; /*Causes a soft-stop on other worker threads */ class SoftStop : boost::noncopyable { AllWorkers* parent; #ifndef single_threaded bool single_threaded_save; #endif public: explicit SoftStop(AllWorkers* nparent) : parent(nparent) { parent->soft_stop_raise(); #ifndef single_threaded single_threaded_save = single_threaded; single_threaded = 1; #endif } ~SoftStop() { #ifndef single_threaded single_threaded = single_threaded_save; #endif parent->soft_stop_lower(); } }; class AnesthesizeProcess : boost::noncopyable { AllWorkers* parent; Process* P; public: bool succeeded; AnesthesizeProcess(Process* nP, AllWorkers* nparent) : parent(nparent), P(nP), succeeded(nP->anesthesize()) { } ~AnesthesizeProcess() { if(succeeded) { if(P->unanesthesize()) { /*Process::unanesthesize should have set status to process_running */ parent->workqueue_push(P); } } } }; /* * Marks all PID's of a process */ void Worker::mark_process(Process* P) { MarkingTraverser mt(gray_set); P->heap().traverse_objects(&mt); /*scan the mailbox*/ ValueHolderRef tmp; LockedValueHolderRef& mailbox = P->mailbox(); mailbox.swap(tmp); if(!tmp.empty()) { /*shouldn't throw: traverse_objects doesn't throw, and MarkingTraverser doesn't either */ tmp->traverse_objects(&mt); /*put back the contents into the mailbox*/ mailbox.swap(tmp); } /*another process might have sent new messages while we were marking - so tmp might not be empty. We just push tmp one-by-one onto the mailbox. */ /* We don't have to rescan the new messages - we only mark during a process-level GC, and messages that are sent while a GC is going on cannot contain references to white processes, because only black processes are actually allowed to run (and by extension, send messages). */ ValueHolderRef tmp2; while(!tmp.empty()) { tmp.remove(tmp2); /* --> tmp2 */ mailbox.insert(tmp2); /* <-- tmp2*/ } /*would be better to insert them all at once rather than one at a time. */ /*does not require atomicity, since only one worker thread can perform marking on any process at a time. */ P->blacken(); } /* * Actual work */ /*please refer to file doc/process-gc.txt*/ void Worker::work(void) { ProcessStatus Rstat; RunningProcessRef R; Process* Q = 0; size_t timeslice; WorkerLoop: if(T) { /*trigger GC*/ if(T == 1) { if(R) { parent->workqueue_push(R); R = 0; } {SoftStop ss(parent); /*all other threads are now suspended*/ SymbolScanner ssc(parent->Ws); symbols->traverse_symbols(&ssc); for(size_t i; i < parent->total_workers; ++i) { parent->gray_workers++; // N parent->Ws[i]->gray_done = 0; parent->Ws[i]->scanning_mode = 1; } } T = 0; } else { --T; } } /*this also checks for soft-stop for us*/ if(R) { parent->workqueue_push_and_pop(R); } else { if(!parent->workqueue_pop(R)) { return; //no more work } } if(scanning_mode) { if(R->is_black()) { scanning_mode = 0; } else { mark_process(R); } } timeslice = parent->default_timeslice; execute: Rstat = R->execute(timeslice, Q); switch(Rstat) { case process_waiting: case process_dead: R = 0; // clear case process_change: parent->workqueue_push(R); R = Q; Q = 0; if(scanning_mode && !R->is_black()) { mark_process(R); } goto execute; } if(!scanning_mode && !gray_done) { if(!gray_set.empty()) { if(R) { parent->workqueue_push(R); R = 0; } std::set<Process*>::const_iterator i; get_gray: i = gray_set.begin(); Q = *i; gray_set.erase(i); {AnesthesizeProcess ap(Q, parent); if(ap.succeeded) { mark_process(Q); } else { goto get_gray; } } Q = 0; } else { gray_done = 1; if((--parent->gray_workers) == 0) { goto Sweep; } } } goto WorkerLoop; Sweep: if(R) { parent->workqueue_push(R); R = 0; } {SoftStop ss(parent); size_t i, j; Process* tmp; std::vector<Process*>& U = parent->U; size_t l = U.size(); for(i = 0, j = 0; i < l; ++i) { if(U[i]->is_black()) { U[i]->whiten(); /*swap in order to partition U into known-live and known-dead */ tmp = U[i]; U[i] = U[j]; U[j] = tmp; ++j; } else { U[i]->kill(); } } /*first clean the symbol's notification lists*/ SymbolNotificationCleaner snc(U, j); symbols->traverse_symbols(&snc); /*now really delete U[j] onwards*/ for(i = j; i < l; ++i) { delete U[i]; } U.resize(j); size_t died = l - j; /*having got the short stick, we now compute the trigger point for the next GC */ T = (died >= 4096) ? 1 : /*otherwise*/ (4096 - died); T += 1; T *= 4; } goto WorkerLoop; } <commit_msg>src/workers.cpp: Added a missing break in switch() form<commit_after>#include"all_defines.hpp" #include"types.hpp" #include"workers.hpp" #include"processes.hpp" #include"mutexes.hpp" #include"lockeds.hpp" #include"symbols.hpp" #include<boost/noncopyable.hpp> #include<iostream> /*----------------------------------------------------------------------------- AllWorkers -----------------------------------------------------------------------------*/ /* * Registration */ void AllWorkers::register_process(Process* P) { AppLock l(U_mtx); U.push_back(P); } void AllWorkers::register_worker(Worker* W) { AppLock l(general_mtx); Ws.push_back(W); total_workers++; } void AllWorkers::unregister_worker(Worker* W) { AppLock lg(general_mtx); size_t l = Ws.size(); for(size_t i = 0; i < l; ++i) { if(Ws[i] == W) { Ws[i] = Ws[l - 1]; Ws.resize(l - 1); --total_workers; /*check if this has changed any of the waiting states */ if(soft_stop_condition) { if(soft_stop_waiting == total_workers) { soft_stop_waiting = 0; soft_stop_cv.broadcast(); } } if(workqueue_waiting > 0) { if(workqueue_waiting == total_workers) { workqueue_waiting = 0; exit_condition = 1; workqueue_cv.broadcast(); } } return; } } } /* * Soft-stop */ void AllWorkers::soft_stop_raise(void) { AppLock l(general_mtx); soft_stop_condition = 1; if(workqueue_waiting != 0) { workqueue_cv.broadcast(); } soft_stop_waiting++; soft_stop_cv.wait(l); } void AllWorkers::soft_stop_lower(void) { AppLock l(general_mtx); soft_stop_condition = 0; soft_stop_cv.broadcast(); } void AllWorkers::soft_stop_check(AppLock& l) { while(soft_stop_condition) { soft_stop_waiting++; if(soft_stop_waiting == total_workers) { soft_stop_waiting = 0; soft_stop_cv.broadcast(); } else { soft_stop_cv.wait(l); } } } /* * Workqueue */ void AllWorkers::workqueue_push(Process* R) { AppLock l(general_mtx); bool sig = workqueue.empty(); workqueue.push(R); if(sig) workqueue_cv.broadcast(); } void AllWorkers::workqueue_push_and_pop(Process*& R) { AppLock l(general_mtx); soft_stop_check(l); /*if workqueue is empty, we'd end up popping what we would have pushed anyway, so just short-circuit it */ if(workqueue.empty()) return; workqueue.push(R); R = workqueue.front(); workqueue.pop(); } bool AllWorkers::workqueue_pop(Process*& R) { AppLock l(general_mtx); start: soft_stop_check(l); if(!workqueue.empty()) { R = workqueue.front(); workqueue.pop(); return 1; } retry: workqueue_waiting++; if(workqueue_waiting == total_workers) { workqueue_waiting = 0; exit_condition = 1; return 0; } workqueue_cv.wait(l); if(exit_condition) return 0; --workqueue_waiting; /*if we exited due to a soft-stop, bar*/ if(soft_stop_condition) goto start; if(workqueue.empty()) goto retry; R = workqueue.front(); workqueue.pop(); return 1; } /*----------------------------------------------------------------------------- Worker -----------------------------------------------------------------------------*/ void Worker::operator()(void) { try { try { parent->register_worker(this); work(); parent->unregister_worker(this); } catch(std::exception& e) { std::cerr << "Unhandled exception:" << std::endl; std::cerr << e.what() << std::endl; std::cerr << "aborting a worker thread..." << std::endl; std::cerr.flush(); parent->unregister_worker(this); return; } } catch(...) { std::cerr << "Unknown exception!" << std::endl; std::cerr << "aborting a worker thread..." << std::endl; std::cerr.flush(); parent->unregister_worker(this); return; } } /* * Helper RAII classes */ class MarkingTraverser : public HeapTraverser { private: std::set<Process*>* pgray_set; public: explicit MarkingTraverser(std::set<Process*>& ngray_set) : pgray_set(&ngray_set) { } virtual void traverse(Generic* gp) { HlPid* pp = dynamic_cast<HlPid*>(gp); if(pp && pp->process->waiting_and_not_black()){ pgray_set->insert(pp->process); } } }; /*Holds the currently-running process. If something throws while we're running that process, just kill the process and drop its references. */ class RunningProcessRef : boost::noncopyable { public: Process* p; RunningProcessRef(void) : p(0) { } RunningProcessRef& operator=(Process* np) { p = np; } ~RunningProcessRef() { /*DON'T delete p, just kill it*/ if(p) p->atomic_kill(); } operator Process*&(void) { return p; } Process* operator->(void) { return p; } Process* operator->(void) const { return p; } Process& operator*(void) { return *p; } Process& operator*(void) const { return *p; } }; /*Causes a soft-stop on other worker threads */ class SoftStop : boost::noncopyable { AllWorkers* parent; #ifndef single_threaded bool single_threaded_save; #endif public: explicit SoftStop(AllWorkers* nparent) : parent(nparent) { parent->soft_stop_raise(); #ifndef single_threaded single_threaded_save = single_threaded; single_threaded = 1; #endif } ~SoftStop() { #ifndef single_threaded single_threaded = single_threaded_save; #endif parent->soft_stop_lower(); } }; class AnesthesizeProcess : boost::noncopyable { AllWorkers* parent; Process* P; public: bool succeeded; AnesthesizeProcess(Process* nP, AllWorkers* nparent) : parent(nparent), P(nP), succeeded(nP->anesthesize()) { } ~AnesthesizeProcess() { if(succeeded) { if(P->unanesthesize()) { /*Process::unanesthesize should have set status to process_running */ parent->workqueue_push(P); } } } }; /* * Marks all PID's of a process */ void Worker::mark_process(Process* P) { MarkingTraverser mt(gray_set); P->heap().traverse_objects(&mt); /*scan the mailbox*/ ValueHolderRef tmp; LockedValueHolderRef& mailbox = P->mailbox(); mailbox.swap(tmp); if(!tmp.empty()) { /*shouldn't throw: traverse_objects doesn't throw, and MarkingTraverser doesn't either */ tmp->traverse_objects(&mt); /*put back the contents into the mailbox*/ mailbox.swap(tmp); } /*another process might have sent new messages while we were marking - so tmp might not be empty. We just push tmp one-by-one onto the mailbox. */ /* We don't have to rescan the new messages - we only mark during a process-level GC, and messages that are sent while a GC is going on cannot contain references to white processes, because only black processes are actually allowed to run (and by extension, send messages). */ ValueHolderRef tmp2; while(!tmp.empty()) { tmp.remove(tmp2); /* --> tmp2 */ mailbox.insert(tmp2); /* <-- tmp2*/ } /*would be better to insert them all at once rather than one at a time. */ /*does not require atomicity, since only one worker thread can perform marking on any process at a time. */ P->blacken(); } /* * Actual work */ /*please refer to file doc/process-gc.txt*/ void Worker::work(void) { ProcessStatus Rstat; RunningProcessRef R; Process* Q = 0; size_t timeslice; WorkerLoop: if(T) { /*trigger GC*/ if(T == 1) { if(R) { parent->workqueue_push(R); R = 0; } {SoftStop ss(parent); /*all other threads are now suspended*/ SymbolScanner ssc(parent->Ws); symbols->traverse_symbols(&ssc); for(size_t i; i < parent->total_workers; ++i) { parent->gray_workers++; // N parent->Ws[i]->gray_done = 0; parent->Ws[i]->scanning_mode = 1; } } T = 0; } else { --T; } } /*this also checks for soft-stop for us*/ if(R) { parent->workqueue_push_and_pop(R); } else { if(!parent->workqueue_pop(R)) { return; //no more work } } if(scanning_mode) { if(R->is_black()) { scanning_mode = 0; } else { mark_process(R); } } timeslice = parent->default_timeslice; execute: Rstat = R->execute(timeslice, Q); switch(Rstat) { case process_waiting: case process_dead: R = 0; // clear break; case process_change: parent->workqueue_push(R); R = Q; Q = 0; if(scanning_mode && !R->is_black()) { mark_process(R); } goto execute; } if(!scanning_mode && !gray_done) { if(!gray_set.empty()) { if(R) { parent->workqueue_push(R); R = 0; } std::set<Process*>::const_iterator i; get_gray: i = gray_set.begin(); Q = *i; gray_set.erase(i); {AnesthesizeProcess ap(Q, parent); if(ap.succeeded) { mark_process(Q); } else { goto get_gray; } } Q = 0; } else { gray_done = 1; if((--parent->gray_workers) == 0) { goto Sweep; } } } goto WorkerLoop; Sweep: if(R) { parent->workqueue_push(R); R = 0; } {SoftStop ss(parent); size_t i, j; Process* tmp; std::vector<Process*>& U = parent->U; size_t l = U.size(); for(i = 0, j = 0; i < l; ++i) { if(U[i]->is_black()) { U[i]->whiten(); /*swap in order to partition U into known-live and known-dead */ tmp = U[i]; U[i] = U[j]; U[j] = tmp; ++j; } else { U[i]->kill(); } } /*first clean the symbol's notification lists*/ SymbolNotificationCleaner snc(U, j); symbols->traverse_symbols(&snc); /*now really delete U[j] onwards*/ for(i = j; i < l; ++i) { delete U[i]; } U.resize(j); size_t died = l - j; /*having got the short stick, we now compute the trigger point for the next GC */ T = (died >= 4096) ? 1 : /*otherwise*/ (4096 - died); T += 1; T *= 4; } goto WorkerLoop; } <|endoftext|>
<commit_before>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); } //ʼɫ int CRoleBase::Init(int nRoleID, const char* strCharFile) { if (m_pCreature)return 1; m_nMoveing = 1; m_nRoleID = nRoleID; m_pCreature = new CCreature(); m_pActionComplete = MakeInterface(this, &CRoleBase::OnActionMsg); m_pCreature->SetActionComplete(m_pActionComplete); m_pCreature->Load(strCharFile); m_pCreature->SetupBody(1, 0); m_pCreature->SetPosition(vec3_zero); m_pCreature->SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pCreature->SetRoleID(nRoleID); m_AngleYaw.SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pPathFind = new CNavigationFinder(); m_pPathFind->SetMode(CNavigationFinder::MODE_PATHFIND_STRAIGHT); return 1; } void CRoleBase::Update(float ifps) { if (NULL == m_pCreature)return; if (m_nUpdateMove) { m_AngleYaw.Update(ifps); UpdateMove(ifps); m_pCreature->SetDirection(m_AngleYaw.GetForwardDirection(), m_nOrceDirection); } m_pCreature->Update(); } int CRoleBase::OnActionMsg(void* pVoid) { _ActionCallback* pInfo = (_ActionCallback*)pVoid; switch (pInfo->nMsgID) { case 0: { OnKeyFrame((_ActionCallback_KeyFrame*)pVoid); }break; case 1: { OnActionComplete((_ActionCallback_Complete*)pVoid); }break; } return 1; } //ؼ֡ص void CRoleBase::OnKeyFrame(_ActionCallback_KeyFrame* pKeyInfo) { }//ɻص void CRoleBase::OnActionComplete(_ActionCallback_Complete* pActInfo) { if (NULL == m_pCreature)return; if (m_nMoveing) { m_pCreature->PlayAction("run"); } else { m_pCreature->PlayAction("stand"); } } CAction* CRoleBase::PlayAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->PlayAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } CAction* CRoleBase::OrceAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->OrceAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } <commit_msg>SetPostion<commit_after>#include "RoleBase.h" #include "Creature.h" #include "interface.h" #include "Action.h" #include "Utils.h" #include "NavigationFinder.h" #include "Engine.h" #include "World.h" #include "Object.h" #include "Avatar.h" CRoleBase::CRoleBase(void) { m_pCreature = NULL; m_pActionComplete = NULL; m_nOrceDirection = 0; m_nMoveing = 0; m_fMoveSpeed = 6.0f; m_nMoveToType = 0; m_nUpdateMove = 1; } CRoleBase::~CRoleBase(void) { SAFE_DELETE(m_pActionComplete); SAFE_DELETE(m_pCreature); SAFE_DELETE(m_pPathFind); } //ʼɫ int CRoleBase::Init(int nRoleID, const char* strCharFile) { if (m_pCreature)return 1; m_nMoveing = 1; m_nRoleID = nRoleID; m_pCreature = new CCreature(); m_pActionComplete = MakeInterface(this, &CRoleBase::OnActionMsg); m_pCreature->SetActionComplete(m_pActionComplete); m_pCreature->Load(strCharFile); m_pCreature->SetupBody(1, 0); m_pCreature->SetPosition(vec3_zero); m_pCreature->SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pCreature->SetRoleID(nRoleID); m_AngleYaw.SetDirection(vec3(0.0f, -1.0f, 0.0f)); m_pPathFind = new CNavigationFinder(); m_pPathFind->SetMode(CNavigationFinder::MODE_PATHFIND_STRAIGHT); return 1; } void CRoleBase::Update(float ifps) { if (NULL == m_pCreature)return; if (m_nUpdateMove) { m_AngleYaw.Update(ifps); UpdateMove(ifps); m_pCreature->SetDirection(m_AngleYaw.GetForwardDirection(), m_nOrceDirection); } m_pCreature->Update(); } int CRoleBase::OnActionMsg(void* pVoid) { _ActionCallback* pInfo = (_ActionCallback*)pVoid; switch (pInfo->nMsgID) { case 0: { OnKeyFrame((_ActionCallback_KeyFrame*)pVoid); }break; case 1: { OnActionComplete((_ActionCallback_Complete*)pVoid); }break; } return 1; } //ؼ֡ص void CRoleBase::OnKeyFrame(_ActionCallback_KeyFrame* pKeyInfo) { }//ɻص void CRoleBase::OnActionComplete(_ActionCallback_Complete* pActInfo) { if (NULL == m_pCreature)return; if (m_nMoveing) { m_pCreature->PlayAction("run"); } else { m_pCreature->PlayAction("stand"); } } CAction* CRoleBase::PlayAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->PlayAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } CAction* CRoleBase::OrceAction(const char* szName, int nLoop, float fCorrectingTime /*= 1.0f*/) { if (NULL == m_pCreature)return NULL; if (1 == m_pCreature->OrceAction(szName, nLoop, fCorrectingTime)) { return m_pCreature->GetNowAction(); } return NULL; } void CRoleBase::SetPosition(const vec3& vPosition, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; m_pCreature->SetPosition(vPosition, nOrce); } void CRoleBase::SetDirection(const vec3& vDirection, int nOrce /*= 0*/) { if (NULL == m_pCreature)return; if (m_pCreature->GetNowAction()->GetLockMove() && !nOrce)return; m_nOrceDirection = nOrce; m_AngleYaw.SetDirection(vDirection); }<|endoftext|>
<commit_before>#include <QSizePolicy> #include <QSpacerItem> #include <QtDebug> #include "librarywidget.h" #include "ui_librarywidget.h" LibraryWidget::LibraryWidget(QWidget* const parent, AppController* const controller) : QWidget(parent) , ui(new Ui::LibraryWidget) , controller(controller) { ui->setupUi(this); tabGameFrames << new QList<GameFrame*> << new QList<GameFrame*>; tabScrollAreas << new QScrollArea() << new QScrollArea(); tabWrappers << new QWidget << new QWidget; tabLayouts << new QVBoxLayout() << new QVBoxLayout(); tabRowLayouts << new QList<QVBoxLayout*> << new QList<QVBoxLayout*>; tabColLayouts << new QList<QHBoxLayout*> << new QList<QHBoxLayout*>; for(int i = 0; i < tabScrollAreas.size(); i++){ tabScrollAreas.at(i)->setObjectName("gamesScroller"); tabWrappers.at(i)->setObjectName("scrollWrapper"); } controller->api->myOwnedKeys([this](QList<DownloadKey> keys) { onMyPurchasedKeys(keys); }); controller->api->myClaimedKeys([this](QList<DownloadKey> keys) { onMyClaimedKeys(keys); }); updateTimer = new QTimer(this); connect(updateTimer, &QTimer::timeout, this, &LibraryWidget::onUpdate); updateTimer->start(60000); } void LibraryWidget::onMyPurchasedKeys(QList<DownloadKey> downloadKeys) { QList<GameFrame*> gameFrames; int repeatCount = 0; foreach (DownloadKey key, downloadKeys) { for(int i = 0; i < tabGameFrames.at(0)->size(); i++){ if(key.game.id == tabGameFrames.at(0)->at(i)->game.id){ repeatCount++; } } if(repeatCount == 0){ gameFrames << new GameFrame(this, key.game, key, controller); } } if(!gameFrames.isEmpty()){ tabGameFrames.at(0)->append(gameFrames); } if(tabSetupCount < 2){ addGamesTab("Purchased", 0); } } void LibraryWidget::onMyClaimedKeys(QList<DownloadKey> downloadKeys) { QList<GameFrame*> gameFrames; int repeatCount = 0; foreach (DownloadKey key, downloadKeys) { for(int i = 0; i < tabGameFrames.at(1)->size(); i++){ if(key.game.id == tabGameFrames.at(1)->at(i)->game.id){ repeatCount++; } } if(repeatCount == 0){ gameFrames << new GameFrame(this, key.game, key, controller); } } if(!gameFrames.isEmpty()){ tabGameFrames.at(1)->append(gameFrames); } if(tabSetupCount < 2){ addGamesTab("Claimed", 1); } } void LibraryWidget::addGamesTab(const QString& title, int tab) { tabRowLayouts.at(tab)->append(new QVBoxLayout); tabColLayouts.at(tab)->append(new QHBoxLayout); tabLayouts.at(tab)->addLayout(tabRowLayouts.at(tab)->at(0)); tabRowLayouts.at(tab)->at(0)->addLayout(tabColLayouts.at(tab)->at(0)); maxGamesFramesPerRow = (ui->tabWidget->width() - 80) / gameFrameWidth; int i = 1; int j = 0; while(i < tabGameFrames.at(tab)->size() + 1) { tabColLayouts.at(tab)->at(j)->addWidget(tabGameFrames.at(tab)->at(i - 1)); if(i % maxGamesFramesPerRow == 0) { tabColLayouts.at(tab)->append(new QHBoxLayout); j++; tabRowLayouts.at(tab)->at(0)->addLayout(tabColLayouts.at(tab)->at(j)); } i++; } int p = maxGamesFramesPerRow - (tabGameFrames.at(tab)->size() % maxGamesFramesPerRow); while(p > 0) { tabColLayouts.at(tab)->at(j)->addSpacerItem(new QSpacerItem(gameFrameWidth, 0)); p--; } tabWrappers.at(tab)->setLayout(tabLayouts.at(tab)); tabScrollAreas.at(tab)->setWidget(tabWrappers.at(tab)); ui->tabWidget->addTab(tabScrollAreas.at(tab), title); tabSetupCount++; } void LibraryWidget::resizeEvent(QResizeEvent *event) { event->accept(); if(tabSetupCount == 2) { adjustTabLayouts(); } } void LibraryWidget::adjustTabLayouts() { if((ui->tabWidget->width() - 80) / gameFrameWidth != maxGamesFramesPerRow){ maxGamesFramesPerRow = (ui->tabWidget->width() - 80) / gameFrameWidth; tabWrappers.clear(); tabLayouts.clear(); for(int i = 0; i < tabScrollAreas.size(); i++){ tabRowLayouts.at(i)->clear(); tabColLayouts.at(i)->clear(); } tabWrappers << new QWidget << new QWidget; tabLayouts << new QVBoxLayout() << new QVBoxLayout(); tabRowLayouts << new QList<QVBoxLayout*> << new QList<QVBoxLayout*>; tabColLayouts << new QList<QHBoxLayout*> << new QList<QHBoxLayout*>; for(int k = 0; k < tabScrollAreas.size(); k++){ tabWrappers.at(k)->setObjectName("scrollWrapper"); tabRowLayouts.at(k)->append(new QVBoxLayout); tabColLayouts.at(k)->append(new QHBoxLayout); tabLayouts.at(k)->addLayout(tabRowLayouts.at(k)->at(0)); tabRowLayouts.at(k)->at(0)->addLayout(tabColLayouts.at(k)->at(0)); int i = 1; int j = 0; while(i < tabGameFrames.at(k)->size() + 1) { tabColLayouts.at(k)->at(j)->addWidget(tabGameFrames.at(k)->at(i - 1)); if(i % maxGamesFramesPerRow == 0) { tabColLayouts.at(k)->append(new QHBoxLayout); j++; tabRowLayouts.at(k)->at(0)->addLayout(tabColLayouts.at(k)->at(j)); } i++; } int p = maxGamesFramesPerRow - (tabGameFrames.at(k)->size() % maxGamesFramesPerRow); while(p > 0) { tabColLayouts.at(k)->at(j)->addSpacerItem(new QSpacerItem(gameFrameWidth, 0)); p--; } tabWrappers.at(k)->setLayout(tabLayouts.at(k)); tabScrollAreas.at(k)->setWidget(tabWrappers.at(k)); } } } void LibraryWidget::onUpdate() { QList<int> gameCount; for(int i = 0; i < tabGameFrames.size(); i++){ gameCount.append(tabGameFrames.at(i)->size()); } controller->api->myOwnedKeys([this](QList<DownloadKey> keys) { onMyPurchasedKeys(keys); }); controller->api->myClaimedKeys([this](QList<DownloadKey> keys) { onMyClaimedKeys(keys); }); for(int i = 0; i < tabGameFrames.size(); i++){ if(gameCount.at(i) != tabGameFrames.at(i)->size()){ adjustTabLayouts(); break; } } } LibraryWidget::~LibraryWidget() { delete ui; } <commit_msg>Library updates now send tray notifications.<commit_after>#include <QSizePolicy> #include <QSpacerItem> #include <QtDebug> #include "librarywidget.h" #include "ui_librarywidget.h" LibraryWidget::LibraryWidget(QWidget* const parent, AppController* const controller) : QWidget(parent) , ui(new Ui::LibraryWidget) , controller(controller) { ui->setupUi(this); tabGameFrames << new QList<GameFrame*> << new QList<GameFrame*>; tabScrollAreas << new QScrollArea() << new QScrollArea(); tabWrappers << new QWidget << new QWidget; tabLayouts << new QVBoxLayout() << new QVBoxLayout(); tabRowLayouts << new QList<QVBoxLayout*> << new QList<QVBoxLayout*>; tabColLayouts << new QList<QHBoxLayout*> << new QList<QHBoxLayout*>; for(int i = 0; i < tabScrollAreas.size(); i++){ tabScrollAreas.at(i)->setObjectName("gamesScroller"); tabWrappers.at(i)->setObjectName("scrollWrapper"); } controller->api->myOwnedKeys([this](QList<DownloadKey> keys) { onMyPurchasedKeys(keys); }); controller->api->myClaimedKeys([this](QList<DownloadKey> keys) { onMyClaimedKeys(keys); }); updateTimer = new QTimer(this); connect(updateTimer, &QTimer::timeout, this, &LibraryWidget::onUpdate); updateTimer->start(60000); } void LibraryWidget::onMyPurchasedKeys(QList<DownloadKey> downloadKeys) { QList<GameFrame*> gameFrames; int repeatCount = 0; foreach (DownloadKey key, downloadKeys) { for(int i = 0; i < tabGameFrames.at(0)->size(); i++){ if(key.game.id == tabGameFrames.at(0)->at(i)->game.id){ repeatCount++; } } if(repeatCount == 0){ gameFrames << new GameFrame(this, key.game, key, controller); } } if(!gameFrames.isEmpty()){ tabGameFrames.at(0)->append(gameFrames); } if(tabSetupCount < 2){ addGamesTab("Purchased", 0); } } void LibraryWidget::onMyClaimedKeys(QList<DownloadKey> downloadKeys) { QList<GameFrame*> gameFrames; int repeatCount = 0; foreach (DownloadKey key, downloadKeys) { for(int i = 0; i < tabGameFrames.at(1)->size(); i++){ if(key.game.id == tabGameFrames.at(1)->at(i)->game.id){ repeatCount++; } } if(repeatCount == 0){ gameFrames << new GameFrame(this, key.game, key, controller); } } if(!gameFrames.isEmpty()){ tabGameFrames.at(1)->append(gameFrames); } if(tabSetupCount < 2){ addGamesTab("Claimed", 1); } } void LibraryWidget::addGamesTab(const QString& title, int tab) { tabRowLayouts.at(tab)->append(new QVBoxLayout); tabColLayouts.at(tab)->append(new QHBoxLayout); tabLayouts.at(tab)->addLayout(tabRowLayouts.at(tab)->at(0)); tabRowLayouts.at(tab)->at(0)->addLayout(tabColLayouts.at(tab)->at(0)); maxGamesFramesPerRow = (ui->tabWidget->width() - 80) / gameFrameWidth; int i = 1; int j = 0; while(i < tabGameFrames.at(tab)->size() + 1) { tabColLayouts.at(tab)->at(j)->addWidget(tabGameFrames.at(tab)->at(i - 1)); if(i % maxGamesFramesPerRow == 0) { tabColLayouts.at(tab)->append(new QHBoxLayout); j++; tabRowLayouts.at(tab)->at(0)->addLayout(tabColLayouts.at(tab)->at(j)); } i++; } int p = maxGamesFramesPerRow - (tabGameFrames.at(tab)->size() % maxGamesFramesPerRow); while(p > 0) { tabColLayouts.at(tab)->at(j)->addSpacerItem(new QSpacerItem(gameFrameWidth, 0)); p--; } tabWrappers.at(tab)->setLayout(tabLayouts.at(tab)); tabScrollAreas.at(tab)->setWidget(tabWrappers.at(tab)); ui->tabWidget->addTab(tabScrollAreas.at(tab), title); tabSetupCount++; } void LibraryWidget::resizeEvent(QResizeEvent *event) { event->accept(); if(tabSetupCount == 2) { adjustTabLayouts(); } } void LibraryWidget::adjustTabLayouts() { if((ui->tabWidget->width() - 80) / gameFrameWidth != maxGamesFramesPerRow){ maxGamesFramesPerRow = (ui->tabWidget->width() - 80) / gameFrameWidth; tabWrappers.clear(); tabLayouts.clear(); for(int i = 0; i < tabScrollAreas.size(); i++){ tabRowLayouts.at(i)->clear(); tabColLayouts.at(i)->clear(); } tabWrappers << new QWidget << new QWidget; tabLayouts << new QVBoxLayout() << new QVBoxLayout(); tabRowLayouts << new QList<QVBoxLayout*> << new QList<QVBoxLayout*>; tabColLayouts << new QList<QHBoxLayout*> << new QList<QHBoxLayout*>; for(int k = 0; k < tabScrollAreas.size(); k++){ tabWrappers.at(k)->setObjectName("scrollWrapper"); tabRowLayouts.at(k)->append(new QVBoxLayout); tabColLayouts.at(k)->append(new QHBoxLayout); tabLayouts.at(k)->addLayout(tabRowLayouts.at(k)->at(0)); tabRowLayouts.at(k)->at(0)->addLayout(tabColLayouts.at(k)->at(0)); int i = 1; int j = 0; while(i < tabGameFrames.at(k)->size() + 1) { tabColLayouts.at(k)->at(j)->addWidget(tabGameFrames.at(k)->at(i - 1)); if(i % maxGamesFramesPerRow == 0) { tabColLayouts.at(k)->append(new QHBoxLayout); j++; tabRowLayouts.at(k)->at(0)->addLayout(tabColLayouts.at(k)->at(j)); } i++; } int p = maxGamesFramesPerRow - (tabGameFrames.at(k)->size() % maxGamesFramesPerRow); while(p > 0) { tabColLayouts.at(k)->at(j)->addSpacerItem(new QSpacerItem(gameFrameWidth, 0)); p--; } tabWrappers.at(k)->setLayout(tabLayouts.at(k)); tabScrollAreas.at(k)->setWidget(tabWrappers.at(k)); } } } void LibraryWidget::onUpdate() { QList<int> gameCount; for(int i = 0; i < tabGameFrames.size(); i++){ gameCount.append(tabGameFrames.at(i)->size()); } controller->api->myOwnedKeys([this](QList<DownloadKey> keys) { onMyPurchasedKeys(keys); }); controller->api->myClaimedKeys([this](QList<DownloadKey> keys) { onMyClaimedKeys(keys); }); for(int i = 0; i < tabGameFrames.size(); i++){ if(gameCount.at(i) != tabGameFrames.at(i)->size()){ adjustTabLayouts(); controller->showTrayIconNotification(TrayNotifications::LIBRARY_UPDATE_AVAILABLE, "New games are available to download."); break; } } } LibraryWidget::~LibraryWidget() { delete ui; } <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: matlab/private/test.cpp * * Copyright 2016 Patrik Huber * * 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 "mexplus.h" #include "mex.h" //#include "matrix.h" #include <iostream> void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check for proper number of input and output arguments: mexPrintf("nlhs: %d, nrhs: %d\n", nlhs, nrhs); if (nrhs != 2) { mexErrMsgIdAndTxt("eos:example:nargin", "example requires two input arguments."); } else if (nlhs >= 1) { mexErrMsgIdAndTxt("eos:example:nargout", "example requires no output argument."); } double *vin1, *vin2; vin1 = (double*)mxGetPr(prhs[0]); vin2 = (double*)mxGetPr(prhs[1]); mexPrintf("%f, %f\n", *vin1, *vin2); }; void func() { int x = 4; }; int func1() { return 5; }; class MyClass { public: MyClass() = default; int test() { return 6; }; }; <commit_msg>Working prototype of Eigen <=> Matlab conversion<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: matlab/private/test.cpp * * Copyright 2016 Patrik Huber * * 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 "mexplus.h" #include "Eigen/Core" #include "mex.h" //#include "matrix.h" #include <iostream> namespace mexplus { // Define template specialisations for Eigen::MatrixXd: template<> mxArray* MxArray::from(const Eigen::MatrixXd& eigen_matrix) { const int num_rows = static_cast<int>(eigen_matrix.rows()); const int num_cols = static_cast<int>(eigen_matrix.cols()); MxArray out_array(MxArray::Numeric<double>(num_rows, num_cols)); // This might not copy the data but it's evil and probably really dangerous!!!: //mxSetData(const_cast<mxArray*>(matrix.get()), (void*)value.data()); // This copies the data. But I suppose it makes sense that we copy the data when we go // from C++ to Matlab, since Matlab can unload the C++ mex module at any time I think. // Loop is column-wise for (int c = 0; c < num_cols; ++c) { for (int r = 0; r < num_rows; ++r) { out_array.set(r, c, eigen_matrix(r, c)); } } return out_array.release(); }; template<> void MxArray::to(const mxArray* in_array, Eigen::MatrixXd* eigen_matrix) { MxArray array(in_array); if (array.dimensionSize() > 2) { mexErrMsgIdAndTxt("eos:matlab", "Given array has > 2 dimensions. Can only create 2-dimensional matrices (and vectors)."); } if (array.dimensionSize() == 1 || array.dimensionSize() == 0) { mexErrMsgIdAndTxt("eos:matlab", "Given array has 0 or 1 dimensions but we expected a 2-dimensional matrix (or row/column vector)."); // Even when given a single value dimensionSize() is 2, with n=m=1. When does this happen? } if (!array.isDouble()) { mexErrMsgIdAndTxt("eos:matlab", "Trying to create a Eigen::MatrixXd in C++, but the given data is not of type double."); } // We can be sure now that the array is 2-dimensional (or 0, but then we're screwed anyway) auto nrows = array.dimensions()[0]; // or use array.rows() auto ncols = array.dimensions()[1]; // I think I can just use Eigen::Matrix, not a Map - the Matrix c'tor that we call creates a Map anyway? Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>> eigen_map(array.getData<double>(), nrows, ncols); // Not sure that's alright - who owns the data? I think as it is now, everything points to the data in the mxArray owned by Matlab, but I'm not 100% sure. *eigen_matrix = eigen_map; }; } // namespace mexplus using namespace mexplus; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { using std::vector; // Check for proper number of input and output arguments: mexPrintf("nlhs: %d, nrhs: %d\n", nlhs, nrhs); if (nrhs != 2) { mexErrMsgIdAndTxt("eos:example:nargin", "Example requires two input arguments."); } else if (nlhs >= 2) { // 'nlhs >= 1' means no output argument apparently? mexErrMsgIdAndTxt("eos:example:nargout", "Example requires zero or one output arguments."); } InputArguments input(nrhs, prhs, 2); double vin1 = input.get<double>(0); // Matlab stores col-wise in memory - hence the entry of the second row comes first auto vin2 = input.get<vector<double>>(1); /* auto test = input[1]; MxArray mxa(test); auto ndim = mxa.dimensionSize(); auto nrows = mxa.dimensions()[0]; auto ncols = mxa.dimensions()[1]; Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>> em(vin2.data(), 2, 3); // ==> Yes, now I can put exactly this in the MxArray namespace! std::stringstream ss; ss << em; std::string msg = ss.str(); */ //auto x = MxArray::Numeric<double>(2, 2); auto asdf = input.get<Eigen::MatrixXd>(1); std::stringstream ss2; ss2 << asdf; std::string msg2 = ss2.str(); OutputArguments output(nlhs, plhs, 1); output.set(0, asdf); //double *vin1, *vin2; //vin1 = (double*)mxGetPr(prhs[0]); //vin2 = (double*)mxGetPr(prhs[1]); mexPrintf("%f, %f\n", vin1, vin2[0]); }; void func() { int x = 4; }; int func1() { return 5; }; class MyClass { public: MyClass() = default; int test() { return 6; }; }; <|endoftext|>
<commit_before>/* * Copyright (C) 2012-2016 Max Kellermann <max@duempel.org> * * 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 * FOUNDATION 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. */ #ifndef FILE_DESCRIPTOR_HXX #define FILE_DESCRIPTOR_HXX #include <inline/compiler.h> #include <utility> #include <assert.h> #include <unistd.h> #include <sys/types.h> #ifdef __linux__ #define HAVE_POSIX #define HAVE_EVENTFD #define HAVE_SIGNALFD #define HAVE_INOTIFY #include <signal.h> #endif /** * An OO wrapper for a UNIX file descriptor. * * This class is unmanaged and trivial; for a managed version, see * #UniqueFileDescriptor. */ class FileDescriptor { protected: int fd; public: FileDescriptor() = default; explicit constexpr FileDescriptor(int _fd):fd(_fd) {} constexpr bool operator==(FileDescriptor other) const { return fd == other.fd; } constexpr bool operator!=(FileDescriptor other) const { return fd != other.fd; } constexpr bool IsDefined() const { return fd >= 0; } /** * Returns the file descriptor. This may only be called if * IsDefined() returns true. */ constexpr int Get() const { return fd; } void Set(int _fd) { fd = _fd; } int Steal() { assert(IsDefined()); return std::exchange(fd, -1); } void SetUndefined() { fd = -1; } static constexpr FileDescriptor Undefined() { return FileDescriptor(-1); } bool Open(const char *pathname, int flags, mode_t mode=0666); bool OpenReadOnly(const char *pathname); #ifdef HAVE_POSIX bool OpenNonBlocking(const char *pathname); static bool CreatePipe(FileDescriptor &r, FileDescriptor &w); /** * Enable non-blocking mode on this file descriptor. */ void SetNonBlocking(); /** * Enable blocking mode on this file descriptor. */ void SetBlocking(); /** * Auto-close this file descriptor when a new program is * executed. */ void EnableCloseOnExec(); /** * Do not auto-close this file descriptor when a new program * is executed. */ void DisableCloseOnExec(); /** * Duplicate the file descriptor onto the given file descriptor. */ bool Duplicate(FileDescriptor new_fd) const { return ::dup2(Get(), new_fd.Get()) == 0; } /** * Similar to Duplicate(), but if destination and source file * descriptor are equal, clear the close-on-exec flag. Use * this method to inject file descriptors into a new child * process, to be used by a newly executed program. */ bool CheckDuplicate(FileDescriptor new_fd); #endif #ifdef HAVE_EVENTFD bool CreateEventFD(unsigned initval=0); #endif #ifdef HAVE_SIGNALFD bool CreateSignalFD(const sigset_t *mask); #endif #ifdef HAVE_INOTIFY bool CreateInotify(); #endif /** * Close the file descriptor. It should not be called on an * "undefined" object. After this call, IsDefined() is guaranteed * to return false, and this object may be reused. */ bool Close() { return ::close(Steal()) == 0; } /** * Rewind the pointer to the beginning of the file. */ bool Rewind(); off_t Seek(off_t offset) { return lseek(Get(), offset, SEEK_SET); } off_t Skip(off_t offset) { return lseek(Get(), offset, SEEK_CUR); } gcc_pure off_t Tell() const { return lseek(Get(), 0, SEEK_CUR); } /** * Returns the size of the file in bytes, or -1 on error. */ gcc_pure off_t GetSize() const; ssize_t Read(void *buffer, size_t length) { return ::read(fd, buffer, length); } ssize_t Write(const void *buffer, size_t length) { return ::write(fd, buffer, length); } #ifdef HAVE_POSIX int Poll(short events, int timeout) const; int WaitReadable(int timeout) const; int WaitWritable(int timeout) const; gcc_pure bool IsReadyForWriting() const; #endif }; #endif <commit_msg>io/FileDescriptor: remove assertion from Steal(), allow on undefined instance<commit_after>/* * Copyright (C) 2012-2016 Max Kellermann <max@duempel.org> * * 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 * FOUNDATION 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. */ #ifndef FILE_DESCRIPTOR_HXX #define FILE_DESCRIPTOR_HXX #include <inline/compiler.h> #include <utility> #include <assert.h> #include <unistd.h> #include <sys/types.h> #ifdef __linux__ #define HAVE_POSIX #define HAVE_EVENTFD #define HAVE_SIGNALFD #define HAVE_INOTIFY #include <signal.h> #endif /** * An OO wrapper for a UNIX file descriptor. * * This class is unmanaged and trivial; for a managed version, see * #UniqueFileDescriptor. */ class FileDescriptor { protected: int fd; public: FileDescriptor() = default; explicit constexpr FileDescriptor(int _fd):fd(_fd) {} constexpr bool operator==(FileDescriptor other) const { return fd == other.fd; } constexpr bool operator!=(FileDescriptor other) const { return fd != other.fd; } constexpr bool IsDefined() const { return fd >= 0; } /** * Returns the file descriptor. This may only be called if * IsDefined() returns true. */ constexpr int Get() const { return fd; } void Set(int _fd) { fd = _fd; } int Steal() { return std::exchange(fd, -1); } void SetUndefined() { fd = -1; } static constexpr FileDescriptor Undefined() { return FileDescriptor(-1); } bool Open(const char *pathname, int flags, mode_t mode=0666); bool OpenReadOnly(const char *pathname); #ifdef HAVE_POSIX bool OpenNonBlocking(const char *pathname); static bool CreatePipe(FileDescriptor &r, FileDescriptor &w); /** * Enable non-blocking mode on this file descriptor. */ void SetNonBlocking(); /** * Enable blocking mode on this file descriptor. */ void SetBlocking(); /** * Auto-close this file descriptor when a new program is * executed. */ void EnableCloseOnExec(); /** * Do not auto-close this file descriptor when a new program * is executed. */ void DisableCloseOnExec(); /** * Duplicate the file descriptor onto the given file descriptor. */ bool Duplicate(FileDescriptor new_fd) const { return ::dup2(Get(), new_fd.Get()) == 0; } /** * Similar to Duplicate(), but if destination and source file * descriptor are equal, clear the close-on-exec flag. Use * this method to inject file descriptors into a new child * process, to be used by a newly executed program. */ bool CheckDuplicate(FileDescriptor new_fd); #endif #ifdef HAVE_EVENTFD bool CreateEventFD(unsigned initval=0); #endif #ifdef HAVE_SIGNALFD bool CreateSignalFD(const sigset_t *mask); #endif #ifdef HAVE_INOTIFY bool CreateInotify(); #endif /** * Close the file descriptor. It should not be called on an * "undefined" object. After this call, IsDefined() is guaranteed * to return false, and this object may be reused. */ bool Close() { assert(IsDefined()); return ::close(Steal()) == 0; } /** * Rewind the pointer to the beginning of the file. */ bool Rewind(); off_t Seek(off_t offset) { return lseek(Get(), offset, SEEK_SET); } off_t Skip(off_t offset) { return lseek(Get(), offset, SEEK_CUR); } gcc_pure off_t Tell() const { return lseek(Get(), 0, SEEK_CUR); } /** * Returns the size of the file in bytes, or -1 on error. */ gcc_pure off_t GetSize() const; ssize_t Read(void *buffer, size_t length) { return ::read(fd, buffer, length); } ssize_t Write(const void *buffer, size_t length) { return ::write(fd, buffer, length); } #ifdef HAVE_POSIX int Poll(short events, int timeout) const; int WaitReadable(int timeout) const; int WaitWritable(int timeout) const; gcc_pure bool IsReadyForWriting() const; #endif }; #endif <|endoftext|>
<commit_before>#include "application.h" // POSIX++ #include <cstring> // for strerror() #include <cstdlib> // for exit // STL #include <atomic> #include <list> // PUT #include <cxxutils/vterm.h> // atomic vars are to avoid race conditions static std::atomic_int s_return_value (0); static std::atomic_bool s_run (true); // quit signal posix::lockable<std::queue<vfunc>> Application::ms_signal_queue; static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; // execution stepper pipe enum { Read = 0, Write = 1, }; Application::Application(void) noexcept { if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe hasn't been initialized yet { flaw(!posix::pipe(s_pipeio), terminal::critical, std::exit(errno),, "Unable to create pipe for execution stepper: %s", std::strerror(errno)) posix::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC); // close on exec*() posix::donotblock(s_pipeio[Read]); // don't block flaw(!EventBackend::add(s_pipeio[Read], EventBackend::SimplePollReadFlags, read), terminal::critical, std::exit(errno),, // watch for when execution stepper pipe has been triggered "Unable to watch execution stepper to backend: %s", std::strerror(errno)) } } void Application::step(void) noexcept { static const uint8_t dummydata = 0; // dummy content flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, std::exit(errno),, // triggers execution stepper FD "Unable to trigger Object signal queue processor: %s", std::strerror(errno)) } // this is the callback function for the signal queue void Application::read(posix::fd_t fd, native_flags_t) noexcept { uint64_t discard; while(posix::read(fd, &discard, sizeof(discard)) != posix::error_response); // execute queue of object signal calls static std::queue<vfunc> exec_queue; if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?) { ms_signal_queue.lock(); // get exclusive access (make thread-safe) exec_queue.swap(ms_signal_queue); // swap the queues ms_signal_queue.unlock(); // access is no longer needed while(!exec_queue.empty()) // while still have object signals to execute { exec_queue.front()(); // execute current object signal/callback exec_queue.pop(); // discard current object signal } } } int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists { while(s_run) // while not quitting { EventBackend::poll(); // get event queue results for(std::pair<posix::fd_t, native_flags_t>& pair : EventBackend::results) // process results { EventBackend::queue.lock(); // get exclusive access (make thread-safe) auto entries = EventBackend::queue.equal_range(pair.first); // get all the entries for that FD std::list<std::pair<posix::fd_t, EventBackend::callback_info_t>> exec_fds(entries.first, entries.second); // copy entries EventBackend::queue.unlock(); // access is no longer needed for(std::pair<posix::fd_t, EventBackend::callback_info_t>& entry : exec_fds) // for each FD if(entry.second.flags & pair.second) // check if there is a matching flag entry.second.function(pair.first, pair.second); // invoke the callback function with the FD and triggering Flag } } return s_return_value; // quit() has been called, return value specified } void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete) { if(s_run) // if not already quitting { s_return_value = return_value; // set application return value s_run = false; // indicate program must quit } } <commit_msg>set run value upon exec()<commit_after>#include "application.h" // POSIX++ #include <cstring> // for strerror() #include <cstdlib> // for exit // STL #include <atomic> #include <list> // PUT #include <cxxutils/vterm.h> // atomic vars are to avoid race conditions static std::atomic_int s_return_value (0); static std::atomic_bool s_run (true); // quit signal posix::lockable<std::queue<vfunc>> Application::ms_signal_queue; static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; // execution stepper pipe enum { Read = 0, Write = 1, }; Application::Application(void) noexcept { if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe hasn't been initialized yet { flaw(!posix::pipe(s_pipeio), terminal::critical, std::exit(errno),, "Unable to create pipe for execution stepper: %s", std::strerror(errno)) posix::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC); // close on exec*() posix::donotblock(s_pipeio[Read]); // don't block flaw(!EventBackend::add(s_pipeio[Read], EventBackend::SimplePollReadFlags, read), terminal::critical, std::exit(errno),, // watch for when execution stepper pipe has been triggered "Unable to watch execution stepper to backend: %s", std::strerror(errno)) } } void Application::step(void) noexcept { static const uint8_t dummydata = 0; // dummy content flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, std::exit(errno),, // triggers execution stepper FD "Unable to trigger Object signal queue processor: %s", std::strerror(errno)) } // this is the callback function for the signal queue void Application::read(posix::fd_t fd, native_flags_t) noexcept { uint64_t discard; while(posix::read(fd, &discard, sizeof(discard)) != posix::error_response); // execute queue of object signal calls static std::queue<vfunc> exec_queue; if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?) { ms_signal_queue.lock(); // get exclusive access (make thread-safe) exec_queue.swap(ms_signal_queue); // swap the queues ms_signal_queue.unlock(); // access is no longer needed while(!exec_queue.empty()) // while still have object signals to execute { exec_queue.front()(); // execute current object signal/callback exec_queue.pop(); // discard current object signal } } } int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists { s_run = true; while(s_run) // while not quitting { EventBackend::poll(); // get event queue results for(std::pair<posix::fd_t, native_flags_t>& pair : EventBackend::results) // process results { EventBackend::queue.lock(); // get exclusive access (make thread-safe) auto entries = EventBackend::queue.equal_range(pair.first); // get all the entries for that FD std::list<std::pair<posix::fd_t, EventBackend::callback_info_t>> exec_fds(entries.first, entries.second); // copy entries EventBackend::queue.unlock(); // access is no longer needed for(std::pair<posix::fd_t, EventBackend::callback_info_t>& entry : exec_fds) // for each FD if(entry.second.flags & pair.second) // check if there is a matching flag entry.second.function(pair.first, pair.second); // invoke the callback function with the FD and triggering Flag } } return s_return_value; // quit() has been called, return value specified } void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete) { if(s_run) // if not already quitting { s_return_value = return_value; // set application return value s_run = false; // indicate program must quit } } <|endoftext|>
<commit_before>#include "diskinfo.hpp" #include <sys/stat.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <string> #include <iostream> #include <fstream> #include <vector> #include <set> #include "logger.hpp" #include "config/cmd_args.hpp" const char *partitions_path = "/proc/partitions"; const char *hdparm_path = "/sbin/hdparm"; struct partition_info_t { partition_info_t(); partition_info_t(int nmajor, int nminor, int nblocks, std::string name); int nmajor; int nminor; int nblocks; std::string name; }; void get_partition_map(std::vector<partition_info_t> &partitions); partition_info_t::partition_info_t(int nmajor, int nminor, int nblocks, std::string name) : nmajor(nmajor), nminor(nminor), nblocks(nblocks), name(name) { } partition_info_t::partition_info_t() {} void tokenize_line(const std::string& line, std::vector<std::string> &tokens) { /* Given a line and an empty vector to fill in, chops the line up by space * characters and puts the words in the tokens vector. */ size_t start, end = 0; while (end < line.size()) { start = end; while (start < line.size() && line[start] == ' ') { start++; } end = start; while (end < line.size() && line[end] != ' ') { end++; } if (end - start > 0) { tokens.push_back(std::string(line, start, end - start)); } } } void get_partition_map(std::vector<partition_info_t *> &partitions) { /* /proc partitions looks like this: * major minor #blocks name * * 8 0 234234234 sda * 8 1 123948586 sda1 * ... * * The major and minor device numbers are hexadecimal numbers. * To parse we skip the first two lines and then chop up each line into * partition_info_t structs. * */ std::ifstream partitions_file (partitions_path); std::string line; std::vector<std::string> tokens; char *endptr; if (partitions_file.is_open()) { getline(partitions_file, line); getline(partitions_file, line); while (partitions_file.good()) { getline(partitions_file, line); tokens.clear(); tokenize_line(line, tokens); if (tokens.size() != 4) { continue; } partition_info_t *partition = new partition_info_t; partition->nmajor = strtol(tokens[0].c_str(), &endptr, 16); partition->nminor = strtol(tokens[1].c_str(), &endptr, 16); partition->nblocks = strtol(tokens[2].c_str(), &endptr, 10); partition->name = tokens[3]; partition->name.insert(0, std::string("/dev/")); partitions.push_back(partition); } } } void log_disk_info(std::vector<log_serializer_private_dynamic_config_t> &serializers) { std::vector<partition_info_t *> partitions; std::set<std::string> devices; logINF("Disk info for database disks:\n"); struct stat st; if (stat(hdparm_path, &st)) { logWRN("System lacks hdparm; giving up\n"); return; } get_partition_map(partitions); int maj, min = 0; const char *path; mlog_start(INF); for (unsigned int i = 0; i < serializers.size(); i++) { path = serializers[i].db_filename.c_str(); if (stat(path, &st)) { mlogf("Cannot stat \"%s\": %s\n", path, strerror(errno)); continue; } maj = major(st.st_dev); min = minor(st.st_dev); if (maj == 0) { /* We're looking at a device, not a file */ if (strncmp("/dev/ram", path, 8)) { devices.insert(path); } else { /* Don't give ramdisks to hdparm because it won't produce * anything useful. */ mlogf("\n%s:\n RAM disk\n", path); } continue; } for (unsigned int j = 0; j < partitions.size(); j++) { if (partitions[j]->nmajor == maj && partitions[j]->nminor == min) { devices.insert(partitions[j]->name); } } } for (unsigned int i = 0; i < partitions.size(); i++) { delete partitions[i]; } partitions.clear(); if (devices.size() < 1) { /* Don't run hdparm unless we have devices to run it on. */ mlog_end(); return; } std::string cmd; for (std::set<std::string>::iterator it = devices.begin(); it != devices.end(); it++) { cmd.append(std::string(hdparm_path)); cmd.append(std::string(" -iI")); cmd.append(*it); /* Standard error from hdparm isn't useful. */ cmd.append(std::string(" 2>/dev/null; ")); } char *buf = (char *) calloc(1024, sizeof(char)); FILE *stream; size_t total_bytes = 0; size_t nbytes = 0; if (NULL == buf) { crash("out of memory\n"); } if (NULL == (stream = popen(cmd.c_str(), "r"))) { crash("popen failed\n"); } while (1023 == (nbytes = fread(buf, 1, 1023, stream))) { total_bytes += nbytes; mlogf("%s", buf); } if (-1 == pclose(stream)) { mlog_end(); crash("pclose failed\n"); } total_bytes += nbytes; buf[nbytes + 1] = '\0'; if (total_bytes < 5) { /* No output. We didn't have enough permissions to run hdparm.*/ mlogf("Must be root or part of group `disk' to get disk info.\n"); } else { mlogf("%s\n", buf); } mlog_end(); free(buf); } <commit_msg>Handle disks that don't support info querying<commit_after>#include "diskinfo.hpp" #include <sys/stat.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <string> #include <iostream> #include <fstream> #include <vector> #include <set> #include "logger.hpp" #include "config/cmd_args.hpp" const char *partitions_path = "/proc/partitions"; const char *hdparm_path = "/sbin/hdparm"; struct partition_info_t { partition_info_t(); partition_info_t(int nmajor, int nminor, int nblocks, std::string name); int nmajor; int nminor; int nblocks; std::string name; }; void get_partition_map(std::vector<partition_info_t> &partitions); partition_info_t::partition_info_t(int nmajor, int nminor, int nblocks, std::string name) : nmajor(nmajor), nminor(nminor), nblocks(nblocks), name(name) { } partition_info_t::partition_info_t() {} void tokenize_line(const std::string& line, std::vector<std::string> &tokens) { /* Given a line and an empty vector to fill in, chops the line up by space * characters and puts the words in the tokens vector. */ size_t start, end = 0; while (end < line.size()) { start = end; while (start < line.size() && line[start] == ' ') { start++; } end = start; while (end < line.size() && line[end] != ' ') { end++; } if (end - start > 0) { tokens.push_back(std::string(line, start, end - start)); } } } void get_partition_map(std::vector<partition_info_t *> &partitions) { /* /proc partitions looks like this: * major minor #blocks name * * 8 0 234234234 sda * 8 1 123948586 sda1 * ... * * The major and minor device numbers are hexadecimal numbers. * To parse we skip the first two lines and then chop up each line into * partition_info_t structs. * */ std::ifstream partitions_file (partitions_path); std::string line; std::vector<std::string> tokens; char *endptr; if (partitions_file.is_open()) { getline(partitions_file, line); getline(partitions_file, line); while (partitions_file.good()) { getline(partitions_file, line); tokens.clear(); tokenize_line(line, tokens); if (tokens.size() != 4) { continue; } partition_info_t *partition = new partition_info_t; partition->nmajor = strtol(tokens[0].c_str(), &endptr, 16); partition->nminor = strtol(tokens[1].c_str(), &endptr, 16); partition->nblocks = strtol(tokens[2].c_str(), &endptr, 10); partition->name = tokens[3]; partition->name.insert(0, std::string("/dev/")); partitions.push_back(partition); } } } void log_disk_info(std::vector<log_serializer_private_dynamic_config_t> &serializers) { std::vector<partition_info_t *> partitions; std::set<std::string> devices; logINF("Disk info for database disks:\n"); struct stat st; if (stat(hdparm_path, &st)) { logWRN("System lacks hdparm; giving up\n"); return; } get_partition_map(partitions); int maj, min = 0; const char *path; const char *dev_path; uid_t uid = geteuid(); int device_idx; mlog_start(INF); for (unsigned int i = 0; i < serializers.size(); i++) { path = serializers[i].db_filename.c_str(); if (stat(path, &st)) { mlogf("Cannot stat \"%s\": %s\n", path, strerror(errno)); continue; } maj = major(st.st_dev); min = minor(st.st_dev); if (maj == 0) { /* We're looking at a device, not a file */ if (strncmp("/dev/ram", path, 8)) { devices.insert(path); } else { /* Don't give ramdisks to hdparm because it won't produce * anything useful. */ mlogf("\n%s:\n RAM disk\n", path); } continue; } device_idx = -1; for (unsigned int j = 0; j < partitions.size(); j++) { if (partitions[j]->nmajor == maj && partitions[j]->nminor == min) { device_idx = j; break; } } if (device_idx != -1) { dev_path = partitions[device_idx]->name.c_str(); if (stat(dev_path, &st)) { mlogf("Cannot stat \"%s\": %s\n", dev_path, strerror(errno)); continue; } if (S_ISDIR(st.st_mode) || S_ISFIFO(st.st_mode)) { mlogf("Invalid database file: \"%s\"\n", dev_path); continue; } if (-1 == access(dev_path, R_OK | W_OK) && 0 != uid) { mlogf("Must be root or have write permissions on \"%s\" to get disk info.\n", dev_path); continue; } devices.insert(partitions[device_idx]->name); } } for (unsigned int i = 0; i < partitions.size(); i++) { delete partitions[i]; } partitions.clear(); if (devices.size() < 1) { /* Don't run hdparm unless we have devices to run it on. */ mlog_end(); return; } std::string cmd; for (std::set<std::string>::iterator it = devices.begin(); it != devices.end(); it++) { cmd.append(std::string(hdparm_path)); cmd.append(std::string(" -iI ")); cmd.append(*it); /* Standard error from hdparm isn't useful. */ cmd.append(std::string(" 2>/dev/null; ")); } printf("%s\n", cmd.c_str()); char *buf = (char *) calloc(1024, sizeof(char)); FILE *stream; size_t total_bytes = 0; size_t nbytes = 0; if (NULL == buf) { crash("out of memory\n"); } if (NULL == (stream = popen(cmd.c_str(), "r"))) { crash("popen failed\n"); } while (1023 == (nbytes = fread(buf, 1, 1023, stream))) { total_bytes += nbytes; mlogf("%s", buf); } if (-1 == pclose(stream)) { mlog_end(); crash("pclose failed\n"); } total_bytes += nbytes; buf[nbytes] = '\0'; if (total_bytes < 20 * devices.size()) { /* No output. We didn't have enough permissions to run hdparm.*/ mlogf("None of the supplied disks support disk info queries.\n"); } else { mlogf("%s\n", buf); } mlog_end(); free(buf); } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <aidu_mobile_base/motor.h> #include <threemxl/C3mxlROS.h> #include <XMLConfiguration.h> #include <string> using namespace aidu; mobile_base::Motor::Motor(std::string name, std::string motor_port_name, std::string motor_config_name, double radiusWheel) { // Load motor configuration CXMLConfiguration motor_config_xml; motor_config_xml.loadFile(motor_config_name); // ThreeMXL initialization // Create configuration config = new CDxlConfig(); config->readConfig(motor_config_xml.root().section(name.c_str())); this->name = name; // Create and configure 3mxl motor motor = new C3mxlROS(motor_port_name.c_str()); motor->setWheelDiameter(radiusWheel * 2.0); motor->setConfig(config); motor->init(); motor->set3MxlMode(POSITION_MODE); currentVelocity = 0; } void mobile_base::Motor::setVelocity(float velocity) { if (fabs(velocity-currentVelocity) > 0.01) { currentVelocity = velocity; // Send velocity to the 3mxl board ROS_INFO("%s: Setting velocity to %f", name.c_str(), velocity); // Check mode of 3mxl motor->get3MxlMode(); if(motor->present3MxlMode() != SPEED_MODE){ motor->set3MxlMode(SPEED_MODE); } // Send speed to 3mxl motor->setSpeed(velocity); } } void mobile_base::Motor::setPosition(float position) { // Send velocity to the 3mxl board ROS_INFO("%s: Setting position to %f", name.c_str(), position); // Check mode of 3mxl motor->get3MxlMode(); if(motor->present3MxlMode() != POSITION_MODE){ motor->set3MxlMode(POSITION_MODE); } // Send position to 3mxl motor->setPos(position); } mobile_base::Motor::~Motor(){ motor->setSpeed(0); serial_port->port_close(); delete config; delete motor; delete serial_port; } <commit_msg>Placed wheel diamater setting of motor after the init<commit_after>#include <ros/ros.h> #include <aidu_mobile_base/motor.h> #include <threemxl/C3mxlROS.h> #include <XMLConfiguration.h> #include <string> using namespace aidu; mobile_base::Motor::Motor(std::string name, std::string motor_port_name, std::string motor_config_name, double radiusWheel) { // Load motor configuration CXMLConfiguration motor_config_xml; motor_config_xml.loadFile(motor_config_name); // ThreeMXL initialization // Create configuration config = new CDxlConfig(); config->readConfig(motor_config_xml.root().section(name.c_str())); this->name = name; // Create and configure 3mxl motor motor = new C3mxlROS(motor_port_name.c_str()); motor->setConfig(config); motor->init(); motor->setWheelDiameter(radiusWheel * 2.0); motor->set3MxlMode(POSITION_MODE); currentVelocity = 0; } void mobile_base::Motor::setVelocity(float velocity) { if (fabs(velocity-currentVelocity) > 0.01) { currentVelocity = velocity; // Send velocity to the 3mxl board ROS_INFO("%s: Setting velocity to %f", name.c_str(), velocity); // Check mode of 3mxl motor->get3MxlMode(); if(motor->present3MxlMode() != SPEED_MODE){ motor->set3MxlMode(SPEED_MODE); } // Send speed to 3mxl motor->setSpeed(velocity); } } void mobile_base::Motor::setPosition(float position) { // Send velocity to the 3mxl board ROS_INFO("%s: Setting position to %f", name.c_str(), position); // Check mode of 3mxl motor->get3MxlMode(); if(motor->present3MxlMode() != POSITION_MODE){ motor->set3MxlMode(POSITION_MODE); } // Send position to 3mxl motor->setPos(position); } mobile_base::Motor::~Motor(){ motor->setSpeed(0); serial_port->port_close(); delete config; delete motor; delete serial_port; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include "ircmessagedecoder_p.h" #include "irccodecplugin.h" #include <QCoreApplication> #include <QPluginLoader> #include <QStringList> #include <QDebug> #include <QMap> #include <QDir> extern "C" { int IsUTF8Text(const char* utf8, int len); } typedef QMap<QByteArray, IrcCodecPlugin*> IrcCodecPluginMap; Q_GLOBAL_STATIC(IrcCodecPluginMap, irc_codec_plugins) static QByteArray irc_plugin_key = qgetenv("COMMUNI_CODEC_PLUGIN"); COMMUNI_EXPORT void irc_set_codec_plugin(const QByteArray& key) { irc_plugin_key = key; } IrcMessageDecoder::IrcMessageDecoder() { d.fallback = QTextCodec::codecForName("ISO-8859-15"); } IrcMessageDecoder::~IrcMessageDecoder() { } QByteArray IrcMessageDecoder::encoding() const { return d.fallback->name(); } void IrcMessageDecoder::setEncoding(const QByteArray& encoding) { if (QTextCodec::availableCodecs().contains(encoding)) d.fallback = QTextCodec::codecForName(encoding); } QString IrcMessageDecoder::decode(const QByteArray& data) const { // TODO: not thread safe static QByteArray pluginKey; static bool initialized = false; if (!initialized) { pluginKey = const_cast<IrcMessageDecoder*>(this)->initialize(); initialized = true; } QTextCodec* codec = 0; if (IsUTF8Text(data, data.length())) { codec = QTextCodec::codecForName("UTF-8"); } else { QByteArray name = d.fallback->name(); IrcCodecPlugin* plugin = irc_codec_plugins()->value(pluginKey); if (plugin) name = plugin->codecForData(data); codec = QTextCodec::codecForName(name); } if (!codec) codec = d.fallback; Q_ASSERT(codec); return codec->toUnicode(data); } QByteArray IrcMessageDecoder::initialize() { bool loaded = loadPlugins(); QByteArray pluginKey = irc_plugin_key; if (!pluginKey.isEmpty() && !irc_codec_plugins()->contains(pluginKey)) { qWarning() << "IrcMessageDecoder:" << pluginKey << "plugin not loaded"; if (loaded) qWarning() << "IrcMessageDecoder: available plugins:" << irc_codec_plugins()->keys(); } if (!loaded) qWarning() << "IrcMessageDecoder: no plugins available"; if (pluginKey.isEmpty() && !irc_codec_plugins()->isEmpty()) pluginKey = irc_codec_plugins()->keys().first(); return pluginKey; } #if defined(Q_OS_WIN) #define COMMUNI_PATH_SEPARATOR ';' #else #define COMMUNI_PATH_SEPARATOR ':' #endif static QStringList pluginPaths() { QStringList paths = QCoreApplication::libraryPaths(); const QByteArray env = qgetenv("COMMUNI_PLUGIN_PATH"); if (!env.isEmpty()) { foreach(const QString & path, QFile::decodeName(env).split(COMMUNI_PATH_SEPARATOR, QString::SkipEmptyParts)) { QString canonicalPath = QDir(path).canonicalPath(); if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath)) paths += canonicalPath; } } static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); if (dbg) qDebug() << "IrcMessageDecoder: dynamic plugin paths:" << paths; return paths; } bool IrcMessageDecoder::loadPlugins() { static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); foreach(QObject* instance, QPluginLoader::staticInstances()) { IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(instance); if (plugin) { irc_codec_plugins()->insert(plugin->key(), plugin); if (dbg) qDebug() << "IrcMessageDecoder: loaded static plugin:" << plugin->key(); } } foreach(const QString & path, pluginPaths()) { QDir dir(path); if (!dir.cd("communi")) continue; foreach(const QFileInfo & file, dir.entryInfoList(QDir::Files)) { QPluginLoader loader(file.absoluteFilePath()); IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(loader.instance()); if (plugin) { irc_codec_plugins()->insert(plugin->key(), plugin); if (dbg) qDebug() << "IrcMessageDecoder: loaded dynamic plugin:" << file.fileName(); } } } return !irc_codec_plugins()->isEmpty(); } <commit_msg>IrcMessageDecoder: pick the last plugin by default<commit_after>/* * Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com> * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. */ #include "ircmessagedecoder_p.h" #include "irccodecplugin.h" #include <QCoreApplication> #include <QPluginLoader> #include <QStringList> #include <QDebug> #include <QMap> #include <QDir> extern "C" { int IsUTF8Text(const char* utf8, int len); } typedef QMap<QByteArray, IrcCodecPlugin*> IrcCodecPluginMap; Q_GLOBAL_STATIC(IrcCodecPluginMap, irc_codec_plugins) static QByteArray irc_plugin_key = qgetenv("COMMUNI_CODEC_PLUGIN"); COMMUNI_EXPORT void irc_set_codec_plugin(const QByteArray& key) { irc_plugin_key = key; } IrcMessageDecoder::IrcMessageDecoder() { d.fallback = QTextCodec::codecForName("ISO-8859-15"); } IrcMessageDecoder::~IrcMessageDecoder() { } QByteArray IrcMessageDecoder::encoding() const { return d.fallback->name(); } void IrcMessageDecoder::setEncoding(const QByteArray& encoding) { if (QTextCodec::availableCodecs().contains(encoding)) d.fallback = QTextCodec::codecForName(encoding); } QString IrcMessageDecoder::decode(const QByteArray& data) const { // TODO: not thread safe static QByteArray pluginKey; static bool initialized = false; if (!initialized) { pluginKey = const_cast<IrcMessageDecoder*>(this)->initialize(); initialized = true; } QTextCodec* codec = 0; if (IsUTF8Text(data, data.length())) { codec = QTextCodec::codecForName("UTF-8"); } else { QByteArray name = d.fallback->name(); IrcCodecPlugin* plugin = irc_codec_plugins()->value(pluginKey); if (plugin) name = plugin->codecForData(data); codec = QTextCodec::codecForName(name); } if (!codec) codec = d.fallback; Q_ASSERT(codec); return codec->toUnicode(data); } QByteArray IrcMessageDecoder::initialize() { bool loaded = loadPlugins(); QByteArray pluginKey = irc_plugin_key; if (!pluginKey.isEmpty() && !irc_codec_plugins()->contains(pluginKey)) { qWarning() << "IrcMessageDecoder:" << pluginKey << "plugin not loaded"; if (loaded) qWarning() << "IrcMessageDecoder: available plugins:" << irc_codec_plugins()->keys(); } if (!loaded) qWarning() << "IrcMessageDecoder: no plugins available"; if (pluginKey.isEmpty() && !irc_codec_plugins()->isEmpty()) pluginKey = irc_codec_plugins()->keys().last(); return pluginKey; } #if defined(Q_OS_WIN) #define COMMUNI_PATH_SEPARATOR ';' #else #define COMMUNI_PATH_SEPARATOR ':' #endif static QStringList pluginPaths() { QStringList paths = QCoreApplication::libraryPaths(); const QByteArray env = qgetenv("COMMUNI_PLUGIN_PATH"); if (!env.isEmpty()) { foreach(const QString & path, QFile::decodeName(env).split(COMMUNI_PATH_SEPARATOR, QString::SkipEmptyParts)) { QString canonicalPath = QDir(path).canonicalPath(); if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath)) paths += canonicalPath; } } static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); if (dbg) qDebug() << "IrcMessageDecoder: dynamic plugin paths:" << paths; return paths; } bool IrcMessageDecoder::loadPlugins() { static bool dbg = qgetenv("COMMUNI_DEBUG").toInt(); foreach(QObject* instance, QPluginLoader::staticInstances()) { IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(instance); if (plugin) { irc_codec_plugins()->insert(plugin->key(), plugin); if (dbg) qDebug() << "IrcMessageDecoder: loaded static plugin:" << plugin->key(); } } foreach(const QString & path, pluginPaths()) { QDir dir(path); if (!dir.cd("communi")) continue; foreach(const QFileInfo & file, dir.entryInfoList(QDir::Files)) { QPluginLoader loader(file.absoluteFilePath()); IrcCodecPlugin* plugin = qobject_cast<IrcCodecPlugin*>(loader.instance()); if (plugin) { irc_codec_plugins()->insert(plugin->key(), plugin); if (dbg) qDebug() << "IrcMessageDecoder: loaded dynamic plugin:" << file.fileName(); } } } return !irc_codec_plugins()->isEmpty(); } <|endoftext|>
<commit_before><commit_msg>Let's check the validity of sheet indices. You never know...<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawvie4.cxx,v $ * * $Revision: 1.28 $ * * last change: $Author: vg $ $Date: 2007-05-22 20:13:10 $ * * 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 _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_ #include <com/sun/star/embed/NoVisualAreaSizeException.hpp> #endif // INCLUDE --------------------------------------------------------------- #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdogrp.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/svdundo.hxx> #include <sfx2/docfile.hxx> #include <tools/urlobj.hxx> #include <toolkit/helper/vclunohelper.hxx> #include "drawview.hxx" #include "global.hxx" #include "drwlayer.hxx" #include "viewdata.hxx" #include "document.hxx" #include "docsh.hxx" #include "drwtrans.hxx" #include "transobj.hxx" // SetDrawClipDoc #include "drawutil.hxx" #include "scmod.hxx" #include "globstr.hrc" #include "chartarr.hxx" using namespace com::sun::star; // STATIC DATA ----------------------------------------------------------- Point aDragStartDiff; // ----------------------------------------------------------------------- //! welche Funktionen aus drawview/drawvie4 muessen wirklich ohne Optimierung sein? #ifdef WNT #pragma optimize ( "", off ) #endif // ----------------------------------------------------------------------- void lcl_CheckOle( const SdrMarkList& rMarkList, BOOL& rAnyOle, BOOL& rOneOle ) { rAnyOle = rOneOle = FALSE; ULONG nCount = rMarkList.GetMarkCount(); for (ULONG i=0; i<nCount; i++) { SdrMark* pMark = rMarkList.GetMark(i); SdrObject* pObj = pMark->GetMarkedSdrObj(); UINT16 nSdrObjKind = pObj->GetObjIdentifier(); if (nSdrObjKind == OBJ_OLE2) { rAnyOle = TRUE; rOneOle = (nCount == 1); break; } else if ( pObj->ISA(SdrObjGroup) ) { SdrObjListIter aIter( *pObj, IM_DEEPNOGROUPS ); SdrObject* pSubObj = aIter.Next(); while (pSubObj) { if ( pSubObj->GetObjIdentifier() == OBJ_OLE2 ) { rAnyOle = TRUE; // rOneOle remains FALSE - a group isn't treated like a single OLE object return; } pSubObj = aIter.Next(); } } } } #if 0 void lcl_RefreshChartData( SdrModel* pModel, ScDocument* pSourceDoc ) { USHORT nPages = pModel->GetPageCount(); for (SCTAB nTab=0; nTab<nPages; nTab++) { SdrPage* pPage = pModel->GetPage(nTab); SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS ); SdrObject* pObject = aIter.Next(); while (pObject) { if ( pObject->GetObjIdentifier() == OBJ_OLE2 ) { SvInPlaceObjectRef aIPObj = ((SdrOle2Obj*)pObject)->GetObjRef(); if ( aIPObj.Is() && SotExchange::IsChart( aIPObj->GetStorage()->GetClassName() ) ) { SchMemChart* pOldData = SchDLL::GetChartData(aIPObj); if ( pOldData ) { // create data from source document ScChartArray aArray( pSourceDoc, *pOldData ); if ( aArray.IsValid() ) { SchMemChart* pNewData = aArray.CreateMemChart(); SchDLL::Update( aIPObj, pNewData ); delete pNewData; ((SdrOle2Obj*)pObject)->GetNewReplacement(); } } } } pObject = aIter.Next(); } } } #endif BOOL ScDrawView::BeginDrag( Window* pWindow, const Point& rStartPos ) { BOOL bReturn = FALSE; if ( AreObjectsMarked() ) { BrkAction(); Rectangle aMarkedRect = GetAllMarkedRect(); Region aRegion( aMarkedRect ); aDragStartDiff = rStartPos - aMarkedRect.TopLeft(); BOOL bAnyOle, bOneOle; const SdrMarkList& rMarkList = GetMarkedObjectList(); lcl_CheckOle( rMarkList, bAnyOle, bOneOle ); ScDocShellRef aDragShellRef; if (bAnyOle) { aDragShellRef = new ScDocShell; // DocShell needs a Ref immediately aDragShellRef->DoInitNew(NULL); } ScDrawLayer::SetGlobalDrawPersist(aDragShellRef); SdrModel* pModel = GetAllMarkedModel(); ScDrawLayer::SetGlobalDrawPersist(NULL); // Charts now always copy their data in addition to the source reference, so // there's no need to call SchDLL::Update for the charts in the clipboard doc. // Update with the data (including NumberFormatter) from the live document would // also store the NumberFormatter in the clipboard chart (#88749#) // lcl_RefreshChartData( pModel, pViewData->GetDocument() ); ScDocShell* pDocSh = pViewData->GetDocShell(); TransferableObjectDescriptor aObjDesc; pDocSh->FillTransferableObjectDescriptor( aObjDesc ); aObjDesc.maDisplayName = pDocSh->GetMedium()->GetURLObject().GetURLNoPass(); // maSize is set in ScDrawTransferObj ctor ScDrawTransferObj* pTransferObj = new ScDrawTransferObj( pModel, pDocSh, aObjDesc ); uno::Reference<datatransfer::XTransferable> xTransferable( pTransferObj ); pTransferObj->SetDrawPersist( &aDragShellRef ); // keep persist for ole objects alive pTransferObj->SetDragSource( this ); // copies selection SC_MOD()->SetDragObject( NULL, pTransferObj ); // for internal D&D pTransferObj->StartDrag( pWindow, DND_ACTION_COPYMOVE | DND_ACTION_LINK ); } return bReturn; } void ScDrawView::DoCopy() { BOOL bAnyOle, bOneOle; const SdrMarkList& rMarkList = GetMarkedObjectList(); lcl_CheckOle( rMarkList, bAnyOle, bOneOle ); // update ScGlobal::pDrawClipDocShellRef ScDrawLayer::SetGlobalDrawPersist( ScTransferObj::SetDrawClipDoc( bAnyOle ) ); SdrModel* pModel = GetAllMarkedModel(); ScDrawLayer::SetGlobalDrawPersist(NULL); // Charts now always copy their data in addition to the source reference, so // there's no need to call SchDLL::Update for the charts in the clipboard doc. // Update with the data (including NumberFormatter) from the live document would // also store the NumberFormatter in the clipboard chart (#88749#) // lcl_RefreshChartData( pModel, pViewData->GetDocument() ); ScDocShell* pDocSh = pViewData->GetDocShell(); TransferableObjectDescriptor aObjDesc; pDocSh->FillTransferableObjectDescriptor( aObjDesc ); aObjDesc.maDisplayName = pDocSh->GetMedium()->GetURLObject().GetURLNoPass(); // maSize is set in ScDrawTransferObj ctor ScDrawTransferObj* pTransferObj = new ScDrawTransferObj( pModel, pDocSh, aObjDesc ); uno::Reference<datatransfer::XTransferable> xTransferable( pTransferObj ); if ( ScGlobal::pDrawClipDocShellRef ) { pTransferObj->SetDrawPersist( &(*ScGlobal::pDrawClipDocShellRef) ); // keep persist for ole objects alive } pTransferObj->CopyToClipboard( pViewData->GetActiveWin() ); // system clipboard SC_MOD()->SetClipObject( NULL, pTransferObj ); // internal clipboard } // Korrektur fuer 100% berechnen, unabhaengig von momentanen Einstellungen void ScDrawView::CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const { Point aLogic = pDev->LogicToPixel( Point(1000,1000), MAP_TWIP ); double nPPTX = ScGlobal::nScreenPPTX; double nPPTY = ScGlobal::nScreenPPTY; if (pViewData) nPPTX /= pViewData->GetDocShell()->GetOutputFactor(); SCCOL nEndCol = 0; SCROW nEndRow = 0; pDoc->GetTableArea( nTab, nEndCol, nEndRow ); if (nEndCol<20) nEndCol = 20; if (nEndRow<20) nEndRow = 20; Fraction aZoom(1,1); ScDrawUtil::CalcScale( pDoc, nTab, 0,0, nEndCol,nEndRow, pDev, aZoom,aZoom, nPPTX, nPPTY, rFractX,rFractY ); } void ScDrawView::SetMarkedOriginalSize() { SdrUndoGroup* pUndoGroup = new SdrUndoGroup(*GetModel()); const SdrMarkList& rMarkList = GetMarkedObjectList(); long nDone = 0; ULONG nCount = rMarkList.GetMarkCount(); for (ULONG i=0; i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetMarkedSdrObj(); USHORT nIdent = pObj->GetObjIdentifier(); BOOL bDo = FALSE; Size aOriginalSize; if (nIdent == OBJ_OLE2) { // TODO/LEAN: working with visual area can switch object to running state uno::Reference < embed::XEmbeddedObject > xObj( ((SdrOle2Obj*)pObj)->GetObjRef(), uno::UNO_QUERY ); if ( xObj.is() ) // #121612# NULL for an invalid object that couldn't be loaded { sal_Int64 nAspect = ((SdrOle2Obj*)pObj)->GetAspect(); if ( nAspect == embed::Aspects::MSOLE_ICON ) { MapMode aMapMode( MAP_100TH_MM ); aOriginalSize = ((SdrOle2Obj*)pObj)->GetOrigObjSize( &aMapMode ); bDo = TRUE; } else { MapUnit aUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( ((SdrOle2Obj*)pObj)->GetAspect() ) ); awt::Size aSz; try { aSz = xObj->getVisualAreaSize( ((SdrOle2Obj*)pObj)->GetAspect() ); aOriginalSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aUnit, MAP_100TH_MM ); bDo = TRUE; } catch( embed::NoVisualAreaSizeException& ) { OSL_ENSURE( sal_False, "Can't get the original size of the object!" ); } } } } else if (nIdent == OBJ_GRAF) { const Graphic& rGraphic = ((SdrGrafObj*)pObj)->GetGraphic(); MapMode aSourceMap = rGraphic.GetPrefMapMode(); MapMode aDestMap( MAP_100TH_MM ); if (aSourceMap.GetMapUnit() == MAP_PIXEL) { // Pixel-Korrektur beruecksichtigen, damit Bitmap auf dem Bildschirm stimmt Fraction aNormScaleX, aNormScaleY; CalcNormScale( aNormScaleX, aNormScaleY ); aDestMap.SetScaleX(aNormScaleX); aDestMap.SetScaleY(aNormScaleY); } if (pViewData) { Window* pActWin = pViewData->GetActiveWin(); if (pActWin) { aOriginalSize = pActWin->LogicToLogic( rGraphic.GetPrefSize(), &aSourceMap, &aDestMap ); bDo = TRUE; } } } if ( bDo ) { Rectangle aDrawRect = pObj->GetLogicRect(); pUndoGroup->AddAction( new SdrUndoGeoObj( *pObj ) ); pObj->Resize( aDrawRect.TopLeft(), Fraction( aOriginalSize.Width(), aDrawRect.GetWidth() ), Fraction( aOriginalSize.Height(), aDrawRect.GetHeight() ) ); ++nDone; } } if (nDone) { pUndoGroup->SetComment(ScGlobal::GetRscString( STR_UNDO_ORIGINALSIZE )); ScDocShell* pDocSh = pViewData->GetDocShell(); pDocSh->GetUndoManager()->AddUndoAction(pUndoGroup); pDocSh->SetDrawModified(); } else delete pUndoGroup; } #ifdef WNT #pragma optimize ( "", on ) #endif <commit_msg>INTEGRATION: CWS c09tosrc (1.28.38); FILE MERGED 2007/06/20 11:29:17 cd 1.28.38.1: #i78694# Calc must support XTransferableSupplier interface<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drawvie4.cxx,v $ * * $Revision: 1.29 $ * * last change: $Author: rt $ $Date: 2007-07-06 12:29:45 $ * * 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 _COM_SUN_STAR_EMBED_NOVISUALAREASIZEEXCEPTION_HPP_ #include <com/sun/star/embed/NoVisualAreaSizeException.hpp> #endif // INCLUDE --------------------------------------------------------------- #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdogrp.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/svdundo.hxx> #include <sfx2/docfile.hxx> #include <tools/urlobj.hxx> #include <toolkit/helper/vclunohelper.hxx> #include "drawview.hxx" #include "global.hxx" #include "drwlayer.hxx" #include "viewdata.hxx" #include "document.hxx" #include "docsh.hxx" #include "drwtrans.hxx" #include "transobj.hxx" // SetDrawClipDoc #include "drawutil.hxx" #include "scmod.hxx" #include "globstr.hrc" #include "chartarr.hxx" using namespace com::sun::star; // STATIC DATA ----------------------------------------------------------- Point aDragStartDiff; // ----------------------------------------------------------------------- //! welche Funktionen aus drawview/drawvie4 muessen wirklich ohne Optimierung sein? #ifdef WNT #pragma optimize ( "", off ) #endif // ----------------------------------------------------------------------- void lcl_CheckOle( const SdrMarkList& rMarkList, BOOL& rAnyOle, BOOL& rOneOle ) { rAnyOle = rOneOle = FALSE; ULONG nCount = rMarkList.GetMarkCount(); for (ULONG i=0; i<nCount; i++) { SdrMark* pMark = rMarkList.GetMark(i); SdrObject* pObj = pMark->GetMarkedSdrObj(); UINT16 nSdrObjKind = pObj->GetObjIdentifier(); if (nSdrObjKind == OBJ_OLE2) { rAnyOle = TRUE; rOneOle = (nCount == 1); break; } else if ( pObj->ISA(SdrObjGroup) ) { SdrObjListIter aIter( *pObj, IM_DEEPNOGROUPS ); SdrObject* pSubObj = aIter.Next(); while (pSubObj) { if ( pSubObj->GetObjIdentifier() == OBJ_OLE2 ) { rAnyOle = TRUE; // rOneOle remains FALSE - a group isn't treated like a single OLE object return; } pSubObj = aIter.Next(); } } } } #if 0 void lcl_RefreshChartData( SdrModel* pModel, ScDocument* pSourceDoc ) { USHORT nPages = pModel->GetPageCount(); for (SCTAB nTab=0; nTab<nPages; nTab++) { SdrPage* pPage = pModel->GetPage(nTab); SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS ); SdrObject* pObject = aIter.Next(); while (pObject) { if ( pObject->GetObjIdentifier() == OBJ_OLE2 ) { SvInPlaceObjectRef aIPObj = ((SdrOle2Obj*)pObject)->GetObjRef(); if ( aIPObj.Is() && SotExchange::IsChart( aIPObj->GetStorage()->GetClassName() ) ) { SchMemChart* pOldData = SchDLL::GetChartData(aIPObj); if ( pOldData ) { // create data from source document ScChartArray aArray( pSourceDoc, *pOldData ); if ( aArray.IsValid() ) { SchMemChart* pNewData = aArray.CreateMemChart(); SchDLL::Update( aIPObj, pNewData ); delete pNewData; ((SdrOle2Obj*)pObject)->GetNewReplacement(); } } } } pObject = aIter.Next(); } } } #endif BOOL ScDrawView::BeginDrag( Window* pWindow, const Point& rStartPos ) { BOOL bReturn = FALSE; if ( AreObjectsMarked() ) { BrkAction(); Rectangle aMarkedRect = GetAllMarkedRect(); Region aRegion( aMarkedRect ); aDragStartDiff = rStartPos - aMarkedRect.TopLeft(); BOOL bAnyOle, bOneOle; const SdrMarkList& rMarkList = GetMarkedObjectList(); lcl_CheckOle( rMarkList, bAnyOle, bOneOle ); ScDocShellRef aDragShellRef; if (bAnyOle) { aDragShellRef = new ScDocShell; // DocShell needs a Ref immediately aDragShellRef->DoInitNew(NULL); } ScDrawLayer::SetGlobalDrawPersist(aDragShellRef); SdrModel* pModel = GetAllMarkedModel(); ScDrawLayer::SetGlobalDrawPersist(NULL); // Charts now always copy their data in addition to the source reference, so // there's no need to call SchDLL::Update for the charts in the clipboard doc. // Update with the data (including NumberFormatter) from the live document would // also store the NumberFormatter in the clipboard chart (#88749#) // lcl_RefreshChartData( pModel, pViewData->GetDocument() ); ScDocShell* pDocSh = pViewData->GetDocShell(); TransferableObjectDescriptor aObjDesc; pDocSh->FillTransferableObjectDescriptor( aObjDesc ); aObjDesc.maDisplayName = pDocSh->GetMedium()->GetURLObject().GetURLNoPass(); // maSize is set in ScDrawTransferObj ctor ScDrawTransferObj* pTransferObj = new ScDrawTransferObj( pModel, pDocSh, aObjDesc ); uno::Reference<datatransfer::XTransferable> xTransferable( pTransferObj ); pTransferObj->SetDrawPersist( &aDragShellRef ); // keep persist for ole objects alive pTransferObj->SetDragSource( this ); // copies selection SC_MOD()->SetDragObject( NULL, pTransferObj ); // for internal D&D pTransferObj->StartDrag( pWindow, DND_ACTION_COPYMOVE | DND_ACTION_LINK ); } return bReturn; } void ScDrawView::DoCopy() { BOOL bAnyOle, bOneOle; const SdrMarkList& rMarkList = GetMarkedObjectList(); lcl_CheckOle( rMarkList, bAnyOle, bOneOle ); // update ScGlobal::pDrawClipDocShellRef ScDrawLayer::SetGlobalDrawPersist( ScTransferObj::SetDrawClipDoc( bAnyOle ) ); SdrModel* pModel = GetAllMarkedModel(); ScDrawLayer::SetGlobalDrawPersist(NULL); // Charts now always copy their data in addition to the source reference, so // there's no need to call SchDLL::Update for the charts in the clipboard doc. // Update with the data (including NumberFormatter) from the live document would // also store the NumberFormatter in the clipboard chart (#88749#) // lcl_RefreshChartData( pModel, pViewData->GetDocument() ); ScDocShell* pDocSh = pViewData->GetDocShell(); TransferableObjectDescriptor aObjDesc; pDocSh->FillTransferableObjectDescriptor( aObjDesc ); aObjDesc.maDisplayName = pDocSh->GetMedium()->GetURLObject().GetURLNoPass(); // maSize is set in ScDrawTransferObj ctor ScDrawTransferObj* pTransferObj = new ScDrawTransferObj( pModel, pDocSh, aObjDesc ); uno::Reference<datatransfer::XTransferable> xTransferable( pTransferObj ); if ( ScGlobal::pDrawClipDocShellRef ) { pTransferObj->SetDrawPersist( &(*ScGlobal::pDrawClipDocShellRef) ); // keep persist for ole objects alive } pTransferObj->CopyToClipboard( pViewData->GetActiveWin() ); // system clipboard SC_MOD()->SetClipObject( NULL, pTransferObj ); // internal clipboard } uno::Reference<datatransfer::XTransferable> ScDrawView::CopyToTransferable() { BOOL bAnyOle, bOneOle; const SdrMarkList& rMarkList = GetMarkedObjectList(); lcl_CheckOle( rMarkList, bAnyOle, bOneOle ); // update ScGlobal::pDrawClipDocShellRef ScDrawLayer::SetGlobalDrawPersist( ScTransferObj::SetDrawClipDoc( bAnyOle ) ); SdrModel* pModel = GetAllMarkedModel(); ScDrawLayer::SetGlobalDrawPersist(NULL); // Charts now always copy their data in addition to the source reference, so // there's no need to call SchDLL::Update for the charts in the clipboard doc. // Update with the data (including NumberFormatter) from the live document would // also store the NumberFormatter in the clipboard chart (#88749#) // lcl_RefreshChartData( pModel, pViewData->GetDocument() ); ScDocShell* pDocSh = pViewData->GetDocShell(); TransferableObjectDescriptor aObjDesc; pDocSh->FillTransferableObjectDescriptor( aObjDesc ); aObjDesc.maDisplayName = pDocSh->GetMedium()->GetURLObject().GetURLNoPass(); // maSize is set in ScDrawTransferObj ctor ScDrawTransferObj* pTransferObj = new ScDrawTransferObj( pModel, pDocSh, aObjDesc ); uno::Reference<datatransfer::XTransferable> xTransferable( pTransferObj ); if ( ScGlobal::pDrawClipDocShellRef ) { pTransferObj->SetDrawPersist( &(*ScGlobal::pDrawClipDocShellRef) ); // keep persist for ole objects alive } return xTransferable; } // Korrektur fuer 100% berechnen, unabhaengig von momentanen Einstellungen void ScDrawView::CalcNormScale( Fraction& rFractX, Fraction& rFractY ) const { Point aLogic = pDev->LogicToPixel( Point(1000,1000), MAP_TWIP ); double nPPTX = ScGlobal::nScreenPPTX; double nPPTY = ScGlobal::nScreenPPTY; if (pViewData) nPPTX /= pViewData->GetDocShell()->GetOutputFactor(); SCCOL nEndCol = 0; SCROW nEndRow = 0; pDoc->GetTableArea( nTab, nEndCol, nEndRow ); if (nEndCol<20) nEndCol = 20; if (nEndRow<20) nEndRow = 20; Fraction aZoom(1,1); ScDrawUtil::CalcScale( pDoc, nTab, 0,0, nEndCol,nEndRow, pDev, aZoom,aZoom, nPPTX, nPPTY, rFractX,rFractY ); } void ScDrawView::SetMarkedOriginalSize() { SdrUndoGroup* pUndoGroup = new SdrUndoGroup(*GetModel()); const SdrMarkList& rMarkList = GetMarkedObjectList(); long nDone = 0; ULONG nCount = rMarkList.GetMarkCount(); for (ULONG i=0; i<nCount; i++) { SdrObject* pObj = rMarkList.GetMark(i)->GetMarkedSdrObj(); USHORT nIdent = pObj->GetObjIdentifier(); BOOL bDo = FALSE; Size aOriginalSize; if (nIdent == OBJ_OLE2) { // TODO/LEAN: working with visual area can switch object to running state uno::Reference < embed::XEmbeddedObject > xObj( ((SdrOle2Obj*)pObj)->GetObjRef(), uno::UNO_QUERY ); if ( xObj.is() ) // #121612# NULL for an invalid object that couldn't be loaded { sal_Int64 nAspect = ((SdrOle2Obj*)pObj)->GetAspect(); if ( nAspect == embed::Aspects::MSOLE_ICON ) { MapMode aMapMode( MAP_100TH_MM ); aOriginalSize = ((SdrOle2Obj*)pObj)->GetOrigObjSize( &aMapMode ); bDo = TRUE; } else { MapUnit aUnit = VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( ((SdrOle2Obj*)pObj)->GetAspect() ) ); awt::Size aSz; try { aSz = xObj->getVisualAreaSize( ((SdrOle2Obj*)pObj)->GetAspect() ); aOriginalSize = OutputDevice::LogicToLogic( Size( aSz.Width, aSz.Height ), aUnit, MAP_100TH_MM ); bDo = TRUE; } catch( embed::NoVisualAreaSizeException& ) { OSL_ENSURE( sal_False, "Can't get the original size of the object!" ); } } } } else if (nIdent == OBJ_GRAF) { const Graphic& rGraphic = ((SdrGrafObj*)pObj)->GetGraphic(); MapMode aSourceMap = rGraphic.GetPrefMapMode(); MapMode aDestMap( MAP_100TH_MM ); if (aSourceMap.GetMapUnit() == MAP_PIXEL) { // Pixel-Korrektur beruecksichtigen, damit Bitmap auf dem Bildschirm stimmt Fraction aNormScaleX, aNormScaleY; CalcNormScale( aNormScaleX, aNormScaleY ); aDestMap.SetScaleX(aNormScaleX); aDestMap.SetScaleY(aNormScaleY); } if (pViewData) { Window* pActWin = pViewData->GetActiveWin(); if (pActWin) { aOriginalSize = pActWin->LogicToLogic( rGraphic.GetPrefSize(), &aSourceMap, &aDestMap ); bDo = TRUE; } } } if ( bDo ) { Rectangle aDrawRect = pObj->GetLogicRect(); pUndoGroup->AddAction( new SdrUndoGeoObj( *pObj ) ); pObj->Resize( aDrawRect.TopLeft(), Fraction( aOriginalSize.Width(), aDrawRect.GetWidth() ), Fraction( aOriginalSize.Height(), aDrawRect.GetHeight() ) ); ++nDone; } } if (nDone) { pUndoGroup->SetComment(ScGlobal::GetRscString( STR_UNDO_ORIGINALSIZE )); ScDocShell* pDocSh = pViewData->GetDocShell(); pDocSh->GetUndoManager()->AddUndoAction(pUndoGroup); pDocSh->SetDrawModified(); } else delete pUndoGroup; } #ifdef WNT #pragma optimize ( "", on ) #endif <|endoftext|>
<commit_before>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE test_proximity_list #include <boost/test/unit_test.hpp> #include "proximity_list/proximity_list.h" #include "proximity_list/proximitylist_api.h" #include "type/data.h" #include "georef/georef.h" using namespace navitia::type; using namespace navitia::proximitylist; BOOST_AUTO_TEST_CASE(distances_grand_cercle) { GeographicalCoord a(0,0); GeographicalCoord b(0,0); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); BOOST_CHECK_CLOSE(a.distance_to(b), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(a), 0, 1e-6); GeographicalCoord nantes(-1.57, 47.22); GeographicalCoord paris(2.36, 48.85); BOOST_CHECK_CLOSE(nantes.distance_to(paris), 340000, 10); BOOST_CHECK_CLOSE(paris.distance_to(nantes), 340000, 10); a.set_lon(180); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(84); a.set_lat(89.999); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(34); a.set_lat(-89.999); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(0); a.set_lat(45); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/4,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/4,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); } BOOST_AUTO_TEST_CASE(approx_distance){ GeographicalCoord canaltp(2.3921, 48.8296); GeographicalCoord tour_eiffel(2.29447,48.85834); double coslat = ::cos(canaltp.lat() * 0.0174532925199432958); BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1); BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1); BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1); BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1); } BOOST_AUTO_TEST_CASE(find_nearest){ constexpr double M_TO_DEG = 1.0/111320.0; typedef std::pair<unsigned int, GeographicalCoord> p; ProximityList<unsigned int> pl; GeographicalCoord c; std::vector<GeographicalCoord> coords; // Exemple d'illustration issu de wikipedia c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); pl.add(c, 1); coords.push_back(c); c.set_lon(M_TO_DEG *5); c.set_lat(M_TO_DEG *4); pl.add(c, 2); coords.push_back(c); c.set_lon(M_TO_DEG *9); c.set_lat(M_TO_DEG *6); pl.add(c, 3); coords.push_back(c); c.set_lon(M_TO_DEG *4); c.set_lat(M_TO_DEG *7); pl.add(c, 4); coords.push_back(c); c.set_lon(M_TO_DEG *8); c.set_lat(M_TO_DEG *1); pl.add(c, 5); coords.push_back(c); c.set_lon(M_TO_DEG *7); c.set_lat(M_TO_DEG *2); pl.add(c, 6); coords.push_back(c); pl.build(); std::vector<unsigned int> expected {1,4,2,6,5,3}; for(size_t i=0; i < expected.size(); ++i) BOOST_CHECK_EQUAL(pl.items[i].element, expected[i]); c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); BOOST_CHECK_EQUAL(pl.find_nearest(c), 1); c.set_lon(M_TO_DEG *7.1); c.set_lat(M_TO_DEG *1.9); BOOST_CHECK_EQUAL(pl.find_nearest(c), 6); c.set_lon(M_TO_DEG *100); c.set_lat(M_TO_DEG *6); BOOST_CHECK_EQUAL(pl.find_nearest(c), 3); c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *4); expected = {1}; auto tmp1 = pl.find_within(c, 1.1); std::vector<unsigned int> tmp; for(auto p : tmp1) tmp.push_back(p.first); BOOST_CHECK_EQUAL(tmp1[0].second, coords[0]); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2}; tmp1 = pl.find_within(c, 3.1); tmp.clear(); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4}; tmp.clear(); tmp1 = pl.find_within(c, 3.7); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4,6}; tmp.clear(); tmp1 = pl.find_within(c, 5.4); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4,5,6}; tmp.clear(); tmp1 = pl.find_within(c, 6.8); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,3,4,5,6}; tmp.clear(); tmp1 = pl.find_within(c, 7.3); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); } <commit_msg>Kraken : Add idx to stop_areas in proximity_list tests<commit_after>#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE test_proximity_list #include <boost/test/unit_test.hpp> #include "proximity_list/proximity_list.h" #include "proximity_list/proximitylist_api.h" #include "type/data.h" #include "georef/georef.h" using namespace navitia::type; using namespace navitia::proximitylist; BOOST_AUTO_TEST_CASE(distances_grand_cercle) { GeographicalCoord a(0,0); GeographicalCoord b(0,0); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); BOOST_CHECK_CLOSE(a.distance_to(b), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(a), 0, 1e-6); GeographicalCoord nantes(-1.57, 47.22); GeographicalCoord paris(2.36, 48.85); BOOST_CHECK_CLOSE(nantes.distance_to(paris), 340000, 10); BOOST_CHECK_CLOSE(paris.distance_to(nantes), 340000, 10); a.set_lon(180); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(84); a.set_lat(89.999); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(34); a.set_lat(-89.999); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/2,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); a.set_lon(0); a.set_lat(45); BOOST_CHECK_CLOSE(a.distance_to(b), 6371*3.14*1000/4,1); BOOST_CHECK_CLOSE(b.distance_to(a), 6371*3.14*1000/4,1); BOOST_CHECK_CLOSE(a.distance_to(a), 0, 1e-6); BOOST_CHECK_CLOSE(b.distance_to(b), 0, 1e-6); } BOOST_AUTO_TEST_CASE(approx_distance){ GeographicalCoord canaltp(2.3921, 48.8296); GeographicalCoord tour_eiffel(2.29447,48.85834); double coslat = ::cos(canaltp.lat() * 0.0174532925199432958); BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1); BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1); BOOST_CHECK_CLOSE(canaltp.distance_to(tour_eiffel), ::sqrt(tour_eiffel.approx_sqr_distance(canaltp, coslat)), 1); BOOST_CHECK_CLOSE(tour_eiffel.distance_to(canaltp), ::sqrt(canaltp.approx_sqr_distance(tour_eiffel, coslat)), 1); } BOOST_AUTO_TEST_CASE(find_nearest){ constexpr double M_TO_DEG = 1.0/111320.0; typedef std::pair<unsigned int, GeographicalCoord> p; ProximityList<unsigned int> pl; GeographicalCoord c; std::vector<GeographicalCoord> coords; // Exemple d'illustration issu de wikipedia c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); pl.add(c, 1); coords.push_back(c); c.set_lon(M_TO_DEG *5); c.set_lat(M_TO_DEG *4); pl.add(c, 2); coords.push_back(c); c.set_lon(M_TO_DEG *9); c.set_lat(M_TO_DEG *6); pl.add(c, 3); coords.push_back(c); c.set_lon(M_TO_DEG *4); c.set_lat(M_TO_DEG *7); pl.add(c, 4); coords.push_back(c); c.set_lon(M_TO_DEG *8); c.set_lat(M_TO_DEG *1); pl.add(c, 5); coords.push_back(c); c.set_lon(M_TO_DEG *7); c.set_lat(M_TO_DEG *2); pl.add(c, 6); coords.push_back(c); pl.build(); std::vector<unsigned int> expected {1,4,2,6,5,3}; for(size_t i=0; i < expected.size(); ++i) BOOST_CHECK_EQUAL(pl.items[i].element, expected[i]); c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *3); BOOST_CHECK_EQUAL(pl.find_nearest(c), 1); c.set_lon(M_TO_DEG *7.1); c.set_lat(M_TO_DEG *1.9); BOOST_CHECK_EQUAL(pl.find_nearest(c), 6); c.set_lon(M_TO_DEG *100); c.set_lat(M_TO_DEG *6); BOOST_CHECK_EQUAL(pl.find_nearest(c), 3); c.set_lon(M_TO_DEG *2); c.set_lat(M_TO_DEG *4); expected = {1}; auto tmp1 = pl.find_within(c, 1.1); std::vector<unsigned int> tmp; for(auto p : tmp1) tmp.push_back(p.first); BOOST_CHECK_EQUAL(tmp1[0].second, coords[0]); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2}; tmp1 = pl.find_within(c, 3.1); tmp.clear(); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4}; tmp.clear(); tmp1 = pl.find_within(c, 3.7); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4,6}; tmp.clear(); tmp1 = pl.find_within(c, 5.4); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,4,5,6}; tmp.clear(); tmp1 = pl.find_within(c, 6.8); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); expected={1,2,3,4,5,6}; tmp.clear(); tmp1 = pl.find_within(c, 7.3); for(auto p : tmp1) tmp.push_back(p.first); std::sort(tmp.begin(), tmp.end()); BOOST_CHECK_EQUAL_COLLECTIONS(tmp.begin(), tmp.end(), expected.begin(), expected.end()); } BOOST_AUTO_TEST_CASE(test_api) { navitia::type::Data data; //Everything in the range auto sa = new navitia::type::StopArea(); sa->coord.set_lon(-1.554514); sa->coord.set_lat(47.218515); sa->idx = 0; data.pt_data.stop_areas.push_back(sa); sa = new navitia::type::StopArea(); sa->coord.set_lon(-1.552044); sa->coord.set_lat(47.212516); sa->idx = 1; data.pt_data.stop_areas.push_back(sa); data.build_proximity_list(); navitia::type::GeographicalCoord c; c.set_lon(-1.554514); c.set_lat(47.218515); auto result = find(c, 700, {navitia::type::Type_e::StopArea, navitia::type::Type_e::POI}, "", 1, 10, 0, data); BOOST_CHECK_EQUAL(result.places_nearby().size(), 2); //One object out of the range } BOOST_AUTO_TEST_CASE(test_api_type) { //Everything of the same type in the range //Everything of the same type and one out of the range //Two types and everything in the range //Two types and one out of the range } BOOST_AUTO_TEST_CASE(test_filter) { //We ask for a stop_area inside the range //We ask for a stop_area outside the range } <|endoftext|>