text
stringlengths
54
60.6k
<commit_before>#ifndef __COMPUTE_TASK_HPP_INCLUDED #define __COMPUTE_TASK_HPP_INCLUDED #include "entity.hpp" #include "compute_task_struct.hpp" #include "pre_iterate_callback.hpp" #include "post_iterate_callback.hpp" #include "family_templates.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <vector> // std::vector // `yli::ontology::ComputeTask` is a class which contains the data for a single // computing task. `ComputeTask` does not have the OpenGL shaders used to process // the data. Instead, the shaders are contained by the parent `Entity` which is // an `yli::ontology::ComputeTask` instance. // // For example, `yli::ontology::Shader` can have vertex and fragment shaders for // computing the distances between nodes of a graph. Then, each `ComputeTask` // would contain the graph data, eg. as a distance matrix. Then, rendering a // `ComputeTask` means computing that task. // // Rendering a `ComputeTask` is done by iterating the task until either // `end_condition_callback_engine->execute()` returns `true`, or until // `n_max_iterations` is reached. If `end_condition_callback_engine` is `nullptr` // or `end_condition_callback_engine->execute()` does not not return an `AnyValue` // which contains `datatypes::BOOL`, then `end_condition_callback_engine` is ignored // and `n_max_iterations` is the exact number of iterations to be done. However, // even if `end_condition_callback_engine->execute()` would return an invalid return // value, that is, not an `AnyValue` which contains `datatypes::BOOL`, // `end_condition_callback_engine->execute()` is still called and taken into account // in every iteration. // // When iterating, there is a `PreIterateCallback` which is executed before each iteration, // and also a `PostIterateCallback` which is executed correspondingly after each iteration. // Of course `PreRenderCallback` and `PostRenderCallback` can be used as well. // `PreRenderCallback` gets executed before the first `PreIterateCallback` call, and // `PostRenderCallback` gets executed after the last `PostRenderCallback` call. // All these callbacks are optional and can be left to `nullptr` if they are not needed. namespace yli { namespace callback_system { class CallbackEngine; } namespace ontology { class Shader; class ComputeTask: public yli::ontology::Entity { public: ComputeTask(yli::ontology::Universe* const universe, const ComputeTaskStruct& compute_task_struct) : Entity(universe) { // constructor. this->parent = compute_task_struct.parent; this->end_condition_callback_engine = compute_task_struct.end_condition_callback_engine; this->n_max_iterations = compute_task_struct.n_max_iterations; this->compute_taskID = compute_task_struct.compute_taskID; this->texture_width = compute_task_struct.texture_width; this->texture_height = compute_task_struct.texture_height; this->framebuffer = 0; this->texture = 0; this->render_buffer = 0; this->vertex_position_modelspaceID = 0; this->vertexUVID = 0; this->vertexbuffer = 0; this->uvbuffer = 0; this->preiterate_callback = compute_task_struct.preiterate_callback; this->postiterate_callback = compute_task_struct.postiterate_callback; // Get `childID` from `Shader` and set pointer to this `ComputeTask`. this->bind_to_parent(); // Create FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); // Bind offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); // Create texture. glGenTextures(1, &this->texture); glBindTexture(GL_TEXTURE_2D, this->texture); // Define texture. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->texture_width, this->texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); yli::opengl::set_filtering_parameters(); // Attach texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->texture, 0); // Create and bind render buffer with depth and stencil attachments. glGenRenderbuffers(1, &this->render_buffer); glBindRenderbuffer(GL_RENDERBUFFER, this->render_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, this->texture_width, this->texture_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->render_buffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cerr << "ERROR: `ComputeTask::ComputeTask`: framebuffer is not complete!\n"; } // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::ComputeTask*"; this->can_be_erased = true; } // destructor. ~ComputeTask(); yli::ontology::Entity* get_parent() const override; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend std::size_t yli::ontology::get_number_of_descendants(const std::vector<T1>& child_pointer_vector); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); private: void bind_to_parent(); // This method renders this `ComputeTask`, that is, computes this task. void render(); void preiterate() const; void postiterate() const; std::size_t get_number_of_children() const override; std::size_t get_number_of_descendants() const override; yli::ontology::Shader* parent; // pointer to the `Shader`. // End iterating when `end_condition_callback_engine` returns `true`. std::shared_ptr<yli::callback_system::CallbackEngine> end_condition_callback_engine; // This is the maximum number of iterations. // If `end_condition_callback_engine` is `nullptr`, then this is the number of iterations. // If `end_condition_callback_engine` is not `nullptr`, then this is the maximum number of iterations. std::size_t n_max_iterations; std::size_t compute_taskID; std::size_t texture_width; std::size_t texture_height; uint32_t framebuffer; uint32_t texture; uint32_t render_buffer; uint32_t vertex_position_modelspaceID; uint32_t vertexUVID; uint32_t vertexbuffer; uint32_t uvbuffer; PreIterateCallback preiterate_callback; PostIterateCallback postiterate_callback; }; } } #endif <commit_msg>`yli::ontology::ComputeTask`: edited whitespace.<commit_after>#ifndef __COMPUTE_TASK_HPP_INCLUDED #define __COMPUTE_TASK_HPP_INCLUDED #include "entity.hpp" #include "compute_task_struct.hpp" #include "pre_iterate_callback.hpp" #include "post_iterate_callback.hpp" #include "family_templates.hpp" #include "code/ylikuutio/opengl/opengl.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <queue> // std::queue #include <stdint.h> // uint32_t etc. #include <vector> // std::vector // `yli::ontology::ComputeTask` is a class which contains the data for a single // computing task. `ComputeTask` does not have the OpenGL shaders used to process // the data. Instead, the shaders are contained by the parent `Entity` which is // an `yli::ontology::ComputeTask` instance. // // For example, `yli::ontology::Shader` can have vertex and fragment shaders for // computing the distances between nodes of a graph. Then, each `ComputeTask` // would contain the graph data, eg. as a distance matrix. Then, rendering a // `ComputeTask` means computing that task. // // Rendering a `ComputeTask` is done by iterating the task until either // `end_condition_callback_engine->execute()` returns `true`, or until // `n_max_iterations` is reached. If `end_condition_callback_engine` is `nullptr` // or `end_condition_callback_engine->execute()` does not not return an `AnyValue` // which contains `datatypes::BOOL`, then `end_condition_callback_engine` is ignored // and `n_max_iterations` is the exact number of iterations to be done. However, // even if `end_condition_callback_engine->execute()` would return an invalid return // value, that is, not an `AnyValue` which contains `datatypes::BOOL`, // `end_condition_callback_engine->execute()` is still called and taken into account // in every iteration. // // When iterating, there is a `PreIterateCallback` which is executed before each iteration, // and also a `PostIterateCallback` which is executed correspondingly after each iteration. // Of course `PreRenderCallback` and `PostRenderCallback` can be used as well. // `PreRenderCallback` gets executed before the first `PreIterateCallback` call, and // `PostRenderCallback` gets executed after the last `PostRenderCallback` call. // All these callbacks are optional and can be left to `nullptr` if they are not needed. namespace yli { namespace callback_system { class CallbackEngine; } namespace ontology { class Shader; class ComputeTask: public yli::ontology::Entity { public: ComputeTask(yli::ontology::Universe* const universe, const ComputeTaskStruct& compute_task_struct) : Entity(universe) { // constructor. this->parent = compute_task_struct.parent; this->end_condition_callback_engine = compute_task_struct.end_condition_callback_engine; this->n_max_iterations = compute_task_struct.n_max_iterations; this->compute_taskID = compute_task_struct.compute_taskID; this->texture_width = compute_task_struct.texture_width; this->texture_height = compute_task_struct.texture_height; this->framebuffer = 0; this->texture = 0; this->render_buffer = 0; this->vertex_position_modelspaceID = 0; this->vertexUVID = 0; this->vertexbuffer = 0; this->uvbuffer = 0; this->preiterate_callback = compute_task_struct.preiterate_callback; this->postiterate_callback = compute_task_struct.postiterate_callback; // Get `childID` from `Shader` and set pointer to this `ComputeTask`. this->bind_to_parent(); // Create FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); // Bind offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); // Create texture. glGenTextures(1, &this->texture); glBindTexture(GL_TEXTURE_2D, this->texture); // Define texture. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this->texture_width, this->texture_height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); yli::opengl::set_filtering_parameters(); // Attach texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->texture, 0); // Create and bind render buffer with depth and stencil attachments. glGenRenderbuffers(1, &this->render_buffer); glBindRenderbuffer(GL_RENDERBUFFER, this->render_buffer); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, this->texture_width, this->texture_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->render_buffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { std::cerr << "ERROR: `ComputeTask::ComputeTask`: framebuffer is not complete!\n"; } // `yli::ontology::Entity` member variables begin here. this->type_string = "yli::ontology::ComputeTask*"; this->can_be_erased = true; } // destructor. ~ComputeTask(); yli::ontology::Entity* get_parent() const override; template<class T1> friend void yli::hierarchy::bind_child_to_parent(T1 child_pointer, std::vector<T1>& child_pointer_vector, std::queue<std::size_t>& free_childID_queue, std::size_t& number_of_children); template<class T1> friend std::size_t yli::ontology::get_number_of_descendants(const std::vector<T1>& child_pointer_vector); template<class T1> friend void yli::ontology::render_children(const std::vector<T1>& child_pointer_vector); private: void bind_to_parent(); // This method renders this `ComputeTask`, that is, computes this task. void render(); void preiterate() const; void postiterate() const; std::size_t get_number_of_children() const override; std::size_t get_number_of_descendants() const override; yli::ontology::Shader* parent; // pointer to the `Shader`. // End iterating when `end_condition_callback_engine` returns `true`. std::shared_ptr<yli::callback_system::CallbackEngine> end_condition_callback_engine; // This is the maximum number of iterations. // If `end_condition_callback_engine` is `nullptr`, then this is the number of iterations. // If `end_condition_callback_engine` is not `nullptr`, then this is the maximum number of iterations. std::size_t n_max_iterations; std::size_t compute_taskID; std::size_t texture_width; std::size_t texture_height; uint32_t framebuffer; uint32_t texture; uint32_t render_buffer; uint32_t vertex_position_modelspaceID; uint32_t vertexUVID; uint32_t vertexbuffer; uint32_t uvbuffer; PreIterateCallback preiterate_callback; PostIterateCallback postiterate_callback; }; } } #endif <|endoftext|>
<commit_before>/* * %injeqt copyright begin% * Copyright 2014 Rafał Malinowski ([email protected]) * %injeqt copyright end% * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dependency-extractor.h" #include "dependency.h" #include "implements-extractor.h" #include "setter-method.h" #include "type.h" #include "type-relations.h" #include "type-relations-factory.h" #include <QtCore/QMetaMethod> #include <QtCore/QMetaType> #include <algorithm> #include <set> namespace injeqt { namespace v1 { namespace { std::string exception_message(const QMetaObject *meta_object, const QMetaObject *dependency_meta_object) { return std::string{meta_object->className()} + "::" + dependency_meta_object->className(); } std::vector<setter_method> extract_setters(const type &for_type) { auto result = std::vector<setter_method>{}; auto meta_object = for_type.meta_object(); auto method_count = meta_object->methodCount(); for (decltype(method_count) i = 0; i < method_count; i++) { auto probably_setter = meta_object->method(i); auto tag = std::string{probably_setter.tag()}; if (tag != "injeqt_setter") continue; result.emplace_back(setter_method{probably_setter}); } return result; } } dependencies dependency_extractor::extract_dependencies(const type &for_type) const try { auto setters = extract_setters(for_type); auto types = std::vector<type>{}; std::transform(std::begin(setters), std::end(setters), std::back_inserter(types), [](const setter_method &setter){ return setter.parameter_type(); } ); auto relations = type_relations_factory{}.create_type_relations(types); for (auto &&ambiguous : relations.ambiguous()) { auto types_it = std::find(std::begin(types), std::end(types), ambiguous); if (types_it != std::end(types)) throw dependency_duplicated_exception(exception_message(for_type.meta_object(), types_it->meta_object())); } auto result = std::vector<dependency>{}; std::transform(std::begin(setters), std::end(setters), std::back_inserter(result), [](const setter_method &setter){ return dependency{setter}; } ); return dependencies{result}; } catch (setter_too_many_parameters_exception &e) { throw dependency_too_many_parameters_exception(); } catch (invalid_setter_exception &e) { throw dependency_not_qobject_exception(); } }} <commit_msg>use match method for testing for conflicting dependencies<commit_after>/* * %injeqt copyright begin% * Copyright 2014 Rafał Malinowski ([email protected]) * %injeqt copyright end% * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "dependency-extractor.h" #include "dependency.h" #include "implements-extractor.h" #include "setter-method.h" #include "type.h" #include "type-relations.h" #include "type-relations-factory.h" #include <QtCore/QMetaMethod> #include <QtCore/QMetaType> #include <algorithm> #include <set> namespace injeqt { namespace v1 { namespace { std::string exception_message(const QMetaObject *meta_object, const QMetaObject *dependency_meta_object) { return std::string{meta_object->className()} + "::" + dependency_meta_object->className(); } std::vector<setter_method> extract_setters(const type &for_type) { auto result = std::vector<setter_method>{}; auto meta_object = for_type.meta_object(); auto method_count = meta_object->methodCount(); for (decltype(method_count) i = 0; i < method_count; i++) { auto probably_setter = meta_object->method(i); auto tag = std::string{probably_setter.tag()}; if (tag != "injeqt_setter") continue; result.emplace_back(setter_method{probably_setter}); } return result; } std::vector<type> extract_parameter_types(const std::vector<setter_method> &setters) { auto result = std::vector<type>{}; std::transform(std::begin(setters), std::end(setters), std::back_inserter(result), [](const setter_method &setter){ return setter.parameter_type(); } ); return result; } } dependencies dependency_extractor::extract_dependencies(const type &for_type) const try { auto setters = extract_setters(for_type); auto parameter_types = extract_parameter_types(setters); auto relations = type_relations_factory{}.create_type_relations(parameter_types); auto matches = match(types{parameter_types}.content(), relations.ambiguous().content()); if (!matches.matched.empty()) throw dependency_duplicated_exception(exception_message(for_type.meta_object(), matches.matched.begin()->first.meta_object())); auto result = std::vector<dependency>{}; std::transform(std::begin(setters), std::end(setters), std::back_inserter(result), [](const setter_method &setter){ return dependency{setter}; } ); return dependencies{result}; } catch (setter_too_many_parameters_exception &e) { throw dependency_too_many_parameters_exception(); } catch (invalid_setter_exception &e) { throw dependency_not_qobject_exception(); } }} <|endoftext|>
<commit_before>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdI18nApplication.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) // // Class implementation. namespace mvd { /* TRANSLATOR mvd::I18nApplication Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ I18nApplication ::I18nApplication( int& argc, char** argv ) : QApplication( argc, argv ), m_IsRunningFromBuildDir( false ) { InitializeLocale(); } /*******************************************************************************/ I18nApplication ::~I18nApplication() { } /*******************************************************************************/ void I18nApplication ::InitializeLocale() { QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) ); // // 1. default UI language is english (no translation). QLocale sys_lc( QLocale::system() ); if( sys_lc.language()==QLocale::C || ( sys_lc.language()==QLocale::English && sys_lc.country()==QLocale::UnitedStates ) ) { return; } // // 2. Choose i18n path between build dir and install dir. QDir i18n_dir; QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) ); QDir build_i18n_dir( bin_dir ); // If build dir is identified... if( build_i18n_dir.cd( "../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) ) { m_IsRunningFromBuildDir = true; // ...use build dir as prioritary load path for translation. i18n_dir = build_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from build directory '%1'." ).arg( bin_dir.path() ); } // Otherwise... else { m_IsRunningFromBuildDir = false; QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) ); // ...if install data dir is identified if( install_i18n_dir.exists() ) { // ...use install data dir as load path for translation. i18n_dir = install_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR ); } // Otherwise else { QString message( tr( "Failed to access translation-files directory '%1'." ) .arg( install_i18n_dir.path() ) ); // TODO: Use log system to trace error while loading locale translation file. qDebug() << message; // TODO: morph into better HMI design. QMessageBox::critical( NULL, tr( "Critical error!" ), message ); return; } } // // 3.1 Stack Qt translator. LoadAndInstallTranslator( "qt_" + sys_lc.name(), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ); // // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator. LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() ); // TODO: Record locale translation filename(s) used in UI component (e.g. // AboutDialog, Settings dialog, Information dialog etc.) } /*******************************************************************************/ bool I18nApplication ::LoadAndInstallTranslator(const QString& filename, const QString& directory, const QString& searchDelimiters, const QString& suffix ) { QString filename_ext( filename + ( suffix.isNull() ? ".qm" : suffix ) ); // (a) Do need to new QTranslator() here! QTranslator* lc_translator = new QTranslator( this ); if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) ) { QString message( tr( "Failed to load '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Use log system to trace error while loading locale translation file. qWarning() << message; // TODO: morph into better HMI design. QMessageBox::warning( NULL, tr( "Warning!" ), message ); return false; } // (a) ...because QTranslator needs to be alive during the whole // lifespan of the application. QCoreApplication::installTranslator( lc_translator ); QString message( tr( "Successfully loaded '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Log locale translation filename used. qDebug() << message; return true; } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ } // end namespace 'mvd' <commit_msg>COMP: support windows build dir<commit_after>/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdI18nApplication.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) // // Class implementation. namespace mvd { /* TRANSLATOR mvd::I18nApplication Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*******************************************************************************/ I18nApplication ::I18nApplication( int& argc, char** argv ) : QApplication( argc, argv ), m_IsRunningFromBuildDir( false ) { InitializeLocale(); } /*******************************************************************************/ I18nApplication ::~I18nApplication() { } /*******************************************************************************/ void I18nApplication ::InitializeLocale() { QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) ); // // 1. default UI language is english (no translation). QLocale sys_lc( QLocale::system() ); if( sys_lc.language()==QLocale::C || ( sys_lc.language()==QLocale::English && sys_lc.country()==QLocale::UnitedStates ) ) { return; } // // 2. Choose i18n path between build dir and install dir. QDir i18n_dir; QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) ); QDir build_i18n_dir( bin_dir ); qDebug() << "build_i18n_dir.exists( ../i18n )" << build_i18n_dir.exists( "../i18n" ); qDebug() << "build_i18n_dir.exists( ../../i18n )" << build_i18n_dir.exists( "../../i18n" ); qDebug() << "build_i18n_dir.exists( ../../i18n )" << build_i18n_dir.exists( "../../" Monteverdi2_CONFIGURE_FILE ); // If build dir is identified... if( build_i18n_dir.exists( "../i18n" ) && build_i18n_dir.cd( "../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) || build_i18n_dir.exists( "../../i18n" ) && build_i18n_dir.cd( "../../i18n" ) && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) ) { m_IsRunningFromBuildDir = true; // ...use build dir as prioritary load path for translation. i18n_dir = build_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from build directory '%1'." ).arg( bin_dir.path() ); } // Otherwise... else { m_IsRunningFromBuildDir = false; QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) ); // ...if install data dir is identified if( install_i18n_dir.exists() ) { // ...use install data dir as load path for translation. i18n_dir = install_i18n_dir; // TODO: Use log system to trace message. qDebug() << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR ); } // Otherwise else { QString message( tr( "Failed to access translation-files directory '%1'." ) .arg( install_i18n_dir.path() ) ); // TODO: Use log system to trace error while loading locale translation file. qDebug() << message; // TODO: morph into better HMI design. QMessageBox::critical( NULL, tr( "Critical error!" ), message ); return; } } // // 3.1 Stack Qt translator. LoadAndInstallTranslator( "qt_" + sys_lc.name(), QLibraryInfo::location( QLibraryInfo::TranslationsPath ) ); // // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator. LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() ); // TODO: Record locale translation filename(s) used in UI component (e.g. // AboutDialog, Settings dialog, Information dialog etc.) } /*******************************************************************************/ bool I18nApplication ::LoadAndInstallTranslator(const QString& filename, const QString& directory, const QString& searchDelimiters, const QString& suffix ) { QString filename_ext( filename + ( suffix.isNull() ? ".qm" : suffix ) ); // (a) Do need to new QTranslator() here! QTranslator* lc_translator = new QTranslator( this ); if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) ) { QString message( tr( "Failed to load '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Use log system to trace error while loading locale translation file. qWarning() << message; // TODO: morph into better HMI design. QMessageBox::warning( NULL, tr( "Warning!" ), message ); return false; } // (a) ...because QTranslator needs to be alive during the whole // lifespan of the application. QCoreApplication::installTranslator( lc_translator ); QString message( tr( "Successfully loaded '%1' translation file from '%2'." ) .arg( filename_ext ) .arg( directory ) ); // TODO: Log locale translation filename used. qDebug() << message; return true; } /*******************************************************************************/ /* SLOTS */ /*******************************************************************************/ } // end namespace 'mvd' <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkOtsuThresholdImageFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkBinaryThresholdImageFilter.h" #include "itkConnectedComponentImageFilter.h" #include "itkRelabelComponentImageFilter.h" #include "itkRescaleIntensityImageFilter.h" int main( int argc, char * argv[] ) { if( argc < 5 ) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImageFile outputImageFile "; std::cerr << " insideValue outsideValue " << std::endl; return EXIT_FAILURE; } typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; const unsigned int Dimension = 2; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > OtsuFilterType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); OtsuFilterType::Pointer otsuFilter = OtsuFilterType::New(); reader->SetFileName( argv[1] ); otsuFilter->SetInput( reader->GetOutput() ); const OutputPixelType outsideValue = atoi( argv[3] ); const OutputPixelType insideValue = atoi( argv[4] ); otsuFilter->SetOutsideValue( outsideValue ); otsuFilter->SetInsideValue( insideValue ); try { otsuFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << excp << std::endl; } int threshold = otsuFilter->GetThreshold(); std::cout << "Threshold = " << threshold << std::endl; typedef unsigned short ComponentPixelType; typedef itk::Image< ComponentPixelType, Dimension > ComponentImageType; typedef itk::ConnectedComponentImageFilter <InputImageType, ComponentImageType > ConnectedComponentImageFilterType; ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New (); connected->SetInput(otsuFilter->GetOutput()); connected->Update(); std::cout << "Number of objects: " << connected->GetObjectCount() << std::endl; typedef itk::RelabelComponentImageFilter< ComponentImageType, ComponentImageType > RelabelFilterType; RelabelFilterType::Pointer relabeler = RelabelFilterType::New(); relabeler->SetInput( connected->GetOutput() ); typedef itk::BinaryThresholdImageFilter< ComponentImageType, OutputImageType > ThresholdFilterType; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetLowerThreshold(1); thresholder->SetUpperThreshold(1); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); thresholder->SetInput( relabeler->GetOutput() ); WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( thresholder->GetOutput() ); writer->Update(); std::cout << "Largest object of " << connected->GetObjectCount() << " objects"; typedef std::vector< itk::SizeValueType > SizesInPixelsType; const SizesInPixelsType & sizesInPixels = relabeler->GetSizeOfObjectsInPixels(); std::cout << "Number of pixels in largest component = " << sizesInPixels[0] << std::endl; std::cout << "Number of pixels in second component = " << sizesInPixels[1] << std::endl; return EXIT_SUCCESS; } <commit_msg>Integrated end to end, producing north and south curves.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkBinaryThresholdImageFilter.h" #include "itkConnectedComponentImageFilter.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkImageLinearIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkOtsuMultipleThresholdsImageFilter.h" #include "itkOtsuThresholdImageFilter.h" #include "itkRelabelComponentImageFilter.h" #include "itkRescaleIntensityImageFilter.h" int main( int argc, char * argv[] ) { if( argc < 3 ) { std::cerr << "Usage: " << argv[0]; std::cerr << " inputImageFile outputImageFile "; return EXIT_FAILURE; } typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; const unsigned int Dimension = 2; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::OtsuThresholdImageFilter< InputImageType, OutputImageType > OtsuFilterType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; ReaderType::Pointer reader = ReaderType::New(); OtsuFilterType::Pointer otsuFilter = OtsuFilterType::New(); reader->SetFileName( argv[1] ); otsuFilter->SetInput( reader->GetOutput() ); const OutputPixelType outsideValue = 255; const OutputPixelType insideValue = 0; otsuFilter->SetOutsideValue( outsideValue ); otsuFilter->SetInsideValue( insideValue ); try { otsuFilter->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << excp << std::endl; } int threshold = otsuFilter->GetThreshold(); std::cout << "Threshold = " << threshold << std::endl; typedef unsigned short ComponentPixelType; typedef itk::Image< ComponentPixelType, Dimension > ComponentImageType; typedef itk::ConnectedComponentImageFilter <InputImageType, ComponentImageType > ConnectedComponentImageFilterType; ConnectedComponentImageFilterType::Pointer connected = ConnectedComponentImageFilterType::New (); connected->SetInput(otsuFilter->GetOutput()); connected->Update(); std::cout << "Number of objects: " << connected->GetObjectCount() << std::endl; typedef itk::RelabelComponentImageFilter< ComponentImageType, ComponentImageType > RelabelFilterType; RelabelFilterType::Pointer relabeler = RelabelFilterType::New(); relabeler->SetInput( connected->GetOutput() ); typedef itk::BinaryThresholdImageFilter< ComponentImageType, OutputImageType > ThresholdFilterType; ThresholdFilterType::Pointer thresholder = ThresholdFilterType::New(); thresholder->SetLowerThreshold(1); thresholder->SetUpperThreshold(1); thresholder->SetOutsideValue(0); thresholder->SetInsideValue(255); thresholder->SetInput( relabeler->GetOutput() ); WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->SetInput( thresholder->GetOutput() ); writer->Update(); std::cout << "Largest object of " << connected->GetObjectCount() << " objects"; typedef std::vector< itk::SizeValueType > SizesInPixelsType; const SizesInPixelsType & sizesInPixels = relabeler->GetSizeOfObjectsInPixels(); std::cout << "Number of pixels in largest component = " << sizesInPixels[0] << std::endl; std::cout << "Number of pixels in second component = " << sizesInPixels[1] << std::endl; // // Compute integrated projection and use Otsu to find borders. // typedef itk::ImageLinearConstIteratorWithIndex< InputImageType > ConstIteratorType; InputImageType::ConstPointer inputImage = thresholder->GetOutput(); const unsigned int CountDimension = 1; typedef unsigned short CountPixelType; typedef itk::Image< CountPixelType, CountDimension > CountImageType; CountImageType::IndexType start; start[0] = 0; CountImageType::SizeType size; size[0] = inputImage->GetRequestedRegion().GetSize()[0]; CountImageType::RegionType region; region.SetSize( size ); region.SetIndex( start ); CountImageType::Pointer countImage = CountImageType::New(); countImage->SetRegions( region ); countImage->Allocate(); typedef itk::ImageRegionIterator< CountImageType > CountIteratorType; CountIteratorType outputIt( countImage, countImage->GetLargestPossibleRegion() ); outputIt.GoToBegin(); ConstIteratorType inputIt( inputImage, inputImage->GetRequestedRegion() ); inputIt.SetDirection(1); // walk faster along the vertical direction. std::vector<unsigned short> counter; unsigned short line = 0; for ( inputIt.GoToBegin(); ! inputIt.IsAtEnd(); inputIt.NextLine() ) { unsigned short count = 0; inputIt.GoToBeginOfLine(); while ( ! inputIt.IsAtEndOfLine() ) { InputPixelType value = inputIt.Get(); if (value == 255 ) { ++count; } ++inputIt; } outputIt.Set(count); ++outputIt; counter.push_back(count); std::cout << line << " " << count << std::endl; ++line; } CountImageType::IndexType leftIndex; CountImageType::IndexType rightIndex; typedef itk::OtsuMultipleThresholdsImageFilter< CountImageType, CountImageType > OtsuMultipleFilterType; OtsuMultipleFilterType::Pointer otsuMultipleFilter = OtsuMultipleFilterType::New(); otsuMultipleFilter->SetInput( countImage ); otsuMultipleFilter->SetNumberOfThresholds(2); otsuMultipleFilter->Update(); CountImageType::Pointer otsuOutput = otsuMultipleFilter->GetOutput(); CountIteratorType bandsIt( otsuOutput, otsuOutput->GetLargestPossibleRegion() ); bandsIt.GoToBegin(); CountPixelType currentValue = bandsIt.Get(); while (!bandsIt.IsAtEnd()) { if (bandsIt.Get() != currentValue) { leftIndex = bandsIt.GetIndex(); currentValue = bandsIt.Get(); break; } ++bandsIt; } while (!bandsIt.IsAtEnd()) { if (bandsIt.Get() != currentValue) { rightIndex = bandsIt.GetIndex(); break; } ++bandsIt; } // Add a safety band leftIndex[0] += 100; rightIndex[0] -= 100; std::cout << "leftIndex " << leftIndex << std::endl; std::cout << "rightIndex " << rightIndex << std::endl; std::vector< unsigned short > north; std::vector< unsigned short > south; unsigned short xpos = 0; ConstIteratorType rangeIt( inputImage, inputImage->GetRequestedRegion() ); rangeIt.SetDirection(1); // walk faster along the vertical direction. for ( rangeIt.GoToBegin(); ! rangeIt.IsAtEnd(); rangeIt.NextLine(), ++xpos ) { unsigned short bottom = 0; unsigned short top = 0; rangeIt.GoToBeginOfLine(); while ( ! rangeIt.IsAtEndOfLine() ) { InputPixelType value = rangeIt.Get(); if (value == 255 ) { if ( bottom == 0 ) { bottom = rangeIt.GetIndex()[1]; } top = rangeIt.GetIndex()[1]; } ++rangeIt; } if (xpos >= leftIndex[0] && xpos <= rightIndex[0]) { north.push_back(top); south.push_back(bottom); } } std::string northFilename(argv[1]); northFilename.erase(northFilename.end()-4, northFilename.end()); northFilename += "_north.csv"; std::string southFilename(argv[1]); southFilename.erase(southFilename.end()-4, southFilename.end()); southFilename += "_south.csv"; std::cout << northFilename << std::endl; std::cout << southFilename << std::endl; std::ofstream northFile(northFilename.c_str()); std::vector<unsigned short>::const_iterator curveIt = north.begin(); xpos = leftIndex[0]; while (curveIt != north.end()) { northFile << xpos << ", " << *curveIt << std::endl; ++xpos; ++curveIt; } northFile.close(); std::ofstream southFile(southFilename.c_str()); curveIt = south.begin(); xpos = leftIndex[0]; while (curveIt != south.end()) { southFile << xpos << ", " << *curveIt << std::endl; ++xpos; ++curveIt; } southFile.close(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlsecctrl.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-11-11 09:13:25 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // include --------------------------------------------------------------- #ifndef _SHL_HXX //autogen #include <tools/shl.hxx> #endif #ifndef _STATUS_HXX //autogen #include <vcl/status.hxx> #endif #ifndef _MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif //#ifndef _SFXITEMPOOL_HXX //#include <svtools/itempool.hxx> //#endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFXMODULE_HXX #include <sfx2/module.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif #include <svtools/intitem.hxx> #include <svtools/eitem.hxx> #include "dialogs.hrc" #include "dialmgr.hxx" #include "xmlsecctrl.hxx" #include <tools/urlobj.hxx> #define PAINT_OFFSET 5 //#include "sizeitem.hxx" //#include "dialmgr.hxx" //#include "dlgutil.hxx" //#include "stbctrls.h" //#include "dialogs.hrc" /*#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX #include <comphelper/processfactory.hxx> #endif*/ SFX_IMPL_STATUSBAR_CONTROL( XmlSecStatusBarControl, SfxUInt16Item ); struct XmlSecStatusBarControl::XmlSecStatusBarControl_Impl { Point maPos; Size maSize; UINT16 mnState; Image maImage; Image maImageBroken; Image maImageNotValidated; }; XmlSecStatusBarControl::XmlSecStatusBarControl( USHORT _nSlotId, USHORT _nId, StatusBar& _rStb ) :SfxStatusBarControl( _nSlotId, _nId, _rStb ) ,mpImpl( new XmlSecStatusBarControl_Impl ) { mpImpl->mnState = SIGNATURESTATE_UNKNOWN; sal_Bool bIsDark = GetStatusBar().GetBackground().GetColor().IsDark(); mpImpl->maImage = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_H : RID_SVXBMP_SIGNET ) ); mpImpl->maImageBroken = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_BROKEN_H : RID_SVXBMP_SIGNET_BROKEN ) ); mpImpl->maImageNotValidated = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_NOTVALIDATED_H : RID_SVXBMP_SIGNET_NOTVALIDATED ) ); } XmlSecStatusBarControl::~XmlSecStatusBarControl() { delete mpImpl; } void XmlSecStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { GetStatusBar().SetHelpText( GetId(), String() );// necessary ? GetStatusBar().SetHelpId( GetId(), nSID ); // necessary ? if( SFX_ITEM_AVAILABLE != eState ) { mpImpl->mnState = SIGNATURESTATE_UNKNOWN; } else if( pState->ISA( SfxUInt16Item ) ) { // mpImpl->mbSigned = ( ( SfxUInt16Item* ) pState )->GetValue() == 1 /* SIGNED*/ ; mpImpl->mnState = ( ( SfxUInt16Item* ) pState )->GetValue(); } else { DBG_ERRORFILE( "+XmlSecStatusBarControl::StateChanged(): invalid item type" ); mpImpl->mnState = SIGNATURESTATE_UNKNOWN; } if( GetStatusBar().AreItemsVisible() ) // necessary ? GetStatusBar().SetItemData( GetId(), 0 ); GetStatusBar().SetItemText( GetId(), String() ); // necessary ? USHORT nResId = RID_SVXSTR_XMLSEC_NO_SIG; if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_OK ) nResId = RID_SVXSTR_XMLSEC_SIG_OK; else if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_BROKEN ) nResId = RID_SVXSTR_XMLSEC_SIG_NOT_OK; else if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED ) nResId = RID_SVXSTR_XMLSEC_SIG_OK_NO_VERIFY; GetStatusBar().SetQuickHelpText( GetId(), SVX_RESSTR( nResId ) ); } void XmlSecStatusBarControl::Command( const CommandEvent& rCEvt ) { if( rCEvt.GetCommand() == COMMAND_CONTEXTMENU ) { PopupMenu aPopupMenu( ResId( RID_SVXMNU_XMLSECSTATBAR, DIALOG_MGR() ) ); if( aPopupMenu.Execute( &GetStatusBar(), rCEvt.GetMousePosPixel() ) ) { ::com::sun::star::uno::Any a; SfxUInt16Item aState( GetSlotId(), 0 ); INetURLObject aObj( m_aCommandURL ); ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aState.QueryValue( a ); aArgs[0].Value = a; execute( aArgs ); } } else SfxStatusBarControl::Command( rCEvt ); } void XmlSecStatusBarControl::Paint( const UserDrawEvent& rUsrEvt ) { OutputDevice* pDev = rUsrEvt.GetDevice(); DBG_ASSERT( pDev, "-XmlSecStatusBarControl::Paint(): no Output Device... this will lead to nirvana..." ); Rectangle aRect = rUsrEvt.GetRect(); StatusBar& rBar = GetStatusBar(); Point aItemPos = rBar.GetItemTextPos( GetId() ); Color aOldLineColor = pDev->GetLineColor(); Color aOldFillColor = pDev->GetFillColor(); pDev->SetLineColor(); pDev->SetFillColor( pDev->GetBackground().GetColor() ); if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_OK ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImage ); } else if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_BROKEN ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImageBroken ); } else if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImageNotValidated ); } else pDev->DrawRect( aRect ); pDev->SetLineColor( aOldLineColor ); pDev->SetFillColor( aOldFillColor ); } long XmlSecStatusBarControl::GetDefItemWidth( StatusBar& _rStatusBar ) { return 16; } <commit_msg>INTEGRATION: CWS pchfix02 (1.6.430); FILE MERGED 2006/09/01 17:47:18 kaib 1.6.430.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlsecctrl.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-17 05:45:54 $ * * 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_svx.hxx" // include --------------------------------------------------------------- #ifndef _SHL_HXX //autogen #include <tools/shl.hxx> #endif #ifndef _STATUS_HXX //autogen #include <vcl/status.hxx> #endif #ifndef _MENU_HXX //autogen #include <vcl/menu.hxx> #endif #ifndef _SV_IMAGE_HXX #include <vcl/image.hxx> #endif //#ifndef _SFXITEMPOOL_HXX //#include <svtools/itempool.hxx> //#endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SFXMODULE_HXX #include <sfx2/module.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFX_OBJSH_HXX //autogen #include <sfx2/objsh.hxx> #endif #ifndef _SFXSIDS_HRC #include <sfx2/sfxsids.hrc> #endif #include <svtools/intitem.hxx> #include <svtools/eitem.hxx> #include "dialogs.hrc" #include "dialmgr.hxx" #include "xmlsecctrl.hxx" #include <tools/urlobj.hxx> #define PAINT_OFFSET 5 //#include "sizeitem.hxx" //#include "dialmgr.hxx" //#include "dlgutil.hxx" //#include "stbctrls.h" //#include "dialogs.hrc" /*#ifndef _UNOTOOLS_LOCALEDATAWRAPPER_HXX #include <unotools/localedatawrapper.hxx> #endif #ifndef _UNOTOOLS_PROCESSFACTORY_HXX #include <comphelper/processfactory.hxx> #endif*/ SFX_IMPL_STATUSBAR_CONTROL( XmlSecStatusBarControl, SfxUInt16Item ); struct XmlSecStatusBarControl::XmlSecStatusBarControl_Impl { Point maPos; Size maSize; UINT16 mnState; Image maImage; Image maImageBroken; Image maImageNotValidated; }; XmlSecStatusBarControl::XmlSecStatusBarControl( USHORT _nSlotId, USHORT _nId, StatusBar& _rStb ) :SfxStatusBarControl( _nSlotId, _nId, _rStb ) ,mpImpl( new XmlSecStatusBarControl_Impl ) { mpImpl->mnState = SIGNATURESTATE_UNKNOWN; sal_Bool bIsDark = GetStatusBar().GetBackground().GetColor().IsDark(); mpImpl->maImage = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_H : RID_SVXBMP_SIGNET ) ); mpImpl->maImageBroken = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_BROKEN_H : RID_SVXBMP_SIGNET_BROKEN ) ); mpImpl->maImageNotValidated = Image( SVX_RES( bIsDark ? RID_SVXBMP_SIGNET_NOTVALIDATED_H : RID_SVXBMP_SIGNET_NOTVALIDATED ) ); } XmlSecStatusBarControl::~XmlSecStatusBarControl() { delete mpImpl; } void XmlSecStatusBarControl::StateChanged( USHORT nSID, SfxItemState eState, const SfxPoolItem* pState ) { GetStatusBar().SetHelpText( GetId(), String() );// necessary ? GetStatusBar().SetHelpId( GetId(), nSID ); // necessary ? if( SFX_ITEM_AVAILABLE != eState ) { mpImpl->mnState = SIGNATURESTATE_UNKNOWN; } else if( pState->ISA( SfxUInt16Item ) ) { // mpImpl->mbSigned = ( ( SfxUInt16Item* ) pState )->GetValue() == 1 /* SIGNED*/ ; mpImpl->mnState = ( ( SfxUInt16Item* ) pState )->GetValue(); } else { DBG_ERRORFILE( "+XmlSecStatusBarControl::StateChanged(): invalid item type" ); mpImpl->mnState = SIGNATURESTATE_UNKNOWN; } if( GetStatusBar().AreItemsVisible() ) // necessary ? GetStatusBar().SetItemData( GetId(), 0 ); GetStatusBar().SetItemText( GetId(), String() ); // necessary ? USHORT nResId = RID_SVXSTR_XMLSEC_NO_SIG; if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_OK ) nResId = RID_SVXSTR_XMLSEC_SIG_OK; else if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_BROKEN ) nResId = RID_SVXSTR_XMLSEC_SIG_NOT_OK; else if ( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED ) nResId = RID_SVXSTR_XMLSEC_SIG_OK_NO_VERIFY; GetStatusBar().SetQuickHelpText( GetId(), SVX_RESSTR( nResId ) ); } void XmlSecStatusBarControl::Command( const CommandEvent& rCEvt ) { if( rCEvt.GetCommand() == COMMAND_CONTEXTMENU ) { PopupMenu aPopupMenu( ResId( RID_SVXMNU_XMLSECSTATBAR, DIALOG_MGR() ) ); if( aPopupMenu.Execute( &GetStatusBar(), rCEvt.GetMousePosPixel() ) ) { ::com::sun::star::uno::Any a; SfxUInt16Item aState( GetSlotId(), 0 ); INetURLObject aObj( m_aCommandURL ); ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > aArgs( 1 ); aArgs[0].Name = aObj.GetURLPath(); aState.QueryValue( a ); aArgs[0].Value = a; execute( aArgs ); } } else SfxStatusBarControl::Command( rCEvt ); } void XmlSecStatusBarControl::Paint( const UserDrawEvent& rUsrEvt ) { OutputDevice* pDev = rUsrEvt.GetDevice(); DBG_ASSERT( pDev, "-XmlSecStatusBarControl::Paint(): no Output Device... this will lead to nirvana..." ); Rectangle aRect = rUsrEvt.GetRect(); StatusBar& rBar = GetStatusBar(); Point aItemPos = rBar.GetItemTextPos( GetId() ); Color aOldLineColor = pDev->GetLineColor(); Color aOldFillColor = pDev->GetFillColor(); pDev->SetLineColor(); pDev->SetFillColor( pDev->GetBackground().GetColor() ); if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_OK ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImage ); } else if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_BROKEN ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImageBroken ); } else if( mpImpl->mnState == SIGNATURESTATE_SIGNATURES_NOTVALIDATED ) { ++aRect.Top(); pDev->DrawImage( aRect.TopLeft(), mpImpl->maImageNotValidated ); } else pDev->DrawRect( aRect ); pDev->SetLineColor( aOldLineColor ); pDev->SetFillColor( aOldFillColor ); } long XmlSecStatusBarControl::GetDefItemWidth( StatusBar& _rStatusBar ) { return 16; } <|endoftext|>
<commit_before>/* $Id$ */ #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <TROOT.h> #include "AliAnalysisDataContainer.h" #include "AliAnalysisDataSlot.h" #include "AliAnalysisManager.h" #include "AliEmcalPhysicsSelection.h" #include "AliEmcalPhysicsSelectionTask.h" #include "AliESDEvent.h" #include "AliInputEventHandler.h" #include "AliLog.h" ClassImp(AliEmcalPhysicsSelectionTask) //__________________________________________________________________________________________________ AliEmcalPhysicsSelectionTask::AliEmcalPhysicsSelectionTask() : AliPhysicsSelectionTask(), fDoWriteHistos(1), fNCalled(0), fNAccepted(0), fHAcc(0) { // Default constructor. } //__________________________________________________________________________________________________ AliEmcalPhysicsSelectionTask::AliEmcalPhysicsSelectionTask(const char* opt) : AliPhysicsSelectionTask(), fDoWriteHistos(1), fNCalled(0), fNAccepted(0), fHAcc(0) { // Constructor. fOption = opt; fPhysicsSelection = new AliEmcalPhysicsSelection; AliInputEventHandler* handler = dynamic_cast<AliInputEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (handler) { handler->SetEventSelection(fPhysicsSelection); AliInfo("Physics Event Selection enabled."); } else { AliError("No input event handler connected to analysis manager. No Physics Event Selection."); } // Define input and output slots here DefineOutput(1, TList::Class()); fBranchNames = "ESD:AliESDRun.,AliESDHeader.,AliMultiplicity.,AliESDFMD.,AliESDVZERO.,AliESDZDC.,SPDVertex.,PrimaryVertex."; AliLog::SetClassDebugLevel("AliEmcalPhysicsSelectionTask", AliLog::kWarning); } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::UserCreateOutputObjects() { // User create outputs. AliPhysicsSelectionTask::UserCreateOutputObjects(); fHAcc = new TH1D("hEvCount",";0=rej/1=acc;#",2,-0.5,1.5); fOutput->Add(fHAcc); if (!fDoWriteHistos) { fOutput->Remove(fPhysicsSelection); } } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::UserExec(const Option_t *opt) { // User exec. AliPhysicsSelectionTask::UserExec(opt); ++fNCalled; UInt_t res = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); if (res>0) { ++fNAccepted; fHAcc->Fill(1); } else { fHAcc->Fill(0); } } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::Terminate(Option_t *) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. AliInfo(Form("Called %d times, accepted %d events", fNCalled, fNAccepted)); if (!fDoWriteHistos) return; fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { AliError("fOutput not available"); return; } AliAnalysisDataSlot *oslot = GetOutputSlot(1); if (!oslot) return; AliAnalysisDataContainer *ocont = oslot->GetContainer(); if (!ocont) return; TFile *file = OpenFile(1); if (!file) return; TDirectory::TContext context(file); if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { fPhysicsSelection = dynamic_cast<AliPhysicsSelection*> (fOutput->FindObject("AliPhysicsSelection")); } if (fPhysicsSelection) { //fPhysicsSelection->Print(); fPhysicsSelection->SaveHistograms(Form("%sHists",ocont->GetName())); AliInfo(Form("Writing result to %s",file->GetName())); } fOutput->Remove(fPhysicsSelection); } <commit_msg>branches<commit_after>/* $Id$ */ #include <TFile.h> #include <TH1F.h> #include <TH2F.h> #include <TROOT.h> #include "AliAnalysisDataContainer.h" #include "AliAnalysisDataSlot.h" #include "AliAnalysisManager.h" #include "AliEmcalPhysicsSelection.h" #include "AliEmcalPhysicsSelectionTask.h" #include "AliESDEvent.h" #include "AliInputEventHandler.h" #include "AliLog.h" ClassImp(AliEmcalPhysicsSelectionTask) //__________________________________________________________________________________________________ AliEmcalPhysicsSelectionTask::AliEmcalPhysicsSelectionTask() : AliPhysicsSelectionTask(), fDoWriteHistos(1), fNCalled(0), fNAccepted(0), fHAcc(0) { // Default constructor. } //__________________________________________________________________________________________________ AliEmcalPhysicsSelectionTask::AliEmcalPhysicsSelectionTask(const char* opt) : AliPhysicsSelectionTask(), fDoWriteHistos(1), fNCalled(0), fNAccepted(0), fHAcc(0) { // Constructor. fOption = opt; fPhysicsSelection = new AliEmcalPhysicsSelection; AliInputEventHandler* handler = dynamic_cast<AliInputEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (handler) { handler->SetEventSelection(fPhysicsSelection); AliInfo("Physics Event Selection enabled."); } else { AliError("No input event handler connected to analysis manager. No Physics Event Selection."); } // Define input and output slots here DefineOutput(1, TList::Class()); fBranchNames = "ESD:AliESDRun.,AliESDHeader.,AliMultiplicity.,AliESDVZERO.," "AliESDZDC.,SPDVertex.,PrimaryVertex.,TPCVertex.,Tracks,SPDPileupVertices"; AliLog::SetClassDebugLevel("AliEmcalPhysicsSelectionTask", AliLog::kWarning); } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::UserCreateOutputObjects() { // User create outputs. AliPhysicsSelectionTask::UserCreateOutputObjects(); fHAcc = new TH1D("hEvCount",";0=rej/1=acc;#",2,-0.5,1.5); fOutput->Add(fHAcc); if (!fDoWriteHistos) { fOutput->Remove(fPhysicsSelection); } } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::UserExec(const Option_t *opt) { // User exec. AliPhysicsSelectionTask::UserExec(opt); ++fNCalled; UInt_t res = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); if (res>0) { ++fNAccepted; fHAcc->Fill(1); } else { fHAcc->Fill(0); } } //__________________________________________________________________________________________________ void AliEmcalPhysicsSelectionTask::Terminate(Option_t *) { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. AliInfo(Form("Called %d times, accepted %d events", fNCalled, fNAccepted)); if (!fDoWriteHistos) return; fOutput = dynamic_cast<TList*> (GetOutputData(1)); if (!fOutput) { AliError("fOutput not available"); return; } AliAnalysisDataSlot *oslot = GetOutputSlot(1); if (!oslot) return; AliAnalysisDataContainer *ocont = oslot->GetContainer(); if (!ocont) return; TFile *file = OpenFile(1); if (!file) return; TDirectory::TContext context(file); if (AliAnalysisManager::GetAnalysisManager()->IsProofMode()) { fPhysicsSelection = dynamic_cast<AliPhysicsSelection*> (fOutput->FindObject("AliPhysicsSelection")); } if (fPhysicsSelection) { //fPhysicsSelection->Print(); fPhysicsSelection->SaveHistograms(Form("%sHists",ocont->GetName())); AliInfo(Form("Writing result to %s",file->GetName())); } fOutput->Remove(fPhysicsSelection); } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 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 <boost/signals2.hpp> #include <boost/signals2/dummy_mutex.hpp> #include <seastar/core/shared_future.hh> namespace bs2 = boost::signals2; namespace gms { class feature_service; /** * A gossip feature tracks whether all the nodes the current one is * aware of support the specified feature. * * A feature should only be created once the gossiper is available. */ class feature final { using signal_type = bs2::signal_type<void (), bs2::keywords::mutex_type<bs2::dummy_mutex>>::type; feature_service* _service = nullptr; sstring _name; bool _enabled = false; mutable shared_promise<> _pr; mutable signal_type _s; friend class gossiper; public: class listener { friend class feature; bs2::scoped_connection _conn; signal_type::slot_type _slot; const signal_type::slot_type& get_slot() const { return _slot; } void set_connection(bs2::scoped_connection&& conn) { _conn = std::move(conn); } void callback() { _conn.disconnect(); on_enabled(); } protected: bool _started = false; public: listener() : _slot(signal_type::slot_type(&listener::callback, this)) {} listener(const listener&) = delete; listener(listener&&) = delete; listener& operator=(const listener&) = delete; listener& operator=(listener&&) = delete; // Has to run inside seastar::async context virtual void on_enabled() = 0; }; explicit feature(feature_service& service, sstring name, bool enabled = false); feature() = default; ~feature(); feature(const feature& other) = delete; // Has to run inside seastar::async context void enable(); feature& operator=(feature&& other); const sstring& name() const { return _name; } explicit operator bool() const { return _enabled; } friend inline std::ostream& operator<<(std::ostream& os, const feature& f) { return os << "{ gossip feature = " << f._name << " }"; } future<> when_enabled() const { return _pr.get_shared_future(); } void when_enabled(listener& callback) { callback.set_connection(_s.connect(callback.get_slot())); if (_enabled) { _s(); } } }; } // namespace gms <commit_msg>gms/feature: Mark all when_enabled() overloads as const<commit_after>/* * Copyright (C) 2016 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 <boost/signals2.hpp> #include <boost/signals2/dummy_mutex.hpp> #include <seastar/core/shared_future.hh> namespace bs2 = boost::signals2; namespace gms { class feature_service; /** * A gossip feature tracks whether all the nodes the current one is * aware of support the specified feature. * * A feature should only be created once the gossiper is available. */ class feature final { using signal_type = bs2::signal_type<void (), bs2::keywords::mutex_type<bs2::dummy_mutex>>::type; feature_service* _service = nullptr; sstring _name; bool _enabled = false; mutable shared_promise<> _pr; mutable signal_type _s; friend class gossiper; public: class listener { friend class feature; bs2::scoped_connection _conn; signal_type::slot_type _slot; const signal_type::slot_type& get_slot() const { return _slot; } void set_connection(bs2::scoped_connection&& conn) { _conn = std::move(conn); } void callback() { _conn.disconnect(); on_enabled(); } protected: bool _started = false; public: listener() : _slot(signal_type::slot_type(&listener::callback, this)) {} listener(const listener&) = delete; listener(listener&&) = delete; listener& operator=(const listener&) = delete; listener& operator=(listener&&) = delete; // Has to run inside seastar::async context virtual void on_enabled() = 0; }; explicit feature(feature_service& service, sstring name, bool enabled = false); feature() = default; ~feature(); feature(const feature& other) = delete; // Has to run inside seastar::async context void enable(); feature& operator=(feature&& other); const sstring& name() const { return _name; } explicit operator bool() const { return _enabled; } friend inline std::ostream& operator<<(std::ostream& os, const feature& f) { return os << "{ gossip feature = " << f._name << " }"; } future<> when_enabled() const { return _pr.get_shared_future(); } void when_enabled(listener& callback) const { callback.set_connection(_s.connect(callback.get_slot())); if (_enabled) { _s(); } } }; } // namespace gms <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: feflyole.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: rt $ $Date: 2005-09-09 03:37:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #ifndef _SFX_CLIENTSH_HXX #include <sfx2/ipclient.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SCH_DLL_HXX #include <sch/schdll.hxx> #endif #ifndef _SCH_MEMCHRT_HXX #include <sch/memchrt.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #include <sot/exchange.hxx> #ifndef _FMTCNTNT_HXX #include <fmtcntnt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FESH_HXX #include <fesh.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _EDIMP_HXX #include <edimp.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _NOTXTFRM_HXX #include <notxtfrm.hxx> #endif #ifndef _NDOLE_HXX #include <ndole.hxx> #endif #ifndef _SWCLI_HXX #include <swcli.hxx> #endif using namespace com::sun::star; SwFlyFrm *SwFEShell::FindFlyFrm( const uno::Reference < embed::XEmbeddedObject >& xObj ) const { SwFlyFrm *pFly = FindFlyFrm(); if ( pFly && pFly->Lower() && pFly->Lower()->IsNoTxtFrm() ) { SwOLENode *pNd = ((SwNoTxtFrm*)pFly->Lower())->GetNode()->GetOLENode(); if ( !pNd || pNd->GetOLEObj().GetOleRef() != xObj ) pFly = 0; } else pFly = 0; if ( !pFly ) { //Kein Fly oder der falsche selektiert. Ergo muessen wir leider suchen. BOOL bExist = FALSE; SwStartNode *pStNd; ULONG nSttIdx = GetNodes().GetEndOfAutotext().StartOfSectionIndex() + 1, nEndIdx = GetNodes().GetEndOfAutotext().GetIndex(); while( nSttIdx < nEndIdx && 0 != (pStNd = GetNodes()[ nSttIdx ]->GetStartNode()) ) { SwNode *pNd = GetNodes()[ nSttIdx+1 ]; if ( pNd->IsOLENode() && ((SwOLENode*)pNd)->GetOLEObj().GetOleRef() == xObj ) { bExist = TRUE; SwFrm *pFrm = ((SwOLENode*)pNd)->GetFrm(); if ( pFrm ) pFly = pFrm->FindFlyFrm(); break; } nSttIdx = pStNd->EndOfSectionIndex() + 1; } ASSERT( bExist, "OLE-Object unknown and FlyFrm not found." ); } return pFly; } String SwFEShell::GetUniqueOLEName() const { return GetDoc()->GetUniqueOLEName(); } String SwFEShell::GetUniqueFrameName() const { return GetDoc()->GetUniqueFrameName(); } void SwFEShell::MakeObjVisible( const uno::Reference < embed::XEmbeddedObject >& xObj ) const { SwFlyFrm *pFly = FindFlyFrm( xObj ); if ( pFly ) { SwRect aTmp( pFly->Prt() ); aTmp += pFly->Frm().Pos(); if ( !aTmp.IsOver( VisArea() ) ) { ((SwFEShell*)this)->StartAction(); ((SwFEShell*)this)->MakeVisible( aTmp ); ((SwFEShell*)this)->EndAction(); } } } BOOL SwFEShell::FinishOLEObj() // Server wird beendet { SfxInPlaceClient* pIPClient = GetSfxViewShell()->GetIPClient(); if ( !pIPClient ) return FALSE; BOOL bRet = pIPClient->IsObjectInPlaceActive(); if( bRet ) { uno::Reference < embed::XEmbeddedObject > xObj = pIPClient->GetObject(); if( CNT_OLE == GetCntType() ) ClearAutomaticContour(); // Link fuer Daten-Highlighting im Chart zuruecksetzen SvtModuleOptions aMOpt; if( aMOpt.IsChart() ) { uno::Reference < embed::XClassifiedObject > xClass( xObj, uno::UNO_QUERY ); SvGlobalName aObjClsId( xClass->getClassID() ); SchMemChart* pMemChart; if( SotExchange::IsChart( aObjClsId ) && 0 != (pMemChart = SchDLL::GetChartData( xObj ) )) { pMemChart->SetSelectionHdl( Link() ); //ggfs. auch die Selektion restaurieren LockView( TRUE ); //Scrollen im EndAction verhindern ClearMark(); LockView( FALSE ); } } if( ((SwOleClient*)pIPClient)->IsCheckForOLEInCaption() != IsCheckForOLEInCaption() ) SetCheckForOLEInCaption( !IsCheckForOLEInCaption() ); //InPlace beenden. xObj->changeState( embed::EmbedStates::RUNNING ); SFX_APP()->SetViewFrame( GetSfxViewShell()->GetViewFrame() ); } return bRet; } <commit_msg>INTEGRATION: CWS sfxcleanup (1.9.242); FILE MERGED 2006/02/27 08:41:44 mba 1.9.242.1: #132394#: remove superfluous code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: feflyole.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2006-05-02 15:17:44 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #pragma hdrstop #ifndef _COM_SUN_STAR_EMBED_EMBEDSTATES_HPP_ #include <com/sun/star/embed/EmbedStates.hpp> #endif #ifndef _SFX_CLIENTSH_HXX #include <sfx2/ipclient.hxx> #endif #ifndef _SFXVIEWSH_HXX #include <sfx2/viewsh.hxx> #endif #ifndef _SFXAPP_HXX #include <sfx2/app.hxx> #endif #ifndef _SCH_DLL_HXX #include <sch/schdll.hxx> #endif #ifndef _SCH_MEMCHRT_HXX #include <sch/memchrt.hxx> #endif #ifndef INCLUDED_SVTOOLS_MODULEOPTIONS_HXX #include <svtools/moduleoptions.hxx> #endif #include <sfx2/viewfrm.hxx> #include <sot/exchange.hxx> #ifndef _FMTCNTNT_HXX #include <fmtcntnt.hxx> #endif #ifndef _FMTANCHR_HXX #include <fmtanchr.hxx> #endif #ifndef _FESH_HXX #include <fesh.hxx> #endif #ifndef _CNTFRM_HXX #include <cntfrm.hxx> #endif #ifndef _FRMFMT_HXX #include <frmfmt.hxx> #endif #ifndef _FLYFRM_HXX #include <flyfrm.hxx> #endif #ifndef _PAM_HXX #include <pam.hxx> #endif #ifndef _EDIMP_HXX #include <edimp.hxx> #endif #ifndef _NDTXT_HXX #include <ndtxt.hxx> #endif #ifndef _NOTXTFRM_HXX #include <notxtfrm.hxx> #endif #ifndef _NDOLE_HXX #include <ndole.hxx> #endif #ifndef _SWCLI_HXX #include <swcli.hxx> #endif using namespace com::sun::star; SwFlyFrm *SwFEShell::FindFlyFrm( const uno::Reference < embed::XEmbeddedObject >& xObj ) const { SwFlyFrm *pFly = FindFlyFrm(); if ( pFly && pFly->Lower() && pFly->Lower()->IsNoTxtFrm() ) { SwOLENode *pNd = ((SwNoTxtFrm*)pFly->Lower())->GetNode()->GetOLENode(); if ( !pNd || pNd->GetOLEObj().GetOleRef() != xObj ) pFly = 0; } else pFly = 0; if ( !pFly ) { //Kein Fly oder der falsche selektiert. Ergo muessen wir leider suchen. BOOL bExist = FALSE; SwStartNode *pStNd; ULONG nSttIdx = GetNodes().GetEndOfAutotext().StartOfSectionIndex() + 1, nEndIdx = GetNodes().GetEndOfAutotext().GetIndex(); while( nSttIdx < nEndIdx && 0 != (pStNd = GetNodes()[ nSttIdx ]->GetStartNode()) ) { SwNode *pNd = GetNodes()[ nSttIdx+1 ]; if ( pNd->IsOLENode() && ((SwOLENode*)pNd)->GetOLEObj().GetOleRef() == xObj ) { bExist = TRUE; SwFrm *pFrm = ((SwOLENode*)pNd)->GetFrm(); if ( pFrm ) pFly = pFrm->FindFlyFrm(); break; } nSttIdx = pStNd->EndOfSectionIndex() + 1; } ASSERT( bExist, "OLE-Object unknown and FlyFrm not found." ); } return pFly; } String SwFEShell::GetUniqueOLEName() const { return GetDoc()->GetUniqueOLEName(); } String SwFEShell::GetUniqueFrameName() const { return GetDoc()->GetUniqueFrameName(); } void SwFEShell::MakeObjVisible( const uno::Reference < embed::XEmbeddedObject >& xObj ) const { SwFlyFrm *pFly = FindFlyFrm( xObj ); if ( pFly ) { SwRect aTmp( pFly->Prt() ); aTmp += pFly->Frm().Pos(); if ( !aTmp.IsOver( VisArea() ) ) { ((SwFEShell*)this)->StartAction(); ((SwFEShell*)this)->MakeVisible( aTmp ); ((SwFEShell*)this)->EndAction(); } } } BOOL SwFEShell::FinishOLEObj() // Server wird beendet { SfxInPlaceClient* pIPClient = GetSfxViewShell()->GetIPClient(); if ( !pIPClient ) return FALSE; BOOL bRet = pIPClient->IsObjectInPlaceActive(); if( bRet ) { uno::Reference < embed::XEmbeddedObject > xObj = pIPClient->GetObject(); if( CNT_OLE == GetCntType() ) ClearAutomaticContour(); // Link fuer Daten-Highlighting im Chart zuruecksetzen SvtModuleOptions aMOpt; if( aMOpt.IsChart() ) { uno::Reference < embed::XClassifiedObject > xClass( xObj, uno::UNO_QUERY ); SvGlobalName aObjClsId( xClass->getClassID() ); SchMemChart* pMemChart; if( SotExchange::IsChart( aObjClsId ) && 0 != (pMemChart = SchDLL::GetChartData( xObj ) )) { pMemChart->SetSelectionHdl( Link() ); //ggfs. auch die Selektion restaurieren LockView( TRUE ); //Scrollen im EndAction verhindern ClearMark(); LockView( FALSE ); } } if( ((SwOleClient*)pIPClient)->IsCheckForOLEInCaption() != IsCheckForOLEInCaption() ) SetCheckForOLEInCaption( !IsCheckForOLEInCaption() ); //InPlace beenden. xObj->changeState( embed::EmbedStates::RUNNING ); //TODO/CLEANUP //SetViewFrame nur SFX SfxViewFrame::SetViewFrame( GetSfxViewShell()->GetViewFrame() ); } return bRet; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/phy_cntrl.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file phy_cntrl.C /// @brief Subroutines for the PHY PC registers /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/phy_cntrl.H> #include <lib/utils/scom.H> #include <lib/utils/c_str.H> #include <lib/utils/index.H> #include <lib/mss_attribute_accessors.H> using fapi2::TARGET_TYPE_MCA; namespace mss { namespace pc { /// /// @brief Reset the PC CONFIG0 register /// @param[in] i_target the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config0(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; l_data.setBit<TT::DDR4_CMD_SIG_REDUCTION>(); l_data.setBit<TT::DDR4_VLEVEL_BANK_GROUP>(); FAPI_TRY( write_config0(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reset the PC CONFIG1 register /// @param[in] i_target <the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config1(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; // Static table of PHY config values for MEMORY_TYPE. // [EMPTY, RDIMM, CDIMM, or LRDIMM][EMPTY, DDR3 or DDR4] constexpr uint64_t memory_type[4][3] = { { 0, 0, 0 }, // Empty, never really used. { 0, 0b001, 0b101 }, // RDIMM { 0, 0b000, 0b000 }, // CDIMM bits, UDIMM enum (placeholder, never used on Nimbus) { 0, 0b011, 0b111 }, // LRDIMM }; fapi2::buffer<uint64_t> l_data; uint8_t l_rlo = 0; uint8_t l_wlo = 0; uint8_t l_dram_gen[MAX_DIMM_PER_PORT] = {0}; uint8_t l_dimm_type[MAX_DIMM_PER_PORT] = {0}; uint8_t l_type_index = 0; uint8_t l_gen_index = 0; FAPI_TRY( mss::vpd_mr_dphy_rlo(i_target, l_rlo) ); FAPI_TRY( mss::vpd_mr_dphy_wlo(i_target, l_wlo) ); FAPI_TRY( mss::eff_dram_gen(i_target, &(l_dram_gen[0])) ); FAPI_TRY( mss::eff_dimm_type(i_target, &(l_dimm_type[0])) ); // There's no way to configure the PHY for more than one value. However, we don't know if there's // a DIMM in one slot, the other or double drop. So we do a little gyration here to make sure // we have one of the two values (and assume effective config caught a bad config) l_type_index = l_dimm_type[0] | l_dimm_type[1]; l_gen_index = l_dram_gen[0] | l_dram_gen[1]; // FOR NIMBUS PHY (as the protocol choice above is) BRS FAPI_TRY( mss::getScom(i_target, MCA_DDRPHY_PC_CONFIG1_P0, l_data) ); l_data.insertFromRight<TT::MEMORY_TYPE, TT::MEMORY_TYPE_LEN>(memory_type[l_type_index][l_gen_index]); l_data.insertFromRight<TT::READ_LATENCY_OFFSET, TT::READ_LATENCY_OFFSET_LEN>(l_rlo); l_data.insertFromRight<TT::WRITE_LATENCY_OFFSET, TT::WRITE_LATENCY_OFFSET_LEN>(l_wlo); // TODO RTC:160355 Need to check what mode to put this bit in if there are mixed 3DS/SDP DIMM l_data.clearBit<TT::DDR4_LATENCY_SW>(); FAPI_TRY( write_config1(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace pc } // close namespace mss <commit_msg>Change DDR4 latency switch to always use MR0 A12<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/phy_cntrl.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file phy_cntrl.C /// @brief Subroutines for the PHY PC registers /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <fapi2.H> #include <lib/phy/phy_cntrl.H> #include <lib/utils/scom.H> #include <lib/utils/c_str.H> #include <lib/utils/index.H> #include <lib/mss_attribute_accessors.H> using fapi2::TARGET_TYPE_MCA; namespace mss { namespace pc { /// /// @brief Reset the PC CONFIG0 register /// @param[in] i_target the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config0(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; fapi2::buffer<uint64_t> l_data; l_data.setBit<TT::DDR4_CMD_SIG_REDUCTION>(); l_data.setBit<TT::DDR4_VLEVEL_BANK_GROUP>(); FAPI_TRY( write_config0(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Reset the PC CONFIG1 register /// @param[in] i_target <the target (MCA or MBA?) /// @return FAPI2_RC_SUCCESS if and only if ok /// template<> fapi2::ReturnCode reset_config1(const fapi2::Target<TARGET_TYPE_MCA>& i_target) { typedef pcTraits<TARGET_TYPE_MCA> TT; // Static table of PHY config values for MEMORY_TYPE. // [EMPTY, RDIMM, CDIMM, or LRDIMM][EMPTY, DDR3 or DDR4] constexpr uint64_t memory_type[4][3] = { { 0, 0, 0 }, // Empty, never really used. { 0, 0b001, 0b101 }, // RDIMM { 0, 0b000, 0b000 }, // CDIMM bits, UDIMM enum (placeholder, never used on Nimbus) { 0, 0b011, 0b111 }, // LRDIMM }; fapi2::buffer<uint64_t> l_data; uint8_t l_rlo = 0; uint8_t l_wlo = 0; uint8_t l_dram_gen[MAX_DIMM_PER_PORT] = {0}; uint8_t l_dimm_type[MAX_DIMM_PER_PORT] = {0}; uint8_t l_type_index = 0; uint8_t l_gen_index = 0; FAPI_TRY( mss::vpd_mr_dphy_rlo(i_target, l_rlo) ); FAPI_TRY( mss::vpd_mr_dphy_wlo(i_target, l_wlo) ); FAPI_TRY( mss::eff_dram_gen(i_target, &(l_dram_gen[0])) ); FAPI_TRY( mss::eff_dimm_type(i_target, &(l_dimm_type[0])) ); // There's no way to configure the PHY for more than one value. However, we don't know if there's // a DIMM in one slot, the other or double drop. So we do a little gyration here to make sure // we have one of the two values (and assume effective config caught a bad config) l_type_index = l_dimm_type[0] | l_dimm_type[1]; l_gen_index = l_dram_gen[0] | l_dram_gen[1]; // FOR NIMBUS PHY (as the protocol choice above is) BRS FAPI_TRY( mss::getScom(i_target, MCA_DDRPHY_PC_CONFIG1_P0, l_data) ); l_data.insertFromRight<TT::MEMORY_TYPE, TT::MEMORY_TYPE_LEN>(memory_type[l_type_index][l_gen_index]); l_data.insertFromRight<TT::READ_LATENCY_OFFSET, TT::READ_LATENCY_OFFSET_LEN>(l_rlo); l_data.insertFromRight<TT::WRITE_LATENCY_OFFSET, TT::WRITE_LATENCY_OFFSET_LEN>(l_wlo); // Always set this bit. It forces the PHY to use A12 when figuring out latency. This makes sense in // all cases as A12 is 0 for non-3DS in MR0. l_data.setBit<TT::DDR4_LATENCY_SW>(); FAPI_TRY( write_config1(i_target, l_data) ); fapi_try_exit: return fapi2::current_err; } } // close namespace pc } // close namespace mss <|endoftext|>
<commit_before><commit_msg>coverity#736853 Dereference before null check<commit_after><|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2011, 2012, 2013, 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/testing/test_case.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_polymorphism namespace abc { namespace test { class exception_polymorphism : public testing::test_case { protected: //! First-level abc::generic_error subclass. class derived1_error : public virtual generic_error { public: //! Constructor. derived1_error() : generic_error() { m_pszWhat = "abc::test::exception_polymorphism::derived1_error"; } }; //! Second-level abc::generic_error subclass. class derived2_error : public virtual derived1_error { public: //! Constructor. derived2_error() : derived1_error() { m_pszWhat = "abc::test::exception_polymorphism::derived2_error"; } }; //! Diamond-inheritance abc::generic_error subclass. class derived3_error : public virtual derived1_error, public virtual derived2_error { public: //! Constructor. derived3_error() : derived1_error(), derived2_error() { m_pszWhat = "abc::test::exception_polymorphism::derived3_error"; } }; public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – polymorphism")); } //! See testing::test_case::run(). virtual void run() override { ABC_TRACE_FUNC(this); ABC_TESTING_ASSERT_THROWS(exception, throw_exception()); ABC_TESTING_ASSERT_THROWS(generic_error, throw_generic_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived1_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived2_error()); ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived2_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived3_error(2351)); ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived3_error(3512)); ABC_TESTING_ASSERT_THROWS(derived3_error, throw_derived3_error(5123)); } void throw_exception() { ABC_TRACE_FUNC(this); ABC_THROW(exception, ()); } void throw_generic_error() { ABC_TRACE_FUNC(this); ABC_THROW(generic_error, ()); } void throw_derived1_error() { ABC_TRACE_FUNC(this); ABC_THROW(derived1_error, ()); } void throw_derived2_error() { ABC_TRACE_FUNC(this); ABC_THROW(derived2_error, ()); } void throw_derived3_error(int i) { ABC_TRACE_FUNC(this, i); ABC_THROW(derived3_error, ()); } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_polymorphism) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_from_os_hard_error namespace abc { namespace test { class exception_from_os_hard_error : public testing::test_case { public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – conversion of hard OS errors into C++ exceptions")); } //! See testing::test_case::run(). virtual void run() override { ABC_TRACE_FUNC(this); { int * p = nullptr; ABC_TESTING_ASSERT_THROWS(null_pointer_error, *p = 1); // Under POSIX, this also counts as second test for SIGSEGV, checking that the handler is // still in place after its first activation above. ABC_TESTING_ASSERT_THROWS(memory_address_error, *++p = 1); } // Enable alignment checking if the architecture supports it. //#define ABC_ALIGN_CHECK #ifdef ABC_ALIGN_CHECK #ifdef __GNUC__ #if ABC_HOST_ARCH_I386 __asm__( "pushf\n" "orl $0x00040000,(%esp)\n" "popf" ); #elif ABC_HOST_ARCH_X86_64 __asm__( "pushf\n" "orl $0x0000000000040000,(%rsp)\n" "popf" ); #endif #endif { // Create an int (with another one following it) and a pointer to it. int i[2]; void * p = &i[0]; // Misalign the pointer, partly entering the second int. p = static_cast<std::int8_t *>(p) + 1; ABC_TESTING_ASSERT_THROWS(memory_access_error, *static_cast<int *>(p) = 1); } // Disable alignment checking back. #ifdef __GNUC__ #if ABC_HOST_ARCH_I386 __asm__( "pushf\n" "andl $0xfffbffff,(%esp)\n" "popf" ); #elif ABC_HOST_ARCH_X86_64 __asm__( "pushf\n" "andl $0xfffffffffffbffff,(%rsp)\n" "popf" ); #endif #endif #endif //ifdef ABC_ALIGN_CHECK { // Non-obvious division by zero that can’t be detected at compile time. istr sEmpty; int iZero = static_cast<int>(sEmpty.size_in_chars()), iOne = 1; ABC_TESTING_ASSERT_THROWS(division_by_zero_error, iOne /= iZero); // The call to istr::format() makes use of the quotient, so it shouldn’t be optimized away. istr(ABC_SL("{}")).format(iOne); } } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_from_os_hard_error) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_scope_trace namespace abc { namespace test { class exception_scope_trace : public testing::test_case { public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – scope/stack trace generation")); } //! See testing::test_case::run(). virtual void run() override { std::uint32_t iTestLocal = 3141592654; ABC_TRACE_FUNC(this, iTestLocal); dmstr sScopeTrace; // Verify that the current scope trace contains this function. sScopeTrace = get_scope_trace(); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); // Verify that an exception in run_sub_*() generates a scope trace with run_sub_*(). try { run_sub_1(12345678u); } catch (std::exception const & x) { sScopeTrace = get_scope_trace(&x); } ABC_TESTING_ASSERT_NOT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_2")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("spam and eggs")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_1")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("12345678")), sScopeTrace.cend()); // This method is invoked via the polymorphic abc::testing::runner class. ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("runner::run")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); // Verify that now the scope trace does not contain run_sub_*(). sScopeTrace = get_scope_trace(); ABC_TESTING_ASSERT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_2")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_EQUAL(sScopeTrace.find(ABC_SL("spam and eggs")), sScopeTrace.cend()); ABC_TESTING_ASSERT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_1")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_EQUAL(sScopeTrace.find(ABC_SL("12345678")), sScopeTrace.cend()); // This method is invoked via the polymorphic abc::testing::runner class. ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("runner::run")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); } static dmstr get_scope_trace(std::exception const * px = nullptr) { ABC_TRACE_FUNC(px); io::text::str_writer tsw; exception::write_with_scope_trace(&tsw, px); return tsw.release_content(); } void run_sub_1(std::uint32_t iArg) { ABC_TRACE_FUNC(this, iArg); run_sub_2(ABC_SL("spam and eggs")); } void run_sub_2(istr const & sArg) { ABC_TRACE_FUNC(this, sArg); throw_exception(); } void throw_exception() { ABC_TRACE_FUNC(this); ABC_THROW(exception, ()); } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_scope_trace) //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Don’t give two meanings to one test assertion<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2011, 2012, 2013, 2014 Raffaello D. Di Napoli This file is part of Abaclade. Abaclade 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. Abaclade 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 Abaclade. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abaclade.hxx> #include <abaclade/testing/test_case.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_polymorphism namespace abc { namespace test { class exception_polymorphism : public testing::test_case { protected: //! First-level abc::generic_error subclass. class derived1_error : public virtual generic_error { public: //! Constructor. derived1_error() : generic_error() { m_pszWhat = "abc::test::exception_polymorphism::derived1_error"; } }; //! Second-level abc::generic_error subclass. class derived2_error : public virtual derived1_error { public: //! Constructor. derived2_error() : derived1_error() { m_pszWhat = "abc::test::exception_polymorphism::derived2_error"; } }; //! Diamond-inheritance abc::generic_error subclass. class derived3_error : public virtual derived1_error, public virtual derived2_error { public: //! Constructor. derived3_error() : derived1_error(), derived2_error() { m_pszWhat = "abc::test::exception_polymorphism::derived3_error"; } }; public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – polymorphism")); } //! See testing::test_case::run(). virtual void run() override { ABC_TRACE_FUNC(this); ABC_TESTING_ASSERT_THROWS(exception, throw_exception()); ABC_TESTING_ASSERT_THROWS(generic_error, throw_generic_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived1_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived2_error()); ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived2_error()); ABC_TESTING_ASSERT_THROWS(derived1_error, throw_derived3_error(2351)); ABC_TESTING_ASSERT_THROWS(derived2_error, throw_derived3_error(3512)); ABC_TESTING_ASSERT_THROWS(derived3_error, throw_derived3_error(5123)); } void throw_exception() { ABC_TRACE_FUNC(this); ABC_THROW(exception, ()); } void throw_generic_error() { ABC_TRACE_FUNC(this); ABC_THROW(generic_error, ()); } void throw_derived1_error() { ABC_TRACE_FUNC(this); ABC_THROW(derived1_error, ()); } void throw_derived2_error() { ABC_TRACE_FUNC(this); ABC_THROW(derived2_error, ()); } void throw_derived3_error(int i) { ABC_TRACE_FUNC(this, i); ABC_THROW(derived3_error, ()); } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_polymorphism) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_from_os_hard_error namespace abc { namespace test { class exception_from_os_hard_error : public testing::test_case { public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – conversion of hard OS errors into C++ exceptions")); } //! See testing::test_case::run(). virtual void run() override { ABC_TRACE_FUNC(this); { int * p = nullptr; ABC_TESTING_ASSERT_THROWS(null_pointer_error, *p = 1); // Check that the handler is still in place after its first activation above. ABC_TESTING_ASSERT_THROWS(null_pointer_error, *p = 2); ABC_TESTING_ASSERT_THROWS(memory_address_error, *++p = 1); } // Enable alignment checking if the architecture supports it. //#define ABC_ALIGN_CHECK #ifdef ABC_ALIGN_CHECK #ifdef __GNUC__ #if ABC_HOST_ARCH_I386 __asm__( "pushf\n" "orl $0x00040000,(%esp)\n" "popf" ); #elif ABC_HOST_ARCH_X86_64 __asm__( "pushf\n" "orl $0x0000000000040000,(%rsp)\n" "popf" ); #endif #endif { // Create an int (with another one following it) and a pointer to it. int i[2]; void * p = &i[0]; // Misalign the pointer, partly entering the second int. p = static_cast<std::int8_t *>(p) + 1; ABC_TESTING_ASSERT_THROWS(memory_access_error, *static_cast<int *>(p) = 1); } // Disable alignment checking back. #ifdef __GNUC__ #if ABC_HOST_ARCH_I386 __asm__( "pushf\n" "andl $0xfffbffff,(%esp)\n" "popf" ); #elif ABC_HOST_ARCH_X86_64 __asm__( "pushf\n" "andl $0xfffffffffffbffff,(%rsp)\n" "popf" ); #endif #endif #endif //ifdef ABC_ALIGN_CHECK { // Non-obvious division by zero that can’t be detected at compile time. istr sEmpty; int iZero = static_cast<int>(sEmpty.size_in_chars()), iOne = 1; ABC_TESTING_ASSERT_THROWS(division_by_zero_error, iOne /= iZero); // The call to istr::format() makes use of the quotient, so it shouldn’t be optimized away. istr(ABC_SL("{}")).format(iOne); } } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_from_os_hard_error) //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::test::exception_scope_trace namespace abc { namespace test { class exception_scope_trace : public testing::test_case { public: //! See testing::test_case::title(). virtual istr title() override { return istr(ABC_SL("abc::exception – scope/stack trace generation")); } //! See testing::test_case::run(). virtual void run() override { std::uint32_t iTestLocal = 3141592654; ABC_TRACE_FUNC(this, iTestLocal); dmstr sScopeTrace; // Verify that the current scope trace contains this function. sScopeTrace = get_scope_trace(); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); // Verify that an exception in run_sub_*() generates a scope trace with run_sub_*(). try { run_sub_1(12345678u); } catch (std::exception const & x) { sScopeTrace = get_scope_trace(&x); } ABC_TESTING_ASSERT_NOT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_2")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("spam and eggs")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_1")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("12345678")), sScopeTrace.cend()); // This method is invoked via the polymorphic abc::testing::runner class. ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("runner::run")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); // Verify that now the scope trace does not contain run_sub_*(). sScopeTrace = get_scope_trace(); ABC_TESTING_ASSERT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_2")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_EQUAL(sScopeTrace.find(ABC_SL("spam and eggs")), sScopeTrace.cend()); ABC_TESTING_ASSERT_EQUAL( sScopeTrace.find(ABC_SL("exception_scope_trace::run_sub_1")), sScopeTrace.cend() ); ABC_TESTING_ASSERT_EQUAL(sScopeTrace.find(ABC_SL("12345678")), sScopeTrace.cend()); // This method is invoked via the polymorphic abc::testing::runner class. ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("runner::run")), sScopeTrace.cend()); ABC_TESTING_ASSERT_NOT_EQUAL(sScopeTrace.find(ABC_SL("3141592654")), sScopeTrace.cend()); } static dmstr get_scope_trace(std::exception const * px = nullptr) { ABC_TRACE_FUNC(px); io::text::str_writer tsw; exception::write_with_scope_trace(&tsw, px); return tsw.release_content(); } void run_sub_1(std::uint32_t iArg) { ABC_TRACE_FUNC(this, iArg); run_sub_2(ABC_SL("spam and eggs")); } void run_sub_2(istr const & sArg) { ABC_TRACE_FUNC(this, sArg); throw_exception(); } void throw_exception() { ABC_TRACE_FUNC(this); ABC_THROW(exception, ()); } }; } //namespace test } //namespace abc ABC_TESTING_REGISTER_TEST_CASE(abc::test::exception_scope_trace) //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.H /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_EFF_CONFIG__ #define __P9_MSS_EFF_CONFIG__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&, const bool i_decode_spd_only); extern "C" { /// /// @brief Configure the attributes for each controller /// @param[in] i_target the controller (e.g., MCS) /// @param[in] i_decode_spd_only options to set VPD and SPD attrs only /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target, const bool i_decode_spd_only = false ); } #endif <commit_msg>L3 work for mss xmls<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.H /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_EFF_CONFIG__ #define __P9_MSS_EFF_CONFIG__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&, const bool i_decode_spd_only); extern "C" { /// /// @brief Configure the attributes for each controller /// @param[in] i_target the controller (e.g., MCS) /// @param[in] i_decode_spd_only options to set VPD and SPD attrs only /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target, const bool i_decode_spd_only = false ); } #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: sddll2.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2004-02-03 20:11:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #define ITEMID_SIZE 0 #define ITEMID_LINE 0 // kann spaeter raus! #define ITEMID_BRUSH 0 // kann spaeter raus! #include <svx/editdata.hxx> #include "eetext.hxx" #include <svx/svxids.hrc> #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #define ITEMID_FIELD EE_FEATURE_FIELD #include <svx/flditem.hxx> #ifndef _IMAPDLG_HXX_ //autogen #include <svx/imapdlg.hxx> #endif #ifndef _BMPMASK_HXX_ //autogen #include <svx/bmpmask.hxx> #endif #ifndef _SVX_GALBRWS_HXX_ //autogen #include <svx/galbrws.hxx> #endif #ifndef _SVX_SRCHDLG_HXX //autogen #include <svx/srchdlg.hxx> #endif #ifndef _SVX_FONTWORK_HXX //autogen #include <svx/fontwork.hxx> #endif #ifndef _SVX_COLRCTRL_HXX //autogen #include <svx/colrctrl.hxx> #endif #ifndef _SVX_VERT_TEXT_TBXCTRL_HXX #include <svx/verttexttbxctrl.hxx> #endif #ifndef _SVX_DLG_HYPERLINK_HXX //autogen #include <svx/hyprlink.hxx> #endif #ifndef _SVX_TAB_HYPERLINK_HXX #include <svx/hyperdlg.hxx> #endif #ifndef _FILLCTRL_HXX //autogen #include <svx/fillctrl.hxx> #endif #ifndef _SVX_LINECTRL_HXX //autogen #include <svx/linectrl.hxx> #endif #ifndef _SVX_TBCONTRL_HXX //autogen #include <svx/tbcontrl.hxx> #endif #ifndef _SVX_ZOOMCTRL_HXX //autogen #include <svx/zoomctrl.hxx> #endif #ifndef _SVX_PSZCTRL_HXX //autogen #include <svx/pszctrl.hxx> #endif #ifndef _SVX_MODCTRL_HXX //autogen #include <svx/modctrl.hxx> #endif #ifndef _SVX_FNTCTL_HXX //autogen #include <svx/fntctl.hxx> #endif #ifndef _SVX_FNTSZCTL_HXX //autogen #include <svx/fntszctl.hxx> #endif #ifndef _SVX_F3DCHILD_HXX //autogen #include <svx/f3dchild.hxx> #endif #ifndef _SVX_GRAFCTRL_HXX #include <svx/grafctrl.hxx> #endif // #UndoRedo# #ifndef _SVX_LBOXCTRL_HXX_ #include <svx/lboxctrl.hxx> #endif #ifndef _SVX_CLIPBOARDCTL_HXX_ #include <svx/clipboardctl.hxx> #endif #include "sddll.hxx" #define _SD_DIACTRL_CXX #include "diactrl.hxx" #include "gluectrl.hxx" #include "tbx_ww.hxx" #ifndef SD_TEXT_OBJECT_BAR_HXX #include "TextObjectBar.hxx" #endif #ifndef SD_BEZIER_OBJECT_BAR_HXX #include "BezierObjectBar.hxx" #endif #ifndef SD_IMPRESS_OBJECT_BAR_HXX #include "ImpressObjectBar.hxx" #endif #ifndef SD_ANIMATION_CHILD_WINDOW_HXX #include "AnimationChildWindow.hxx" #endif #include "animobjs.hxx" #ifndef SD_NAVIGATOR_CHILD_WINDOW_HXX #include "NavigatorChildWindow.hxx" #endif #ifndef SD_PREVIEW_CHILD_WINDOW_HXX #include "PreviewChildWindow.hxx" #endif #ifndef SD_EFFECT_CHILD_WINDOW_HXX #include "EffectChildWindow.hxx" #endif #ifndef SD_SLIDE_CHANGE_CHILD_WINDOW_HXX #include "SlideChangeChildWindow.hxx" #endif //#include "3dchld.hxx" #include "app.hrc" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_GRAPHIC_VIEW_SHELL_HXX #include "GraphicViewShell.hxx" #endif /************************************************************************* |* |* Register all Controllers |* \************************************************************************/ void SdDLL::RegisterControllers() { SfxModule* pMod = SD_MOD(); // ToolBoxControls registrieren SdTbxControl::RegisterControl( SID_OBJECT_ALIGN, pMod ); SdTbxControl::RegisterControl( SID_ZOOM_TOOLBOX, pMod ); SdTbxControl::RegisterControl( SID_OBJECT_CHOOSE_MODE, pMod ); SdTbxControl::RegisterControl( SID_POSITION, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_TEXT, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_RECTANGLES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_ELLIPSES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_LINES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_ARROWS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_3D_OBJECTS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_CONNECTORS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_INSERT, pMod ); SdTbxCtlDiaEffect::RegisterControl(0, pMod); SdTbxCtlDiaSpeed::RegisterControl(0, pMod); SdTbxCtlDiaAuto::RegisterControl(0, pMod); SdTbxCtlDiaTime::RegisterControl(0, pMod); SdTbxCtlDiaPages::RegisterControl( SID_PAGES_PER_ROW, pMod ); SdTbxCtlGlueEscDir::RegisterControl( SID_GLUE_ESCDIR, pMod ); ::sd::AnimationChildWindow::RegisterChildWindow(0, pMod); ::sd::NavigatorChildWindow::RegisterChildWindowContext( ::sd::DrawViewShell::_GetInterfaceIdImpl(), pMod ); ::sd::NavigatorChildWindow::RegisterChildWindowContext( ::sd::GraphicViewShell::_GetInterfaceIdImpl(), pMod ); ::sd::PreviewChildWindow::RegisterChildWindow(0, pMod); ::sd::EffectChildWindow::RegisterChildWindow(0, pMod); ::sd::SlideChangeChildWindow::RegisterChildWindow(0, pMod); //Sd3DChildWindow::RegisterChildWindow(0, pMod); Svx3DChildWindow::RegisterChildWindow(0, pMod); SvxFontWorkChildWindow::RegisterChildWindow(0, pMod); SvxColorChildWindow::RegisterChildWindow(0, pMod, SFX_CHILDWIN_TASK); SvxSearchDialogWrapper::RegisterChildWindow(0, pMod); SvxBmpMaskChildWindow::RegisterChildWindow(0, pMod); GalleryChildWindow::RegisterChildWindow(0, pMod); SvxIMapDlgChildWindow::RegisterChildWindow(0, pMod); SvxHyperlinkDlgWrapper::RegisterChildWindow(0, pMod); SvxHlinkDlgWrapper::RegisterChildWindow(0, pMod); SvxFillToolBoxControl::RegisterControl(0, pMod); SvxLineStyleToolBoxControl::RegisterControl(0, pMod); SvxLineWidthToolBoxControl::RegisterControl(0, pMod); SvxLineColorToolBoxControl::RegisterControl(0, pMod); SvxLineEndToolBoxControl::RegisterControl( SID_ATTR_LINEEND_STYLE, pMod ); SvxStyleToolBoxControl::RegisterControl(0, pMod); SvxFontNameToolBoxControl::RegisterControl(0, pMod); SvxFontHeightToolBoxControl::RegisterControl(0, pMod); SvxFontColorToolBoxControl::RegisterControl(0, pMod); SvxGrafFilterToolBoxControl::RegisterControl( SID_GRFFILTER, pMod ); SvxGrafModeToolBoxControl::RegisterControl( SID_ATTR_GRAF_MODE, pMod ); SvxGrafRedToolBoxControl::RegisterControl( SID_ATTR_GRAF_RED, pMod ); SvxGrafGreenToolBoxControl::RegisterControl( SID_ATTR_GRAF_GREEN, pMod ); SvxGrafBlueToolBoxControl::RegisterControl( SID_ATTR_GRAF_BLUE, pMod ); SvxGrafLuminanceToolBoxControl::RegisterControl( SID_ATTR_GRAF_LUMINANCE, pMod ); SvxGrafContrastToolBoxControl::RegisterControl( SID_ATTR_GRAF_CONTRAST, pMod ); SvxGrafGammaToolBoxControl::RegisterControl( SID_ATTR_GRAF_GAMMA, pMod ); SvxGrafTransparenceToolBoxControl::RegisterControl( SID_ATTR_GRAF_TRANSPARENCE, pMod ); SvxVertTextTbxCtrl::RegisterControl(SID_TEXTDIRECTION_TOP_TO_BOTTOM, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_TEXTDIRECTION_LEFT_TO_RIGHT, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_DRAW_CAPTION_VERTICAL, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_DRAW_TEXT_VERTICAL, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_TEXT_FITTOSIZE_VERTICAL, pMod); SvxCTLTextTbxCtrl::RegisterControl(SID_ATTR_PARA_LEFT_TO_RIGHT, pMod); SvxCTLTextTbxCtrl::RegisterControl(SID_ATTR_PARA_RIGHT_TO_LEFT, pMod); // StatusBarControls registrieren SvxZoomStatusBarControl::RegisterControl( SID_ATTR_ZOOM, pMod ); SvxPosSizeStatusBarControl::RegisterControl( SID_ATTR_SIZE, pMod ); SvxModifyControl::RegisterControl( SID_DOC_MODIFIED, pMod ); //SvxInsertStatusBarControl::RegisterControl(0, pModd); // MenuControls fuer PopupMenu SvxFontMenuControl::RegisterControl( SID_ATTR_CHAR_FONT, pMod ); SvxFontSizeMenuControl::RegisterControl( SID_ATTR_CHAR_FONTHEIGHT, pMod ); SfxMenuControl::RegisterControl( SID_SET_SNAPITEM, pMod ); SfxMenuControl::RegisterControl( SID_DELETE_SNAPITEM, pMod ); SfxMenuControl::RegisterControl( SID_BEZIER_CLOSE, pMod ); // #UndoRedo# SvxUndoRedoControl::RegisterControl( SID_UNDO , pMod ); SvxUndoRedoControl::RegisterControl( SID_REDO , pMod ); SvxClipBoardControl::RegisterControl( SID_PASTE, pMod ); } <commit_msg>INTEGRATION: CWS sj05 (1.10.228); FILE MERGED 2004/02/13 14:35:12 sj 1.10.228.2: RESYNC: (1.10-1.12); FILE MERGED 2004/01/23 17:19:37 cl 1.10.228.1: #i20484# adding autoshape ui<commit_after>/************************************************************************* * * $RCSfile: sddll2.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2004-04-02 13:22:24 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #define ITEMID_SIZE 0 #define ITEMID_LINE 0 // kann spaeter raus! #define ITEMID_BRUSH 0 // kann spaeter raus! #include <svx/editdata.hxx> #include "eetext.hxx" #include <svx/svxids.hrc> #ifndef _EEITEM_HXX //autogen #include <svx/eeitem.hxx> #endif #define ITEMID_FIELD EE_FEATURE_FIELD #include <svx/flditem.hxx> #ifndef _IMAPDLG_HXX_ //autogen #include <svx/imapdlg.hxx> #endif #ifndef _BMPMASK_HXX_ //autogen #include <svx/bmpmask.hxx> #endif #ifndef _SVX_GALBRWS_HXX_ //autogen #include <svx/galbrws.hxx> #endif #ifndef _SVX_SRCHDLG_HXX //autogen #include <svx/srchdlg.hxx> #endif #ifndef _SVX_FONTWORK_HXX //autogen #include <svx/fontwork.hxx> #endif #ifndef _SVX_COLRCTRL_HXX //autogen #include <svx/colrctrl.hxx> #endif #ifndef _SVX_VERT_TEXT_TBXCTRL_HXX #include <svx/verttexttbxctrl.hxx> #endif #ifndef _SVX_DLG_HYPERLINK_HXX //autogen #include <svx/hyprlink.hxx> #endif #ifndef _SVX_TAB_HYPERLINK_HXX #include <svx/hyperdlg.hxx> #endif #ifndef _FILLCTRL_HXX //autogen #include <svx/fillctrl.hxx> #endif #ifndef _SVX_LINECTRL_HXX //autogen #include <svx/linectrl.hxx> #endif #ifndef _SVX_TBCONTRL_HXX //autogen #include <svx/tbcontrl.hxx> #endif #ifndef _SVX_ZOOMCTRL_HXX //autogen #include <svx/zoomctrl.hxx> #endif #ifndef _SVX_PSZCTRL_HXX //autogen #include <svx/pszctrl.hxx> #endif #ifndef _SVX_MODCTRL_HXX //autogen #include <svx/modctrl.hxx> #endif #ifndef _SVX_FNTCTL_HXX //autogen #include <svx/fntctl.hxx> #endif #ifndef _SVX_FNTSZCTL_HXX //autogen #include <svx/fntszctl.hxx> #endif #ifndef _SVX_F3DCHILD_HXX //autogen #include <svx/f3dchild.hxx> #endif #ifndef _SVX_GRAFCTRL_HXX #include <svx/grafctrl.hxx> #endif // #UndoRedo# #ifndef _SVX_LBOXCTRL_HXX_ #include <svx/lboxctrl.hxx> #endif #ifndef _SVX_CLIPBOARDCTL_HXX_ #include <svx/clipboardctl.hxx> #endif #ifndef _SVX_EXTRUSION_CONTROLS_HXX #include <svx/extrusioncontrols.hxx> #endif #include "sddll.hxx" #define _SD_DIACTRL_CXX #include "diactrl.hxx" #include "gluectrl.hxx" #include "tbx_ww.hxx" #ifndef SD_TEXT_OBJECT_BAR_HXX #include "TextObjectBar.hxx" #endif #ifndef SD_BEZIER_OBJECT_BAR_HXX #include "BezierObjectBar.hxx" #endif #ifndef SD_IMPRESS_OBJECT_BAR_HXX #include "ImpressObjectBar.hxx" #endif #ifndef SD_ANIMATION_CHILD_WINDOW_HXX #include "AnimationChildWindow.hxx" #endif #include "animobjs.hxx" #ifndef SD_NAVIGATOR_CHILD_WINDOW_HXX #include "NavigatorChildWindow.hxx" #endif #ifndef SD_PREVIEW_CHILD_WINDOW_HXX #include "PreviewChildWindow.hxx" #endif #ifndef SD_EFFECT_CHILD_WINDOW_HXX #include "EffectChildWindow.hxx" #endif #ifndef SD_SLIDE_CHANGE_CHILD_WINDOW_HXX #include "SlideChangeChildWindow.hxx" #endif //#include "3dchld.hxx" #include "app.hrc" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_GRAPHIC_VIEW_SHELL_HXX #include "GraphicViewShell.hxx" #endif /************************************************************************* |* |* Register all Controllers |* \************************************************************************/ void SdDLL::RegisterControllers() { SfxModule* pMod = SD_MOD(); // ToolBoxControls registrieren SdTbxControl::RegisterControl( SID_OBJECT_ALIGN, pMod ); SdTbxControl::RegisterControl( SID_ZOOM_TOOLBOX, pMod ); SdTbxControl::RegisterControl( SID_OBJECT_CHOOSE_MODE, pMod ); SdTbxControl::RegisterControl( SID_POSITION, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_TEXT, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_RECTANGLES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_ELLIPSES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_LINES, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_ARROWS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_3D_OBJECTS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_CONNECTORS, pMod ); SdTbxControl::RegisterControl( SID_DRAWTBX_INSERT, pMod ); SdTbxCtlDiaEffect::RegisterControl(0, pMod); SdTbxCtlDiaSpeed::RegisterControl(0, pMod); SdTbxCtlDiaAuto::RegisterControl(0, pMod); SdTbxCtlDiaTime::RegisterControl(0, pMod); SdTbxCtlDiaPages::RegisterControl( SID_PAGES_PER_ROW, pMod ); SdTbxCtlGlueEscDir::RegisterControl( SID_GLUE_ESCDIR, pMod ); ::sd::AnimationChildWindow::RegisterChildWindow(0, pMod); ::sd::NavigatorChildWindow::RegisterChildWindowContext( ::sd::DrawViewShell::_GetInterfaceIdImpl(), pMod ); ::sd::NavigatorChildWindow::RegisterChildWindowContext( ::sd::GraphicViewShell::_GetInterfaceIdImpl(), pMod ); ::sd::PreviewChildWindow::RegisterChildWindow(0, pMod); ::sd::EffectChildWindow::RegisterChildWindow(0, pMod); ::sd::SlideChangeChildWindow::RegisterChildWindow(0, pMod); //Sd3DChildWindow::RegisterChildWindow(0, pMod); Svx3DChildWindow::RegisterChildWindow(0, pMod); SvxFontWorkChildWindow::RegisterChildWindow(0, pMod); SvxColorChildWindow::RegisterChildWindow(0, pMod, SFX_CHILDWIN_TASK); SvxSearchDialogWrapper::RegisterChildWindow(0, pMod); SvxBmpMaskChildWindow::RegisterChildWindow(0, pMod); GalleryChildWindow::RegisterChildWindow(0, pMod); SvxIMapDlgChildWindow::RegisterChildWindow(0, pMod); SvxHyperlinkDlgWrapper::RegisterChildWindow(0, pMod); SvxHlinkDlgWrapper::RegisterChildWindow(0, pMod); SvxFillToolBoxControl::RegisterControl(0, pMod); SvxLineStyleToolBoxControl::RegisterControl(0, pMod); SvxLineWidthToolBoxControl::RegisterControl(0, pMod); SvxLineColorToolBoxControl::RegisterControl(0, pMod); SvxLineEndToolBoxControl::RegisterControl( SID_ATTR_LINEEND_STYLE, pMod ); SvxStyleToolBoxControl::RegisterControl(0, pMod); SvxFontNameToolBoxControl::RegisterControl(0, pMod); SvxFontHeightToolBoxControl::RegisterControl(0, pMod); SvxFontColorToolBoxControl::RegisterControl(0, pMod); SvxGrafFilterToolBoxControl::RegisterControl( SID_GRFFILTER, pMod ); SvxGrafModeToolBoxControl::RegisterControl( SID_ATTR_GRAF_MODE, pMod ); SvxGrafRedToolBoxControl::RegisterControl( SID_ATTR_GRAF_RED, pMod ); SvxGrafGreenToolBoxControl::RegisterControl( SID_ATTR_GRAF_GREEN, pMod ); SvxGrafBlueToolBoxControl::RegisterControl( SID_ATTR_GRAF_BLUE, pMod ); SvxGrafLuminanceToolBoxControl::RegisterControl( SID_ATTR_GRAF_LUMINANCE, pMod ); SvxGrafContrastToolBoxControl::RegisterControl( SID_ATTR_GRAF_CONTRAST, pMod ); SvxGrafGammaToolBoxControl::RegisterControl( SID_ATTR_GRAF_GAMMA, pMod ); SvxGrafTransparenceToolBoxControl::RegisterControl( SID_ATTR_GRAF_TRANSPARENCE, pMod ); SvxVertTextTbxCtrl::RegisterControl(SID_TEXTDIRECTION_TOP_TO_BOTTOM, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_TEXTDIRECTION_LEFT_TO_RIGHT, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_DRAW_CAPTION_VERTICAL, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_DRAW_FONTWORK_VERTICAL, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_DRAW_TEXT_VERTICAL, pMod); SvxVertTextTbxCtrl::RegisterControl(SID_TEXT_FITTOSIZE_VERTICAL, pMod); SvxCTLTextTbxCtrl::RegisterControl(SID_ATTR_PARA_LEFT_TO_RIGHT, pMod); SvxCTLTextTbxCtrl::RegisterControl(SID_ATTR_PARA_RIGHT_TO_LEFT, pMod); // StatusBarControls registrieren SvxZoomStatusBarControl::RegisterControl( SID_ATTR_ZOOM, pMod ); SvxPosSizeStatusBarControl::RegisterControl( SID_ATTR_SIZE, pMod ); SvxModifyControl::RegisterControl( SID_DOC_MODIFIED, pMod ); //SvxInsertStatusBarControl::RegisterControl(0, pModd); // MenuControls fuer PopupMenu SvxFontMenuControl::RegisterControl( SID_ATTR_CHAR_FONT, pMod ); SvxFontSizeMenuControl::RegisterControl( SID_ATTR_CHAR_FONTHEIGHT, pMod ); SfxMenuControl::RegisterControl( SID_SET_SNAPITEM, pMod ); SfxMenuControl::RegisterControl( SID_DELETE_SNAPITEM, pMod ); SfxMenuControl::RegisterControl( SID_BEZIER_CLOSE, pMod ); // #UndoRedo# SvxUndoRedoControl::RegisterControl( SID_UNDO , pMod ); SvxUndoRedoControl::RegisterControl( SID_REDO , pMod ); SvxClipBoardControl::RegisterControl( SID_PASTE, pMod ); svx::ExtrusionDepthControl::RegisterControl( SID_EXTRUSION_DEPTH_FLOATER, pMod ); svx::ExtrusionDirectionControl::RegisterControl( SID_EXTRUSION_DIRECTION_FLOATER, pMod ); svx::ExtrusionLightingControl::RegisterControl( SID_EXTRUSION_LIGHTING_FLOATER, pMod ); svx::ExtrusionSurfaceControl::RegisterControl( SID_EXTRUSION_SURFACE_FLOATER, pMod ); svx::ExtrusionColorControl::RegisterControl( SID_EXTRUSION_3D_COLOR, pMod ); } <|endoftext|>
<commit_before>/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * [email protected] * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include <oBase/concurrent_pool.h> #include <oBase/allocate.h> #include <oBase/bit.h> #include <oBase/byte.h> #include <oBase/compiler_config.h> #include <oBase/macros.h> #include <stdexcept> namespace ouro { static_assert(sizeof(concurrent_pool) == oCACHE_LINE_SIZE, "unexpected class size"); static_assert(sizeof(std::atomic_uint) == sizeof(unsigned int), "mismatch atomic size"); struct tagged { tagged() {} tagged(unsigned int _all) : all(_all) {} union { unsigned int all; struct { unsigned int index : 24; unsigned int tag : 8; }; }; }; concurrent_pool::concurrent_pool() : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { tagged h(nullidx); head = h.all; for (char& c : cache_padding) c = 0; } concurrent_pool::concurrent_pool(concurrent_pool&& _That) : blocks(_That.blocks) , stride(_That.stride) , nblocks(_That.nblocks) , head(_That.head) , owns_memory(_That.owns_memory) { _That.owns_memory = false; _That.deinitialize(); } concurrent_pool::concurrent_pool(void* memory, size_type block_size, size_type capacity, size_type alignment) : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { if (!initialize(memory, block_size, capacity, alignment)) throw std::invalid_argument("concurrent_pool initialize failed"); } concurrent_pool::concurrent_pool(size_type block_size, size_type capacity, size_type alignment) : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { if (!initialize(block_size, capacity, alignment)) throw std::invalid_argument("concurrent_pool initialize failed"); } concurrent_pool::~concurrent_pool() { deinitialize(); } concurrent_pool& concurrent_pool::operator=(concurrent_pool&& _That) { if (this != &_That) { deinitialize(); oMOVE0(blocks); oMOVE0(stride); oMOVE0(nblocks); oMOVE0(owns_memory); head = _That.head; _That.head = nullidx; } return *this; } concurrent_pool::index_type concurrent_pool::initialize(void* memory, size_type block_size, size_type capacity, size_type alignment) { if (capacity > max_capacity()) return 0; if (block_size < sizeof(index_type)) return 0; if (!is_pow2(alignment)) return 0; for (char& c : cache_padding) c = 0; size_type req = __max(block_size, sizeof(index_type)) * capacity; if (memory) { if (!byte_aligned(memory, alignment)) return 0; head = 0; blocks = memory; stride = block_size; nblocks = capacity; const index_type n = nblocks - 1; for (index_type i = 0; i < n; i++) *byte_add((index_type*)blocks, stride, i) = i + 1; *byte_add((index_type*)blocks, stride, n) = nullidx; } return req; } concurrent_pool::size_type concurrent_pool::initialize(size_type block_size, size_type capacity, size_type block_alignment) { size_type req = initialize(nullptr, block_size, capacity, block_alignment); if (!req) return 0; allocate_options o; o.alignment = bit_high(block_alignment); void* p = default_allocate(req, o); return initialize(p, block_size, capacity, block_alignment); } void* concurrent_pool::deinitialize() { if (owns_memory) { default_deallocate(blocks); blocks = nullptr; } void* p = blocks; blocks = nullptr; stride = 0; nblocks = 0; head = nullidx; return p; } concurrent_pool::size_type concurrent_pool::count_free() const { tagged o(head); size_type n = 0; index_type i = o.index; while (i != nullidx) { n++; i = *byte_add((index_type*)blocks, stride, i); } return n; } bool concurrent_pool::empty() const { tagged o(head); return o.index == nullidx; } concurrent_pool::index_type concurrent_pool::allocate() { index_type i; tagged n, o(head); do { i = o.index; if (i == nullidx) break; n.tag = o.tag + 1; n.index = *byte_add((index_type*)blocks, stride, i); } while (!head.compare_exchange_strong(o.all, n.all)); return i; } void concurrent_pool::deallocate(index_type index) { tagged n, o(head); do { *byte_add((index_type*)blocks, stride, index) = o.index; n.tag = o.tag + 1; n.index = index; } while (!head.compare_exchange_strong(o.all, n.all)); } // convert between allocated index and pointer values void* concurrent_pool::pointer(index_type index) const { return index != nullidx ? byte_add(blocks, stride, index) : nullptr; } concurrent_pool::index_type concurrent_pool::index(void* pointer) const { return pointer ? (index_type)index_of(pointer, blocks, stride) : nullidx; } } // namespace ouro <commit_msg>remove unneeded include<commit_after>/************************************************************************** * The MIT License * * Copyright (c) 2013 Antony Arciuolo. * * [email protected] * * * * Permission is hereby granted, free of charge, to any person obtaining * * a copy of this software and associated documentation files (the * * "Software"), to deal in the Software without restriction, including * * without limitation the rights to use, copy, modify, merge, publish, * * distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to * * the following conditions: * * * * The above copyright notice and this permission notice shall be * * included in all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include <oBase/concurrent_pool.h> #include <oBase/allocate.h> #include <oBase/bit.h> #include <oBase/byte.h> #include <oBase/macros.h> #include <stdexcept> namespace ouro { static_assert(sizeof(concurrent_pool) == oCACHE_LINE_SIZE, "unexpected class size"); static_assert(sizeof(std::atomic_uint) == sizeof(unsigned int), "mismatch atomic size"); struct tagged { tagged() {} tagged(unsigned int _all) : all(_all) {} union { unsigned int all; struct { unsigned int index : 24; unsigned int tag : 8; }; }; }; concurrent_pool::concurrent_pool() : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { tagged h(nullidx); head = h.all; for (char& c : cache_padding) c = 0; } concurrent_pool::concurrent_pool(concurrent_pool&& _That) : blocks(_That.blocks) , stride(_That.stride) , nblocks(_That.nblocks) , head(_That.head) , owns_memory(_That.owns_memory) { _That.owns_memory = false; _That.deinitialize(); } concurrent_pool::concurrent_pool(void* memory, size_type block_size, size_type capacity, size_type alignment) : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { if (!initialize(memory, block_size, capacity, alignment)) throw std::invalid_argument("concurrent_pool initialize failed"); } concurrent_pool::concurrent_pool(size_type block_size, size_type capacity, size_type alignment) : blocks(nullptr) , stride(0) , nblocks(0) , owns_memory(false) { if (!initialize(block_size, capacity, alignment)) throw std::invalid_argument("concurrent_pool initialize failed"); } concurrent_pool::~concurrent_pool() { deinitialize(); } concurrent_pool& concurrent_pool::operator=(concurrent_pool&& _That) { if (this != &_That) { deinitialize(); oMOVE0(blocks); oMOVE0(stride); oMOVE0(nblocks); oMOVE0(owns_memory); head = _That.head; _That.head = nullidx; } return *this; } concurrent_pool::index_type concurrent_pool::initialize(void* memory, size_type block_size, size_type capacity, size_type alignment) { if (capacity > max_capacity()) return 0; if (block_size < sizeof(index_type)) return 0; if (!is_pow2(alignment)) return 0; for (char& c : cache_padding) c = 0; size_type req = __max(block_size, sizeof(index_type)) * capacity; if (memory) { if (!byte_aligned(memory, alignment)) return 0; head = 0; blocks = memory; stride = block_size; nblocks = capacity; const index_type n = nblocks - 1; for (index_type i = 0; i < n; i++) *byte_add((index_type*)blocks, stride, i) = i + 1; *byte_add((index_type*)blocks, stride, n) = nullidx; } return req; } concurrent_pool::size_type concurrent_pool::initialize(size_type block_size, size_type capacity, size_type block_alignment) { size_type req = initialize(nullptr, block_size, capacity, block_alignment); if (!req) return 0; allocate_options o; o.alignment = bit_high(block_alignment); void* p = default_allocate(req, o); return initialize(p, block_size, capacity, block_alignment); } void* concurrent_pool::deinitialize() { if (owns_memory) { default_deallocate(blocks); blocks = nullptr; } void* p = blocks; blocks = nullptr; stride = 0; nblocks = 0; head = nullidx; return p; } concurrent_pool::size_type concurrent_pool::count_free() const { tagged o(head); size_type n = 0; index_type i = o.index; while (i != nullidx) { n++; i = *byte_add((index_type*)blocks, stride, i); } return n; } bool concurrent_pool::empty() const { tagged o(head); return o.index == nullidx; } concurrent_pool::index_type concurrent_pool::allocate() { index_type i; tagged n, o(head); do { i = o.index; if (i == nullidx) break; n.tag = o.tag + 1; n.index = *byte_add((index_type*)blocks, stride, i); } while (!head.compare_exchange_strong(o.all, n.all)); return i; } void concurrent_pool::deallocate(index_type index) { tagged n, o(head); do { *byte_add((index_type*)blocks, stride, index) = o.index; n.tag = o.tag + 1; n.index = index; } while (!head.compare_exchange_strong(o.all, n.all)); } // convert between allocated index and pointer values void* concurrent_pool::pointer(index_type index) const { return index != nullidx ? byte_add(blocks, stride, index) : nullptr; } concurrent_pool::index_type concurrent_pool::index(void* pointer) const { return pointer ? (index_type)index_of(pointer, blocks, stride) : nullidx; } } // namespace ouro <|endoftext|>
<commit_before>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr = "LHC11h", const char *pass = 0 /*should not be needed*/ ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalPreparation", "No analysis manager to connect to."); return NULL; } TString period(perstr); period.ToLower(); Bool_t isMC = kFALSE; if(period.Sizeof()>7) isMC = kTRUE; // Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD if(isMC) Printf("AddTaskEmcalPreparation: Running on MC"); else Printf("AddTaskEmcalPreparation: Running on DATA"); //----------------------- Add tender ------------------------------------------------------- Bool_t distBC = kFALSE; //switch for recalculation cluster position from bad channel Bool_t recalibClus = kFALSE; Bool_t recalcClusPos = kFALSE; Bool_t nonLinearCorr = kFALSE; Bool_t remExoticCell = kFALSE; Bool_t remExoticClus = kFALSE; Bool_t fidRegion = kFALSE; Bool_t calibEnergy = kTRUE; Bool_t calibTime = kTRUE; Bool_t remBC = kTRUE; UInt_t nonLinFunct = 0; Bool_t reclusterize = kFALSE; Float_t seedthresh = 0.1; // 100 MeV Float_t cellthresh = 0.05; // 50 MeV UInt_t clusterizer = 0; Bool_t trackMatch = kFALSE; Bool_t updateCellOnly = kFALSE; Float_t timeMin = -50e-9; // minimum time of physical signal in a cell/digit Float_t timeMax = 50e-9; // maximum time of physical signal in a cell/digit Float_t timeCut = 1e6; if(isMC) { calibEnergy = kFALSE; calibTime = kFALSE; timeMin = -1.; timeMax = 1e6; } gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass); //----------------------- Add clusterizer ------------------------------------------------------- clusterizer = AliEMCALRecParam::kClusterizerv2; remExoticCell = kTRUE; gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C"); AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh, timeMin,timeMax,timeCut,remExoticCell,distBC, AliAnalysisTaskEMCALClusterizeFast::kFEEData); //----------------------- Add cluster maker ----------------------------------------------------- gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity, UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected; if(isMC) { if(period == "lhc12a15a") nonLinFunct = AliEMCALRecoUtils::kPi0MCv2; else nonLinFunct = AliEMCALRecoUtils::kPi0MCv3; } remExoticClus = kTRUE; AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE); return clusterizerTask; } <commit_msg>set default timing cuts LHC11h<commit_after>AliAnalysisTaskSE *AddTaskEmcalPreparation(const char *perstr = "LHC11h", const char *pass = 0 /*should not be needed*/ ) { AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskEmcalPreparation", "No analysis manager to connect to."); return NULL; } TString period(perstr); period.ToLower(); Bool_t isMC = kFALSE; if(period.Sizeof()>7) isMC = kTRUE; // Bool_t isMC = (mgr->GetMCtruthEventHandler() != NULL); //only works for ESD if(isMC) Printf("AddTaskEmcalPreparation: Running on MC"); else Printf("AddTaskEmcalPreparation: Running on DATA"); //----------------------- Add tender ------------------------------------------------------- Bool_t distBC = kFALSE; //switch for recalculation cluster position from bad channel Bool_t recalibClus = kFALSE; Bool_t recalcClusPos = kFALSE; Bool_t nonLinearCorr = kFALSE; Bool_t remExoticCell = kFALSE; Bool_t remExoticClus = kFALSE; Bool_t fidRegion = kFALSE; Bool_t calibEnergy = kTRUE; Bool_t calibTime = kTRUE; Bool_t remBC = kTRUE; UInt_t nonLinFunct = 0; Bool_t reclusterize = kFALSE; Float_t seedthresh = 0.1; // 100 MeV Float_t cellthresh = 0.05; // 50 MeV UInt_t clusterizer = 0; Bool_t trackMatch = kFALSE; Bool_t updateCellOnly = kFALSE; Float_t timeMin = -50e-9; // minimum time of physical signal in a cell/digit Float_t timeMax = 50e-9; // maximum time of physical signal in a cell/digit Float_t timeCut = 1e6; if(period.Contains("lhc11h")) { timeMin = -50e-9; timeMax = 100e-9; } if(isMC) { calibEnergy = kFALSE; calibTime = kFALSE; timeMin = -1.; timeMax = 1e6; } gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEMCALTender.C");//tendertasks AliAnalysisTaskSE *tender = AddTaskEMCALTender(distBC, recalibClus, recalcClusPos, nonLinearCorr, remExoticCell, remExoticClus, fidRegion, calibEnergy, calibTime, remBC, nonLinFunct, reclusterize, seedthresh, cellthresh, clusterizer, trackMatch, updateCellOnly, timeMin, timeMax, timeCut,pass); //----------------------- Add clusterizer ------------------------------------------------------- clusterizer = AliEMCALRecParam::kClusterizerv2; remExoticCell = kTRUE; gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskClusterizerFast.C"); AliAnalysisTaskEMCALClusterizeFast *clusterizerTask = AddTaskClusterizerFast("ClusterizerFast","","",clusterizer,cellthresh,seedthresh, timeMin,timeMax,timeCut,remExoticCell,distBC, AliAnalysisTaskEMCALClusterizeFast::kFEEData); //----------------------- Add cluster maker ----------------------------------------------------- gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusterMaker.C"); //cluster maker: non-linearity, UInt_t nonLinFunct = AliEMCALRecoUtils::kBeamTestCorrected; if(isMC) { if(period == "lhc12a15a") nonLinFunct = AliEMCALRecoUtils::kPi0MCv2; else nonLinFunct = AliEMCALRecoUtils::kPi0MCv3; } remExoticClus = kTRUE; AliEmcalClusterMaker *clusMaker = AddTaskEmcalClusterMaker(nonLinFunct,remExoticClus,0,"EmcCaloClusters",0.,kTRUE); return clusterizerTask; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlscript.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ab $ $Date: 2000-12-05 09:34:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PRECOMPILED #include "filt_pch.hxx" #endif #pragma hdrstop #include <hintids.hxx> #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_ #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLMETAI_HXX #include <xmloff/xmlscripti.hxx> #endif #ifndef _XMLOFF_XMLMETAE_HXX #include <xmloff/xmlscripte.hxx> #endif #ifndef _SVX_LANGITEM_HXX #include <svx/langitem.hxx> #endif #ifndef _SWDOCSH_HXX #include "docsh.hxx" #endif #ifndef _DOC_HXX //autogen wg. SwDoc #include <doc.hxx> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLEXP_HXX #include "xmlexp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; // --------------------------------------------------------------------- SvXMLImportContext *SwXMLImport::CreateScriptContext( const OUString& rLocalName ) { SvXMLImportContext *pContext = 0; if( !(IsStylesOnlyMode() || IsInsertMode()) ) { pContext = new XMLScriptContext( *this, XML_NAMESPACE_OFFICE, rLocalName, GetModel() ); } if( !pContext ) pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE, rLocalName ); return pContext; } <commit_msg>INTEGRATION: CWS os8 (1.2.178); FILE MERGED 2003/04/03 07:13:22 os 1.2.178.1: #108583# precompiled headers removed<commit_after>/************************************************************************* * * $RCSfile: xmlscript.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2003-04-17 15:08:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include <hintids.hxx> #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTINFOSUPPLIER_HPP_ #include <com/sun/star/document/XDocumentInfoSupplier.hpp> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include <xmloff/xmlnmspe.hxx> #endif #ifndef _XMLOFF_XMLMETAI_HXX #include <xmloff/xmlscripti.hxx> #endif #ifndef _XMLOFF_XMLMETAE_HXX #include <xmloff/xmlscripte.hxx> #endif #ifndef _SVX_LANGITEM_HXX #include <svx/langitem.hxx> #endif #ifndef _SWDOCSH_HXX #include "docsh.hxx" #endif #ifndef _DOC_HXX //autogen wg. SwDoc #include <doc.hxx> #endif #ifndef _XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLEXP_HXX #include "xmlexp.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; // --------------------------------------------------------------------- SvXMLImportContext *SwXMLImport::CreateScriptContext( const OUString& rLocalName ) { SvXMLImportContext *pContext = 0; if( !(IsStylesOnlyMode() || IsInsertMode()) ) { pContext = new XMLScriptContext( *this, XML_NAMESPACE_OFFICE, rLocalName, GetModel() ); } if( !pContext ) pContext = new SvXMLImportContext( *this, XML_NAMESPACE_OFFICE, rLocalName ); return pContext; } <|endoftext|>
<commit_before>//-*- Mode: C++ -*- // $Id$ //* This file is property of and copyright by the ALICE Project * //* ALICE Experiment at CERN, All rights reserved. * //* See cxx source for full Copyright notice * /// @file compile-DxHFE.C /// @author Matthias Richter /// @date 2012-03-19 /// @brief Compile classes for the D0 - HFE correlation studies /// /// Usage: aliroot -l $ALICE_ROOT/PWGHF/correlationHF/compile-DxHFE.C #if defined(__CINT__) && !defined(__MAKECINT__) { //----------- Loading the required libraries ---------// gInterpreter->ExecuteMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/LoadLibraries.C"); gSystem->Load("libSTEERBase"); gSystem->Load("libESD"); gSystem->Load("libAOD"); gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libPWGHFhfe"); gSystem->Load("libCORRFW"); gSystem->AddIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/hfe "); TString dir("$ALICE_ROOT/PWGHF/correlationHF/"); gROOT->LoadMacro(dir+"AliHFAssociatedTrackCuts.cxx+"); gROOT->LoadMacro(dir+"AliReducedParticle.cxx+"); gROOT->LoadMacro(dir+"AliHFCorrelator.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelection.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionD0.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionEl.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEToolsMC.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCD0.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCEl.cxx+"); gROOT->LoadMacro(dir+"AliDxHFECorrelation.cxx+"); gROOT->LoadMacro(dir+"AliDxHFECorrelationMC.cxx+"); gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFEParticleSelection.cxx+"); gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFECorrelation.cxx+"); } #elif { cerr << "this macro can not be compiled, remove option '+'" << endl; } #endif <commit_msg>can compile also in current directory<commit_after>//-*- Mode: C++ -*- // $Id$ //* This file is property of and copyright by the ALICE Project * //* ALICE Experiment at CERN, All rights reserved. * //* See cxx source for full Copyright notice * /// @file compile-DxHFE.C /// @author Matthias Richter /// @date 2012-03-19 /// @brief Compile classes for the D0 - HFE correlation studies /// /// Usage: aliroot -l $ALICE_ROOT/PWGHF/correlationHF/compile-DxHFE.C void compile_DxHFE(Bool_t bUseLocalDir=kFALSE){ #if defined(__CINT__) && !defined(__MAKECINT__) { //----------- Loading the required libraries ---------// gInterpreter->ExecuteMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/LoadLibraries.C"); gSystem->Load("libSTEERBase"); gSystem->Load("libESD"); gSystem->Load("libAOD"); gSystem->Load("libANALYSIS"); gSystem->Load("libANALYSISalice"); gSystem->Load("libPWGHFhfe.so"); gSystem->Load("libCORRFW"); gSystem->AddIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_ROOT/PWGHF/vertexingHF -I$ALICE_ROOT/PWGHF/base -I$ALICE_ROOT/PWGHF/hfe "); if(bUseLocalDir) TString dir("./"); else TString dir("$ALICE_ROOT/PWGHF/correlationHF/"); gROOT->LoadMacro(dir+"AliSingleTrackEffCuts.cxx+"); gROOT->LoadMacro(dir+"AliCFSingleTrackEfficiencyTask.cxx+"); gROOT->LoadMacro(dir+"AliHFAssociatedTrackCuts.cxx+"); gROOT->LoadMacro(dir+"AliReducedParticle.cxx+"); gROOT->LoadMacro(dir+"AliHFCorrelator.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelection.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionD0.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionEl.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEToolsMC.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCD0.cxx+"); gROOT->LoadMacro(dir+"AliDxHFEParticleSelectionMCEl.cxx+"); gROOT->LoadMacro(dir+"AliDxHFECorrelation.cxx+"); gROOT->LoadMacro(dir+"AliDxHFECorrelationMC.cxx+"); gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFEParticleSelection.cxx+"); gROOT->LoadMacro(dir+"AliAnalysisTaskDxHFECorrelation.cxx+"); } #elif { cerr << "this macro can not be compiled, remove option '+'" << endl; } #endif } <|endoftext|>
<commit_before>#include "SwiftExtractor.h" #include <iostream> #include <memory> #include <unordered_set> #include <queue> #include <swift/AST/SourceFile.h> #include <swift/Basic/FileTypes.h> #include <llvm/ADT/SmallString.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include "swift/extractor/trap/generated/TrapClasses.h" #include "swift/extractor/trap/TrapDomain.h" #include "swift/extractor/visitors/SwiftVisitor.h" #include "swift/extractor/infra/TargetFile.h" using namespace codeql; using namespace std::string_literals; static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) { if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) { std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) { std::cerr << "Cannot create source archive directory: " << ec.message() << "\n"; return; } llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename()); llvm::sys::fs::make_absolute(srcFilePath); llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir); llvm::sys::path::append(dstFilePath, srcFilePath); llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath); if (std::error_code ec = llvm::sys::fs::create_directories(parent)) { std::cerr << "Cannot create source archive destination directory '" << parent.str() << "': " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) { std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '" << dstFilePath.str().str() << "': " << ec.message() << "\n"; return; } } static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) { if (primaryFile) { return primaryFile->getFilename().str(); } // PCM clang module if (module.isNonSwiftModule()) { // Several modules with different names might come from .pcm (clang module) files // In this case we want to differentiate them // Moreover, pcm files may come from caches located in different directories, but are // unambiguously identified by the base file name, so we can discard the absolute directory std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str(); filename += "-"; filename += module.getName().str(); return filename; } return module.getModuleFilename().str(); } static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { llvm::SmallVector<swift::Decl*> ret; ret.push_back(&module); if (primaryFile) { primaryFile->getTopLevelDecls(ret); } else { module.getTopLevelDecls(ret); } return ret; } static void dumpArgs(TargetFile& out, const SwiftExtractorConfiguration& config) { out << "/* extractor-args:\n"; for (const auto& opt : config.frontendOptions) { out << " " << std::quoted(opt) << " \\\n"; } out << "\n*/\n"; out << "/* swift-frontend-args:\n"; for (const auto& opt : config.patchedFrontendOptions) { out << " " << std::quoted(opt) << " \\\n"; } out << "\n*/\n"; } static void extractDeclarations(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler, swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { auto filename = getFilename(module, primaryFile); // The extractor can be called several times from different processes with // the same input file(s). Using `TargetFile` the first process will win, and the following // will just skip the work auto trapTarget = TargetFile::create(filename + ".trap", config.trapDir, config.getTempTrapDir()); if (!trapTarget) { // another process arrived first, nothing to do for us return; } dumpArgs(*trapTarget, config); TrapDomain trap{*trapTarget}; // TODO: remove this and recreate it with IPA when we have that // the following cannot conflict with actual files as those have an absolute path starting with / File unknownFileEntry{trap.createLabel<FileTag>("unknown")}; Location unknownLocationEntry{trap.createLabel<LocationTag>("unknown")}; unknownLocationEntry.file = unknownFileEntry.id; trap.emit(unknownFileEntry); trap.emit(unknownLocationEntry); SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile); auto topLevelDecls = getTopLevelDecls(module, primaryFile); for (auto decl : topLevelDecls) { visitor.extract(decl); } } static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) { // The frontend can be called in many different ways. // At each invocation we only extract system and builtin modules and any input source files that // have an output associated with them. std::unordered_set<std::string> sourceFiles; auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs(); for (auto& input : inputFiles) { if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) { sourceFiles.insert(input.getFileName()); } } return sourceFiles; } static std::unordered_set<swift::ModuleDecl*> collectModules(swift::CompilerInstance& compiler) { // getASTContext().getLoadedModules() does not provide all the modules available within the // program. // We need to iterate over all the imported modules (recursively) to see the whole "universe." std::unordered_set<swift::ModuleDecl*> allModules; std::queue<swift::ModuleDecl*> worklist; for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) { worklist.push(module); allModules.insert(module); } while (!worklist.empty()) { auto module = worklist.front(); worklist.pop(); llvm::SmallVector<swift::ImportedModule> importedModules; // TODO: we may need more than just Exported ones module->getImportedModules(importedModules, swift::ModuleDecl::ImportFilterKind::Exported); for (auto& imported : importedModules) { if (allModules.count(imported.importedModule) == 0) { worklist.push(imported.importedModule); allModules.insert(imported.importedModule); } } } return allModules; } void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler) { auto inputFiles = collectInputFilenames(compiler); auto modules = collectModules(compiler); // we want to make sure any following extractor run will not try to extract things from // the swiftmodule files we are creating in this run, as those things will already have been // extracted from source with more information. We do this by creating empty trap files. // TargetFile semantics will ensure any following run trying to extract that swiftmodule will just // skip doing it for (const auto& output : config.outputSwiftModules) { TargetFile::create(output, config.trapDir, config.getTempTrapDir()); } for (auto& module : modules) { bool isFromSourceFile = false; for (auto file : module->getFiles()) { auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file); if (!sourceFile) { continue; } isFromSourceFile = true; if (inputFiles.count(sourceFile->getFilename().str()) == 0) { continue; } archiveFile(config, *sourceFile); extractDeclarations(config, compiler, *module, sourceFile); } if (!isFromSourceFile) { extractDeclarations(config, compiler, *module); } } } <commit_msg>Swift: readd .trap suffix to swiftmodule trap files<commit_after>#include "SwiftExtractor.h" #include <iostream> #include <memory> #include <unordered_set> #include <queue> #include <swift/AST/SourceFile.h> #include <swift/Basic/FileTypes.h> #include <llvm/ADT/SmallString.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/Path.h> #include "swift/extractor/trap/generated/TrapClasses.h" #include "swift/extractor/trap/TrapDomain.h" #include "swift/extractor/visitors/SwiftVisitor.h" #include "swift/extractor/infra/TargetFile.h" using namespace codeql; using namespace std::string_literals; static void archiveFile(const SwiftExtractorConfiguration& config, swift::SourceFile& file) { if (std::error_code ec = llvm::sys::fs::create_directories(config.trapDir)) { std::cerr << "Cannot create TRAP directory: " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::create_directories(config.sourceArchiveDir)) { std::cerr << "Cannot create source archive directory: " << ec.message() << "\n"; return; } llvm::SmallString<PATH_MAX> srcFilePath(file.getFilename()); llvm::sys::fs::make_absolute(srcFilePath); llvm::SmallString<PATH_MAX> dstFilePath(config.sourceArchiveDir); llvm::sys::path::append(dstFilePath, srcFilePath); llvm::StringRef parent = llvm::sys::path::parent_path(dstFilePath); if (std::error_code ec = llvm::sys::fs::create_directories(parent)) { std::cerr << "Cannot create source archive destination directory '" << parent.str() << "': " << ec.message() << "\n"; return; } if (std::error_code ec = llvm::sys::fs::copy_file(srcFilePath, dstFilePath)) { std::cerr << "Cannot archive source file '" << srcFilePath.str().str() << "' -> '" << dstFilePath.str().str() << "': " << ec.message() << "\n"; return; } } static std::string getFilename(swift::ModuleDecl& module, swift::SourceFile* primaryFile) { if (primaryFile) { return primaryFile->getFilename().str(); } // PCM clang module if (module.isNonSwiftModule()) { // Several modules with different names might come from .pcm (clang module) files // In this case we want to differentiate them // Moreover, pcm files may come from caches located in different directories, but are // unambiguously identified by the base file name, so we can discard the absolute directory std::string filename = "/pcms/"s + llvm::sys::path::filename(module.getModuleFilename()).str(); filename += "-"; filename += module.getName().str(); return filename; } return module.getModuleFilename().str(); } static llvm::SmallVector<swift::Decl*> getTopLevelDecls(swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { llvm::SmallVector<swift::Decl*> ret; ret.push_back(&module); if (primaryFile) { primaryFile->getTopLevelDecls(ret); } else { module.getTopLevelDecls(ret); } return ret; } static void dumpArgs(TargetFile& out, const SwiftExtractorConfiguration& config) { out << "/* extractor-args:\n"; for (const auto& opt : config.frontendOptions) { out << " " << std::quoted(opt) << " \\\n"; } out << "\n*/\n"; out << "/* swift-frontend-args:\n"; for (const auto& opt : config.patchedFrontendOptions) { out << " " << std::quoted(opt) << " \\\n"; } out << "\n*/\n"; } static void extractDeclarations(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler, swift::ModuleDecl& module, swift::SourceFile* primaryFile = nullptr) { auto filename = getFilename(module, primaryFile); // The extractor can be called several times from different processes with // the same input file(s). Using `TargetFile` the first process will win, and the following // will just skip the work auto trapTarget = TargetFile::create(filename + ".trap", config.trapDir, config.getTempTrapDir()); if (!trapTarget) { // another process arrived first, nothing to do for us return; } dumpArgs(*trapTarget, config); TrapDomain trap{*trapTarget}; // TODO: remove this and recreate it with IPA when we have that // the following cannot conflict with actual files as those have an absolute path starting with / File unknownFileEntry{trap.createLabel<FileTag>("unknown")}; Location unknownLocationEntry{trap.createLabel<LocationTag>("unknown")}; unknownLocationEntry.file = unknownFileEntry.id; trap.emit(unknownFileEntry); trap.emit(unknownLocationEntry); SwiftVisitor visitor(compiler.getSourceMgr(), trap, module, primaryFile); auto topLevelDecls = getTopLevelDecls(module, primaryFile); for (auto decl : topLevelDecls) { visitor.extract(decl); } } static std::unordered_set<std::string> collectInputFilenames(swift::CompilerInstance& compiler) { // The frontend can be called in many different ways. // At each invocation we only extract system and builtin modules and any input source files that // have an output associated with them. std::unordered_set<std::string> sourceFiles; auto inputFiles = compiler.getInvocation().getFrontendOptions().InputsAndOutputs.getAllInputs(); for (auto& input : inputFiles) { if (input.getType() == swift::file_types::TY_Swift && !input.outputFilename().empty()) { sourceFiles.insert(input.getFileName()); } } return sourceFiles; } static std::unordered_set<swift::ModuleDecl*> collectModules(swift::CompilerInstance& compiler) { // getASTContext().getLoadedModules() does not provide all the modules available within the // program. // We need to iterate over all the imported modules (recursively) to see the whole "universe." std::unordered_set<swift::ModuleDecl*> allModules; std::queue<swift::ModuleDecl*> worklist; for (auto& [_, module] : compiler.getASTContext().getLoadedModules()) { worklist.push(module); allModules.insert(module); } while (!worklist.empty()) { auto module = worklist.front(); worklist.pop(); llvm::SmallVector<swift::ImportedModule> importedModules; // TODO: we may need more than just Exported ones module->getImportedModules(importedModules, swift::ModuleDecl::ImportFilterKind::Exported); for (auto& imported : importedModules) { if (allModules.count(imported.importedModule) == 0) { worklist.push(imported.importedModule); allModules.insert(imported.importedModule); } } } return allModules; } void codeql::extractSwiftFiles(const SwiftExtractorConfiguration& config, swift::CompilerInstance& compiler) { auto inputFiles = collectInputFilenames(compiler); auto modules = collectModules(compiler); // we want to make sure any following extractor run will not try to extract things from // the swiftmodule files we are creating in this run, as those things will already have been // extracted from source with more information. We do this by creating empty trap files. // TargetFile semantics will ensure any following run trying to extract that swiftmodule will just // skip doing it for (const auto& output : config.outputSwiftModules) { TargetFile::create(output + ".trap", config.trapDir, config.getTempTrapDir()); } for (auto& module : modules) { bool isFromSourceFile = false; for (auto file : module->getFiles()) { auto sourceFile = llvm::dyn_cast<swift::SourceFile>(file); if (!sourceFile) { continue; } isFromSourceFile = true; if (inputFiles.count(sourceFile->getFilename().str()) == 0) { continue; } archiveFile(config, *sourceFile); extractDeclarations(config, compiler, *module, sourceFile); } if (!isFromSourceFile) { extractDeclarations(config, compiler, *module); } } } <|endoftext|>
<commit_before>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2011, 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: Enrico Siragusa <[email protected]> // ========================================================================== // This file contains the masai_mapper application. // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include "options.h" #include "mapper.h" using namespace seqan; // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Class Options // ---------------------------------------------------------------------------- struct Options : public MasaiOptions { CharString genomeFile; CharString genomeIndexFile; IndexType genomeIndexType; CharString readsFile; CharString mappedReadsFile; OutputFormat outputFormat; bool outputCigar; MappingMode mappingMode; unsigned errorsPerRead; unsigned errorsLossy; unsigned seedLength; bool mismatchesOnly; bool verifyHits; bool dumpResults; bool multipleBacktracking; Options() : MasaiOptions(), genomeIndexType(INDEX_SA), outputFormat(RAW), outputCigar(true), mappingMode(ANY_BEST), errorsPerRead(5), errorsLossy(0), seedLength(33), mismatchesOnly(false), verifyHits(true), dumpResults(true), multipleBacktracking(true) {} }; // ============================================================================ void setupArgumentParser(ArgumentParser & parser, Options const & options) { setAppName(parser, "masai_mapper"); setShortDescription(parser, "Masai Mapper"); setCategory(parser, "Read Mapping"); setDateAndVersion(parser); setDescription(parser); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); setValidValues(parser, 0, "fasta fa"); setValidValues(parser, 1, "fastq fasta fa"); addSection(parser, "Mapping Options"); addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING)); setValidValues(parser, "mapping-mode", options.mappingModeList); setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]); addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER)); setMinValue(parser, "errors", "0"); setMaxValue(parser, "errors", "32"); setDefaultValue(parser, "errors", options.errorsPerRead); // addOption(parser, ArgParseOption("el", "errors-lossy", // "Maximum number of errors per read to report. For any-best mode only.", // ArgParseOption::INTEGER)); // setMinValue(parser, "errors-lossy", "0"); // setMaxValue(parser, "errors-lossy", "32"); // setDefaultValue(parser, "errors-lossy", options.errorsLossy); addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER)); setMinValue(parser, "seed-length", "10"); setMaxValue(parser, "seed-length", "100"); setDefaultValue(parser, "seed-length", options.seedLength); addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps.")); addSection(parser, "Genome Index Options"); setIndexType(parser, options); setIndexPrefix(parser); addSection(parser, "Output Options"); setOutputFile(parser); setOutputFormat(parser, options); addSection(parser, "Debug Options"); addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits.")); addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results.")); addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking.")); } ArgumentParser::ParseResult parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv) { ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res; // Parse genome input file. getArgumentValue(options.genomeFile, parser, 0); // Parse reads input file. getArgumentValue(options.readsFile, parser, 1); // Parse mapping mode. getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList); // Parse mapping options. getOptionValue(options.errorsPerRead, parser, "errors"); // getOptionValue(options.errorsLossy, parser, "errors-lossy"); options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead); getOptionValue(options.seedLength, parser, "seed-length"); options.mismatchesOnly = isSet(parser, "no-gaps"); // Parse genome index prefix. getIndexPrefix(options, parser); // Parse genome index type. getIndexType(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output file. getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, ""); // Parse debug options. options.verifyHits = !isSet(parser, "no-verify"); options.dumpResults = !isSet(parser, "no-dump"); options.multipleBacktracking = !isSet(parser, "no-multiple"); return seqan::ArgumentParser::PARSE_OK; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex> int runMapper(Options & options) { // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec. typedef Mapper<TIndex> TMapper; // TODO(esiragusa): Remove writeCigar from Mapper members. TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults); double start, finish; // Loading genome. std::cout << "Loading genome:\t\t\t" << std::flush; start = sysTime(); if (!loadGenome(mapper.indexer, options.genomeFile)) { std::cerr << "Error while loading genome" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl; // Loading genome index. std::cout << "Loading genome index:\t\t" << std::flush; start = sysTime(); if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile)) { std::cout << "Error while loading genome index" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // Loading reads. std::cout << "Loading reads:\t\t\t" << std::flush; start = sysTime(); if (!loadReads(mapper, options.readsFile, TFormat())) { std::cerr << "Error while loading reads" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl; // Mapping reads. start = sysTime(); if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy, TDistance(), TStrategy(), TBacktracking(), TFormat())) { std::cerr << "Error while writing results" << std::endl; return 1; } finish = sysTime(); std::cout << "Mapping time:\t\t\t" << std::flush; std::cout << finish - start << " sec" << std::endl; return 0; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking> int configureGenomeIndex(Options & options) { switch (options.genomeIndexType) { case Options::INDEX_ESA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options); case Options::INDEX_SA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options); // case Options::INDEX_QGRAM: // return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options); case Options::INDEX_FM: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options); default: return 1; } } template <typename TStrategy, typename TDistance, typename TFormat> int configureBacktracking(Options & options) { if (options.multipleBacktracking) return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options); else return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options); } template <typename TStrategy, typename TDistance> int configureOutputFormat(Options & options) { switch (options.outputFormat) { case Options::RAW: return configureBacktracking<TStrategy, TDistance, Raw>(options); case Options::SAM: return configureBacktracking<TStrategy, TDistance, Sam>(options); case Options::SAM_NO_CIGAR: options.outputCigar = false; return configureBacktracking<TStrategy, TDistance, Sam>(options); default: return 1; } } template <typename TStrategy> int configureDistance(Options & options) { if (options.mismatchesOnly) return configureOutputFormat<TStrategy, HammingDistance>(options); else return configureOutputFormat<TStrategy, EditDistance>(options); } int mainWithOptions(Options & options) { switch (options.mappingMode) { case Options::ANY_BEST: return configureDistance<AnyBest>(options); case Options::ALL_BEST: return configureDistance<AllBest>(options); case Options::ALL: return configureDistance<All>(options); default: return 1; } } int main(int argc, char const ** argv) { ArgumentParser parser; Options options; setupArgumentParser(parser, options); ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) return mainWithOptions(options); else return res; } <commit_msg>[FIX] masai: fixing a typo in argument parsing<commit_after>// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2011, 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: Enrico Siragusa <[email protected]> // ========================================================================== // This file contains the masai_mapper application. // ========================================================================== #include <seqan/basic.h> #include <seqan/sequence.h> #include "options.h" #include "mapper.h" using namespace seqan; // ============================================================================ // Tags, Classes, Enums // ============================================================================ // ---------------------------------------------------------------------------- // Class Options // ---------------------------------------------------------------------------- struct Options : public MasaiOptions { CharString genomeFile; CharString genomeIndexFile; IndexType genomeIndexType; CharString readsFile; CharString mappedReadsFile; OutputFormat outputFormat; bool outputCigar; MappingMode mappingMode; unsigned errorsPerRead; unsigned errorsLossy; unsigned seedLength; bool mismatchesOnly; bool verifyHits; bool dumpResults; bool multipleBacktracking; Options() : MasaiOptions(), genomeIndexType(INDEX_SA), outputFormat(RAW), outputCigar(true), mappingMode(ANY_BEST), errorsPerRead(5), errorsLossy(0), seedLength(33), mismatchesOnly(false), verifyHits(true), dumpResults(true), multipleBacktracking(true) {} }; // ============================================================================ void setupArgumentParser(ArgumentParser & parser, Options const & options) { setAppName(parser, "masai_mapper"); setShortDescription(parser, "Masai Mapper"); setCategory(parser, "Read Mapping"); setDateAndVersion(parser); setDescription(parser); addUsageLine(parser, "[\\fIOPTIONS\\fP] <\\fIGENOME FILE\\fP> <\\fIREADS FILE\\fP>"); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); addArgument(parser, ArgParseArgument(ArgParseArgument::INPUTFILE)); setValidValues(parser, 0, "fasta fa"); setValidValues(parser, 1, "fastq fasta fa"); addSection(parser, "Mapping Options"); addOption(parser, ArgParseOption("mm", "mapping-mode", "Select mapping mode.", ArgParseOption::STRING)); setValidValues(parser, "mapping-mode", options.mappingModeList); setDefaultValue(parser, "mapping-mode", options.mappingModeList[options.mappingMode]); addOption(parser, ArgParseOption("e", "errors", "Maximum number of errors per read.", ArgParseOption::INTEGER)); setMinValue(parser, "errors", "0"); setMaxValue(parser, "errors", "32"); setDefaultValue(parser, "errors", options.errorsPerRead); // addOption(parser, ArgParseOption("el", "errors-lossy", // "Maximum number of errors per read to report. For any-best mode only.", // ArgParseOption::INTEGER)); // setMinValue(parser, "errors-lossy", "0"); // setMaxValue(parser, "errors-lossy", "32"); // setDefaultValue(parser, "errors-lossy", options.errorsLossy); addOption(parser, ArgParseOption("sl", "seed-length", "Minimum seed length.", ArgParseOption::INTEGER)); setMinValue(parser, "seed-length", "10"); setMaxValue(parser, "seed-length", "100"); setDefaultValue(parser, "seed-length", options.seedLength); addOption(parser, ArgParseOption("ng", "no-gaps", "Do not align reads with gaps.")); addSection(parser, "Genome Index Options"); setIndexType(parser, options); setIndexPrefix(parser); addSection(parser, "Output Options"); setOutputFile(parser); setOutputFormat(parser, options); addSection(parser, "Debug Options"); addOption(parser, ArgParseOption("nv", "no-verify", "Do not verify seed hits.")); addOption(parser, ArgParseOption("nd", "no-dump", "Do not dump results.")); addOption(parser, ArgParseOption("nm", "no-multiple", "Disable multiple backtracking.")); } ArgumentParser::ParseResult parseCommandLine(Options & options, ArgumentParser & parser, int argc, char const ** argv) { ArgumentParser::ParseResult res = parse(parser, argc, argv); if (res != seqan::ArgumentParser::PARSE_OK) return res; // Parse genome input file. getArgumentValue(options.genomeFile, parser, 0); // Parse reads input file. getArgumentValue(options.readsFile, parser, 1); // Parse mapping mode. getOptionValue(options.mappingMode, parser, "mapping-mode", options.mappingModeList); // Parse mapping options. getOptionValue(options.errorsPerRead, parser, "errors"); // getOptionValue(options.errorsLossy, parser, "errors-lossy"); options.errorsLossy = std::max(options.errorsLossy, options.errorsPerRead); getOptionValue(options.seedLength, parser, "seed-length"); options.mismatchesOnly = isSet(parser, "no-gaps"); // Parse genome index prefix. getIndexPrefix(options, parser); // Parse genome index type. getIndexType(options, parser); // Parse output format. getOutputFormat(options, parser); // Parse output file. getOutputFile(options.mappedReadsFile, options, parser, options.readsFile, ""); // Parse debug options. options.verifyHits = !isSet(parser, "no-verify"); options.dumpResults = !isSet(parser, "no-dump"); options.multipleBacktracking = !isSet(parser, "no-multiple"); return seqan::ArgumentParser::PARSE_OK; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking, typename TIndex> int runMapper(Options & options) { // TODO(esiragusa): Use typename TGenomeIndex instead of TSpec. typedef Mapper<TIndex> TMapper; // TODO(esiragusa): Remove writeCigar from Mapper members. TMapper mapper(options.seedLength, options.outputCigar, options.verifyHits, options.dumpResults); double start, finish; // Loading genome. std::cout << "Loading genome:\t\t\t" << std::flush; start = sysTime(); if (!loadGenome(mapper.indexer, options.genomeFile)) { std::cerr << "Error while loading genome" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // std::cout << "Contigs count:\t\t\t" << mapper.indexer.contigsCount << std::endl; // Loading genome index. std::cout << "Loading genome index:\t\t" << std::flush; start = sysTime(); if (!loadGenomeIndex(mapper.indexer, options.genomeIndexFile)) { std::cout << "Error while loading genome index" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; // Loading reads. std::cout << "Loading reads:\t\t\t" << std::flush; start = sysTime(); if (!loadReads(mapper, options.readsFile, TFormat())) { std::cerr << "Error while loading reads" << std::endl; return 1; } finish = sysTime(); std::cout << finish - start << " sec" << std::endl; std::cout << "Reads count:\t\t\t" << mapper.readsCount << std::endl; // Mapping reads. start = sysTime(); if (!mapReads(mapper, options.mappedReadsFile, options.errorsPerRead, options.errorsLossy, TDistance(), TStrategy(), TBacktracking(), TFormat())) { std::cerr << "Error while writing results" << std::endl; return 1; } finish = sysTime(); std::cout << "Mapping time:\t\t\t" << std::flush; std::cout << finish - start << " sec" << std::endl; return 0; } // ============================================================================ template <typename TStrategy, typename TDistance, typename TFormat, typename TBacktracking> int configureGenomeIndex(Options & options) { switch (options.genomeIndexType) { case Options::INDEX_ESA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeEsa>(options); case Options::INDEX_SA: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeSa>(options); // case Options::INDEX_QGRAM: // return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeQGram>(options); case Options::INDEX_FM: return runMapper<TStrategy, TDistance, TFormat, TBacktracking, TGenomeFM>(options); default: return 1; } } template <typename TStrategy, typename TDistance, typename TFormat> int configureBacktracking(Options & options) { if (options.multipleBacktracking) return configureGenomeIndex<TStrategy, TDistance, TFormat, MultipleBacktracking>(options); else return configureGenomeIndex<TStrategy, TDistance, TFormat, SingleBacktracking>(options); } template <typename TStrategy, typename TDistance> int configureOutputFormat(Options & options) { switch (options.outputFormat) { case Options::RAW: return configureBacktracking<TStrategy, TDistance, Raw>(options); case Options::SAM: return configureBacktracking<TStrategy, TDistance, Sam>(options); case Options::SAM_NO_CIGAR: options.outputCigar = false; return configureBacktracking<TStrategy, TDistance, Sam>(options); default: return 1; } } template <typename TStrategy> int configureDistance(Options & options) { if (options.mismatchesOnly) return configureOutputFormat<TStrategy, HammingDistance>(options); else return configureOutputFormat<TStrategy, EditDistance>(options); } int mainWithOptions(Options & options) { switch (options.mappingMode) { case Options::ANY_BEST: return configureDistance<AnyBest>(options); case Options::ALL_BEST: return configureDistance<AllBest>(options); case Options::ALL: return configureDistance<All>(options); default: return 1; } } int main(int argc, char const ** argv) { ArgumentParser parser; Options options; setupArgumentParser(parser, options); ArgumentParser::ParseResult res = parseCommandLine(options, parser, argc, argv); if (res == seqan::ArgumentParser::PARSE_OK) return mainWithOptions(options); else return res; } <|endoftext|>
<commit_before>/* * MoleculeBallifier.cpp * * Copyright (C) 2012 by TU Dresden * All rights reserved. */ #include "stdafx.h" #include "MoleculeBallifier.h" #include "protein_calls/MolecularDataCall.h" #include "geometry_calls/MultiParticleDataCall.h" using namespace megamol; using namespace megamol::protein; using namespace megamol::geocalls; using namespace megamol::protein_calls; /* * */ MoleculeBallifier::MoleculeBallifier(void) : core::Module(), outDataSlot("outData", "Sends MultiParticleDataCall data out into the world"), inDataSlot("inData", "Fetches MolecularDataCall data"), inHash(0), outHash(0), data(), colMin(0.0f), colMax(1.0f), frameOld(-1) { this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>(); this->MakeSlotAvailable(&this->inDataSlot); this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(), geocalls::MultiParticleDataCall::FunctionName(0), &MoleculeBallifier::getData); this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(), geocalls::MultiParticleDataCall::FunctionName(1), &MoleculeBallifier::getExt); this->MakeSlotAvailable(&this->outDataSlot); } /* * */ MoleculeBallifier::~MoleculeBallifier(void) { this->Release(); } /* * */ bool MoleculeBallifier::create(void) { // intentionally empty return true; } /* * */ void MoleculeBallifier::release(void) { // intentionally empty } /* * */ bool MoleculeBallifier::getData(core::Call& c) { using geocalls::MultiParticleDataCall; MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c); if (ic == NULL) return false; MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>(); if (oc == NULL) return false; // Transfer frame ID plus force flag oc->SetFrameID(ic->FrameID(), ic->IsFrameForced()); if ((*oc)(0)) { // Rewrite data if the frame number OR the datahash has changed if ((this->inHash != oc->DataHash())||(this->frameOld = static_cast<int>(oc->FrameID()))) { this->inHash = oc->DataHash(); this->frameOld = static_cast<int>(oc->FrameID()); this->outHash++; /* da kannst Du die atom-position und den B-Faktor auslesen AtomCount, AtomPositions, AtomBFactors ueber den Atom-Type kannst Du auf das Type-Array zugreifen, das den Radius drin hat */ unsigned int cnt = oc->AtomCount(); this->data.AssertSize(sizeof(float) * 5 * cnt); float *fData = this->data.As<float>(); for (unsigned int i = 0; i < cnt; i++, fData += 5) { fData[0] = oc->AtomPositions()[i * 3 + 0]; fData[1] = oc->AtomPositions()[i * 3 + 1]; fData[2] = oc->AtomPositions()[i * 3 + 2]; fData[3] = oc->AtomTypes()[oc->AtomTypeIndices()[i]].Radius(); fData[4] = oc->AtomBFactors()[i]; if ((i == 0) || (this->colMin > fData[4])) this->colMin = fData[4]; if ((i == 0) || (this->colMax < fData[4])) this->colMax = fData[4]; } } ic->SetDataHash(this->outHash); ic->SetParticleListCount(1); MultiParticleDataCall::Particles& p = ic->AccessParticles(0); p.SetCount(this->data.GetSize() / (sizeof(float) * 5)); if (p.GetCount() > 0) { p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, this->data.At(0), sizeof(float) * 5); p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, this->data.At(sizeof(float) * 4), sizeof(float) * 5); p.SetColourMapIndexValues(this->colMin, this->colMax); } } return true; } /* * */ bool MoleculeBallifier::getExt(core::Call& c) { using geocalls::MultiParticleDataCall; MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c); if (ic == NULL) return false; MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>(); if (oc == NULL) return false; if ((*oc)(1)) { ic->SetFrameCount(oc->FrameCount()); ic->AccessBoundingBoxes() = oc->AccessBoundingBoxes(); return true; } return false; } <commit_msg>as Karsten said...<commit_after>/* * MoleculeBallifier.cpp * * Copyright (C) 2012 by TU Dresden * All rights reserved. */ #include "stdafx.h" #include "MoleculeBallifier.h" #include "protein_calls/MolecularDataCall.h" #include "geometry_calls/MultiParticleDataCall.h" using namespace megamol; using namespace megamol::protein; using namespace megamol::geocalls; using namespace megamol::protein_calls; /* * */ MoleculeBallifier::MoleculeBallifier(void) : core::Module(), outDataSlot("outData", "Sends MultiParticleDataCall data out into the world"), inDataSlot("inData", "Fetches MolecularDataCall data"), inHash(0), outHash(0), data(), colMin(0.0f), colMax(1.0f), frameOld(-1) { this->inDataSlot.SetCompatibleCall<MolecularDataCallDescription>(); this->MakeSlotAvailable(&this->inDataSlot); this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(), geocalls::MultiParticleDataCall::FunctionName(0), &MoleculeBallifier::getData); this->outDataSlot.SetCallback(geocalls::MultiParticleDataCall::ClassName(), geocalls::MultiParticleDataCall::FunctionName(1), &MoleculeBallifier::getExt); this->MakeSlotAvailable(&this->outDataSlot); } /* * */ MoleculeBallifier::~MoleculeBallifier(void) { this->Release(); } /* * */ bool MoleculeBallifier::create(void) { // intentionally empty return true; } /* * */ void MoleculeBallifier::release(void) { // intentionally empty } /* * */ bool MoleculeBallifier::getData(core::Call& c) { using geocalls::MultiParticleDataCall; MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c); if (ic == NULL) return false; MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>(); if (oc == NULL) return false; // Transfer frame ID plus force flag oc->SetFrameID(ic->FrameID(), ic->IsFrameForced()); if ((*oc)(0)) { // Rewrite data if the frame number OR the datahash has changed if ((this->inHash != oc->DataHash())||(this->frameOld != static_cast<int>(oc->FrameID()))) { this->inHash = oc->DataHash(); this->frameOld = static_cast<int>(oc->FrameID()); this->outHash++; /* da kannst Du die atom-position und den B-Faktor auslesen AtomCount, AtomPositions, AtomBFactors ueber den Atom-Type kannst Du auf das Type-Array zugreifen, das den Radius drin hat */ unsigned int cnt = oc->AtomCount(); this->data.AssertSize(sizeof(float) * 5 * cnt); float *fData = this->data.As<float>(); for (unsigned int i = 0; i < cnt; i++, fData += 5) { fData[0] = oc->AtomPositions()[i * 3 + 0]; fData[1] = oc->AtomPositions()[i * 3 + 1]; fData[2] = oc->AtomPositions()[i * 3 + 2]; fData[3] = oc->AtomTypes()[oc->AtomTypeIndices()[i]].Radius(); fData[4] = oc->AtomBFactors()[i]; if ((i == 0) || (this->colMin > fData[4])) this->colMin = fData[4]; if ((i == 0) || (this->colMax < fData[4])) this->colMax = fData[4]; } } ic->SetDataHash(this->outHash); ic->SetParticleListCount(1); MultiParticleDataCall::Particles& p = ic->AccessParticles(0); p.SetCount(this->data.GetSize() / (sizeof(float) * 5)); if (p.GetCount() > 0) { p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, this->data.At(0), sizeof(float) * 5); p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, this->data.At(sizeof(float) * 4), sizeof(float) * 5); p.SetColourMapIndexValues(this->colMin, this->colMax); } } return true; } /* * */ bool MoleculeBallifier::getExt(core::Call& c) { using geocalls::MultiParticleDataCall; MultiParticleDataCall *ic = dynamic_cast<MultiParticleDataCall*>(&c); if (ic == NULL) return false; MolecularDataCall *oc = this->inDataSlot.CallAs<MolecularDataCall>(); if (oc == NULL) return false; if ((*oc)(1)) { ic->SetFrameCount(oc->FrameCount()); ic->AccessBoundingBoxes() = oc->AccessBoundingBoxes(); return true; } return false; } <|endoftext|>
<commit_before>// schokwaveDeath.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> // event handaler callback class DeathHandaler : public bz_EventHandaler { public: virtual void process ( bz_EventData *eventData ); }; DeathHandaler deathHandaler; extern "C" int bz_Load ( const char* commandLine ) { bz_debugMessage(3,"shockwaveDeath plugin called"); bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&deathHandaler); return 0; } extern "C" int bz_Unload ( void ) { return 0; } void DeathHandaler::process ( bz_EventData *eventData ) { if (eventData->eventType != bz_ePlayerDieEvent) return; bz_PlayerDieEventData *dieData = (bz_PlayerDieEventData*)eventData; bz_fireWorldWep("SW",(float)bz_getBZDBDouble("_reloadTime"),BZ_SERVER,dieData->pos,0,0,0,0.0f); } <commit_msg>cleaup to use #def for export on all OSs<commit_after>// schokwaveDeath.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" #include <string> // event handaler callback class DeathHandaler : public bz_EventHandaler { public: virtual void process ( bz_EventData *eventData ); }; DeathHandaler deathHandaler; BZF_API int bz_Load ( const char* commandLine ) { bz_debugMessage(3,"shockwaveDeath plugin called"); bz_registerEvent(bz_ePlayerDieEvent,BZ_ALL_USERS,&deathHandaler); return 0; } BZF_API int bz_Unload ( void ) { return 0; } void DeathHandaler::process ( bz_EventData *eventData ) { if (eventData->eventType != bz_ePlayerDieEvent) return; bz_PlayerDieEventData *dieData = (bz_PlayerDieEventData*)eventData; bz_fireWorldWep("SW",(float)bz_getBZDBDouble("_reloadTime"),BZ_SERVER,dieData->pos,0,0,0,0.0f); } <|endoftext|>
<commit_before>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include "agent/resource_collector.h" #include <errno.h> #include <string.h> #include <time.h> #include <string> #include <boost/lexical_cast.hpp> #include "common/logging.h" namespace galaxy { #define SAFE_FREE(x) \ do { \ if (x != NULL) {\ free(x); \ x = NULL; \ } \ } while(0) const std::string CGROUP_MOUNT_PATH = "/cgroups/"; const std::string CPUACT_SUBSYSTEM_PATH = "cpuacct"; static long SYS_TIMER_HZ = sysconf(_SC_CLK_TCK); static long CPU_CORES = sysconf(_SC_NPROCESSORS_CONF); // unit jiffies struct ResourceStatistics { // cpu long cpu_user_time; long cpu_nice_time; long cpu_system_time; long cpu_idle_time; long cpu_iowait_time; long cpu_irq_time; long cpu_softirq_time; long cpu_stealstolen; long cpu_guest; long cpu_cores; }; // unit jiffies struct CgroupResourceStatistics { long cpu_user_time; long cpu_system_time; // cpu_cores from cfs_quota_usota_us double cpu_cores_limit; }; // get cpu usage from /cgroups/cpuacct/xxxxx/cpuacct.stat // get cpu limit cores from /cgroups/cpu/xxxxx/cpu.cfs_quota_usota_us and cpu.cfs_ static bool GetCgroupCpuUsage( const std::string& group_path, CgroupResourceStatistics* statistics); // get total cpu usage from /proc/stat static bool GetGlobalCpuUsage(ResourceStatistics* statistics); static bool GetCgroupCpuCoresLimit( const std::string& group_path, CgroupResourceStatistics* statistics); class CGroupResourceCollectorImpl { public: CGroupResourceCollectorImpl() {} explicit CGroupResourceCollectorImpl(const std::string& cgroup_name) : cgroup_name_(cgroup_name), global_statistics_prev_(), global_statistics_cur_(), cgroup_statistics_prev_(), cgroup_statistics_cur_(), timestamp_prev_(0.0), timestamp_cur_(0.0), mutex_() { } virtual ~CGroupResourceCollectorImpl() {} virtual bool CollectStatistics(); double GetCpuUsage(); long GetMemoryUsage() {return 0;} private: std::string cgroup_name_; // global resource statistics ResourceStatistics global_statistics_prev_; ResourceStatistics global_statistics_cur_; // cgroup resource statistics CgroupResourceStatistics cgroup_statistics_prev_; CgroupResourceStatistics cgroup_statistics_cur_; double timestamp_prev_; double timestamp_cur_; long collector_times_; common::Mutex mutex_; }; double CGroupResourceCollectorImpl::GetCpuUsage() { const int MIN_COLLOECT_TIMES_NEED = 2; common::MutexLock lock(&mutex_); if (collector_times_ < MIN_COLLOECT_TIMES_NEED) { LOG(WARNING, "need try agin"); return 0.0; } long global_cpu_before = global_statistics_prev_.cpu_user_time + global_statistics_prev_.cpu_nice_time + global_statistics_prev_.cpu_system_time + global_statistics_prev_.cpu_idle_time + global_statistics_prev_.cpu_iowait_time + global_statistics_prev_.cpu_irq_time + global_statistics_prev_.cpu_softirq_time + global_statistics_prev_.cpu_stealstolen + global_statistics_prev_.cpu_guest; long global_cpu_after = global_statistics_cur_.cpu_user_time + global_statistics_cur_.cpu_nice_time + global_statistics_cur_.cpu_system_time + global_statistics_cur_.cpu_idle_time + global_statistics_cur_.cpu_iowait_time + global_statistics_cur_.cpu_irq_time + global_statistics_cur_.cpu_softirq_time + global_statistics_cur_.cpu_stealstolen + global_statistics_cur_.cpu_guest; long cgroup_cpu_before = cgroup_statistics_prev_.cpu_user_time + cgroup_statistics_prev_.cpu_system_time; long cgroup_cpu_after = cgroup_statistics_cur_.cpu_user_time + cgroup_statistics_cur_.cpu_system_time; double radio = cgroup_statistics_cur_.cpu_cores_limit / global_statistics_cur_.cpu_cores; LOG(DEBUG, "radio = limit(%f) / cores(%ld)", cgroup_statistics_cur_.cpu_cores_limit, global_statistics_cur_.cpu_cores); double rs = (cgroup_cpu_after - cgroup_cpu_before) / (double)(global_cpu_after - global_cpu_before) ; rs /= radio; LOG(DEBUG, "p prev :%ld p post:%ld g pre:%ld g post:%ld radir:%f rs:%f", cgroup_cpu_before, cgroup_cpu_after, global_cpu_before, global_cpu_after, radio, rs); return rs; } bool CGroupResourceCollectorImpl::CollectStatistics() { common::MutexLock lock(&mutex_); global_statistics_prev_ = global_statistics_cur_; cgroup_statistics_prev_ = cgroup_statistics_cur_; timestamp_prev_ = timestamp_cur_; timestamp_cur_ = time(NULL); if (!GetCgroupCpuUsage(cgroup_name_, &cgroup_statistics_cur_)) { return false; } if (!GetGlobalCpuUsage(&global_statistics_cur_)) { return false; } if (!GetCgroupCpuCoresLimit(cgroup_name_, &cgroup_statistics_cur_)) { return false; } collector_times_ ++; return true; } // ----------- CGroupResourceCollector implement ----- CGroupResourceCollector::CGroupResourceCollector( const std::string& cgroup_name) : impl_(NULL) { impl_ = new CGroupResourceCollectorImpl(cgroup_name); } bool CGroupResourceCollector::CollectStatistics() { return impl_->CollectStatistics(); } double CGroupResourceCollector::GetCpuUsage() { return impl_->GetCpuUsage(); } long CGroupResourceCollector::GetMemoryUsage() { return impl_->GetMemoryUsage(); } CGroupResourceCollector::~CGroupResourceCollector() { delete impl_; } // ----------- resource collector utils ------------- bool GetCgroupCpuUsage( const std::string& group_path, CgroupResourceStatistics* statistics) { if (statistics == NULL) { return false; } std::string path = CGROUP_MOUNT_PATH + "/" + CPUACT_SUBSYSTEM_PATH + "/" + group_path + "/cpuacct.stat"; FILE* fin = fopen(path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; // read user time if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } char cpu_tmp_char[20]; int item_size = sscanf(line, "%s %ld", cpu_tmp_char, &(statistics->cpu_user_time)); SAFE_FREE(line); if (item_size != 2) { LOG(WARNING, "read from %s format err", path.c_str()); fclose(fin); return false; } // read sys time if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } item_size = sscanf(line, "%s %ld", cpu_tmp_char, &(statistics->cpu_system_time)); SAFE_FREE(line); if (item_size != 2) { LOG(WARNING, "read from %s format err", path.c_str()); fclose(fin); return false; } fclose(fin); return true; } bool GetGlobalCpuUsage(ResourceStatistics* statistics) { if (statistics == NULL) { return false; } statistics->cpu_cores = CPU_CORES; std::string path = "/proc/stat"; FILE* fin = fopen(path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); char cpu[5]; int item_size = sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld", cpu, &(statistics->cpu_user_time), &(statistics->cpu_nice_time), &(statistics->cpu_system_time), &(statistics->cpu_idle_time), &(statistics->cpu_iowait_time), &(statistics->cpu_irq_time), &(statistics->cpu_softirq_time), &(statistics->cpu_stealstolen), &(statistics->cpu_guest)); SAFE_FREE(line); if (item_size != 10) { LOG(WARNING, "read from /proc/stat format err"); return false; } return true; } bool GetCgroupCpuCoresLimit( const std::string& group_path, CgroupResourceStatistics* statistics) { std::string period_path = CGROUP_MOUNT_PATH + "/cpu/" + group_path + "/cpu.cfs_period_us"; std::string quota_path = CGROUP_MOUNT_PATH + "/cpu/" + group_path + "/cpu.cfs_quota_us"; FILE* fin = fopen(period_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", period_path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); long period_time = 0; int item_size = sscanf(line, "%ld", &period_time); SAFE_FREE(line); if (item_size != 1) { LOG(WARNING, "read from %s format err", period_path.c_str()); return false; } fin = fopen(quota_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", quota_path.c_str()); return false; } line = NULL; len = 0; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); long quota_value = 0; item_size = sscanf(line, "%ld", &quota_value); SAFE_FREE(line); if (item_size != 1) { LOG(WARNING, "read from %s format err", quota_path.c_str()); return false; } LOG(DEBUG, "cpu cores limit : quota(%ld), period(%ld)", quota_value, period_time); statistics->cpu_cores_limit = quota_value * 1.0 / period_time; return true; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <commit_msg>add memory collect<commit_after>// Copyright (c) 2015, Galaxy Authors. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: [email protected] #include "agent/resource_collector.h" #include <errno.h> #include <string.h> #include <time.h> #include <string> #include <boost/lexical_cast.hpp> #include "common/logging.h" namespace galaxy { #define SAFE_FREE(x) \ do { \ if (x != NULL) {\ free(x); \ x = NULL; \ } \ } while(0) const std::string CGROUP_MOUNT_PATH = "/cgroups/"; const std::string CPUACT_SUBSYSTEM_PATH = "cpuacct"; static long SYS_TIMER_HZ = sysconf(_SC_CLK_TCK); static long CPU_CORES = sysconf(_SC_NPROCESSORS_CONF); // unit jiffies struct ResourceStatistics { // cpu long cpu_user_time; long cpu_nice_time; long cpu_system_time; long cpu_idle_time; long cpu_iowait_time; long cpu_irq_time; long cpu_softirq_time; long cpu_stealstolen; long cpu_guest; long cpu_cores; }; // unit jiffies struct CgroupResourceStatistics { long cpu_user_time; long cpu_system_time; // cpu_cores from cfs_quota_usota_us double cpu_cores_limit; long memory_rss_in_bytes; }; // get cpu usage from /cgroups/cpuacct/xxxxx/cpuacct.stat static bool GetCgroupCpuUsage( const std::string& group_path, CgroupResourceStatistics* statistics); // get memory usage from /cgroups/memory/xxxxx/memory.stat static bool GetCgroupMemoryUsage( const std::string& group_path, CgroupResourceStatistics* statistics); // get total cpu usage from /proc/stat static bool GetGlobalCpuUsage(ResourceStatistics* statistics); // get cpu limit cores from /cgroups/cpu/xxxxx/cpu.cfs_quota_usota_us and cpu.cfs_ static bool GetCgroupCpuCoresLimit( const std::string& group_path, CgroupResourceStatistics* statistics); class CGroupResourceCollectorImpl { public: CGroupResourceCollectorImpl() {} explicit CGroupResourceCollectorImpl(const std::string& cgroup_name) : cgroup_name_(cgroup_name), global_statistics_prev_(), global_statistics_cur_(), cgroup_statistics_prev_(), cgroup_statistics_cur_(), timestamp_prev_(0.0), timestamp_cur_(0.0), mutex_() { } virtual ~CGroupResourceCollectorImpl() {} virtual bool CollectStatistics(); double GetCpuUsage(); long GetMemoryUsage() { return cgroup_statistics_cur_.memory_rss_in_bytes; } private: std::string cgroup_name_; // global resource statistics ResourceStatistics global_statistics_prev_; ResourceStatistics global_statistics_cur_; // cgroup resource statistics CgroupResourceStatistics cgroup_statistics_prev_; CgroupResourceStatistics cgroup_statistics_cur_; double timestamp_prev_; double timestamp_cur_; long collector_times_; common::Mutex mutex_; }; double CGroupResourceCollectorImpl::GetCpuUsage() { const int MIN_COLLOECT_TIMES_NEED = 2; common::MutexLock lock(&mutex_); if (collector_times_ < MIN_COLLOECT_TIMES_NEED) { LOG(WARNING, "need try agin"); return 0.0; } long global_cpu_before = global_statistics_prev_.cpu_user_time + global_statistics_prev_.cpu_nice_time + global_statistics_prev_.cpu_system_time + global_statistics_prev_.cpu_idle_time + global_statistics_prev_.cpu_iowait_time + global_statistics_prev_.cpu_irq_time + global_statistics_prev_.cpu_softirq_time + global_statistics_prev_.cpu_stealstolen + global_statistics_prev_.cpu_guest; long global_cpu_after = global_statistics_cur_.cpu_user_time + global_statistics_cur_.cpu_nice_time + global_statistics_cur_.cpu_system_time + global_statistics_cur_.cpu_idle_time + global_statistics_cur_.cpu_iowait_time + global_statistics_cur_.cpu_irq_time + global_statistics_cur_.cpu_softirq_time + global_statistics_cur_.cpu_stealstolen + global_statistics_cur_.cpu_guest; long cgroup_cpu_before = cgroup_statistics_prev_.cpu_user_time + cgroup_statistics_prev_.cpu_system_time; long cgroup_cpu_after = cgroup_statistics_cur_.cpu_user_time + cgroup_statistics_cur_.cpu_system_time; double radio = cgroup_statistics_cur_.cpu_cores_limit / global_statistics_cur_.cpu_cores; LOG(DEBUG, "radio = limit(%f) / cores(%ld)", cgroup_statistics_cur_.cpu_cores_limit, global_statistics_cur_.cpu_cores); double rs = (cgroup_cpu_after - cgroup_cpu_before) / (double)(global_cpu_after - global_cpu_before) ; rs /= radio; LOG(DEBUG, "p prev :%ld p post:%ld g pre:%ld g post:%ld radir:%f rs:%f", cgroup_cpu_before, cgroup_cpu_after, global_cpu_before, global_cpu_after, radio, rs); return rs; } bool CGroupResourceCollectorImpl::CollectStatistics() { common::MutexLock lock(&mutex_); global_statistics_prev_ = global_statistics_cur_; cgroup_statistics_prev_ = cgroup_statistics_cur_; timestamp_prev_ = timestamp_cur_; timestamp_cur_ = time(NULL); if (!GetCgroupCpuUsage(cgroup_name_, &cgroup_statistics_cur_)) { return false; } if (!GetGlobalCpuUsage(&global_statistics_cur_)) { return false; } if (!GetCgroupCpuCoresLimit(cgroup_name_, &cgroup_statistics_cur_)) { return false; } if (!GetCgroupMemoryUsage(cgroup_name_, &cgroup_statistics_cur_)) { return false; } collector_times_ ++; return true; } // ----------- CGroupResourceCollector implement ----- CGroupResourceCollector::CGroupResourceCollector( const std::string& cgroup_name) : impl_(NULL) { impl_ = new CGroupResourceCollectorImpl(cgroup_name); } bool CGroupResourceCollector::CollectStatistics() { return impl_->CollectStatistics(); } double CGroupResourceCollector::GetCpuUsage() { return impl_->GetCpuUsage(); } long CGroupResourceCollector::GetMemoryUsage() { return impl_->GetMemoryUsage(); } CGroupResourceCollector::~CGroupResourceCollector() { delete impl_; } // ----------- resource collector utils ------------- bool GetCgroupCpuUsage( const std::string& group_path, CgroupResourceStatistics* statistics) { if (statistics == NULL) { return false; } std::string path = CGROUP_MOUNT_PATH + "/" + CPUACT_SUBSYSTEM_PATH + "/" + group_path + "/cpuacct.stat"; FILE* fin = fopen(path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; // read user time if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } char cpu_tmp_char[20]; int item_size = sscanf(line, "%s %ld", cpu_tmp_char, &(statistics->cpu_user_time)); SAFE_FREE(line); if (item_size != 2) { LOG(WARNING, "read from %s format err", path.c_str()); fclose(fin); return false; } // read sys time if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } item_size = sscanf(line, "%s %ld", cpu_tmp_char, &(statistics->cpu_system_time)); SAFE_FREE(line); if (item_size != 2) { LOG(WARNING, "read from %s format err", path.c_str()); fclose(fin); return false; } fclose(fin); return true; } bool GetGlobalCpuUsage(ResourceStatistics* statistics) { if (statistics == NULL) { return false; } statistics->cpu_cores = CPU_CORES; std::string path = "/proc/stat"; FILE* fin = fopen(path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); char cpu[5]; int item_size = sscanf(line, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld", cpu, &(statistics->cpu_user_time), &(statistics->cpu_nice_time), &(statistics->cpu_system_time), &(statistics->cpu_idle_time), &(statistics->cpu_iowait_time), &(statistics->cpu_irq_time), &(statistics->cpu_softirq_time), &(statistics->cpu_stealstolen), &(statistics->cpu_guest)); SAFE_FREE(line); if (item_size != 10) { LOG(WARNING, "read from /proc/stat format err"); return false; } return true; } bool GetCgroupCpuCoresLimit( const std::string& group_path, CgroupResourceStatistics* statistics) { std::string period_path = CGROUP_MOUNT_PATH + "/cpu/" + group_path + "/cpu.cfs_period_us"; std::string quota_path = CGROUP_MOUNT_PATH + "/cpu/" + group_path + "/cpu.cfs_quota_us"; FILE* fin = fopen(period_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", period_path.c_str()); return false; } ssize_t read; size_t len = 0; char* line = NULL; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); long period_time = 0; int item_size = sscanf(line, "%ld", &period_time); SAFE_FREE(line); if (item_size != 1) { LOG(WARNING, "read from %s format err", period_path.c_str()); return false; } fin = fopen(quota_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", quota_path.c_str()); return false; } line = NULL; len = 0; if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); fclose(fin); return false; } fclose(fin); long quota_value = 0; item_size = sscanf(line, "%ld", &quota_value); SAFE_FREE(line); if (item_size != 1) { LOG(WARNING, "read from %s format err", quota_path.c_str()); return false; } LOG(DEBUG, "cpu cores limit : quota(%ld), period(%ld)", quota_value, period_time); statistics->cpu_cores_limit = quota_value * 1.0 / period_time; return true; } bool GetCgroupMemoryUsage(const std::string& group_path, CgroupResourceStatistics* statistics) { std::string memory_path = CGROUP_MOUNT_PATH + "/memory/" + group_path + "/memory.stat"; FILE* fin = fopen(memory_path.c_str(), "r"); if (fin == NULL) { LOG(WARNING, "open %s failed", memory_path.c_str()); return false; } ssize_t read; char* line = NULL; size_t len = 0; // escape first line for cache usage if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); return false; } fclose(fin); SAFE_FREE(line); if ((read = getline(&line, &len, fin)) == -1) { LOG(WARNING, "read line failed err[%d: %s]", errno, strerror(errno)); return false; } int item_size = sscanf(line, "%ld", &(statistics->memory_rss_in_bytes)); SAFE_FREE(line); if (item_size != 1) { LOG(WARNING, "read from %s format err", memory_path.c_str()); return false; } return true; } } // ending namespace galaxy /* vim: set ts=4 sw=4 sts=4 tw=100 */ <|endoftext|>
<commit_before>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "system_wrappers/include/cpu_info.h" #if defined(WEBRTC_WIN) #include <windows.h> #elif defined(WEBRTC_LINUX) #include <unistd.h> #endif #if defined(WEBRTC_MAC) #include <sys/sysctl.h> #endif #include "rtc_base/logging.h" namespace internal { static int DetectNumberOfCores() { // We fall back on assuming a single core in case of errors. int number_of_cores = 1; #if defined(WEBRTC_WIN) SYSTEM_INFO si; GetNativeSystemInfo(&si); number_of_cores = static_cast<int>(si.dwNumberOfProcessors); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) number_of_cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN)); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) int name[] = {CTL_HW, HW_AVAILCPU}; size_t size = sizeof(number_of_cores); if (0 != sysctl(name, 2, &number_of_cores, &size, NULL, 0)) { RTC_LOG(LS_ERROR) << "Failed to get number of cores"; number_of_cores = 1; } #else RTC_LOG(LS_ERROR) << "No function to get number of cores"; #endif RTC_LOG(LS_INFO) << "Available number of cores: " << number_of_cores; return number_of_cores; } } // namespace internal namespace webrtc { uint32_t CpuInfo::DetectNumberOfCores() { // Statically cache the number of system cores available since if the process // is running in a sandbox, we may only be able to read the value once (before // the sandbox is initialized) and not thereafter. // For more information see crbug.com/176522. static uint32_t logical_cpus = 0; if (!logical_cpus) logical_cpus = static_cast<uint32_t>(internal::DetectNumberOfCores()); return logical_cpus; } } // namespace webrtc <commit_msg>[Fuchsia] Implement detection of available cores.<commit_after>/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "system_wrappers/include/cpu_info.h" #if defined(WEBRTC_WIN) #include <windows.h> #elif defined(WEBRTC_LINUX) #include <unistd.h> #elif defined(WEBRTC_MAC) #include <sys/sysctl.h> #elif defined(WEBRTC_FUCHSIA) #include <zircon/syscalls.h> #endif #include "rtc_base/logging.h" namespace internal { static int DetectNumberOfCores() { // We fall back on assuming a single core in case of errors. int number_of_cores = 1; #if defined(WEBRTC_WIN) SYSTEM_INFO si; GetNativeSystemInfo(&si); number_of_cores = static_cast<int>(si.dwNumberOfProcessors); #elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID) number_of_cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN)); #elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS) int name[] = {CTL_HW, HW_AVAILCPU}; size_t size = sizeof(number_of_cores); if (0 != sysctl(name, 2, &number_of_cores, &size, NULL, 0)) { RTC_LOG(LS_ERROR) << "Failed to get number of cores"; number_of_cores = 1; } #elif defined(WEBRTC_FUCHSIA) number_of_cores = zx_system_get_num_cpus(); #else RTC_LOG(LS_ERROR) << "No function to get number of cores"; #endif RTC_LOG(LS_INFO) << "Available number of cores: " << number_of_cores; return number_of_cores; } } // namespace internal namespace webrtc { uint32_t CpuInfo::DetectNumberOfCores() { // Statically cache the number of system cores available since if the process // is running in a sandbox, we may only be able to read the value once (before // the sandbox is initialized) and not thereafter. // For more information see crbug.com/176522. static uint32_t logical_cpus = 0; if (!logical_cpus) logical_cpus = static_cast<uint32_t>(internal::DetectNumberOfCores()); return logical_cpus; } } // namespace webrtc <|endoftext|>
<commit_before>// Copyright 2014-2017 Open Source Robotics Foundation, 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 <set> #include <map> #include <string> #include "rcutils/allocator.h" #include "rcutils/logging_macros.h" #include "rcutils/strdup.h" #include "rmw/error_handling.h" #include "rmw/names_and_types.h" #include "rmw/get_service_names_and_types.h" #include "rmw/types.h" #include "rmw/convert_rcutils_ret_to_rmw_ret.h" #include "rmw/impl/cpp/macros.hpp" #include "identifier.hpp" #include "types.hpp" #include "demangle.hpp" #define SAMPLE_PREFIX "/Sample_" // The extern "C" here enforces that overloading is not used. extern "C" { rmw_ret_t rmw_get_service_names_and_types( const rmw_node_t * node, rcutils_allocator_t * allocator, rmw_names_and_types_t * service_names_and_types) { if (!allocator) { RMW_SET_ERROR_MSG("allocator is null") return RMW_RET_INVALID_ARGUMENT; } if (!node) { RMW_SET_ERROR_MSG_ALLOC("null node handle", *allocator) return RMW_RET_INVALID_ARGUMENT; } RMW_CHECK_TYPE_IDENTIFIERS_MATCH( node handle, node->implementation_identifier, opensplice_cpp_identifier, return RMW_RET_ERROR) rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types); if (ret != RMW_RET_OK) { return ret; } auto node_info = static_cast<OpenSpliceStaticNodeInfo *>(node->data); if (!node_info) { RMW_SET_ERROR_MSG("node info handle is null"); } if (!node_info->publisher_listener) { RMW_SET_ERROR_MSG("publisher listener handle is null"); return RMW_RET_ERROR; } if (!node_info->publisher_listener) { RMW_SET_ERROR_MSG("publisher listener handle is null"); return RMW_RET_ERROR; } if (!node_info->subscriber_listener) { RMW_SET_ERROR_MSG("subscriber listener handle is null"); return RMW_RET_ERROR; } // combine publisher and subscriber information std::map<std::string, std::set<std::string>> services; node_info->publisher_listener->fill_service_names_and_types(services); node_info->subscriber_listener->fill_service_names_and_types(services); // Fill out service_names_and_types if (services.size()) { // Setup string array to store names rmw_ret_t rmw_ret = rmw_names_and_types_init(service_names_and_types, services.size(), allocator); if (rmw_ret != RMW_RET_OK) { return rmw_ret; } // Setup cleanup function, in case of failure below auto fail_cleanup = [&service_names_and_types]() { rmw_ret_t rmw_ret = rmw_names_and_types_fini(service_names_and_types); if (rmw_ret != RMW_RET_OK) { RCUTILS_LOG_ERROR("error during report of error: %s", rmw_get_error_string_safe()) } }; // For each service, store the name, initialize the string array for types, and store all types size_t index = 0; for (const auto & service_n_types : services) { // Duplicate and store the service_name char * service_name = rcutils_strdup(service_n_types.first.c_str(), *allocator); if (!service_name) { RMW_SET_ERROR_MSG_ALLOC("failed to allocate memory for service name", *allocator); fail_cleanup(); return RMW_RET_BAD_ALLOC; } service_names_and_types->names.data[index] = service_name; // Setup storage for types { rcutils_ret_t rcutils_ret = rcutils_string_array_init( &service_names_and_types->types[index], service_n_types.second.size(), allocator); if (rcutils_ret != RCUTILS_RET_OK) { RMW_SET_ERROR_MSG(rcutils_get_error_string_safe()) fail_cleanup(); return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret); } } // Duplicate and store each type for the service size_t type_index = 0; for (const auto & type : service_n_types.second) { size_t n = type.find(SAMPLE_PREFIX); if (std::string::npos == n) { char * error_msg = rcutils_format_string( *allocator, "failed to convert DDS type name to ROS service type name: '" SAMPLE_PREFIX "' not found in type: '%s'", type.c_str()); RMW_SET_ERROR_MSG(error_msg) allocator->deallocate(error_msg, allocator->state); fail_cleanup(); return RMW_RET_ERROR; } std::string stripped_type = type.substr(0, n + 1) + type.substr(n + strlen(SAMPLE_PREFIX)); char * type_name = rcutils_strdup(stripped_type.c_str(), *allocator); if (!type_name) { RMW_SET_ERROR_MSG_ALLOC("failed to allocate memory for type name", *allocator) fail_cleanup(); return RMW_RET_BAD_ALLOC; } service_names_and_types->types[index].data[type_index] = type_name; ++type_index; } // for each type ++index; } // for each service } return RMW_RET_OK; } } // extern "C" <commit_msg>Don't error if Sample_ prefix not found in service type (#240)<commit_after>// Copyright 2014-2017 Open Source Robotics Foundation, 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 <set> #include <map> #include <string> #include "rcutils/allocator.h" #include "rcutils/logging_macros.h" #include "rcutils/strdup.h" #include "rmw/error_handling.h" #include "rmw/names_and_types.h" #include "rmw/get_service_names_and_types.h" #include "rmw/types.h" #include "rmw/convert_rcutils_ret_to_rmw_ret.h" #include "rmw/impl/cpp/macros.hpp" #include "identifier.hpp" #include "types.hpp" #include "demangle.hpp" #define SAMPLE_PREFIX "/Sample_" // The extern "C" here enforces that overloading is not used. extern "C" { rmw_ret_t rmw_get_service_names_and_types( const rmw_node_t * node, rcutils_allocator_t * allocator, rmw_names_and_types_t * service_names_and_types) { if (!allocator) { RMW_SET_ERROR_MSG("allocator is null") return RMW_RET_INVALID_ARGUMENT; } if (!node) { RMW_SET_ERROR_MSG_ALLOC("null node handle", *allocator) return RMW_RET_INVALID_ARGUMENT; } RMW_CHECK_TYPE_IDENTIFIERS_MATCH( node handle, node->implementation_identifier, opensplice_cpp_identifier, return RMW_RET_ERROR) rmw_ret_t ret = rmw_names_and_types_check_zero(service_names_and_types); if (ret != RMW_RET_OK) { return ret; } auto node_info = static_cast<OpenSpliceStaticNodeInfo *>(node->data); if (!node_info) { RMW_SET_ERROR_MSG("node info handle is null"); } if (!node_info->publisher_listener) { RMW_SET_ERROR_MSG("publisher listener handle is null"); return RMW_RET_ERROR; } if (!node_info->publisher_listener) { RMW_SET_ERROR_MSG("publisher listener handle is null"); return RMW_RET_ERROR; } if (!node_info->subscriber_listener) { RMW_SET_ERROR_MSG("subscriber listener handle is null"); return RMW_RET_ERROR; } // combine publisher and subscriber information std::map<std::string, std::set<std::string>> services; node_info->publisher_listener->fill_service_names_and_types(services); node_info->subscriber_listener->fill_service_names_and_types(services); // Fill out service_names_and_types if (services.size()) { // Setup string array to store names rmw_ret_t rmw_ret = rmw_names_and_types_init(service_names_and_types, services.size(), allocator); if (rmw_ret != RMW_RET_OK) { return rmw_ret; } // Setup cleanup function, in case of failure below auto fail_cleanup = [&service_names_and_types]() { rmw_ret_t rmw_ret = rmw_names_and_types_fini(service_names_and_types); if (rmw_ret != RMW_RET_OK) { RCUTILS_LOG_ERROR("error during report of error: %s", rmw_get_error_string_safe()) } }; // For each service, store the name, initialize the string array for types, and store all types size_t index = 0; for (const auto & service_n_types : services) { // Duplicate and store the service_name char * service_name = rcutils_strdup(service_n_types.first.c_str(), *allocator); if (!service_name) { RMW_SET_ERROR_MSG_ALLOC("failed to allocate memory for service name", *allocator); fail_cleanup(); return RMW_RET_BAD_ALLOC; } service_names_and_types->names.data[index] = service_name; // Setup storage for types { rcutils_ret_t rcutils_ret = rcutils_string_array_init( &service_names_and_types->types[index], service_n_types.second.size(), allocator); if (rcutils_ret != RCUTILS_RET_OK) { RMW_SET_ERROR_MSG(rcutils_get_error_string_safe()) fail_cleanup(); return rmw_convert_rcutils_ret_to_rmw_ret(rcutils_ret); } } // Duplicate and store each type for the service size_t type_index = 0; for (const auto & type : service_n_types.second) { // Strip the SAMPLE_PREFIX if it is found (e.g. from services using OpenSplice typesupport). // It may not be found if services are detected using other typesupports. size_t n = type.find(SAMPLE_PREFIX); std::string stripped_type = type; if (std::string::npos != n) { stripped_type = type.substr(0, n + 1) + type.substr(n + strlen(SAMPLE_PREFIX)); } char * type_name = rcutils_strdup(stripped_type.c_str(), *allocator); if (!type_name) { RMW_SET_ERROR_MSG_ALLOC("failed to allocate memory for type name", *allocator) fail_cleanup(); return RMW_RET_BAD_ALLOC; } service_names_and_types->types[index].data[type_index] = type_name; ++type_index; } // for each type ++index; } // for each service } return RMW_RET_OK; } } // extern "C" <|endoftext|>
<commit_before>// // Created by ZhangMing on 02-26-17 // #include "mainwindow.h" #include "ui_mainwindow.h" #include "function.h" #include <QDebug> #include <QUrl> #include <QDesktopServices> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_ServiceHub_triggered() { const QUrl url("http://hub.hust.edu.cn/index.jsp"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_ServiceHubEmail_triggered() { const QUrl url("https://mail.hust.edu.cn/"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_ServiceGithub_triggered() { const QUrl url("https://github.com/"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_FunCourseTree_triggered() { CourseTree *p; QString queryname; if(BuildCourseTree() == false) { QMessageBox::information(this,"error","No File"); return; } else { // Dialog if((p = QueryCourse(queryname)) == nullptr) { QMessageBox::information(this, "error", "No Such Course"); return; } // Web Page DataVisualization(p); } } <commit_msg>add dialog with users on searching course, by zm, on 03-01-17<commit_after>// // Created by ZhangMing on 02-26-17 // #include "mainwindow.h" #include "ui_mainwindow.h" #include "function.h" #include <QDebug> #include <QUrl> #include <QDesktopServices> #include <QMessageBox> #include <QInputDialog> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_ServiceHub_triggered() { const QUrl url("http://hub.hust.edu.cn/index.jsp"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_ServiceHubEmail_triggered() { const QUrl url("https://mail.hust.edu.cn/"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_ServiceGithub_triggered() { const QUrl url("https://github.com/"); qDebug() << url.scheme(); qDebug() << url.port(); QDesktopServices::openUrl(url); } void MainWindow::on_FunCourseTree_triggered() { CourseTree *p; if(BuildCourseTree() == false) { QMessageBox::information(this,"error","No File"); return; } else { bool ok; QString name = QInputDialog::getText(NULL,QObject::tr("查询"),QObject::tr("请输入正确课程名"),QLineEdit::Normal,QString(),&ok); if(!ok)// click cancle return; // click ok if(name.isEmpty()) { QMessageBox::information(this,"error","输入为空"); return; } else if((p = QueryCourse(name)) == nullptr) { QMessageBox::information(this,"error","查无此课程"); } else { //Web Page,use p } } } <|endoftext|>
<commit_before>#include "apisurface.h" #include "thumbnail.h" #include <sstream> #include <QDebug> #include <QSysInfo> #include "image/image.hpp" ApiSurface::ApiSurface() { } QSize ApiSurface::size() const { return m_size; } void ApiSurface::setSize(const QSize &size) { m_size = size; } struct ByteArrayBuf : public std::streambuf { ByteArrayBuf(QByteArray & a) { setg(a.data(), a.data(), a.data() + a.size()); } }; void ApiSurface::contentsFromBase64(const QByteArray &base64) { m_base64Data = base64; /* * We need to do the conversion to create the thumbnail */ image::Image *image = imageFromBase64(base64); Q_ASSERT(image); QImage img = qimageFromRawImage(image); m_thumb = thumbnail(img); delete image; } QByteArray ApiSurface::base64Data() const { return m_base64Data; } QImage ApiSurface::thumb() const { return m_thumb; } int ApiSurface::depth() const { return m_depth; } void ApiSurface::setDepth(int depth) { m_depth = depth; } QString ApiSurface::formatName() const { return m_formatName; } void ApiSurface::setFormatName(const QString &str) { m_formatName = str; } ApiTexture::ApiTexture() : ApiSurface() { } QString ApiTexture::label() const { return m_label; } void ApiTexture::setLabel(const QString &str) { m_label = str; } ApiFramebuffer::ApiFramebuffer() : ApiSurface() { } QString ApiFramebuffer::type() const { return m_type; } void ApiFramebuffer::setType(const QString &str) { m_type = str; } image::Image * ApiSurface::imageFromBase64(const QByteArray &base64) { QByteArray dataArray = QByteArray::fromBase64(base64); image::Image *image; /* * Detect the PNG vs PFM images. */ const char pngSignature[] = {(char)0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0}; if (dataArray.startsWith(pngSignature)) { ByteArrayBuf buf(dataArray); std::istream istr(&buf); image = image::readPNG(istr); } else { image = image::readPNM(dataArray.data(), dataArray.size()); } return image; } QImage ApiSurface::qimageFromRawImage(const image::Image *image) { QImage img; int width = image->width; int height = image->height; img = QImage(width, height, QImage::Format_ARGB32); const unsigned char *srcRow = image->start(); for (int y = 0; y < height; ++y) { QRgb *dst = (QRgb *)img.scanLine(y); if (image->channelType == image::TYPE_UNORM8) { const unsigned char *src = srcRow; for (int x = 0; x < width; ++x) { unsigned char rgba[4]; for (int c = 0; c < image->channels; ++c) { rgba[c] = *src++; } if (image->channels == 1) { // Use gray-scale instead of red rgba[1] = rgba[0]; rgba[2] = rgba[0]; } dst[x] = qRgba(rgba[0], rgba[1], rgba[2], rgba[3]); } } else { const float *src = (const float *)srcRow; for (int x = 0; x < width; ++x) { unsigned char rgba[4] = {0, 0, 0, 0xff}; for (int c = 0; c < image->channels; ++c) { float f = *src++; unsigned char u; if (f >= 1.0f) { u = 255; } else if (f <= 0.0f) { u = 0; } else { u = f * 255 + 0.5; } rgba[c] = u; } if (image->channels == 1) { // Use gray-scale instead of red rgba[1] = rgba[0]; rgba[2] = rgba[0]; } dst[x] = qRgba(rgba[0], rgba[1], rgba[2], rgba[3]); } } srcRow += image->stride(); } return img; } <commit_msg>gui: make sure that the alpha channel is initialized<commit_after>#include "apisurface.h" #include "thumbnail.h" #include <sstream> #include <QDebug> #include <QSysInfo> #include "image/image.hpp" ApiSurface::ApiSurface() { } QSize ApiSurface::size() const { return m_size; } void ApiSurface::setSize(const QSize &size) { m_size = size; } struct ByteArrayBuf : public std::streambuf { ByteArrayBuf(QByteArray & a) { setg(a.data(), a.data(), a.data() + a.size()); } }; void ApiSurface::contentsFromBase64(const QByteArray &base64) { m_base64Data = base64; /* * We need to do the conversion to create the thumbnail */ image::Image *image = imageFromBase64(base64); Q_ASSERT(image); QImage img = qimageFromRawImage(image); m_thumb = thumbnail(img); delete image; } QByteArray ApiSurface::base64Data() const { return m_base64Data; } QImage ApiSurface::thumb() const { return m_thumb; } int ApiSurface::depth() const { return m_depth; } void ApiSurface::setDepth(int depth) { m_depth = depth; } QString ApiSurface::formatName() const { return m_formatName; } void ApiSurface::setFormatName(const QString &str) { m_formatName = str; } ApiTexture::ApiTexture() : ApiSurface() { } QString ApiTexture::label() const { return m_label; } void ApiTexture::setLabel(const QString &str) { m_label = str; } ApiFramebuffer::ApiFramebuffer() : ApiSurface() { } QString ApiFramebuffer::type() const { return m_type; } void ApiFramebuffer::setType(const QString &str) { m_type = str; } image::Image * ApiSurface::imageFromBase64(const QByteArray &base64) { QByteArray dataArray = QByteArray::fromBase64(base64); image::Image *image; /* * Detect the PNG vs PFM images. */ const char pngSignature[] = {(char)0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0}; if (dataArray.startsWith(pngSignature)) { ByteArrayBuf buf(dataArray); std::istream istr(&buf); image = image::readPNG(istr); } else { image = image::readPNM(dataArray.data(), dataArray.size()); } return image; } QImage ApiSurface::qimageFromRawImage(const image::Image *image) { QImage img; int width = image->width; int height = image->height; img = QImage(width, height, QImage::Format_ARGB32); const unsigned char *srcRow = image->start(); for (int y = 0; y < height; ++y) { QRgb *dst = (QRgb *)img.scanLine(y); if (image->channelType == image::TYPE_UNORM8) { const unsigned char *src = srcRow; for (int x = 0; x < width; ++x) { unsigned char rgba[4] = {0, 0, 0, 0xff}; for (int c = 0; c < image->channels; ++c) { rgba[c] = *src++; } if (image->channels == 1) { // Use gray-scale instead of red rgba[1] = rgba[0]; rgba[2] = rgba[0]; } dst[x] = qRgba(rgba[0], rgba[1], rgba[2], rgba[3]); } } else { const float *src = (const float *)srcRow; for (int x = 0; x < width; ++x) { unsigned char rgba[4] = {0, 0, 0, 0xff}; for (int c = 0; c < image->channels; ++c) { float f = *src++; unsigned char u; if (f >= 1.0f) { u = 255; } else if (f <= 0.0f) { u = 0; } else { u = f * 255 + 0.5; } rgba[c] = u; } if (image->channels == 1) { // Use gray-scale instead of red rgba[1] = rgba[0]; rgba[2] = rgba[0]; } dst[x] = qRgba(rgba[0], rgba[1], rgba[2], rgba[3]); } } srcRow += image->stride(); } return img; } <|endoftext|>
<commit_before>//===- ObjectTransformLayerTest.cpp - Unit tests for ObjectTransformLayer -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/NullResolver.h" #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" #include "llvm/Object/ObjectFile.h" #include "gtest/gtest.h" using namespace llvm::orc; namespace { // Stand-in for RuntimeDyld::MemoryManager typedef int MockMemoryManager; // Stand-in for RuntimeDyld::SymbolResolver typedef int MockSymbolResolver; // stand-in for object::ObjectFile typedef int MockObjectFile; // stand-in for llvm::MemoryBuffer set typedef int MockMemoryBufferSet; // Mock transform that operates on unique pointers to object files, and // allocates new object files rather than mutating the given ones. struct AllocatingTransform { std::unique_ptr<MockObjectFile> operator()(std::unique_ptr<MockObjectFile> Obj) const { return llvm::make_unique<MockObjectFile>(*Obj + 1); } }; // Mock base layer for verifying behavior of transform layer. // Each method "T foo(args)" is accompanied by two auxiliary methods: // - "void expectFoo(args)", to be called before calling foo on the transform // layer; saves values of args, which mock layer foo then verifies against. // - "void verifyFoo(T)", to be called after foo, which verifies that the // transform layer called the base layer and forwarded any return value. class MockBaseLayer { public: typedef int ObjSetHandleT; MockBaseLayer() : MockSymbol(nullptr) { resetExpectations(); } template <typename ObjSetT, typename MemoryManagerPtrT, typename SymbolResolverPtrT> ObjSetHandleT addObjectSet(ObjSetT Objects, MemoryManagerPtrT MemMgr, SymbolResolverPtrT Resolver) { EXPECT_EQ(MockManager, *MemMgr) << "MM should pass through"; EXPECT_EQ(MockResolver, *Resolver) << "Resolver should pass through"; size_t I = 0; for (auto &ObjPtr : Objects) { EXPECT_EQ(MockObjects[I++] + 1, *ObjPtr) << "Transform should be applied"; } EXPECT_EQ(MockObjects.size(), I) << "Number of objects should match"; LastCalled = "addObjectSet"; MockObjSetHandle = 111; return MockObjSetHandle; } template <typename ObjSetT> void expectAddObjectSet(ObjSetT &Objects, MockMemoryManager *MemMgr, MockSymbolResolver *Resolver) { MockManager = *MemMgr; MockResolver = *Resolver; for (auto &ObjPtr : Objects) { MockObjects.push_back(*ObjPtr); } } void verifyAddObjectSet(ObjSetHandleT Returned) { EXPECT_EQ("addObjectSet", LastCalled); EXPECT_EQ(MockObjSetHandle, Returned) << "Return should pass through"; resetExpectations(); } void removeObjectSet(ObjSetHandleT H) { EXPECT_EQ(MockObjSetHandle, H); LastCalled = "removeObjectSet"; } void expectRemoveObjectSet(ObjSetHandleT H) { MockObjSetHandle = H; } void verifyRemoveObjectSet() { EXPECT_EQ("removeObjectSet", LastCalled); resetExpectations(); } JITSymbol findSymbol(const std::string &Name, bool ExportedSymbolsOnly) { EXPECT_EQ(MockName, Name) << "Name should pass through"; EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through"; LastCalled = "findSymbol"; MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None); return MockSymbol; } void expectFindSymbol(const std::string &Name, bool ExportedSymbolsOnly) { MockName = Name; MockBool = ExportedSymbolsOnly; } void verifyFindSymbol(llvm::orc::JITSymbol Returned) { EXPECT_EQ("findSymbol", LastCalled); EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress()) << "Return should pass through"; resetExpectations(); } JITSymbol findSymbolIn(ObjSetHandleT H, const std::string &Name, bool ExportedSymbolsOnly) { EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through"; EXPECT_EQ(MockName, Name) << "Name should pass through"; EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through"; LastCalled = "findSymbolIn"; MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None); return MockSymbol; } void expectFindSymbolIn(ObjSetHandleT H, const std::string &Name, bool ExportedSymbolsOnly) { MockObjSetHandle = H; MockName = Name; MockBool = ExportedSymbolsOnly; } void verifyFindSymbolIn(llvm::orc::JITSymbol Returned) { EXPECT_EQ("findSymbolIn", LastCalled); EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress()) << "Return should pass through"; resetExpectations(); } void emitAndFinalize(ObjSetHandleT H) { EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through"; LastCalled = "emitAndFinalize"; } void expectEmitAndFinalize(ObjSetHandleT H) { MockObjSetHandle = H; } void verifyEmitAndFinalize() { EXPECT_EQ("emitAndFinalize", LastCalled); resetExpectations(); } void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress, TargetAddress TargetAddr) { EXPECT_EQ(MockObjSetHandle, H); EXPECT_EQ(MockLocalAddress, LocalAddress); EXPECT_EQ(MockTargetAddress, TargetAddr); LastCalled = "mapSectionAddress"; } void expectMapSectionAddress(ObjSetHandleT H, const void *LocalAddress, TargetAddress TargetAddr) { MockObjSetHandle = H; MockLocalAddress = LocalAddress; MockTargetAddress = TargetAddr; } void verifyMapSectionAddress() { EXPECT_EQ("mapSectionAddress", LastCalled); resetExpectations(); } private: // Backing fields for remembering parameter/return values std::string LastCalled; MockMemoryManager MockManager; MockSymbolResolver MockResolver; std::vector<MockObjectFile> MockObjects; ObjSetHandleT MockObjSetHandle; std::string MockName; bool MockBool; JITSymbol MockSymbol; const void *MockLocalAddress; TargetAddress MockTargetAddress; MockMemoryBufferSet MockBufferSet; // Clear remembered parameters between calls void resetExpectations() { LastCalled = "nothing"; MockManager = 0; MockResolver = 0; MockObjects.clear(); MockObjSetHandle = 0; MockName = "bogus"; MockSymbol = JITSymbol(nullptr); MockLocalAddress = nullptr; MockTargetAddress = 0; MockBufferSet = 0; } }; // Test each operation on ObjectTransformLayer. TEST(ObjectTransformLayerTest, Main) { MockBaseLayer M; // Create one object transform layer using a transform (as a functor) // that allocates new objects, and deals in unique pointers. ObjectTransformLayer<MockBaseLayer, AllocatingTransform> T1(M); // Create a second object transform layer using a transform (as a lambda) // that mutates objects in place, and deals in naked pointers ObjectTransformLayer<MockBaseLayer, std::function<MockObjectFile *(MockObjectFile *)>> T2(M, [](MockObjectFile *Obj) { ++(*Obj); return Obj; }); // Instantiate some mock objects to use below MockObjectFile MockObject1 = 211; MockObjectFile MockObject2 = 222; MockMemoryManager MockManager = 233; MockSymbolResolver MockResolver = 244; // Test addObjectSet with T1 (allocating, unique pointers) std::vector<std::unique_ptr<MockObjectFile>> Objs1; Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject1)); Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject2)); auto MM = llvm::make_unique<MockMemoryManager>(MockManager); auto SR = llvm::make_unique<MockSymbolResolver>(MockResolver); M.expectAddObjectSet(Objs1, MM.get(), SR.get()); auto H = T1.addObjectSet(std::move(Objs1), std::move(MM), std::move(SR)); M.verifyAddObjectSet(H); // Test addObjectSet with T2 (mutating, naked pointers) llvm::SmallVector<MockObjectFile *, 2> Objs2Vec; Objs2Vec.push_back(&MockObject1); Objs2Vec.push_back(&MockObject2); llvm::MutableArrayRef<MockObjectFile *> Objs2(Objs2Vec); M.expectAddObjectSet(Objs2, &MockManager, &MockResolver); H = T2.addObjectSet(Objs2, &MockManager, &MockResolver); M.verifyAddObjectSet(H); EXPECT_EQ(212, MockObject1) << "Expected mutation"; EXPECT_EQ(223, MockObject2) << "Expected mutation"; // Test removeObjectSet M.expectRemoveObjectSet(H); T1.removeObjectSet(H); M.verifyRemoveObjectSet(); // Test findSymbol std::string Name = "foo"; bool ExportedOnly = true; M.expectFindSymbol(Name, ExportedOnly); JITSymbol Symbol = T2.findSymbol(Name, ExportedOnly); M.verifyFindSymbol(Symbol); // Test findSymbolIn Name = "bar"; ExportedOnly = false; M.expectFindSymbolIn(H, Name, ExportedOnly); Symbol = T1.findSymbolIn(H, Name, ExportedOnly); M.verifyFindSymbolIn(Symbol); // Test emitAndFinalize M.expectEmitAndFinalize(H); T2.emitAndFinalize(H); M.verifyEmitAndFinalize(); // Test mapSectionAddress char Buffer[24]; TargetAddress MockAddress = 255; M.expectMapSectionAddress(H, Buffer, MockAddress); T1.mapSectionAddress(H, Buffer, MockAddress); M.verifyMapSectionAddress(); // Verify transform getter (non-const) MockObjectFile Mutatee = 277; MockObjectFile *Out = T2.getTransform()(&Mutatee); EXPECT_EQ(&Mutatee, Out) << "Expected in-place transform"; EXPECT_EQ(278, Mutatee) << "Expected incrementing transform"; // Verify transform getter (const) auto OwnedObj = llvm::make_unique<MockObjectFile>(288); const auto &T1C = T1; OwnedObj = T1C.getTransform()(std::move(OwnedObj)); EXPECT_EQ(289, *OwnedObj) << "Expected incrementing transform"; volatile bool RunStaticChecks = false; if (RunStaticChecks) { // Make sure that ObjectTransformLayer implements the object layer concept // correctly by sandwitching one between an ObjectLinkingLayer and an // IRCompileLayer, verifying that it compiles if we have a call to the // IRComileLayer's addModuleSet that should call the transform layer's // addObjectSet, and also calling the other public transform layer methods // directly to make sure the methods they intend to forward to exist on // the ObjectLinkingLayer. // We'll need a concrete MemoryManager class. class NullManager : public llvm::RuntimeDyld::MemoryManager { public: uint8_t *allocateCodeSection(uintptr_t, unsigned, unsigned, llvm::StringRef) override { return nullptr; } uint8_t *allocateDataSection(uintptr_t, unsigned, unsigned, llvm::StringRef, bool) override { return nullptr; } void registerEHFrames(uint8_t *, uint64_t, size_t) override {} void deregisterEHFrames(uint8_t *, uint64_t, size_t) override {} bool finalizeMemory(std::string *) { return false; } }; // Construct the jit layers. ObjectLinkingLayer<> BaseLayer; auto IdentityTransform = []( std::unique_ptr<llvm::object::OwningBinary<llvm::object::ObjectFile>> Obj) { return std::move(Obj); }; ObjectTransformLayer<decltype(BaseLayer), decltype(IdentityTransform)> TransformLayer(BaseLayer, IdentityTransform); auto NullCompiler = [](llvm::Module &) { return llvm::object::OwningBinary<llvm::object::ObjectFile>(); }; IRCompileLayer<decltype(TransformLayer)> CompileLayer(TransformLayer, NullCompiler); std::vector<llvm::Module *> Modules; // Make sure that the calls from IRCompileLayer to ObjectTransformLayer // compile. NullResolver Resolver; NullManager Manager; CompileLayer.addModuleSet(std::vector<llvm::Module *>(), &Manager, &Resolver); // Make sure that the calls from ObjectTransformLayer to ObjectLinkingLayer // compile. decltype(TransformLayer)::ObjSetHandleT ObjSet; TransformLayer.emitAndFinalize(ObjSet); TransformLayer.findSymbolIn(ObjSet, Name, false); TransformLayer.findSymbol(Name, true); TransformLayer.mapSectionAddress(ObjSet, nullptr, 0); TransformLayer.removeObjectSet(ObjSet); } } } <commit_msg>ObjectTransformLayerTest.cpp: Fix a warning. [-Winconsistent-missing-override]<commit_after>//===- ObjectTransformLayerTest.cpp - Unit tests for ObjectTransformLayer -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/NullResolver.h" #include "llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h" #include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h" #include "llvm/Object/ObjectFile.h" #include "gtest/gtest.h" using namespace llvm::orc; namespace { // Stand-in for RuntimeDyld::MemoryManager typedef int MockMemoryManager; // Stand-in for RuntimeDyld::SymbolResolver typedef int MockSymbolResolver; // stand-in for object::ObjectFile typedef int MockObjectFile; // stand-in for llvm::MemoryBuffer set typedef int MockMemoryBufferSet; // Mock transform that operates on unique pointers to object files, and // allocates new object files rather than mutating the given ones. struct AllocatingTransform { std::unique_ptr<MockObjectFile> operator()(std::unique_ptr<MockObjectFile> Obj) const { return llvm::make_unique<MockObjectFile>(*Obj + 1); } }; // Mock base layer for verifying behavior of transform layer. // Each method "T foo(args)" is accompanied by two auxiliary methods: // - "void expectFoo(args)", to be called before calling foo on the transform // layer; saves values of args, which mock layer foo then verifies against. // - "void verifyFoo(T)", to be called after foo, which verifies that the // transform layer called the base layer and forwarded any return value. class MockBaseLayer { public: typedef int ObjSetHandleT; MockBaseLayer() : MockSymbol(nullptr) { resetExpectations(); } template <typename ObjSetT, typename MemoryManagerPtrT, typename SymbolResolverPtrT> ObjSetHandleT addObjectSet(ObjSetT Objects, MemoryManagerPtrT MemMgr, SymbolResolverPtrT Resolver) { EXPECT_EQ(MockManager, *MemMgr) << "MM should pass through"; EXPECT_EQ(MockResolver, *Resolver) << "Resolver should pass through"; size_t I = 0; for (auto &ObjPtr : Objects) { EXPECT_EQ(MockObjects[I++] + 1, *ObjPtr) << "Transform should be applied"; } EXPECT_EQ(MockObjects.size(), I) << "Number of objects should match"; LastCalled = "addObjectSet"; MockObjSetHandle = 111; return MockObjSetHandle; } template <typename ObjSetT> void expectAddObjectSet(ObjSetT &Objects, MockMemoryManager *MemMgr, MockSymbolResolver *Resolver) { MockManager = *MemMgr; MockResolver = *Resolver; for (auto &ObjPtr : Objects) { MockObjects.push_back(*ObjPtr); } } void verifyAddObjectSet(ObjSetHandleT Returned) { EXPECT_EQ("addObjectSet", LastCalled); EXPECT_EQ(MockObjSetHandle, Returned) << "Return should pass through"; resetExpectations(); } void removeObjectSet(ObjSetHandleT H) { EXPECT_EQ(MockObjSetHandle, H); LastCalled = "removeObjectSet"; } void expectRemoveObjectSet(ObjSetHandleT H) { MockObjSetHandle = H; } void verifyRemoveObjectSet() { EXPECT_EQ("removeObjectSet", LastCalled); resetExpectations(); } JITSymbol findSymbol(const std::string &Name, bool ExportedSymbolsOnly) { EXPECT_EQ(MockName, Name) << "Name should pass through"; EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through"; LastCalled = "findSymbol"; MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None); return MockSymbol; } void expectFindSymbol(const std::string &Name, bool ExportedSymbolsOnly) { MockName = Name; MockBool = ExportedSymbolsOnly; } void verifyFindSymbol(llvm::orc::JITSymbol Returned) { EXPECT_EQ("findSymbol", LastCalled); EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress()) << "Return should pass through"; resetExpectations(); } JITSymbol findSymbolIn(ObjSetHandleT H, const std::string &Name, bool ExportedSymbolsOnly) { EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through"; EXPECT_EQ(MockName, Name) << "Name should pass through"; EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through"; LastCalled = "findSymbolIn"; MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None); return MockSymbol; } void expectFindSymbolIn(ObjSetHandleT H, const std::string &Name, bool ExportedSymbolsOnly) { MockObjSetHandle = H; MockName = Name; MockBool = ExportedSymbolsOnly; } void verifyFindSymbolIn(llvm::orc::JITSymbol Returned) { EXPECT_EQ("findSymbolIn", LastCalled); EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress()) << "Return should pass through"; resetExpectations(); } void emitAndFinalize(ObjSetHandleT H) { EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through"; LastCalled = "emitAndFinalize"; } void expectEmitAndFinalize(ObjSetHandleT H) { MockObjSetHandle = H; } void verifyEmitAndFinalize() { EXPECT_EQ("emitAndFinalize", LastCalled); resetExpectations(); } void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress, TargetAddress TargetAddr) { EXPECT_EQ(MockObjSetHandle, H); EXPECT_EQ(MockLocalAddress, LocalAddress); EXPECT_EQ(MockTargetAddress, TargetAddr); LastCalled = "mapSectionAddress"; } void expectMapSectionAddress(ObjSetHandleT H, const void *LocalAddress, TargetAddress TargetAddr) { MockObjSetHandle = H; MockLocalAddress = LocalAddress; MockTargetAddress = TargetAddr; } void verifyMapSectionAddress() { EXPECT_EQ("mapSectionAddress", LastCalled); resetExpectations(); } private: // Backing fields for remembering parameter/return values std::string LastCalled; MockMemoryManager MockManager; MockSymbolResolver MockResolver; std::vector<MockObjectFile> MockObjects; ObjSetHandleT MockObjSetHandle; std::string MockName; bool MockBool; JITSymbol MockSymbol; const void *MockLocalAddress; TargetAddress MockTargetAddress; MockMemoryBufferSet MockBufferSet; // Clear remembered parameters between calls void resetExpectations() { LastCalled = "nothing"; MockManager = 0; MockResolver = 0; MockObjects.clear(); MockObjSetHandle = 0; MockName = "bogus"; MockSymbol = JITSymbol(nullptr); MockLocalAddress = nullptr; MockTargetAddress = 0; MockBufferSet = 0; } }; // Test each operation on ObjectTransformLayer. TEST(ObjectTransformLayerTest, Main) { MockBaseLayer M; // Create one object transform layer using a transform (as a functor) // that allocates new objects, and deals in unique pointers. ObjectTransformLayer<MockBaseLayer, AllocatingTransform> T1(M); // Create a second object transform layer using a transform (as a lambda) // that mutates objects in place, and deals in naked pointers ObjectTransformLayer<MockBaseLayer, std::function<MockObjectFile *(MockObjectFile *)>> T2(M, [](MockObjectFile *Obj) { ++(*Obj); return Obj; }); // Instantiate some mock objects to use below MockObjectFile MockObject1 = 211; MockObjectFile MockObject2 = 222; MockMemoryManager MockManager = 233; MockSymbolResolver MockResolver = 244; // Test addObjectSet with T1 (allocating, unique pointers) std::vector<std::unique_ptr<MockObjectFile>> Objs1; Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject1)); Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject2)); auto MM = llvm::make_unique<MockMemoryManager>(MockManager); auto SR = llvm::make_unique<MockSymbolResolver>(MockResolver); M.expectAddObjectSet(Objs1, MM.get(), SR.get()); auto H = T1.addObjectSet(std::move(Objs1), std::move(MM), std::move(SR)); M.verifyAddObjectSet(H); // Test addObjectSet with T2 (mutating, naked pointers) llvm::SmallVector<MockObjectFile *, 2> Objs2Vec; Objs2Vec.push_back(&MockObject1); Objs2Vec.push_back(&MockObject2); llvm::MutableArrayRef<MockObjectFile *> Objs2(Objs2Vec); M.expectAddObjectSet(Objs2, &MockManager, &MockResolver); H = T2.addObjectSet(Objs2, &MockManager, &MockResolver); M.verifyAddObjectSet(H); EXPECT_EQ(212, MockObject1) << "Expected mutation"; EXPECT_EQ(223, MockObject2) << "Expected mutation"; // Test removeObjectSet M.expectRemoveObjectSet(H); T1.removeObjectSet(H); M.verifyRemoveObjectSet(); // Test findSymbol std::string Name = "foo"; bool ExportedOnly = true; M.expectFindSymbol(Name, ExportedOnly); JITSymbol Symbol = T2.findSymbol(Name, ExportedOnly); M.verifyFindSymbol(Symbol); // Test findSymbolIn Name = "bar"; ExportedOnly = false; M.expectFindSymbolIn(H, Name, ExportedOnly); Symbol = T1.findSymbolIn(H, Name, ExportedOnly); M.verifyFindSymbolIn(Symbol); // Test emitAndFinalize M.expectEmitAndFinalize(H); T2.emitAndFinalize(H); M.verifyEmitAndFinalize(); // Test mapSectionAddress char Buffer[24]; TargetAddress MockAddress = 255; M.expectMapSectionAddress(H, Buffer, MockAddress); T1.mapSectionAddress(H, Buffer, MockAddress); M.verifyMapSectionAddress(); // Verify transform getter (non-const) MockObjectFile Mutatee = 277; MockObjectFile *Out = T2.getTransform()(&Mutatee); EXPECT_EQ(&Mutatee, Out) << "Expected in-place transform"; EXPECT_EQ(278, Mutatee) << "Expected incrementing transform"; // Verify transform getter (const) auto OwnedObj = llvm::make_unique<MockObjectFile>(288); const auto &T1C = T1; OwnedObj = T1C.getTransform()(std::move(OwnedObj)); EXPECT_EQ(289, *OwnedObj) << "Expected incrementing transform"; volatile bool RunStaticChecks = false; if (RunStaticChecks) { // Make sure that ObjectTransformLayer implements the object layer concept // correctly by sandwitching one between an ObjectLinkingLayer and an // IRCompileLayer, verifying that it compiles if we have a call to the // IRComileLayer's addModuleSet that should call the transform layer's // addObjectSet, and also calling the other public transform layer methods // directly to make sure the methods they intend to forward to exist on // the ObjectLinkingLayer. // We'll need a concrete MemoryManager class. class NullManager : public llvm::RuntimeDyld::MemoryManager { public: uint8_t *allocateCodeSection(uintptr_t, unsigned, unsigned, llvm::StringRef) override { return nullptr; } uint8_t *allocateDataSection(uintptr_t, unsigned, unsigned, llvm::StringRef, bool) override { return nullptr; } void registerEHFrames(uint8_t *, uint64_t, size_t) override {} void deregisterEHFrames(uint8_t *, uint64_t, size_t) override {} virtual bool finalizeMemory(std::string *) { return false; } }; // Construct the jit layers. ObjectLinkingLayer<> BaseLayer; auto IdentityTransform = []( std::unique_ptr<llvm::object::OwningBinary<llvm::object::ObjectFile>> Obj) { return std::move(Obj); }; ObjectTransformLayer<decltype(BaseLayer), decltype(IdentityTransform)> TransformLayer(BaseLayer, IdentityTransform); auto NullCompiler = [](llvm::Module &) { return llvm::object::OwningBinary<llvm::object::ObjectFile>(); }; IRCompileLayer<decltype(TransformLayer)> CompileLayer(TransformLayer, NullCompiler); std::vector<llvm::Module *> Modules; // Make sure that the calls from IRCompileLayer to ObjectTransformLayer // compile. NullResolver Resolver; NullManager Manager; CompileLayer.addModuleSet(std::vector<llvm::Module *>(), &Manager, &Resolver); // Make sure that the calls from ObjectTransformLayer to ObjectLinkingLayer // compile. decltype(TransformLayer)::ObjSetHandleT ObjSet; TransformLayer.emitAndFinalize(ObjSet); TransformLayer.findSymbolIn(ObjSet, Name, false); TransformLayer.findSymbol(Name, true); TransformLayer.mapSectionAddress(ObjSet, nullptr, 0); TransformLayer.removeObjectSet(ObjSet); } } } <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <math.h> #include <vector> #include "classifier.h" #include <numeric> /** * Initializes GNB */ GNB::GNB() { } GNB::~GNB() {} void GNB::train(vector<vector<double>> data, vector<string> labels) { /* Trains the classifier with N data points and labels. INPUTS data - array of N observations - Each observation is a tuple with 4 values: s, d, s_dot and d_dot. - Example : [ [3.5, 0.1, 5.9, -0.02], [8.0, -0.3, 3.0, 2.2], ... ] labels - array of N labels - Each label is one of "left", "keep", or "right". */ int n = data[0].size(); // number of features int m = data.size(); // number of instances int k = possible_labels.size(); // number of classes mean_.resize(k, vector<double>(n)); // n col and k row var_.resize(k, vector<double>(n)); // n col and k row // Separate data by class // separated[0] will contain all the instances for left turn // separated[1] will contain all the instances for keep going // separated[2] will contain all the instances for right turn vector< vector< vector<double >>> separated (k); for(int i = 0; i < m; i++) for(int j = 0; j < k; j++) if(labels[i] == possible_labels[j]) separated[j].push_back(data[i]); // Calculate Mean for(int ik = 0; ik < k; ik++){ for(int in = 0; in < n; in++){ for(int im = 0; im < separated[ik].size(); im++){ mean_[ik][in] += separated[ik][im][in]; } mean_[ik][in] /= separated[ik].size(); } } // Calculate the variance for(int ik = 0; ik < k; ik++){ for(int in = 0; in < n; in++){ for(int im = 0; im < separated[ik].size(); im++){ var_[ik][in] += pow(separated[ik][im][in] - mean_[ik][in], 2); } var_[ik][in] /= separated[ik].size(); } } } string GNB::predict(vector<double> sample) { /* Once trained, this method is called and expected to return a predicted behavior for the given observation. INPUTS observation - a 4 tuple with s, d, s_dot, d_dot. - Example: [3.5, 0.1, 8.5, -0.2] OUTPUT A label representing the best guess of the classifier. Can be one of "left", "keep" or "right". """ # TODO - complete this */ return this->possible_labels[1]; }<commit_msg>feat: compute the prediction step<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <math.h> #include <vector> #include "classifier.h" #include <numeric> /** * Initializes GNB */ GNB::GNB() { } GNB::~GNB() {} void GNB::train(vector<vector<double>> data, vector<string> labels) { /* Trains the classifier with N data points and labels. INPUTS data - array of N observations - Each observation is a tuple with 4 values: s, d, s_dot and d_dot. - Example : [ [3.5, 0.1, 5.9, -0.02], [8.0, -0.3, 3.0, 2.2], ... ] labels - array of N labels - Each label is one of "left", "keep", or "right". */ int n = data[0].size(); // number of features int m = data.size(); // number of instances int k = possible_labels.size(); // number of classes mean_.resize(k, vector<double>(n)); // n col and k row var_.resize(k, vector<double>(n)); // n col and k row // Separate data by class // separated[0] will contain all the instances for left turn // separated[1] will contain all the instances for keep going // separated[2] will contain all the instances for right turn vector< vector< vector<double >>> separated (k); for(int i = 0; i < m; i++) for(int j = 0; j < k; j++) if(labels[i] == possible_labels[j]) separated[j].push_back(data[i]); // Calculate Mean for(int ik = 0; ik < k; ik++){ for(int in = 0; in < n; in++){ for(int im = 0; im < separated[ik].size(); im++){ mean_[ik][in] += separated[ik][im][in]; } mean_[ik][in] /= separated[ik].size(); } } // Calculate the variance for(int ik = 0; ik < k; ik++){ for(int in = 0; in < n; in++){ for(int im = 0; im < separated[ik].size(); im++){ var_[ik][in] += pow(separated[ik][im][in] - mean_[ik][in], 2); } var_[ik][in] /= separated[ik].size(); } } } string GNB::predict(vector<double> sample) { /* Once trained, this method is called and expected to return a predicted behavior for the given observation. INPUTS observation - a 4 tuple with s, d, s_dot, d_dot. - Example: [3.5, 0.1, 8.5, -0.2] OUTPUT A label representing the best guess of the classifier. Can be one of "left", "keep" or "right". """ # TODO - complete this */ vector<double> posterior(possible_labels.size()); // calculate the posteriori for belong to each class for(int i = 0; i < possible_labels.size(); i++){ posterior[i] = 0.33; for(int j = 0; j < sample.size(); j++){ double x = sample[j]; double gauss = exp(-pow(x - mean_[i][j], 2) / (2*var_[i][j])) / sqrt(2*M_PI*var_[i][j]); posterior[i] *= gauss; } } // take the maximum double max = 0; int r = 0; for(int i = 0; i < possible_labels.size(); i++){ if(posterior[i] > max){ max = posterior[i]; r = i; } } return this->possible_labels[r]; }<|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.7.158); FILE MERGED 2005/09/05 13:21:09 rt 1.7.158.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>
<commit_before>/* * Copyright 2011, 2012 Esrille 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. */ // A test harness for the implementation report of // the CSS2.1 Conformance Test Suite // http://test.csswg.org/suites/css2.1/20110323/ #include <unistd.h> #include <sys/wait.h> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <boost/version.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> enum { INTERACTIVE = 0, HEADLESS, REPORT, UPDATE, // exit status codes ES_PASS = 0, ES_FATAL, ES_FAIL, ES_INVALID, ES_NA, ES_SKIP, ES_UNCERTAIN }; const char* StatusStrings[] = { "pass", "fatal", "fail", "invalid", "?", "skip", "uncertain", }; struct ForkStatus { pid_t pid; std::string url; int code; public: ForkStatus() : pid(-1), code(0) {} }; size_t forkMax = 1; size_t forkCount = 0; std::vector<ForkStatus> forkStates(1); int processOutput(std::istream& stream, std::string& result) { std::string output; bool completed = false; while (std::getline(stream, output)) { if (!completed) { if (output == "## complete") completed = true; continue; } if (output == "##") break; result += output + '\n'; } return 0; } int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout) { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; return -1; } if (pid == 0) { close(1); dup(pipefd[1]); close(pipefd[0]); int argi = argc - 1; if (!userStyle.empty()) argv[argi++] = strdup(userStyle.c_str()); if (testFonts == "on") argv[argi++] ="-testfonts"; url = "http://localhost:8000/" + url; // url = "http://test.csswg.org/suites/css2.1/20110323/" + url; argv[argi++] = strdup(url.c_str()); argv[argi] = 0; if (timeout) alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds. execvp(argv[0], argv); exit(EXIT_FAILURE); } close(pipefd[1]); #if 104400 <= BOOST_VERSION boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle); #else boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true); #endif processOutput(stream, result); return pid; } void killTest(int pid) { int status; kill(pid, SIGTERM); if (wait(&status) == -1) std::cerr << "error: failed to wait for a test process to complete\n"; } bool loadLog(const std::string& path, std::string& result, std::string& log) { std::ifstream file(path.c_str()); if (!file) { result = "?"; return false; } std::string line; std::getline(file, line); size_t pos = line.find('\t'); if (pos != std::string::npos) result = line.substr(pos + 1); else { result = "?"; return false; } log.clear(); while (std::getline(file, line)) log += line + '\n'; return true; } bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log) { std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc); if (!file) { std::cerr << "error: failed to open the report file\n"; return false; } file << "# " << url.c_str() << '\t' << result << '\n' << log; file.flush(); file.close(); return true; } std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout) { std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case REPORT: break; case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout); break; } std::string result; if (0 < pid && output.empty()) result = "fatal"; else if (mode == INTERACTIVE) { std::cout << "## complete\n" << output; std::cout << '[' << url << "] "; if (evaluation.empty() || evaluation[0] == '?') std::cout << "pass? "; else { std::cout << evaluation << "? "; if (evaluation != "pass") std::cout << '\a'; } std::getline(std::cin, result); if (result.empty()) { if (evaluation.empty() || evaluation[0] == '?') result = "pass"; else result = evaluation; } else if (result == "p" || result == "\x1b") result = "pass"; else if (result == "f") result = "fail"; else if (result == "i") result = "invalid"; else if (result == "k") // keep result = evaluation; else if (result == "n") result = "na"; else if (result == "s") result = "skip"; else if (result == "u") result = "uncertain"; else if (result == "q" || result == "quit") exit(EXIT_FAILURE); else if (result == "z") result = "undo"; if (result != "undo" && !saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; } else if (mode == REPORT) { result = evaluation; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } } if (0 < pid) killTest(pid); if (mode != INTERACTIVE && result[0] != '?') std::cout << url << '\t' << result << '\n'; return result; } void reduce(std::ostream& report) { for (int i = 0; i < forkCount; ++i) { int status; pid_t pid = wait(&status); for (int j = 0; j < forkCount; ++j) { if (forkStates[j].pid == pid) { forkStates[j].pid = -1; forkStates[j].code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL; break; } } } for (int i = 0; i < forkCount; ++i) { if (forkStates[i].code != ES_NA) std::cout << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n'; report << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n'; } forkCount = 0; } void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout) { pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; exit(EXIT_FAILURE); } if (pid == 0) { std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout); break; } std::string result; if (0 < pid && output.empty()) result = "fatal"; else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } } if (0 < pid) killTest(pid); int status = ES_NA; if (!result.compare(0, 4, "pass")) status = ES_PASS; else if (!result.compare(0, 5, "fatal")) status = ES_FATAL; else if (!result.compare(0, 4, "fail")) status = ES_FAIL; else if (!result.compare(0, 7, "invalid")) status = ES_INVALID; else if (!result.compare(0, 4, "skip")) status = ES_SKIP; else if (!result.compare(0, 9, "uncertain")) status = ES_UNCERTAIN; exit(status); } else { forkStates[forkCount].url = url; forkStates[forkCount].pid = pid; } if (++forkCount == forkMax) reduce(report); } int main(int argc, char* argv[]) { int mode = HEADLESS; unsigned timeout = 10; int argi = 1; while (*argv[argi] == '-') { switch (argv[argi][1]) { case 'i': mode = INTERACTIVE; timeout = 0; break; case 'r': mode = REPORT; break; case 'u': mode = UPDATE; break; case 'j': forkMax = strtoul(argv[argi] + 2, 0, 10); if (forkMax == 0) forkMax = 1; forkStates.resize(forkMax); break; default: break; } ++argi; } if (argc < argi + 2) { std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n"; return EXIT_FAILURE; } std::ifstream data(argv[argi]); if (!data) { std::cerr << "error: " << argv[argi] << ": no such file\n"; return EXIT_FAILURE; } std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc); if (!report) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } char* args[argc - argi + 3]; for (int i = 2; i < argc; ++i) args[i - 2] = argv[i + argi - 1]; args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0; std::string result; std::string url; std::string undo; std::string userStyle; std::string testFonts; bool redo = false; while (data) { if (result == "undo") { std::swap(url, undo); redo = true; } else if (redo) { std::swap(url, undo); redo = false; } else { std::string line; std::getline(data, line); if (line.empty()) continue; if (line == "testname result comment") { report << line << '\n'; continue; } if (line[0] == '#') { if (line.compare(1, 9, "userstyle") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> userStyle; } else userStyle.clear(); } else if (line.compare(1, 9, "testfonts") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> testFonts; } else testFonts.clear(); } reduce(report); report << line << '\n'; continue; } undo = url; std::stringstream s(line, std::stringstream::in); s >> url; } if (url.empty()) continue; switch (mode) { case HEADLESS: case UPDATE: map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout); break; default: result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout); if (result != "undo") report << url << '\t' << result << '\n'; break; } } if (mode == HEADLESS || mode == UPDATE) reduce(report); report.close(); } <commit_msg>(harness) : Set the exit code to EXIT_SUCCESS when there's no changes, and EXIT_FAILURE otherwise in the headless and update mode.<commit_after>/* * Copyright 2011, 2012 Esrille 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. */ // A test harness for the implementation report of // the CSS2.1 Conformance Test Suite // http://test.csswg.org/suites/css2.1/20110323/ #include <unistd.h> #include <sys/wait.h> #include <cstring> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <boost/version.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file_descriptor.hpp> enum { INTERACTIVE = 0, HEADLESS, REPORT, UPDATE, // exit status codes ES_PASS = 0, ES_FATAL, ES_FAIL, ES_INVALID, ES_NA, ES_SKIP, ES_UNCERTAIN }; const char* StatusStrings[] = { "pass", "fatal", "fail", "invalid", "?", "skip", "uncertain", }; struct ForkStatus { pid_t pid; std::string url; int code; public: ForkStatus() : pid(-1), code(0) {} }; size_t forkMax = 1; size_t forkCount = 0; std::vector<ForkStatus> forkStates(1); size_t uncertainCount = 0; int processOutput(std::istream& stream, std::string& result) { std::string output; bool completed = false; while (std::getline(stream, output)) { if (!completed) { if (output == "## complete") completed = true; continue; } if (output == "##") break; result += output + '\n'; } return 0; } int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout) { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; return -1; } if (pid == 0) { close(1); dup(pipefd[1]); close(pipefd[0]); int argi = argc - 1; if (!userStyle.empty()) argv[argi++] = strdup(userStyle.c_str()); if (testFonts == "on") argv[argi++] ="-testfonts"; url = "http://localhost:8000/" + url; // url = "http://test.csswg.org/suites/css2.1/20110323/" + url; argv[argi++] = strdup(url.c_str()); argv[argi] = 0; if (timeout) alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds. execvp(argv[0], argv); exit(EXIT_FAILURE); } close(pipefd[1]); #if 104400 <= BOOST_VERSION boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle); #else boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true); #endif processOutput(stream, result); return pid; } void killTest(int pid) { int status; kill(pid, SIGTERM); if (wait(&status) == -1) std::cerr << "error: failed to wait for a test process to complete\n"; } bool loadLog(const std::string& path, std::string& result, std::string& log) { std::ifstream file(path.c_str()); if (!file) { result = "?"; return false; } std::string line; std::getline(file, line); size_t pos = line.find('\t'); if (pos != std::string::npos) result = line.substr(pos + 1); else { result = "?"; return false; } log.clear(); while (std::getline(file, line)) log += line + '\n'; return true; } bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log) { std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc); if (!file) { std::cerr << "error: failed to open the report file\n"; return false; } file << "# " << url.c_str() << '\t' << result << '\n' << log; file.flush(); file.close(); return true; } std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout) { std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case REPORT: break; case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout); break; } std::string result; if (0 < pid && output.empty()) result = "fatal"; else if (mode == INTERACTIVE) { std::cout << "## complete\n" << output; std::cout << '[' << url << "] "; if (evaluation.empty() || evaluation[0] == '?') std::cout << "pass? "; else { std::cout << evaluation << "? "; if (evaluation != "pass") std::cout << '\a'; } std::getline(std::cin, result); if (result.empty()) { if (evaluation.empty() || evaluation[0] == '?') result = "pass"; else result = evaluation; } else if (result == "p" || result == "\x1b") result = "pass"; else if (result == "f") result = "fail"; else if (result == "i") result = "invalid"; else if (result == "k") // keep result = evaluation; else if (result == "n") result = "na"; else if (result == "s") result = "skip"; else if (result == "u") result = "uncertain"; else if (result == "q" || result == "quit") exit(EXIT_FAILURE); else if (result == "z") result = "undo"; if (result != "undo" && !saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; } else if (mode == REPORT) { result = evaluation; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } } if (0 < pid) killTest(pid); if (mode != INTERACTIVE && result[0] != '?') std::cout << url << '\t' << result << '\n'; return result; } void reduce(std::ostream& report) { for (int i = 0; i < forkCount; ++i) { int status; pid_t pid = wait(&status); for (int j = 0; j < forkCount; ++j) { if (forkStates[j].pid == pid) { forkStates[j].pid = -1; forkStates[j].code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL; break; } } } for (int i = 0; i < forkCount; ++i) { if (forkStates[i].code == ES_UNCERTAIN) ++uncertainCount; if (forkStates[i].code != ES_NA) std::cout << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n'; report << forkStates[i].url << '\t' << StatusStrings[forkStates[i].code] << '\n'; } forkCount = 0; } void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout) { pid_t pid = fork(); if (pid == -1) { std::cerr << "error: no more process to create\n"; exit(EXIT_FAILURE); } if (pid == 0) { std::string path(url); size_t pos = path.rfind('.'); if (pos != std::string::npos) { path.erase(pos); path += ".log"; } std::string evaluation; std::string log; loadLog(path, evaluation, log); pid_t pid = -1; std::string output; switch (mode) { case UPDATE: if (evaluation[0] == '?') break; // FALL THROUGH default: pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout); break; } std::string result; if (0 < pid && output.empty()) result = "fatal"; else if (mode == HEADLESS) { if (evaluation != "?" && output != log) result = "uncertain"; else result = evaluation; } else if (mode == UPDATE) { result = evaluation; if (result[0] != '?') { if (!saveLog(path, url, result, output)) { std::cerr << "error: failed to open the report file\n"; exit(EXIT_FAILURE); } } } if (0 < pid) killTest(pid); int status = ES_NA; if (!result.compare(0, 4, "pass")) status = ES_PASS; else if (!result.compare(0, 5, "fatal")) status = ES_FATAL; else if (!result.compare(0, 4, "fail")) status = ES_FAIL; else if (!result.compare(0, 7, "invalid")) status = ES_INVALID; else if (!result.compare(0, 4, "skip")) status = ES_SKIP; else if (!result.compare(0, 9, "uncertain")) status = ES_UNCERTAIN; exit(status); } else { forkStates[forkCount].url = url; forkStates[forkCount].pid = pid; } if (++forkCount == forkMax) reduce(report); } int main(int argc, char* argv[]) { int mode = HEADLESS; unsigned timeout = 10; int argi = 1; while (*argv[argi] == '-') { switch (argv[argi][1]) { case 'i': mode = INTERACTIVE; timeout = 0; break; case 'r': mode = REPORT; break; case 'u': mode = UPDATE; break; case 'j': forkMax = strtoul(argv[argi] + 2, 0, 10); if (forkMax == 0) forkMax = 1; forkStates.resize(forkMax); break; default: break; } ++argi; } if (argc < argi + 2) { std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n"; return EXIT_FAILURE; } std::ifstream data(argv[argi]); if (!data) { std::cerr << "error: " << argv[argi] << ": no such file\n"; return EXIT_FAILURE; } std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc); if (!report) { std::cerr << "error: failed to open the report file\n"; return EXIT_FAILURE; } char* args[argc - argi + 3]; for (int i = 2; i < argc; ++i) args[i - 2] = argv[i + argi - 1]; args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0; std::string result; std::string url; std::string undo; std::string userStyle; std::string testFonts; bool redo = false; while (data) { if (result == "undo") { std::swap(url, undo); redo = true; } else if (redo) { std::swap(url, undo); redo = false; } else { std::string line; std::getline(data, line); if (line.empty()) continue; if (line == "testname result comment") { report << line << '\n'; continue; } if (line[0] == '#') { if (line.compare(1, 9, "userstyle") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> userStyle; } else userStyle.clear(); } else if (line.compare(1, 9, "testfonts") == 0) { if (10 < line.length()) { std::stringstream s(line.substr(10), std::stringstream::in); s >> testFonts; } else testFonts.clear(); } reduce(report); report << line << '\n'; continue; } undo = url; std::stringstream s(line, std::stringstream::in); s >> url; } if (url.empty()) continue; switch (mode) { case HEADLESS: case UPDATE: map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout); break; default: result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout); if (result != "undo") report << url << '\t' << result << '\n'; break; } } if (mode == HEADLESS || mode == UPDATE) reduce(report); report.close(); return (0 < uncertainCount) ? EXIT_FAILURE : EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright 2011, 2012 Esrille 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 "URI.h" #include <assert.h> #include <unicode/uidna.h> #include "utf.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { std::string URI::percentEncode(const std::u16string& string, size_t pos, size_t n) { std::string encoding; if (n == std::string::npos) n = string.length(); const char16_t* p = string.c_str() + pos; for (const char16_t* s = p; s < p + n; ) { char32_t utf32; s = utf16to32(s, &utf32); assert(s); char utf8[5]; char* end = utf32to8(utf32, utf8); assert(end); for (const char* p = utf8; p < end; ++p) { if (*p <= 0x20 || (*p < 127 && strchr("\"#%<>[\\]^{|}", *p))) { encoding += '%'; char hex[3]; sprintf(hex, "%02X", *p & 0xff); encoding += hex; } else encoding += *p; } } return encoding; } std::string URI::percentDecode(const std::string& string, size_t pos, size_t n) { std::string decoding; if (n == std::string::npos) n = string.length(); const char* p = string.c_str() + pos; const char* end = p + n; while (p < end) { char c = *p++; if (c == '%' && p + 2 <= end) { int x0 = isHexDigit(p[0]); int x1 = isHexDigit(p[1]); if (x0 && x1) decoding += static_cast<char>(((p[0] - x0) << 4) | (p[1] - x1)); else { decoding += '%'; decoding += p[0]; decoding += p[1]; } p += 2; } else decoding += c; } return decoding; } void URI::clear() { protocolEnd = 0; hostStart = hostEnd = 0; hostnameStart = hostnameEnd = 0; portStart = portEnd = 0; pathnameStart = pathnameEnd = 0; searchStart = searchEnd = 0; hashStart = hashEnd = 0; uri.clear(); } URI::URI(const URL& url) { if (url.isEmpty()) { protocolEnd = 0; hostStart = hostEnd = 0; hostnameStart = hostnameEnd = 0; portStart = portEnd = 0; pathnameStart = pathnameEnd = 0; searchStart = searchEnd = 0; hashStart = hashEnd = 0; return; } uri += percentEncode(url.url, 0, url.protocolEnd); protocolEnd = uri.length(); if (url.hostnameStart == url.hostnameEnd) hostStart = hostnameStart = 0; else { uri += "//"; hostStart = hostnameStart = uri.length(); UChar idn[256]; int32_t len; UErrorCode status = U_ZERO_ERROR; len = uidna_IDNToASCII(reinterpret_cast<const UChar*>(url.url.c_str()) + url.hostnameStart, url.hostnameEnd - url.hostnameStart, idn, 256, UIDNA_DEFAULT, 0, &status); if (status != U_ZERO_ERROR) { // TODO: error clear(); return; } for (int32_t i = 0; i < len; ++i) uri += static_cast<char>(idn[i]); } hostnameEnd = uri.length(); if (url.portStart < url.portEnd) { uri += ':'; portStart = uri.length(); uri += percentEncode(url.url, url.portStart, url.portEnd - url.portStart); portEnd = uri.length(); } else portStart = portEnd = 0; pathnameStart = hostEnd = uri.length(); uri += percentEncode(url.url, url.pathnameStart, url.pathnameEnd - url.pathnameStart); pathnameEnd = uri.length(); if (url.searchStart < url.searchEnd) { searchStart = uri.length(); uri += percentEncode(url.url, url.searchStart, url.searchEnd - url.searchStart); searchEnd = uri.length(); } else searchStart = searchEnd = 0; if (url.hashStart < url.hashEnd) { hashStart = uri.length(); uri += percentEncode(url.url, url.hashStart, url.hashEnd - url.hashStart); hashEnd = uri.length(); } else hashStart = hashEnd = 0; } std::string URI::getPort() const { if (portStart < portEnd) return uri.substr(portStart, portEnd - portStart); if (!uri.compare(0, 5, "http:")) return "80"; if (!uri.compare(0, 6, "https:")) return "443"; return ""; } }}}} // org::w3c::dom::bootstrap <commit_msg>(URI::percentEncode) : Fix a bug.<commit_after>/* * Copyright 2011, 2012 Esrille 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 "URI.h" #include <assert.h> #include <unicode/uidna.h> #include "utf.h" namespace org { namespace w3c { namespace dom { namespace bootstrap { std::string URI::percentEncode(const std::u16string& string, size_t pos, size_t n) { std::string encoding; if (n == std::string::npos) n = string.length(); const char16_t* p = string.c_str() + pos; for (const char16_t* s = p; s < p + n; ) { char32_t utf32; s = utf16to32(s, &utf32); assert(s); char utf8[5]; char* end = utf32to8(utf32, utf8); assert(end); for (const char* p = utf8; p < end; ++p) { // Note percent-encoding characters in the original URL value must be preserved. if (isalnum(*p) || strchr("%" "!*'();:@&=+$,/?#[]-_.~", *p)) encoding += *p; else { encoding += '%'; char hex[3]; sprintf(hex, "%02X", *p & 0xff); encoding += hex; } } } return encoding; } std::string URI::percentDecode(const std::string& string, size_t pos, size_t n) { std::string decoding; if (n == std::string::npos) n = string.length(); const char* p = string.c_str() + pos; const char* end = p + n; while (p < end) { char c = *p++; if (c == '%' && p + 2 <= end) { int x0 = isHexDigit(p[0]); int x1 = isHexDigit(p[1]); if (x0 && x1) decoding += static_cast<char>(((p[0] - x0) << 4) | (p[1] - x1)); else { decoding += '%'; decoding += p[0]; decoding += p[1]; } p += 2; } else decoding += c; } return decoding; } void URI::clear() { protocolEnd = 0; hostStart = hostEnd = 0; hostnameStart = hostnameEnd = 0; portStart = portEnd = 0; pathnameStart = pathnameEnd = 0; searchStart = searchEnd = 0; hashStart = hashEnd = 0; uri.clear(); } URI::URI(const URL& url) { if (url.isEmpty()) { protocolEnd = 0; hostStart = hostEnd = 0; hostnameStart = hostnameEnd = 0; portStart = portEnd = 0; pathnameStart = pathnameEnd = 0; searchStart = searchEnd = 0; hashStart = hashEnd = 0; return; } uri += percentEncode(url.url, 0, url.protocolEnd); protocolEnd = uri.length(); if (url.hostnameStart == url.hostnameEnd) hostStart = hostnameStart = 0; else { uri += "//"; hostStart = hostnameStart = uri.length(); UChar idn[256]; int32_t len; UErrorCode status = U_ZERO_ERROR; len = uidna_IDNToASCII(reinterpret_cast<const UChar*>(url.url.c_str()) + url.hostnameStart, url.hostnameEnd - url.hostnameStart, idn, 256, UIDNA_DEFAULT, 0, &status); if (status != U_ZERO_ERROR) { // TODO: error clear(); return; } for (int32_t i = 0; i < len; ++i) uri += static_cast<char>(idn[i]); } hostnameEnd = uri.length(); if (url.portStart < url.portEnd) { uri += ':'; portStart = uri.length(); uri += percentEncode(url.url, url.portStart, url.portEnd - url.portStart); portEnd = uri.length(); } else portStart = portEnd = 0; pathnameStart = hostEnd = uri.length(); uri += percentEncode(url.url, url.pathnameStart, url.pathnameEnd - url.pathnameStart); pathnameEnd = uri.length(); if (url.searchStart < url.searchEnd) { searchStart = uri.length(); uri += percentEncode(url.url, url.searchStart, url.searchEnd - url.searchStart); searchEnd = uri.length(); } else searchStart = searchEnd = 0; if (url.hashStart < url.hashEnd) { hashStart = uri.length(); uri += percentEncode(url.url, url.hashStart, url.hashEnd - url.hashStart); hashEnd = uri.length(); } else hashStart = hashEnd = 0; } std::string URI::getPort() const { if (portStart < portEnd) return uri.substr(portStart, portEnd - portStart); if (!uri.compare(0, 5, "http:")) return "80"; if (!uri.compare(0, 6, "https:")) return "443"; return ""; } }}}} // org::w3c::dom::bootstrap <|endoftext|>
<commit_before>#include <iostream> //Always needed #include <random> //PRNG stuff #include <algorithm> //Transform function #include <fstream> //File I/O #include <iomanip> //Convenient spacing #include <string> //Manipulate strings using namespace std; void MakeLine(int lineLength); void PrintAttempt(int attemptAmount); void EndProgram(string givenReason); bool Prompt(string type, bool& choice); void GeneratePass(int passLength, int runAmount, bool wantLower, bool wantUpper, bool wantSymbols, ostream& outstream); int main() { //Declare and initialize variables int length = 0; //Length of password to be generated int attempts = 0; //Amount of attempts for length input int amountGen = 0; //Amount of passwords to generate bool failure = false; //Failure to input the length bool smallAlpha = false; //Inclusion of lowercase letters bool largeAlpha = false; //Inclusion of uppercase letters bool symbols = false; //Whether or not to include symbols ofstream outFile; //The stream for the output file char outName[80] = { '\0' }; //The name of the output file //Give the header for the program MakeLine(35); cout << endl << "==== RANDOM PASSWORD GENERATOR ====" << endl; MakeLine(35); //Request password length cout << endl << "Input integer (8 to 256) for length" << endl; while (attempts <= 6) { cin.clear(); cin.sync(); MakeLine(35); cout << endl; //Line for amount of attempts PrintAttempt(attempts); cout << "> "; if (!(cin >> length)) { if (attempts < 6) { cerr << "ERROR: Not an integer!" << endl << endl; attempts++; continue; } else { failure = true; break; } } else if (length < 8 || length > 256) { if (attempts < 6) { cerr << "ERROR: Not within specified range!" << endl << endl; attempts++; continue; } else { failure = true; break; } } else break; } //Check if too many attempts have been performed if (failure == true) { EndProgram("Too many attempts!"); return -1; } //Check for wanting letters and symbols smallAlpha = Prompt("lowercase letters", smallAlpha); largeAlpha = Prompt("uppercase letters", largeAlpha); symbols = Prompt("symbols", symbols); //Request amount of passwords to generate while (amountGen < 1 || amountGen > 100) { cin.clear(); cin.sync(); //Prints the prompt cout << endl; MakeLine(35); cout << endl << "Passwords to generate (1 to 100)" << endl; MakeLine(35); cout << endl; PrintAttempt(attempts); cout << "> "; cin >> amountGen; //Check range if (amountGen < 1 || amountGen > 100) { if (attempts < 6) { cerr << "ERROR: Not within specified range!" << endl; attempts++; continue; } else { failure = true; break; } } else break; } //Check if too many attempts have been performed if (failure == true) { EndProgram("Too many attempts!"); return -1; } //Request output file name MakeLine(35); cout << endl << "Input an output file name: "; cin >> outName; //Try to create the file specified outFile.open(outName, ios::app); if (outFile.fail()) { MakeLine(35); cerr << endl << "ERROR: Failed to create file " << outName << endl; MakeLine(35); EndProgram("Couldn't create file!"); return -1; } //Send to function for (int pass = 1; pass <= amountGen; pass++) { if (pass == 1) { cout << endl; outFile << "= " << "Length: " << setw(4) << length << " ==== Amount: " << setw(4) << amountGen << ' '; for (int equalism = 33; equalism < (length - 1); equalism++) { outFile << '='; } outFile << '=' << endl; } GeneratePass(length, pass, smallAlpha, largeAlpha, symbols, outFile); MakeLine(13); cout << "Generated: " << setw(4) << pass << " / " << setw(4) << amountGen << endl; } outFile << endl; outFile.close(); EndProgram("Success, enjoy your file.\n"); return 0; } //Produces lines across screen void MakeLine(int lineLength) { for (int i = 0; i < lineLength; i++) { cout << '='; } cout << ' '; } void PrintAttempt(int attemptAmount) { MakeLine(19); cout << "Attempts: " << attemptAmount << " / 6" << endl; if (attemptAmount == 6) { cout << "[FINAL] "; } } //Prints failure message and ends program void EndProgram(string givenReason) { //Ensure nothing remains in the input stream cin.clear(); cin.sync(); cout << endl << givenReason << endl << "Press Enter / Return key"; cin.get(); } bool Prompt(string type, bool& choice) { //Initialize variable string ask = "\0"; //Print prompt cout << endl; MakeLine(35); cout << endl << "Should " << type << " be included?" << endl << "> "; cin.clear(); cin.sync(); while (ask == "\0") { getline(cin, ask); } //Convert input to lowercase transform(ask.begin(), ask.end(), ask.begin(), ::tolower); //Convert type to capital letters transform(type.begin(), type.end(), type.begin(), ::toupper); cout << "[STATUS: " << type; //Check input try { if (ask == "true" || ask == "yes" || ask == "affirmative" || ask == "yeah" || ask.at(0) == 'y') { cout << " ENABLED]" << endl; return true; } else if (ask == "ayy lmao") { cout << " ARE FOR HUMANS]" << endl << "[THEREFORE, NOT INCLUDED]" << endl; return false; } else { cout << " DISABLED]" << endl; return false; } } catch (...) { cerr << "[ERROR - DEFAULTING TO FALSE]" << endl; return false; } } //Function to generate password void GeneratePass(int passLength, int runAmount, bool wantLower, bool wantUpper, bool wantSymbols, ostream& outstream) { //Initializes random number generator random_device rd; mt19937 mt(rd()); //Provides boundaries for where to distribute numbers uniform_int_distribution<int> numDist(0, 9); //Random distribution for numbers uniform_int_distribution<int> letDist(0, 25); //Random distribution for letters uniform_int_distribution<int> symDist(0, 13); //Random distribution for symbols //Determines which options can be used for the output vector<int> choices = {1}; //Always include numbers if (wantLower) choices.push_back(2); //Include lowercase if (wantUpper) choices.push_back(3); //Include uppercase if (wantSymbols) choices.push_back(4); //Include symbols uniform_int_distribution<int> typeDist(0, choices.size() - 1); //Storage of characters available char lowerCase[26] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; char upperCase[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char symbo[14] = { '!', '#', '@', '~', '$', '^', '.', ',', '-', '+', '%', '?', '*', '=' }; //Prints to output file for (int p = 0; p < passLength; p++) { switch (choices[typeDist(mt)]) { case 1: //Numbers outstream << numDist(mt); break; case 2: //Lowercase outstream << lowerCase[letDist(mt)]; break; case 3: //Uppercase outstream << upperCase[letDist(mt)]; break; case 4: //Symbols outstream << symbo[symDist(mt)]; break; } } outstream << endl; }<commit_msg>Revisions<commit_after>#include <iostream> //Always needed #include <random> //PRNG stuff #include <algorithm> //Transform function #include <fstream> //File I/O #include <iomanip> //Convenient spacing #include <string> //Manipulate strings void MakeLine(int lineLength); void PrintAttempt(int attemptAmount); void EndProgram(std::string givenReason); bool Prompt(std::string type, bool &choice); void GeneratePass(int passLength, int runAmount, bool wantLower, bool wantUpper, bool wantSymbols, std::ostream &outstream); int main() { //Declare and initialize variables int length = 0; //Length of password to be generated int attempts = 0; //Amount of attempts for length input int amountGen = 0; //Amount of passwords to generate bool failure = false; //Failure to input the length bool smallAlpha = false; //Inclusion of lowercase letters bool largeAlpha = false; //Inclusion of uppercase letters bool symbols = false; //Whether or not to include symbols bool correctAmount = false; //Whether or not valid amount was given std::ofstream outFile; //The stream for the output file char outName[80] = { '\0' }; //The name of the output file //Give the header for the program MakeLine(35); std::cout << std::endl << "==== RANDOM PASSWORD GENERATOR ====" << std::endl; MakeLine(35); //Request password length std::cout << std::endl << "Input integer (8 to 256) for length" << std::endl; while (attempts <= 6) { std::cin.clear(); std::cin.sync(); MakeLine(35); std::cout << std::endl; //Line for amount of attempts PrintAttempt(attempts); std::cout << "> "; if (!(std::cin >> length)) { if (attempts < 6) { std::cerr << "ERROR: Not an integer!" << std::endl << std::endl; attempts++; continue; } else { failure = true; break; } } else if (length < 8 || length > 256) { if (attempts < 6) { std::cerr << "ERROR: Not within specified range!" << std::endl << std::endl; attempts++; continue; } else { failure = true; break; } } else break; } //Check if too many attempts have been performed if (failure == true) { EndProgram("Too many attempts!"); return -1; } //Check for wanting letters and symbols smallAlpha = Prompt("lowercase letters", smallAlpha); largeAlpha = Prompt("uppercase letters", largeAlpha); symbols = Prompt("symbols", symbols); //Request amount of passwords to generate do { //Reset for loop correctAmount = false; std::cin.clear(); std::cin.sync(); //Prints the prompt std::cout << std::endl; MakeLine(35); std::cout << std::endl << "How many passwords to generate " << std::endl << "Input an integer (1 to 100)" << std::endl; MakeLine(35); std::cout << std::endl; PrintAttempt(attempts); std::cout << "> "; try { std::cin >> amountGen; //Check range if (amountGen < 1 || amountGen > 100) { if (attempts < 6) { std::cerr << "ERROR: Not within specified range!" << std::endl; attempts++; continue; } else { failure = true; break; } } else correctAmount = true; } catch (...) { std::cerr << "ERROR: Could not understand input!" << std::endl; attempts++; if (attempts >= 6) { failure = true; break; } } } while (correctAmount == false); //Check if too many attempts have been performed if (failure == true) { EndProgram("Too many attempts!"); return -1; } //Request output file name MakeLine(35); std::cout << std::endl << "Input a file name to use for output" << std::endl << "> "; try { std::cin >> outName; //Try to create the file specified outFile.open(outName, std::ios::app); if (outFile.fail()) { outFile.close(); std::cerr << "ERROR: Failed to create file " << outName << std::endl; MakeLine(35); EndProgram("Couldn't create file!"); return -1; } } catch (...) { outFile.close(); std::cerr << "ERROR: Critical failure, shutting down" << std::endl; EndProgram("Critical failure!"); return -1; } //Send to function for (int pass = 1; pass <= amountGen; pass++) { if (pass == 1) { std::cout << std::endl; outFile << "= " << "Length: " << std::setw(4) << length << " ==== Amount: " << std::setw(4) << amountGen << ' '; for (int equalism = 33; equalism < (length - 1); equalism++) { outFile << '='; } outFile << '=' << std::endl; } GeneratePass(length, pass, smallAlpha, largeAlpha, symbols, outFile); MakeLine(13); std::cout << "Generated: " << std::setw(4) << pass << " / " << std::setw(4) << amountGen << std::endl; } outFile << std::endl; outFile.close(); EndProgram("Success, enjoy your file.\n"); return 0; } //Produces lines across screen void MakeLine(int lineLength) { for (int i = 0; i < lineLength; i++) { std::cout << '='; } std::cout << ' '; } void PrintAttempt(int attemptAmount) { MakeLine(19); std::cout << "Attempts: " << attemptAmount << " / 6" << std::endl; if (attemptAmount == 6) { std::cout << "[FINAL] "; } } //Prints failure message and ends program void EndProgram(std::string givenReason) { //Ensure nothing remains in the input stream std::cin.clear(); std::cin.sync(); std::cout << std::endl << givenReason << std::endl << "Press Enter / Return key"; std::cin.get(); } //Asks if a type is desired bool Prompt(std::string type, bool &choice) { //Initialize variable std::string ask = "\0"; //Print prompt std::cout << std::endl; MakeLine(35); std::cout << std::endl << "Should " << type << " be included?" << std::endl << "> "; std::cin.clear(); std::cin.sync(); while (ask == "\0") { getline(std::cin, ask); } //Convert input to lowercase transform(ask.begin(), ask.end(), ask.begin(), ::tolower); //Convert type to capital letters transform(type.begin(), type.end(), type.begin(), ::toupper); std::cout << "[STATUS: " << type; //Check input try { if (ask == "true" || ask == "yes" || ask == "affirmative" || ask == "yeah" || ask.at(0) == 'y') { std::cout << " ENABLED]" << std::endl; return true; } else { std::cout << " DISABLED]" << std::endl; return false; } } catch (...) { std::cerr << "[ERROR - DEFAULTING TO FALSE]" << std::endl; return false; } } //Function to generate password void GeneratePass(int passLength, int runAmount, bool wantLower, bool wantUpper, bool wantSymbols, std::ostream &outstream) { //Initializes random number generator std::random_device rd; std::mt19937 mt(rd()); //Provides boundaries for where to distribute numbers std::uniform_int_distribution<int> numDist(0, 9); //Random distribution for numbers std::uniform_int_distribution<int> letDist(0, 25); //Random distribution for letters std::uniform_int_distribution<int> symDist(0, 13); //Random distribution for symbols //Determines which options can be used for the output std::vector<int> choices = {1}; //Always include numbers if (wantLower) choices.push_back(2); //Include lowercase if (wantUpper) choices.push_back(3); //Include uppercase if (wantSymbols) choices.push_back(4); //Include symbols std::uniform_int_distribution<int> typeDist(0, choices.size() - 1); //Storage of characters available char lowerCase[26] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; char upperCase[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char symbo[14] = { '!', '#', '@', '~', '$', '^', '.', ',', '-', '+', '%', '?', '*', '=' }; //Prints to output file for (int p = 0; p < passLength; p++) { switch (choices[typeDist(mt)]) { case 1: //Numbers outstream << numDist(mt); break; case 2: //Lowercase outstream << lowerCase[letDist(mt)]; break; case 3: //Uppercase outstream << upperCase[letDist(mt)]; break; case 4: //Symbols outstream << symbo[symDist(mt)]; break; } } outstream << std::endl; }<|endoftext|>
<commit_before>// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #if !defined(__CINT__) || defined(__MAKECINT__) #include <TFile.h> #include <TGLViewer.h> #include <TEveManager.h> #include <TEveElement.h> #include <TEveGeoShape.h> #include <TEveGeoShapeExtract.h> #endif TEveGeoShape* geom_gentle_trd() { TFile f("$ALICE_ROOT/EVE/alice-data/gentle_geo_trd.root"); TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) f.Get("Gentle TRD"); TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse); gEve->AddGlobalElement(gsre); f.Close(); const Int_t smInstalled[]={0, 1, 7, 8, 9, 10, 11, 15, 16, 17}; const Int_t nInstalled = static_cast<Int_t>(sizeof(smInstalled)/sizeof(Int_t)); Int_t sm = 0; // Fix visibility, color and transparency gsre->SetRnrSelf(kFALSE); for (TEveElement::List_i i = gsre->BeginChildren(); i != gsre->EndChildren(); ++i) { TEveGeoShape* lvl1 = (TEveGeoShape*) *i; lvl1->SetRnrSelf(kFALSE); for (TEveElement::List_i j = lvl1->BeginChildren(); j != lvl1->EndChildren(); ++j) { TEveGeoShape* lvl2 = (TEveGeoShape*) *j; lvl2->SetRnrSelf(kFALSE); for(Int_t ism(nInstalled); ism--;){ if ( sm == smInstalled[ism] ){ lvl2->SetRnrSelf(kTRUE); break; } } lvl2->SetMainColor(3); lvl2->SetMainTransparency(80); ++sm; } } return gsre; } <commit_msg>update installed supermodules for 2013<commit_after>// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #if !defined(__CINT__) || defined(__MAKECINT__) #include <TFile.h> #include <TGLViewer.h> #include <TEveManager.h> #include <TEveElement.h> #include <TEveGeoShape.h> #include <TEveGeoShapeExtract.h> #endif TEveGeoShape* geom_gentle_trd() { TFile f("$ALICE_ROOT/EVE/alice-data/gentle_geo_trd.root"); TEveGeoShapeExtract* gse = (TEveGeoShapeExtract*) f.Get("Gentle TRD"); TEveGeoShape* gsre = TEveGeoShape::ImportShapeExtract(gse); gEve->AddGlobalElement(gsre); f.Close(); const Int_t smInstalled[]={0, 1, 2, 3, 6, 7, 8, 9, 10, 11, 15, 16, 17}; const Int_t nInstalled = static_cast<Int_t>(sizeof(smInstalled)/sizeof(Int_t)); Int_t sm = 0; // Fix visibility, color and transparency gsre->SetRnrSelf(kFALSE); for (TEveElement::List_i i = gsre->BeginChildren(); i != gsre->EndChildren(); ++i) { TEveGeoShape* lvl1 = (TEveGeoShape*) *i; lvl1->SetRnrSelf(kFALSE); for (TEveElement::List_i j = lvl1->BeginChildren(); j != lvl1->EndChildren(); ++j) { TEveGeoShape* lvl2 = (TEveGeoShape*) *j; lvl2->SetRnrSelf(kFALSE); for(Int_t ism(nInstalled); ism--;){ if ( sm == smInstalled[ism] ){ lvl2->SetRnrSelf(kTRUE); break; } } lvl2->SetMainColor(3); lvl2->SetMainTransparency(80); ++sm; } } return gsre; } <|endoftext|>
<commit_before>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Our algorithm uses equally sized /// intervals, for each thread the interval_size is /// segment_size * segments_per_thread and the threads process /// adjacent intervals i.e. /// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)]. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval_size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval_size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval_size. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), avg_seconds_(0), count_(0), sqrtz_(isqrt(z)) { init(threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), avg_seconds_(0), count_(0), sqrtz_(isqrt(z)) { init(threads); } void S2LoadBalancer::init(int64_t threads) { // determined by benchmarking double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; update_min_size(log(x_) * log(log(x_))); double alpha = get_alpha(x_, y_); smallest_hard_leaf_ = (int64_t) (x_ / (y_ * sqrt(alpha) * iroot<6>(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds) const { double log_seconds = max(min_seconds_, log(seconds)); double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / ++count_; } void S2LoadBalancer::update_min_size(double divisor) { int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); int64_t min_size = 1 << 9; min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds); rsd_ = max(0.1, relative_standard_deviation(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } int64_t high = low + *segment_size * *segments_per_thread * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; high = low + *segment_size * *segments_per_thread * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } } // namespace <commit_msg>Refactoring<commit_after>/// /// @file S2LoadBalancer.cpp /// @brief The S2LoadBalancer evenly distributes the work load between /// the threads in the computation of the special leaves. /// /// Simply parallelizing the computation of the special leaves in the /// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by /// subdividing the sieve interval by the number of threads into /// equally sized subintervals does not scale because the distribution /// of the special leaves is highly skewed and most special leaves are /// in the first few segments whereas later on there are very few /// special leaves. /// /// Based on the above observations it is clear that we need some kind /// of load balancing in order to scale our parallel algorithm for /// computing special leaves. Below are the ideas I used to develop a /// load balancing algorithm that achieves a high load balance by /// dynamically increasing or decreasing the interval size based on /// the relative standard deviation of the thread run-times. /// /// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x) /// and one segment per thread. Our algorithm uses equally sized /// intervals, for each thread the interval_size is /// segment_size * segments_per_thread and the threads process /// adjacent intervals i.e. /// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)]. /// /// 2) If the relative standard deviation of the thread run-times is /// large then we know the special leaves are distributed unevenly, /// else if the relative standard deviation is low the special /// leaves are more evenly distributed. /// /// 3) If the special leaves are distributed unevenly then we can /// increase the load balance by decreasing the interval_size. /// Contrary if the special leaves are more evenly distributed /// we can increase the interval_size in order to improve the /// algorithm's efficiency. /// /// 4) We can't use a static threshold for as to when the relative /// standard deviation is low or large as this threshold varies for /// different PC architectures. So instead we compare the current /// relative standard deviation to the previous one in order to /// decide whether to increase or decrease the interval_size. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads) : x_((double) x), y_((double) y), z_((double) z), rsd_(40), avg_seconds_(0), count_(0), sqrtz_(isqrt(z)) { init(threads); } S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t y, int64_t z, int64_t threads, double rsd) : x_((double) x), y_((double) y), z_((double) z), rsd_(rsd), avg_seconds_(0), count_(0), sqrtz_(isqrt(z)) { init(threads); } void S2LoadBalancer::init(int64_t threads) { // determined by benchmarking double log_threads = max(1.0, log((double) threads)); decrease_dividend_ = max(0.5, log_threads / 3); min_seconds_ = 0.02 * log_threads; update_min_size(log(x_) * log(log(x_))); double alpha = get_alpha(x_, y_); smallest_hard_leaf_ = (int64_t) (x_ / (y_ * sqrt(alpha) * iroot<6>(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds) const { double log_seconds = max(min_seconds_, log(seconds)); double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / ++count_; } void S2LoadBalancer::update_min_size(double divisor) { int64_t size = (int64_t) (sqrtz_ / max(1.0, divisor)); int64_t min_size = 1 << 9; min_size_ = max(size, min_size); min_size_ = next_power_of_2(min_size_); } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds); rsd_ = max(0.1, relative_standard_deviation(timings)); // 1 segment per thread if (*segment_size < sqrtz_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; } // many segments per thread else if (low > smallest_hard_leaf_) { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } int64_t interval_per_thread = *segment_size * *segments_per_thread; int64_t high = low + interval_per_thread * threads; // near smallest_hard_leaf_ the hard special leaves // are distributed unevenly so use min_size_ if (low <= smallest_hard_leaf_ && high > smallest_hard_leaf_) { *segment_size = min_size_; interval_per_thread = *segment_size * *segments_per_thread; high = low + interval_per_thread * threads; } // slightly increase min_size_ if (high >= smallest_hard_leaf_) { update_min_size(log(y_)); *segment_size = max(min_size_, *segment_size); } } } // namespace <|endoftext|>
<commit_before>/// /// @file S2LoadBalancer.cpp /// @brief Dynamically increase or decrease the segment_size or the /// segments_per_thread in order to improve the load balancing /// in the computation of the special leaves. The algorithm /// calculates the relative standard deviation of the timings /// of the individual threads and then decides whether to /// assign more work (low relative standard deviation) or less /// work (large relative standard deviation) to the threads. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) : x_((double) x), z_((double) z), rsd_(40), avg_seconds_(0), count_(0) { double log_threads = max(1.0, log((double) threads)); min_seconds_ = 0.02 * log_threads; max_size_ = next_power_of_2(isqrt(z)); update_min_size(log(x_) * log(log(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / (count_ + 1); count_++; } void S2LoadBalancer::update_min_size(double divisor) { double size = sqrt(z_) / max(1.0, divisor); min_size_ = max((int64_t) (1 << 9), (int64_t) size); min_size_ = next_power_of_2(min_size_); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds, int64_t threads) const { double log_threads = log((double) threads); double log_seconds = max(min_seconds_, log(seconds)); double dividend = max(0.1, log_threads / 4.0); double dont_decrease = min(dividend / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds, threads); rsd_ = max(0.1, relative_standard_deviation(timings)); // if low > sqrt(z) we use a larger min_size_ as the // special leaves are distributed more evenly if (low > max_size_) update_min_size(log(x_)); // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } } } //namespace <commit_msg>Improved minimum segment size<commit_after>/// /// @file S2LoadBalancer.cpp /// @brief Dynamically increase or decrease the segment_size or the /// segments_per_thread in order to improve the load balancing /// in the computation of the special leaves. The algorithm /// calculates the relative standard deviation of the timings /// of the individual threads and then decides whether to /// assign more work (low relative standard deviation) or less /// work (large relative standard deviation) to the threads. /// /// Copyright (C) 2014 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <S2LoadBalancer.hpp> #include <primecount-internal.hpp> #include <aligned_vector.hpp> #include <pmath.hpp> #include <int128.hpp> #include <stdint.h> #include <algorithm> #include <cmath> using namespace std; using namespace primecount; namespace { double get_average(aligned_vector<double>& timings) { size_t n = timings.size(); double sum = 0; for (size_t i = 0; i < n; i++) sum += timings[i]; return sum / n; } double relative_standard_deviation(aligned_vector<double>& timings) { size_t n = timings.size(); double average = get_average(timings); double sum = 0; if (average == 0) return 0; for (size_t i = 0; i < n; i++) { double mean = timings[i] - average; sum += mean * mean; } double std_dev = sqrt(sum / max(1.0, n - 1.0)); double rsd = 100 * std_dev / average; return rsd; } } // namespace namespace primecount { S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) : x_((double) x), z_((double) z), rsd_(40), avg_seconds_(0), count_(0) { double log_threads = max(1.0, log((double) threads)); min_seconds_ = 0.02 * log_threads; max_size_ = next_power_of_2(isqrt(z)); update_min_size(log(x_) * log(log(x_))); } double S2LoadBalancer::get_rsd() const { return rsd_; } int64_t S2LoadBalancer::get_min_segment_size() const { return min_size_; } bool S2LoadBalancer::decrease_size(double seconds, double decrease) const { return seconds > min_seconds_ && rsd_ > decrease; } bool S2LoadBalancer::increase_size(double seconds, double decrease) const { return seconds < avg_seconds_ && !decrease_size(seconds, decrease); } void S2LoadBalancer::update_avg_seconds(double seconds) { seconds = max(seconds, min_seconds_); double dividend = avg_seconds_ * count_ + seconds; avg_seconds_ = dividend / (count_ + 1); count_++; } void S2LoadBalancer::update_min_size(double divisor) { double size = sqrt(z_) / max(1.0, divisor); min_size_ = max((int64_t) (1 << 9), (int64_t) size); min_size_ = next_power_of_2(min_size_); } /// Used to decide whether to use a smaller or larger /// segment_size and/or segments_per_thread. /// double S2LoadBalancer::get_decrease_threshold(double seconds, int64_t threads) const { double log_threads = log((double) threads); double log_seconds = max(min_seconds_, log(seconds)); double dividend = max(0.1, log_threads / 4.0); double dont_decrease = min(dividend / (seconds * log_seconds), rsd_); return rsd_ + dont_decrease; } /// Balance the load in the computation of the special leaves /// by dynamically adjusting the segment_size and segments_per_thread. /// @param timings Timings of the threads. /// void S2LoadBalancer::update(int64_t low, int64_t threads, int64_t* segment_size, int64_t* segments_per_thread, aligned_vector<double>& timings) { double seconds = get_average(timings); update_avg_seconds(seconds); double decrease_threshold = get_decrease_threshold(seconds, threads); rsd_ = max(0.1, relative_standard_deviation(timings)); // if low > sqrt(z) we use a larger min_size_ as the // special leaves are distributed more evenly if (low > max_size_) { update_min_size(log(x_)); *segment_size = max(*segment_size, min_size_); } // 1 segment per thread if (*segment_size < max_size_) { if (increase_size(seconds, decrease_threshold)) *segment_size <<= 1; else if (decrease_size(seconds, decrease_threshold)) if (*segment_size > min_size_) *segment_size >>= 1; // near sqrt(z) there is a short peak of special // leaves so we use the minium segment size int64_t high = low + *segment_size * *segments_per_thread * threads; if (low <= max_size_ && high > max_size_) *segment_size = min_size_; } else // many segments per thread { double factor = decrease_threshold / rsd_; factor = in_between(0.5, factor, 2); double n = *segments_per_thread * factor; n = max(1.0, n); if ((n < *segments_per_thread && seconds > min_seconds_) || (n > *segments_per_thread && seconds < avg_seconds_)) { *segments_per_thread = (int) n; } } } } //namespace <|endoftext|>
<commit_before>// // Created by Zal on 11/19/16. // #include <assert.h> #include <utility> #include "BinaryMatrix.h" void BinaryMatrix::BinaryMatrix(int w, int h) { this->width = w; this->height = h; this->baseSize = sizeof(char) * 8; int n = w*h; this->dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1; this->data = new char[dataLength]; } void BinaryMatrix::~BinaryMatrix() { delete[] data; } void BinaryMatrix::T() { this->transposed = !this->transposed; } BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) { BinaryMatrix res(this->width, this->height); for(int i = 0; i < this->dataLength; ++i) { res.data[i] = !(this->data[i] ^ other.data[i]); } return res; } std::pair<int, int> BinaryMatrix::elem_accessor(int i, int rows, int cols, bool transposed) { if (transposed) { return std::make_pair(i % rows, i / rows); } else { return std::make_pair(i / cols, i % cols); } } char BinaryMatrix::get_bit(char elem, int bit_id) { return (elem >> (this->baseSize - bit_id)) & 1; } char BinaryMatrix::set_bit(char elem, int bit_id, char bit) { // assumes originally the bit is set to 0 char mask = 1 << (this->baseSize - bit_id); return (elem | (bit << mask)); } BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) { int w = this->width; int h = this->height; if (this->transposed) { w = other.width; h = other.height; } int this_n = this->dataLength; int other_n = other.dataLength; int res_n = res.dataLength; BinaryMatrix res(w, h); for (int bit_id = 0; bit_id < (w * h); ++bit_id) { std::pair<int, int> this_rc = elem_accessor(bit_id, this_n, this->baseSize, this->transposed); std::pair<int, int> other_rc = elem_accessor(bit_id, other_n, other->baseSize, other.transposed); std::pair<int, int> res_rc = elem_accessor(bit_id, res_n, res->baseSize, res.transposed); char this_c = this->data[this_rc.first]; char other_c = other.data[other_rc.first]; char res_c = res.data[res_rc.first]; char answer = !(get_bit(this_c, this_rc.second) ^ get_bit(other_c, other_rc.second)) & 1; res.data[res_rc.first] = set_bit(res_c, res_rc.second, answer); } return res; } double BinaryMatrix::doubleMultiply(const double& other) { } BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) { if(this->transposed != other.transposed) { assert(this->width == other.height); assert(this->height == other.width); return this->tBinMultiply(other); } else { assert(this->width == other.width); assert(this->height == other.height); return this->binMultiply(other); } } <commit_msg>Fixed set_bit to work with no assumptions on original bit<commit_after>// // Created by Zal on 11/19/16. // #include <assert.h> #include <utility> #include "BinaryMatrix.h" void BinaryMatrix::BinaryMatrix(int w, int h) { this->width = w; this->height = h; this->baseSize = sizeof(char) * 8; int n = w*h; this->dataLength = (n % baseSize == 0)? n/baseSize : n/baseSize +1; this->data = new char[dataLength]; } void BinaryMatrix::~BinaryMatrix() { delete[] data; } void BinaryMatrix::T() { this->transposed = !this->transposed; } BinaryMatrix BinaryMatrix::binMultiply(const BinaryMatrix& other) { BinaryMatrix res(this->width, this->height); for(int i = 0; i < this->dataLength; ++i) { res.data[i] = !(this->data[i] ^ other.data[i]); } return res; } std::pair<int, int> BinaryMatrix::elem_accessor(int i, int rows, int cols, bool transposed) { if (transposed) { return std::make_pair(i % rows, i / rows); } else { return std::make_pair(i / cols, i % cols); } } char BinaryMatrix::get_bit(char elem, int bit_id) { return (elem >> (this->baseSize - bit_id)) & 1; } char BinaryMatrix::set_bit(char elem, int bit_id, char bit) { // assumes originally the bit is set to 0 char mask = 1 << (this->baseSize - bit_id); if (get_bit(elem, bit_id) == 1 && bit == 0) { return (elem & !(1 << mask)); } else { return (elem | (bit << mask)); } } BinaryMatrix BinaryMatrix::tBinMultiply(const BinaryMatrix& other) { int w = this->width; int h = this->height; if (this->transposed) { w = other.width; h = other.height; } int this_n = this->dataLength; int other_n = other.dataLength; int res_n = res.dataLength; BinaryMatrix res(w, h); for (int bit_id = 0; bit_id < (w * h); ++bit_id) { std::pair<int, int> this_rc = elem_accessor(bit_id, this_n, this->baseSize, this->transposed); std::pair<int, int> other_rc = elem_accessor(bit_id, other_n, other->baseSize, other.transposed); std::pair<int, int> res_rc = elem_accessor(bit_id, res_n, res->baseSize, res.transposed); char this_c = this->data[this_rc.first]; char other_c = other.data[other_rc.first]; char res_c = res.data[res_rc.first]; char answer = !(get_bit(this_c, this_rc.second) ^ get_bit(other_c, other_rc.second)) & 1; res.data[res_rc.first] = set_bit(res_c, res_rc.second, answer); } return res; } double BinaryMatrix::doubleMultiply(const double& other) { } BinaryMatrix BinaryMatrix::operator*(const BinaryMatrix& other ) { if(this->transposed != other.transposed) { assert(this->width == other.height); assert(this->height == other.width); return this->tBinMultiply(other); } else { assert(this->width == other.width); assert(this->height == other.height); return this->binMultiply(other); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: EDriver.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:12:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_ #define _CONNECTIVITY_FLAT_EDRIVER_HXX_ #ifndef _CPPUHELPER_COMPBASE2_HXX_ #include <cppuhelper/compbase2.hxx> #endif #ifndef _CONNECTIVITY_COMMONTOOLS_HXX_ #include "connectivity/CommonTools.hxx" #endif #ifndef _CONNECTIVITY_FILE_ODRIVER_HXX_ #include "file/FDriver.hxx" #endif namespace connectivity { namespace flat { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ); class ODriver : public file::OFileDriver { public: ODriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) : file::OFileDriver(_rxFactory){} // XInterface static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); // static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); // XDriver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } } #endif //_CONNECTIVITY_FLAT_DDRIVER_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.3.372); FILE MERGED 2008/04/01 15:09:12 thb 1.3.372.3: #i85898# Stripping all external header guards 2008/04/01 10:53:29 thb 1.3.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:21 rt 1.3.372.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: EDriver.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _CONNECTIVITY_FLAT_EDRIVER_HXX_ #define _CONNECTIVITY_FLAT_EDRIVER_HXX_ #include <cppuhelper/compbase2.hxx> #include "connectivity/CommonTools.hxx" #include "file/FDriver.hxx" namespace connectivity { namespace flat { ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception ); class ODriver : public file::OFileDriver { public: ODriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) : file::OFileDriver(_rxFactory){} // XInterface static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException); // static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException); ::rtl::OUString SAL_CALL getImplementationName( ) throw(::com::sun::star::uno::RuntimeException); // XDriver virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException); }; } } #endif //_CONNECTIVITY_FLAT_DDRIVER_HXX_ <|endoftext|>
<commit_before>// See the file in the main distribution directory for copyright. #include <zeek/zeek-config.h> #include "TestimonySource.h" #include <zeek/iosource/Packet.h> #include <zeek/iosource/BPF_Program.h> #include <unistd.h> #include <zeek/Event.h> using namespace ZEEK_IOSOURCE_NS::testimony; TestimonySource::~TestimonySource() { Close(); } void TestimonySource::Open() { OpenLive(); } void TestimonySource::Close() { //temporary_queue_writer will be deleted automatically by thread manager testimony_close(td); Closed(); } void TestimonySource::OpenLive() { int res; const char *fanout_str = getenv("TESTIMONY_FANOUT_ID"); uint32_t fanout_id; res = testimony_connect(&td, props.path.c_str()); if ( res < 0 ) { Error("testimony_connect: " + std::string(strerror(-res))); return; } if ( fanout_str ) { sscanf(fanout_str, "%u", &fanout_id); testimony_conn(td)->fanout_index = fanout_id; } res = testimony_init(td); if ( res < 0 ) { Error("testimony_init: " + std::string(testimony_error(td)) + strerror(-res)); return; } testimony_iter_init(&td_iter); props.selectable_fd = -1; props.link_type = DLT_EN10MB; props.is_live = true; temporary_queue_writer = new TemporaryQueueWriter(); temporary_queue_writer->SetTestimonySource([this] () { this->AddPacketsToTemporaryQueue(); }); temporary_queue_writer->SetStoppingProcess([this] () { this->running = false; } ); temporary_queue_writer->StartThread(); Opened(props); } void TestimonySource::AddPacketsToTemporaryQueue() { while (running) { const tpacket_block_desc *block = NULL; const tpacket3_hdr *packet; int res = testimony_get_block(td, 0, &block); if ( res == 0 && !block ) { if (!running) { return; } // Timeout continue; } if ( res < 0 ) { Error("testimony_get_block:" + std::string(testimony_error(td)) + strerror(-res)); running = false; Close(); } int cnt = 0; testimony_iter_reset(td_iter, block); queue_access_mutex.lock(); while ( (packet = testimony_iter_next(td_iter)) ) { // Queue the packet char *data = new char[packet->tp_len + packet->tp_mac]; // 0 bytes alloc`d inside block of size 144 memcpy(data, packet, packet->tp_len + packet->tp_mac); temp_packets.emplace((tpacket3_hdr *) data); ++stats.received; ++cnt; stats.bytes_received += packet->tp_len; delete[] data; //asd } queue_access_mutex.unlock(); testimony_return_block(td, block); } Error("testimony loop stopped:"); } bool TestimonySource::ExtractNextPacket(Packet* pkt) { if ( ! packets.empty() ) { curr_packet = packets.front(); packets.pop(); curr_timeval.tv_sec = curr_packet->tp_sec; curr_timeval.tv_usec = curr_packet->tp_nsec / 1000; pkt->Init(props.link_type, &curr_timeval, curr_packet->tp_snaplen, curr_packet->tp_len, (const u_char *) curr_packet + curr_packet->tp_mac); return true; } else { queue_access_mutex.lock(); if(!temp_packets.empty()) { packets = std::move(temp_packets); queue_access_mutex.unlock(); return ExtractNextPacket(pkt); } queue_access_mutex.unlock(); } return false; } void TestimonySource::DoneWithPacket() { if ( curr_packet ) { delete curr_packet; //mismatched free/delate/delate[] curr_packet = NULL; } } bool TestimonySource::PrecompileFilter(int index, const std::string& filter) { // Nothing to do. Packet filters are configured on // testimony daemon side return true; } bool TestimonySource::SetFilter(int index) { return true; } void TestimonySource::Statistics(Stats* s) { queue_access_mutex.lock(); s->received = stats.received; s->bytes_received = stats.bytes_received; // TODO: get this information from the daemon s->link = stats.received; s->dropped = 0; queue_access_mutex.unlock(); } ZEEK_IOSOURCE_NS::PktSrc* TestimonySource::Instantiate(const std::string& path, bool is_live) { return new TestimonySource(path, is_live); } <commit_msg>Added fix for swapping queues<commit_after>// See the file in the main distribution directory for copyright. #include <zeek/zeek-config.h> #include "TestimonySource.h" #include <zeek/iosource/Packet.h> #include <zeek/iosource/BPF_Program.h> #include <unistd.h> #include <zeek/Event.h> using namespace ZEEK_IOSOURCE_NS::testimony; TestimonySource::~TestimonySource() { Close(); } void TestimonySource::Open() { OpenLive(); } void TestimonySource::Close() { //temporary_queue_writer will be deleted automatically by thread manager testimony_close(td); Closed(); } void TestimonySource::OpenLive() { int res; const char *fanout_str = getenv("TESTIMONY_FANOUT_ID"); uint32_t fanout_id; res = testimony_connect(&td, props.path.c_str()); if ( res < 0 ) { Error("testimony_connect: " + std::string(strerror(-res))); return; } if ( fanout_str ) { sscanf(fanout_str, "%u", &fanout_id); testimony_conn(td)->fanout_index = fanout_id; } res = testimony_init(td); if ( res < 0 ) { Error("testimony_init: " + std::string(testimony_error(td)) + strerror(-res)); return; } testimony_iter_init(&td_iter); props.selectable_fd = -1; props.link_type = DLT_EN10MB; props.is_live = true; temporary_queue_writer = new TemporaryQueueWriter(); temporary_queue_writer->SetTestimonySource([this] () { this->AddPacketsToTemporaryQueue(); }); temporary_queue_writer->SetStoppingProcess([this] () { this->running = false; } ); temporary_queue_writer->StartThread(); Opened(props); } void TestimonySource::AddPacketsToTemporaryQueue() { while (running) { const tpacket_block_desc *block = NULL; const tpacket3_hdr *packet; int res = testimony_get_block(td, 0, &block); if ( res == 0 && !block ) { if (!running) { return; } // Timeout continue; } if ( res < 0 ) { Error("testimony_get_block:" + std::string(testimony_error(td)) + strerror(-res)); running = false; Close(); } int cnt = 0; testimony_iter_reset(td_iter, block); queue_access_mutex.lock(); while ( (packet = testimony_iter_next(td_iter)) ) { // Queue the packet char *data = new char[packet->tp_len + packet->tp_mac]; // 0 bytes alloc`d inside block of size 144 memcpy(data, packet, packet->tp_len + packet->tp_mac); temp_packets.emplace((tpacket3_hdr *) data); ++stats.received; ++cnt; stats.bytes_received += packet->tp_len; delete[] data; //asd } queue_access_mutex.unlock(); testimony_return_block(td, block); } Error("testimony loop stopped:"); } bool TestimonySource::ExtractNextPacket(Packet* pkt) { if ( ! packets.empty() ) { curr_packet = packets.front(); packets.pop(); curr_timeval.tv_sec = curr_packet->tp_sec; curr_timeval.tv_usec = curr_packet->tp_nsec / 1000; pkt->Init(props.link_type, &curr_timeval, curr_packet->tp_snaplen, curr_packet->tp_len, (const u_char *) curr_packet + curr_packet->tp_mac); return true; } else { queue_access_mutex.lock(); if(!temp_packets.empty()) { std::swap(packets, temp_packets); queue_access_mutex.unlock(); return ExtractNextPacket(pkt); } queue_access_mutex.unlock(); } return false; } void TestimonySource::DoneWithPacket() { if ( curr_packet ) { delete curr_packet; //mismatched free/delate/delate[] curr_packet = NULL; } } bool TestimonySource::PrecompileFilter(int index, const std::string& filter) { // Nothing to do. Packet filters are configured on // testimony daemon side return true; } bool TestimonySource::SetFilter(int index) { return true; } void TestimonySource::Statistics(Stats* s) { queue_access_mutex.lock(); s->received = stats.received; s->bytes_received = stats.bytes_received; // TODO: get this information from the daemon s->link = stats.received; s->dropped = 0; queue_access_mutex.unlock(); } ZEEK_IOSOURCE_NS::PktSrc* TestimonySource::Instantiate(const std::string& path, bool is_live) { return new TestimonySource(path, is_live); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLChangeTrackingExportHelper.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: sab $ $Date: 2001-09-13 15:15:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX #define _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef __SGI_STL_LIST #include <list> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif class ScChangeAction; class ScChangeTrack; class ScXMLExport; class ScBaseCell; class ScChangeActionDel; class ScBigRange; class ScEditEngineTextObj; class ScChangeActionTable; class DateTime; typedef std::list<ScChangeActionDel*> ScMyDeletionsList; class ScChangeTrackingExportHelper { ScXMLExport& rExport; ScChangeTrack* pChangeTrack; ScEditEngineTextObj* pEditTextObj; ScChangeActionTable* pDependings; rtl::OUString sChangeIDPrefix; com::sun::star::uno::Reference<com::sun::star::text::XText> xText; rtl::OUString GetChangeID(const sal_uInt32 nActionNumber); void GetAcceptanceState(const ScChangeAction* pAction); void WriteBigRange(const ScBigRange& rBigRange, xmloff::token::XMLTokenEnum aName); void WriteChangeInfo(const ScChangeAction* pAction); void WriteGenerated(const ScChangeAction* pDependAction); void WriteDeleted(const ScChangeAction* pDependAction); void WriteDepending(const ScChangeAction* pDependAction); void WriteDependings(ScChangeAction* pAction); void WriteEmptyCell(); void SetValueAttributes(const double& fValue, const String& sValue); void WriteValueCell(const ScBaseCell* pCell, const String& sValue); void WriteStringCell(const ScBaseCell* pCell); void WriteEditCell(const ScBaseCell* pCell); void WriteFormulaCell(const ScBaseCell* pCell, const String& sValue); void WriteCell(const ScBaseCell* pCell, const String& sValue); void WriteContentChange(ScChangeAction* pAction); void AddInsertionAttributes(const ScChangeAction* pAction); void WriteInsertion(ScChangeAction* pAction); void AddDeletionAttributes(const ScChangeActionDel* pAction, const ScChangeActionDel* pLastAction); void WriteDeletionCells(ScChangeActionDel* pAction); void WriteCutOffs(const ScChangeActionDel* pAction); void WriteDeletion(ScChangeAction* pAction); void WriteMovement(ScChangeAction* pAction); void WriteRejection(ScChangeAction* pAction); void CollectCellAutoStyles(const ScBaseCell* pBaseCell); void CollectActionAutoStyles(ScChangeAction* pAction); void WorkWithChangeAction(ScChangeAction* pAction); public: ScChangeTrackingExportHelper(ScXMLExport& rExport); ~ScChangeTrackingExportHelper(); void WriteChangeViewSettings(); void CollectAutoStyles(); void CollectAndWriteChanges(); }; #endif <commit_msg>INTEGRATION: CWS visibility03 (1.13.798); FILE MERGED 2005/03/07 18:48:46 mhu 1.13.798.1: #i40092# Added missing forward declaration.<commit_after>/************************************************************************* * * $RCSfile: XMLChangeTrackingExportHelper.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2005-04-13 12:19:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX #define _SC_XMLCHANGETRACKINGEXPORTHELPER_HXX #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef __SGI_STL_LIST #include <list> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_ #include <com/sun/star/text/XText.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif class ScChangeAction; class ScChangeTrack; class ScXMLExport; class ScBaseCell; class ScChangeActionDel; class ScBigRange; class ScEditEngineTextObj; class ScChangeActionTable; class String; class DateTime; typedef std::list<ScChangeActionDel*> ScMyDeletionsList; class ScChangeTrackingExportHelper { ScXMLExport& rExport; ScChangeTrack* pChangeTrack; ScEditEngineTextObj* pEditTextObj; ScChangeActionTable* pDependings; rtl::OUString sChangeIDPrefix; com::sun::star::uno::Reference<com::sun::star::text::XText> xText; rtl::OUString GetChangeID(const sal_uInt32 nActionNumber); void GetAcceptanceState(const ScChangeAction* pAction); void WriteBigRange(const ScBigRange& rBigRange, xmloff::token::XMLTokenEnum aName); void WriteChangeInfo(const ScChangeAction* pAction); void WriteGenerated(const ScChangeAction* pDependAction); void WriteDeleted(const ScChangeAction* pDependAction); void WriteDepending(const ScChangeAction* pDependAction); void WriteDependings(ScChangeAction* pAction); void WriteEmptyCell(); void SetValueAttributes(const double& fValue, const String& sValue); void WriteValueCell(const ScBaseCell* pCell, const String& sValue); void WriteStringCell(const ScBaseCell* pCell); void WriteEditCell(const ScBaseCell* pCell); void WriteFormulaCell(const ScBaseCell* pCell, const String& sValue); void WriteCell(const ScBaseCell* pCell, const String& sValue); void WriteContentChange(ScChangeAction* pAction); void AddInsertionAttributes(const ScChangeAction* pAction); void WriteInsertion(ScChangeAction* pAction); void AddDeletionAttributes(const ScChangeActionDel* pAction, const ScChangeActionDel* pLastAction); void WriteDeletionCells(ScChangeActionDel* pAction); void WriteCutOffs(const ScChangeActionDel* pAction); void WriteDeletion(ScChangeAction* pAction); void WriteMovement(ScChangeAction* pAction); void WriteRejection(ScChangeAction* pAction); void CollectCellAutoStyles(const ScBaseCell* pBaseCell); void CollectActionAutoStyles(ScChangeAction* pAction); void WorkWithChangeAction(ScChangeAction* pAction); public: ScChangeTrackingExportHelper(ScXMLExport& rExport); ~ScChangeTrackingExportHelper(); void WriteChangeViewSettings(); void CollectAutoStyles(); void CollectAndWriteChanges(); }; #endif <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2012 Igor Mironchik 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. */ // QtConfFile include. #include <QtConfFile/private/Lex> #include <QtConfFile/private/InputStream> #include <QtConfFile/Exceptions> namespace QtConfFile { static const QChar c_beginTag = QChar( '{' ); static const QChar c_endTag = QChar( '}' ); static const QChar c_quotes = QChar( '"' ); static const QChar c_n = QChar( 'n' ); static const QChar c_t = QChar( 't' ); static const QChar c_r = QChar( 'r' ); static const QChar c_backSlash = QChar( '\\' ); static const QChar c_space = QChar( ' ' ); static const QChar c_tab = QChar( '\t' ); static const QChar c_carriageReturn = QChar( '\n' ); static const QChar c_lineFeed = QChar( '\r' ); static const QChar c_verticalBar = QChar( '|' ); static const QChar c_sharp = QChar( '#' ); // // LexicalAnalyzer::LexicalAnalyzerPrivate // struct LexicalAnalyzer::LexicalAnalyzerPrivate { explicit LexicalAnalyzerPrivate( InputStream & stream ) : m_stream( stream ) { } //! \return Is character a space character? bool isSpaceChar( QChar ch ) { if( ch == c_space || ch == c_tab || ch == c_carriageReturn || ch == c_lineFeed ) return true; else return false; } //! Skip spaces in the stream. void skipSpaces() { QChar ch = m_stream.get(); while( isSpaceChar( ch ) ) { ch = m_stream.get(); } m_stream.putBack( ch ); } //! Process back-slash sequence. bool processBackSlash( QChar & ch ) { ch = m_stream.get(); if( ch == c_n ) ch = c_carriageReturn; else if( ch == c_t ) ch = c_tab; else if( ch == c_r ) ch = c_lineFeed; else if( ch == c_quotes ) ch = c_quotes; else if( ch == c_backSlash ) ch = c_backSlash; else return false; return true; } //! Skip one-line comment. void skipOneLineComment() { QChar ch = m_stream.get(); while( ( ch != c_carriageReturn && ch != c_lineFeed ) && !m_stream.atEnd() ) ch = m_stream.get(); skipSpaces(); } //! Skip multi-line comment. void skipMultiLineComment() { QChar ch = m_stream.get(); if( m_stream.atEnd() ) return; QChar nextChar = m_stream.get(); while( ( ch != c_sharp && nextChar != c_verticalBar ) && !m_stream.atEnd() ) { ch = nextChar; nextChar = m_stream.get(); } skipSpaces(); } InputStream & m_stream; }; // struct LexicalAnalyzer::LexicalAnalyzerPrivate // // LexicalAnalyzer // LexicalAnalyzer::LexicalAnalyzer( InputStream & stream ) : d( new LexicalAnalyzerPrivate( stream ) ) { } LexicalAnalyzer::~LexicalAnalyzer() { } LexicalAnalyzer::Lexeme LexicalAnalyzer::nextLexeme() { if( d->m_stream.atEnd() ) return Lexeme( NullLexeme, QString() ); QString result; bool quotedLexeme = false; bool firstSymbol = true; d->skipSpaces(); while( true ) { QChar ch = d->m_stream.get(); if( ch == c_quotes ) { if( quotedLexeme ) break; else if( firstSymbol ) quotedLexeme = true; else { d->m_stream.putBack( ch ); break; } } else if( ch == c_backSlash ) { QChar newChar; if( !quotedLexeme ) result.append( ch ); else if( d->processBackSlash( newChar ) ) result.append( newChar ); else throw Exception( QString( "Unrecognized back-slash sequence: \"\\%1\". " "In file \"%2\" on line %3." ).arg( newChar ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); } else if( ch == c_beginTag ) { if( result.isEmpty() ) return Lexeme( StartTagLexeme, ch ); else if( quotedLexeme ) result.append( ch ); else { d->m_stream.putBack( ch ); break; } } else if( ch == c_endTag ) { if( result.isEmpty() ) return Lexeme( FinishTagLexeme, ch ); else if( quotedLexeme ) result.append( ch ); else { d->m_stream.putBack( ch ); break; } } else if( ch == c_space || ch == c_tab ) { if( quotedLexeme ) result.append( ch ); else break; } else if( ch == c_carriageReturn || ch == c_lineFeed ) { if( quotedLexeme ) throw Exception( QString( "Unfinished quoted lexeme. " "New line detected. In file \"%1\" on line %2." ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); else break; } else if( ch == c_verticalBar ) { if( quotedLexeme ) result.append( ch ); else { QChar nextChar = d->m_stream.get(); if( nextChar == c_verticalBar ) d->skipOneLineComment(); else if( nextChar == c_sharp ) d->skipMultiLineComment(); else { result.append( ch ); d->m_stream.putBack( nextChar ); } } } else result.append( ch ); if( d->m_stream.atEnd() ) { if( quotedLexeme ) throw Exception( QString( "Unfinished quoted lexeme. " "End of file riched. In file \"%1\" on line %2." ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); else break; } firstSymbol = false; } return Lexeme( StringLexeme, result ); } } /* namespace QtConfFile */ <commit_msg>Fixed issue with multi-line comments.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2012 Igor Mironchik 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. */ // QtConfFile include. #include <QtConfFile/private/Lex> #include <QtConfFile/private/InputStream> #include <QtConfFile/Exceptions> namespace QtConfFile { static const QChar c_beginTag = QChar( '{' ); static const QChar c_endTag = QChar( '}' ); static const QChar c_quotes = QChar( '"' ); static const QChar c_n = QChar( 'n' ); static const QChar c_t = QChar( 't' ); static const QChar c_r = QChar( 'r' ); static const QChar c_backSlash = QChar( '\\' ); static const QChar c_space = QChar( ' ' ); static const QChar c_tab = QChar( '\t' ); static const QChar c_carriageReturn = QChar( '\n' ); static const QChar c_lineFeed = QChar( '\r' ); static const QChar c_verticalBar = QChar( '|' ); static const QChar c_sharp = QChar( '#' ); // // LexicalAnalyzer::LexicalAnalyzerPrivate // struct LexicalAnalyzer::LexicalAnalyzerPrivate { explicit LexicalAnalyzerPrivate( InputStream & stream ) : m_stream( stream ) { } //! \return Is character a space character? bool isSpaceChar( QChar ch ) { if( ch == c_space || ch == c_tab || ch == c_carriageReturn || ch == c_lineFeed ) return true; else return false; } //! Skip spaces in the stream. void skipSpaces() { QChar ch = m_stream.get(); while( isSpaceChar( ch ) ) { ch = m_stream.get(); } m_stream.putBack( ch ); } //! Process back-slash sequence. bool processBackSlash( QChar & ch ) { ch = m_stream.get(); if( ch == c_n ) ch = c_carriageReturn; else if( ch == c_t ) ch = c_tab; else if( ch == c_r ) ch = c_lineFeed; else if( ch == c_quotes ) ch = c_quotes; else if( ch == c_backSlash ) ch = c_backSlash; else return false; return true; } //! Skip one-line comment. void skipOneLineComment() { QChar ch = m_stream.get(); while( ( ch != c_carriageReturn && ch != c_lineFeed ) && !m_stream.atEnd() ) ch = m_stream.get(); } //! Skip multi-line comment. void skipMultiLineComment() { QChar ch = m_stream.get(); if( m_stream.atEnd() ) return; QChar nextChar = m_stream.get(); while( ( ch != c_sharp && nextChar != c_verticalBar ) && !m_stream.atEnd() ) { ch = nextChar; nextChar = m_stream.get(); } } InputStream & m_stream; }; // struct LexicalAnalyzer::LexicalAnalyzerPrivate // // LexicalAnalyzer // LexicalAnalyzer::LexicalAnalyzer( InputStream & stream ) : d( new LexicalAnalyzerPrivate( stream ) ) { } LexicalAnalyzer::~LexicalAnalyzer() { } LexicalAnalyzer::Lexeme LexicalAnalyzer::nextLexeme() { if( d->m_stream.atEnd() ) return Lexeme( NullLexeme, QString() ); QString result; bool quotedLexeme = false; bool firstSymbol = true; d->skipSpaces(); while( true ) { QChar ch = d->m_stream.get(); if( ch == c_quotes ) { if( quotedLexeme ) break; else if( firstSymbol ) quotedLexeme = true; else { d->m_stream.putBack( ch ); break; } } else if( ch == c_backSlash ) { QChar newChar; if( !quotedLexeme ) result.append( ch ); else if( d->processBackSlash( newChar ) ) result.append( newChar ); else throw Exception( QString( "Unrecognized back-slash sequence: \"\\%1\". " "In file \"%2\" on line %3." ).arg( newChar ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); } else if( ch == c_beginTag ) { if( result.isEmpty() ) return Lexeme( StartTagLexeme, ch ); else if( quotedLexeme ) result.append( ch ); else { d->m_stream.putBack( ch ); break; } } else if( ch == c_endTag ) { if( result.isEmpty() ) return Lexeme( FinishTagLexeme, ch ); else if( quotedLexeme ) result.append( ch ); else { d->m_stream.putBack( ch ); break; } } else if( ch == c_space || ch == c_tab ) { if( quotedLexeme ) result.append( ch ); else break; } else if( ch == c_carriageReturn || ch == c_lineFeed ) { if( quotedLexeme ) throw Exception( QString( "Unfinished quoted lexeme. " "New line detected. In file \"%1\" on line %2." ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); else break; } else if( ch == c_verticalBar ) { if( quotedLexeme ) result.append( ch ); else { QChar nextChar = d->m_stream.get(); if( nextChar == c_verticalBar ) { d->skipOneLineComment(); if( firstSymbol ) d->skipSpaces(); else break; } else if( nextChar == c_sharp ) { d->skipMultiLineComment(); if( firstSymbol ) d->skipSpaces(); else break; } else { result.append( ch ); d->m_stream.putBack( nextChar ); } } } else result.append( ch ); if( d->m_stream.atEnd() ) { if( quotedLexeme ) throw Exception( QString( "Unfinished quoted lexeme. " "End of file riched. In file \"%1\" on line %2." ) .arg( d->m_stream.fileName() ) .arg( d->m_stream.lineNumber() ) ); else break; } firstSymbol = false; } return Lexeme( StringLexeme, result ); } } /* namespace QtConfFile */ <|endoftext|>
<commit_before> #include "toy/math/NumberFormat.hpp" namespace toy{ namespace math{ struct NumberFormatPrivate { uint8_t isGood : 1; uint8_t isInteger : 1; uint8_t isNegative : 1; uint8_t isDecimal : 1; uint8_t isHexadecimal : 1; uint8_t : 0; }; }} using namespace toy; using namespace math; auto NumberFormat::operator = ( const NumberFormat & m ) -> const NumberFormat& { *_this = *(m._this); return *this; } NumberFormat::NumberFormat(const NumberFormat & m):_this(new NumberFormatPrivate) { *_this = *(m._this); } static bool IsNumberChar(char c) { if ( c<'0' || c>'9' ) { return false; } return true; } static bool IsHexNumberChar(char c) { if ( ( c<'0' || c>'9' ) && ( c<'a' || c>'f' ) ) { return false; } return true; } NumberFormat::NumberFormat(const std::string &num):_this(new NumberFormatPrivate) { *((uint8_t*)_this) = uint8_t(0); int size = num.size(); if ( size==0 ) { return; } int index = 0; if ( num[index]=='-' ) { index++; _this->isNegative = 1; } if ( size<index+2 ) return; bool maybeIsHexadecimal = false; bool dotFound = false; bool (*func)(char) = IsNumberChar; if ( num[index]=='0' ) { if ( size<index+2 ) return; if ( num[index+1]=='x' ) { if ( size<index+3 ) return; func = IsHexNumberChar; index += 2; maybeIsHexadecimal = true; if ( num[index]=='0' ) { if ( size<index+2 ) { return; // 0x0 } else { if ( num[index+1]=='.' ) { if ( size<index+3 ) return; // 0x0. dotFound = true; index += 2; } else { return; // 0x0123 } } } else if ( num[index]=='.' ) { return; } } else if ( num[index+1]=='.' ) { if ( size<index+3 ) return; // 0x0. dotFound = true; index += 2; } else { return; } } else if ( num[index]=='.' ) { return; } for (; size>index+1 ;index++) { if ( num[index]=='.' ) { if ( dotFound ) { return; } else { dotFound = true; } } else if ( ! func(num[index]) ) return; } if ( num[size-1]=='.' ) { return; // xxx. } _this->isGood = 1; if ( maybeIsHexadecimal ) { _this->isHexadecimal = 1; } else { _this->isDecimal = 1; } if ( dotFound==false ) { _this->isInteger = 1; } } NumberFormat::~NumberFormat() { delete _this; } bool NumberFormat::isGood() { return _this->isGood; } bool NumberFormat::isInteger() { return _this->isInteger; } bool NumberFormat::isNegative() { return _this->isNegative; } bool NumberFormat::isDecimal() { return _this->isDecimal; } bool NumberFormat::isHexadecimal() { return _this->isHexadecimal; } <commit_msg>Fix a stupid bug of toy::math::NumberFormat.<commit_after> #include "toy/math/NumberFormat.hpp" namespace toy{ namespace math{ struct NumberFormatPrivate { uint8_t isGood : 1; uint8_t isInteger : 1; uint8_t isNegative : 1; uint8_t isDecimal : 1; uint8_t isHexadecimal : 1; uint8_t : 0; }; }} using namespace toy; using namespace math; auto NumberFormat::operator = ( const NumberFormat & m ) -> const NumberFormat& { *_this = *(m._this); return *this; } NumberFormat::NumberFormat(const NumberFormat & m):_this(new NumberFormatPrivate) { *_this = *(m._this); } static bool IsNumberChar(char c) { if ( c<'0' || c>'9' ) { return false; } return true; } static bool IsHexNumberChar(char c) { if ( ( c<'0' || c>'9' ) && ( c<'a' || c>'f' ) ) { return false; } return true; } NumberFormat::NumberFormat(const std::string &num):_this(new NumberFormatPrivate) { *((uint8_t*)_this) = uint8_t(0); int size = num.size(); if ( size==0 ) { return; } int index = 0; if ( num[index]=='-' ) { index++; _this->isNegative = 1; } if ( size<index+2 ) return; bool maybeIsHexadecimal = false; bool dotFound = false; bool (*func)(char) = IsNumberChar; if ( num[index]=='0' ) { if ( size<index+2 ) return; if ( num[index+1]=='x' ) { if ( size<index+3 ) return; func = IsHexNumberChar; index += 2; maybeIsHexadecimal = true; if ( num[index]=='0' ) { if ( size<index+2 ) { return; // 0x0 } else { if ( num[index+1]=='.' ) { if ( size<index+3 ) return; // 0x0. dotFound = true; index += 2; } else { return; // 0x0123 } } } else if ( num[index]=='.' ) { return; } } else if ( num[index+1]=='.' ) { if ( size<index+3 ) return; // 0x0. dotFound = true; index += 2; } else { return; } } else if ( num[index]=='.' ) { return; } for (; size>index ;index++) { if ( num[index]=='.' ) { if ( dotFound ) { return; } else { dotFound = true; } } else if ( ! func(num[index]) ) return; } if ( num[size-1]=='.' ) { return; // xxx. } _this->isGood = 1; if ( maybeIsHexadecimal ) { _this->isHexadecimal = 1; } else { _this->isDecimal = 1; } if ( dotFound==false ) { _this->isInteger = 1; } } NumberFormat::~NumberFormat() { delete _this; } bool NumberFormat::isGood() { return _this->isGood; } bool NumberFormat::isInteger() { return _this->isInteger; } bool NumberFormat::isNegative() { return _this->isNegative; } bool NumberFormat::isDecimal() { return _this->isDecimal; } bool NumberFormat::isHexadecimal() { return _this->isHexadecimal; } <|endoftext|>
<commit_before>/* * Copyright 2006 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Most of this was borrowed (with minor modifications) from V8's and Chromium's // src/base/logging.cc. // Use the C++ version to provide __GLIBCXX__. #include <cstdio> #include <cstdarg> #if defined(__GLIBCXX__) && !defined(__UCLIBC__) #include <cxxabi.h> #include <execinfo.h> #endif #if defined(WEBRTC_ANDROID) #define LOG_TAG "rtc" #include <android/log.h> // NOLINT #endif #include "webrtc/base/checks.h" #if defined(_MSC_VER) // Warning C4722: destructor never returns, potential memory leak. // FatalMessage's dtor very intentionally aborts. #pragma warning(disable:4722) #endif namespace rtc { void VPrintError(const char* format, va_list args) { #if defined(WEBRTC_ANDROID) __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args); #else vfprintf(stderr, format, args); #endif } void PrintError(const char* format, ...) { va_list args; va_start(args, format); VPrintError(format, args); va_end(args); } // TODO(ajm): This works on Mac (although the parsing fails) but I don't seem // to get usable symbols on Linux. This is copied from V8. Chromium has a more // advanced stace trace system; also more difficult to copy. void DumpBacktrace() { #if defined(__GLIBCXX__) && !defined(__UCLIBC__) void* trace[100]; int size = backtrace(trace, sizeof(trace) / sizeof(*trace)); char** symbols = backtrace_symbols(trace, size); PrintError("\n==== C stack trace ===============================\n\n"); if (size == 0) { PrintError("(empty)\n"); } else if (symbols == NULL) { PrintError("(no symbols)\n"); } else { for (int i = 1; i < size; ++i) { char mangled[201]; if (sscanf(symbols[i], "%*[^(]%*[(]%200[^)+]", mangled) == 1) { // NOLINT PrintError("%2d: ", i); int status; size_t length; char* demangled = abi::__cxa_demangle(mangled, NULL, &length, &status); PrintError("%s\n", demangled != NULL ? demangled : mangled); free(demangled); } else { // If parsing failed, at least print the unparsed symbol. PrintError("%s\n", symbols[i]); } } } free(symbols); #endif } FatalMessage::FatalMessage(const char* file, int line) { Init(file, line); } FatalMessage::FatalMessage(const char* file, int line, std::string* result) { Init(file, line); stream_ << "Check failed: " << *result << std::endl << "# "; delete result; } NO_RETURN FatalMessage::~FatalMessage() { fflush(stdout); fflush(stderr); stream_ << std::endl << "#" << std::endl; PrintError(stream_.str().c_str()); DumpBacktrace(); fflush(stderr); abort(); } void FatalMessage::Init(const char* file, int line) { stream_ << std::endl << std::endl << "#" << std::endl << "# Fatal error in " << file << ", line " << line << std::endl << "# "; } // Refer to comments in checks.h. #ifndef WEBRTC_CHROMIUM_BUILD // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) // Explicit instantiations for commonly used comparisons. template std::string* MakeCheckOpString<int, int>( const int&, const int&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned long>( const unsigned long&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned int>( const unsigned long&, const unsigned int&, const char* names); template std::string* MakeCheckOpString<unsigned int, unsigned long>( const unsigned int&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<std::string, std::string>( const std::string&, const std::string&, const char* name); #endif #endif // WEBRTC_CHROMIUM_BUILD } // namespace rtc <commit_msg>include cstdlib for free() and abort()<commit_after>/* * Copyright 2006 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // Most of this was borrowed (with minor modifications) from V8's and Chromium's // src/base/logging.cc. // Use the C++ version to provide __GLIBCXX__. #include <cstdarg> #include <cstdio> #include <cstdlib> #if defined(__GLIBCXX__) && !defined(__UCLIBC__) #include <cxxabi.h> #include <execinfo.h> #endif #if defined(WEBRTC_ANDROID) #define LOG_TAG "rtc" #include <android/log.h> // NOLINT #endif #include "webrtc/base/checks.h" #if defined(_MSC_VER) // Warning C4722: destructor never returns, potential memory leak. // FatalMessage's dtor very intentionally aborts. #pragma warning(disable:4722) #endif namespace rtc { void VPrintError(const char* format, va_list args) { #if defined(WEBRTC_ANDROID) __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args); #else vfprintf(stderr, format, args); #endif } void PrintError(const char* format, ...) { va_list args; va_start(args, format); VPrintError(format, args); va_end(args); } // TODO(ajm): This works on Mac (although the parsing fails) but I don't seem // to get usable symbols on Linux. This is copied from V8. Chromium has a more // advanced stace trace system; also more difficult to copy. void DumpBacktrace() { #if defined(__GLIBCXX__) && !defined(__UCLIBC__) void* trace[100]; int size = backtrace(trace, sizeof(trace) / sizeof(*trace)); char** symbols = backtrace_symbols(trace, size); PrintError("\n==== C stack trace ===============================\n\n"); if (size == 0) { PrintError("(empty)\n"); } else if (symbols == NULL) { PrintError("(no symbols)\n"); } else { for (int i = 1; i < size; ++i) { char mangled[201]; if (sscanf(symbols[i], "%*[^(]%*[(]%200[^)+]", mangled) == 1) { // NOLINT PrintError("%2d: ", i); int status; size_t length; char* demangled = abi::__cxa_demangle(mangled, NULL, &length, &status); PrintError("%s\n", demangled != NULL ? demangled : mangled); free(demangled); } else { // If parsing failed, at least print the unparsed symbol. PrintError("%s\n", symbols[i]); } } } free(symbols); #endif } FatalMessage::FatalMessage(const char* file, int line) { Init(file, line); } FatalMessage::FatalMessage(const char* file, int line, std::string* result) { Init(file, line); stream_ << "Check failed: " << *result << std::endl << "# "; delete result; } NO_RETURN FatalMessage::~FatalMessage() { fflush(stdout); fflush(stderr); stream_ << std::endl << "#" << std::endl; PrintError(stream_.str().c_str()); DumpBacktrace(); fflush(stderr); abort(); } void FatalMessage::Init(const char* file, int line) { stream_ << std::endl << std::endl << "#" << std::endl << "# Fatal error in " << file << ", line " << line << std::endl << "# "; } // Refer to comments in checks.h. #ifndef WEBRTC_CHROMIUM_BUILD // MSVC doesn't like complex extern templates and DLLs. #if !defined(COMPILER_MSVC) // Explicit instantiations for commonly used comparisons. template std::string* MakeCheckOpString<int, int>( const int&, const int&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned long>( const unsigned long&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<unsigned long, unsigned int>( const unsigned long&, const unsigned int&, const char* names); template std::string* MakeCheckOpString<unsigned int, unsigned long>( const unsigned int&, const unsigned long&, const char* names); template std::string* MakeCheckOpString<std::string, std::string>( const std::string&, const std::string&, const char* name); #endif #endif // WEBRTC_CHROMIUM_BUILD } // namespace rtc <|endoftext|>
<commit_before>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/SwSwitch.h" #include <folly/Range.h> #include <folly/ThreadName.h> namespace facebook { namespace fboss { void SwSwitch::initThread(folly::StringPiece name) { // We need a null-terminated string to pass to folly::setThreadName(). // The pthread name can be at most 15 bytes long, so truncate it if necessary // when creating the string. size_t pthreadLength = std::min(name.size(), (size_t)15); char pthreadName[pthreadLength + 1]; memcpy(pthreadName, name.begin(), pthreadLength); pthreadName[pthreadLength] = '\0'; folly::setThreadName(pthread_self(), pthreadName); } void SwSwitch::publishInitTimes(std::string name, const float& time) {} void SwSwitch::publishStats() {} void SwSwitch::publishSwitchInfo(struct HwInitResult hwInitRet) {} void SwSwitch::logLinkStateEvent(PortID port, bool up) { std::string logMsg = folly::sformat("LinkState: Port {0} {1}", (uint16_t)port, (up ? "Up" : "Down")); VLOG(2) << logMsg; } }} // facebook::fboss <commit_msg>Don't pass the thread ID when calling folly::setThreadName for the current thread<commit_after>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/SwSwitch.h" #include <folly/Range.h> #include <folly/ThreadName.h> namespace facebook { namespace fboss { void SwSwitch::initThread(folly::StringPiece name) { // We need a null-terminated string to pass to folly::setThreadName(). // The pthread name can be at most 15 bytes long, so truncate it if necessary // when creating the string. size_t pthreadLength = std::min(name.size(), (size_t)15); char pthreadName[pthreadLength + 1]; memcpy(pthreadName, name.begin(), pthreadLength); pthreadName[pthreadLength] = '\0'; folly::setThreadName(pthreadName); } void SwSwitch::publishInitTimes(std::string name, const float& time) {} void SwSwitch::publishStats() {} void SwSwitch::publishSwitchInfo(struct HwInitResult hwInitRet) {} void SwSwitch::logLinkStateEvent(PortID port, bool up) { std::string logMsg = folly::sformat("LinkState: Port {0} {1}", (uint16_t)port, (up ? "Up" : "Down")); VLOG(2) << logMsg; } }} // facebook::fboss <|endoftext|>
<commit_before>#ifndef __ARCH_RUNTIME_COROUTINES_HPP__ #define __ARCH_RUNTIME_COROUTINES_HPP__ #ifndef NDEBUG #include <string> #endif #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/runtime_utils.hpp" #include "arch/runtime/context_switching.hpp" const size_t MAX_COROUTINE_STACK_SIZE = 8*1024*1024; const size_t CALLABLE_CUTOFF_SIZE = 128; int get_thread_id(); class coro_globals_t; class coro_action_t { public: virtual void run_action() = 0; coro_action_t() { } virtual ~coro_action_t() { } private: DISABLE_COPYING(coro_action_t); }; template<class Callable> class coro_action_instance_t : public coro_action_t { public: coro_action_instance_t(const Callable& callable) : callable_(callable) { } void run_action() { callable_(); } private: Callable callable_; }; /* A coro_t represents a fiber of execution within a thread. Create one with spawn_*(). Within a coroutine, call wait() to return control to the scheduler; the coroutine will be resumed when another fiber calls notify_*() on it. coro_t objects can switch threads with move_to_thread(), but it is recommended that you use on_thread_t for more safety. */ class coro_t : private linux_thread_message_t, public intrusive_list_node_t<coro_t>, public home_thread_mixin_t { public: friend bool is_coroutine_stack_overflow(void *); template<class Callable> static void spawn_now(const Callable &action) { get_and_init_coro(action)->notify_now(); } template<class Callable> static void spawn_sometime(const Callable &action) { get_and_init_coro(action)->notify_sometime(); } // TODO: spawn_later_ordered is usually what naive people want, // but it's such a long and onerous name. It should have the // shortest name. template<class Callable> static void spawn_later_ordered(const Callable &action) { get_and_init_coro(action)->notify_later_ordered(); } template<class Callable> static void spawn_on_thread(int thread, const Callable &action) { if (get_thread_id() == thread) { spawn_later_ordered(action); } else { do_on_thread(thread, boost::bind(&spawn_now, action)); } } // Use coro_t::spawn_*(boost::bind(...)) for spawning with parameters. /* `spawn()` and `notify()` are aliases for `spawn_later_ordered()` and `notify_later_ordered()`. They are deprecated and new code should not use them. */ template<class Callable> static void spawn(const Callable &action) { spawn_later_ordered(action); } template<class Callable> void assign(const Callable &action) { // Allocate the action inside this object, if possible, or the heap otherwise if (sizeof(Callable) >= CALLABLE_CUTOFF_SIZE) { action_ = new coro_action_instance_t<Callable>(action); action_on_heap = true; } else { action_ = new (action_data) coro_action_instance_t<Callable>(action); action_on_heap = false; } } /* Pauses the current coroutine until it is notified */ static void wait(); /* Gives another coroutine a chance to run, but schedules this coroutine to be run at some point in the future. Might not preserve order; two calls to `yield()` by different coroutines may return in a different order than they began in. */ static void yield(); /* Returns a pointer to the current coroutine, or `NULL` if we are not in a coroutine. */ static coro_t *self(); /* Transfers control immediately to the coroutine. Returns when the coroutine calls `wait()`. Note: `notify_now()` may become deprecated eventually. The original purpose was to provide better performance than could be achieved with `notify_later_ordered()`, but `notify_sometime()` is now filling that role instead. */ void notify_now(); /* Schedules the coroutine to be woken up eventually. Can be safely called from any thread. Returns immediately. Does not provide any ordering guarantees. If you don't need the ordering guarantees that `notify_later_ordered()` provides, use `notify_sometime()` instead. */ void notify_sometime(); // TODO: notify_later_ordered is usually what naive people want // and should get, but it's such a long and onerous name. It // should have the shortest name. /* Pushes the coroutine onto the event queue for the thread it's currently on, such that it will be run. This can safely be called from any thread. Returns immediately. If you call `notify_later_ordered()` on two coroutines that are on the same thread, they will run in the same order you call `notify_later_ordered()` in. */ void notify_later_ordered(); #ifndef NDEBUG // A unique identifier for this particular instance of coro_t over // the lifetime of the process. static int64_t selfname() { coro_t *self = coro_t::self(); return self ? self->selfname_number : 0; } #endif static void set_coroutine_stack_size(size_t size); artificial_stack_t* get_stack(); private: /* When called from within a coroutine, schedules the coroutine to be run on the given thread and then suspends the coroutine until that other thread picks it up again. Do not call this directly; use `on_thread_t` instead. */ friend class on_thread_t; static void move_to_thread(int thread); // Contructor sets up the stack, get_and_init_coro will load a function to be run // at which point the coroutine can be notified coro_t(); template<class Callable> static coro_t * get_and_init_coro(const Callable &action) { coro_t *coro = get_coro(); #ifndef NDEBUG coro->coroutine_info = __PRETTY_FUNCTION__; #endif coro->assign(action); return coro; } static coro_t * get_coro(); static void return_coro_to_free_list(coro_t *coro); artificial_stack_t stack; static void run(); friend struct coro_globals_t; ~coro_t(); virtual void on_thread_switch(); int current_thread_; // Sanity check variables bool notified_; bool waiting_; // Buffer to store callable-object data bool action_on_heap; coro_action_t *action_; char action_data[CALLABLE_CUTOFF_SIZE] __attribute__((aligned(sizeof(void*)))); #ifndef NDEBUG int64_t selfname_number; const char *coroutine_info; #endif DISABLE_COPYING(coro_t); }; /* Returns true if the given address is in the protection page of the current coroutine. */ bool is_coroutine_stack_overflow(void *addr); #ifndef NDEBUG /* If `ASSERT_NO_CORO_WAITING;` appears at the top of a block, then it is illegal to call `coro_t::wait()`, `coro_t::spawn_now()`, or `coro_t::notify_now()` within that block and any attempt to do so will be a fatal error. */ #define ASSERT_NO_CORO_WAITING assert_no_coro_waiting_t assert_no_coro_waiting_var(__FILE__, __LINE__) /* If `ASSERT_FINITE_CORO_WAITING;` appears at the top of a block, then code within that block may call `coro_t::spawn_now()` or `coro_t::notify_now()` but not `coro_t::wait()`. This is because `coro_t::spawn_now()` and `coro_t::notify_now()` will return control directly to the coroutine that called then. */ #define ASSERT_FINITE_CORO_WAITING assert_finite_coro_waiting_t assert_finite_coro_waiting_var(__FILE__, __LINE__) /* Implementation support for `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING` */ struct assert_no_coro_waiting_t { assert_no_coro_waiting_t(std::string, int); ~assert_no_coro_waiting_t(); }; struct assert_finite_coro_waiting_t { assert_finite_coro_waiting_t(std::string, int); ~assert_finite_coro_waiting_t(); }; #else // NDEBUG /* In release mode, these assertions are no-ops. */ #define ASSERT_NO_CORO_WAITING do { } while (0) #define ASSERT_FINITE_CORO_WAITING do { } while (0) #endif // NDEBUG #endif // __ARCH_RUNTIME_COROUTINES_HPP__ <commit_msg>moving coro_t public function to private, where it should be<commit_after>#ifndef __ARCH_RUNTIME_COROUTINES_HPP__ #define __ARCH_RUNTIME_COROUTINES_HPP__ #ifndef NDEBUG #include <string> #endif #include "errors.hpp" #include <boost/bind.hpp> #include "arch/runtime/runtime_utils.hpp" #include "arch/runtime/context_switching.hpp" const size_t MAX_COROUTINE_STACK_SIZE = 8*1024*1024; const size_t CALLABLE_CUTOFF_SIZE = 128; int get_thread_id(); class coro_globals_t; class coro_action_t { public: virtual void run_action() = 0; coro_action_t() { } virtual ~coro_action_t() { } private: DISABLE_COPYING(coro_action_t); }; template<class Callable> class coro_action_instance_t : public coro_action_t { public: coro_action_instance_t(const Callable& callable) : callable_(callable) { } void run_action() { callable_(); } private: Callable callable_; }; /* A coro_t represents a fiber of execution within a thread. Create one with spawn_*(). Within a coroutine, call wait() to return control to the scheduler; the coroutine will be resumed when another fiber calls notify_*() on it. coro_t objects can switch threads with move_to_thread(), but it is recommended that you use on_thread_t for more safety. */ class coro_t : private linux_thread_message_t, public intrusive_list_node_t<coro_t>, public home_thread_mixin_t { public: friend bool is_coroutine_stack_overflow(void *); template<class Callable> static void spawn_now(const Callable &action) { get_and_init_coro(action)->notify_now(); } template<class Callable> static void spawn_sometime(const Callable &action) { get_and_init_coro(action)->notify_sometime(); } // TODO: spawn_later_ordered is usually what naive people want, // but it's such a long and onerous name. It should have the // shortest name. template<class Callable> static void spawn_later_ordered(const Callable &action) { get_and_init_coro(action)->notify_later_ordered(); } template<class Callable> static void spawn_on_thread(int thread, const Callable &action) { if (get_thread_id() == thread) { spawn_later_ordered(action); } else { do_on_thread(thread, boost::bind(&spawn_now, action)); } } // Use coro_t::spawn_*(boost::bind(...)) for spawning with parameters. /* `spawn()` and `notify()` are aliases for `spawn_later_ordered()` and `notify_later_ordered()`. They are deprecated and new code should not use them. */ template<class Callable> static void spawn(const Callable &action) { spawn_later_ordered(action); } /* Pauses the current coroutine until it is notified */ static void wait(); /* Gives another coroutine a chance to run, but schedules this coroutine to be run at some point in the future. Might not preserve order; two calls to `yield()` by different coroutines may return in a different order than they began in. */ static void yield(); /* Returns a pointer to the current coroutine, or `NULL` if we are not in a coroutine. */ static coro_t *self(); /* Transfers control immediately to the coroutine. Returns when the coroutine calls `wait()`. Note: `notify_now()` may become deprecated eventually. The original purpose was to provide better performance than could be achieved with `notify_later_ordered()`, but `notify_sometime()` is now filling that role instead. */ void notify_now(); /* Schedules the coroutine to be woken up eventually. Can be safely called from any thread. Returns immediately. Does not provide any ordering guarantees. If you don't need the ordering guarantees that `notify_later_ordered()` provides, use `notify_sometime()` instead. */ void notify_sometime(); // TODO: notify_later_ordered is usually what naive people want // and should get, but it's such a long and onerous name. It // should have the shortest name. /* Pushes the coroutine onto the event queue for the thread it's currently on, such that it will be run. This can safely be called from any thread. Returns immediately. If you call `notify_later_ordered()` on two coroutines that are on the same thread, they will run in the same order you call `notify_later_ordered()` in. */ void notify_later_ordered(); #ifndef NDEBUG // A unique identifier for this particular instance of coro_t over // the lifetime of the process. static int64_t selfname() { coro_t *self = coro_t::self(); return self ? self->selfname_number : 0; } #endif static void set_coroutine_stack_size(size_t size); artificial_stack_t* get_stack(); private: /* When called from within a coroutine, schedules the coroutine to be run on the given thread and then suspends the coroutine until that other thread picks it up again. Do not call this directly; use `on_thread_t` instead. */ friend class on_thread_t; static void move_to_thread(int thread); // Contructor sets up the stack, get_and_init_coro will load a function to be run // at which point the coroutine can be notified coro_t(); template<class Callable> static coro_t * get_and_init_coro(const Callable &action) { coro_t *coro = get_coro(); #ifndef NDEBUG coro->coroutine_info = __PRETTY_FUNCTION__; #endif coro->assign(action); return coro; } template<class Callable> void assign(const Callable &action) { // Allocate the action inside this object, if possible, or the heap otherwise if (sizeof(Callable) >= CALLABLE_CUTOFF_SIZE) { action_ = new coro_action_instance_t<Callable>(action); action_on_heap = true; } else { action_ = new (action_data) coro_action_instance_t<Callable>(action); action_on_heap = false; } } static coro_t * get_coro(); static void return_coro_to_free_list(coro_t *coro); artificial_stack_t stack; static void run(); friend struct coro_globals_t; ~coro_t(); virtual void on_thread_switch(); int current_thread_; // Sanity check variables bool notified_; bool waiting_; // Buffer to store callable-object data bool action_on_heap; coro_action_t *action_; char action_data[CALLABLE_CUTOFF_SIZE] __attribute__((aligned(sizeof(void*)))); #ifndef NDEBUG int64_t selfname_number; const char *coroutine_info; #endif DISABLE_COPYING(coro_t); }; /* Returns true if the given address is in the protection page of the current coroutine. */ bool is_coroutine_stack_overflow(void *addr); #ifndef NDEBUG /* If `ASSERT_NO_CORO_WAITING;` appears at the top of a block, then it is illegal to call `coro_t::wait()`, `coro_t::spawn_now()`, or `coro_t::notify_now()` within that block and any attempt to do so will be a fatal error. */ #define ASSERT_NO_CORO_WAITING assert_no_coro_waiting_t assert_no_coro_waiting_var(__FILE__, __LINE__) /* If `ASSERT_FINITE_CORO_WAITING;` appears at the top of a block, then code within that block may call `coro_t::spawn_now()` or `coro_t::notify_now()` but not `coro_t::wait()`. This is because `coro_t::spawn_now()` and `coro_t::notify_now()` will return control directly to the coroutine that called then. */ #define ASSERT_FINITE_CORO_WAITING assert_finite_coro_waiting_t assert_finite_coro_waiting_var(__FILE__, __LINE__) /* Implementation support for `ASSERT_NO_CORO_WAITING` and `ASSERT_FINITE_CORO_WAITING` */ struct assert_no_coro_waiting_t { assert_no_coro_waiting_t(std::string, int); ~assert_no_coro_waiting_t(); }; struct assert_finite_coro_waiting_t { assert_finite_coro_waiting_t(std::string, int); ~assert_finite_coro_waiting_t(); }; #else // NDEBUG /* In release mode, these assertions are no-ops. */ #define ASSERT_NO_CORO_WAITING do { } while (0) #define ASSERT_FINITE_CORO_WAITING do { } while (0) #endif // NDEBUG #endif // __ARCH_RUNTIME_COROUTINES_HPP__ <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 <string.h> // for strdup #include <algorithm> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DEFINE_int32(paddle_num_threads, 1, "Number of threads for each paddle instance."); namespace paddle { namespace framework { std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(10) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitDevices(bool init_p2p) { /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { int count = platform::GetCUDADeviceCount(); for (int i = 0; i < count; ++i) { devices.push_back(i); } } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; int count = 0; #ifdef PADDLE_WITH_CUDA try { count = platform::GetCUDADeviceCount(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif for (size_t i = 0; i < devices.size(); ++i) { if (devices[i] >= count || devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); // windows has no support for openblas multi-thread #ifdef _WIN32 if (FLAGS_paddle_num_threads > 1) { FLAGS_paddle_num_threads = 1; } #endif #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::jit::MayIUse(platform::jit::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::jit::MayIUse(platform::jit::avx512f)) { if (platform::jit::MayIUse(platform::jit::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::jit::MayIUse(platform::jit::avx2)) { if (platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); #endif } } // namespace framework } // namespace paddle <commit_msg>print output log warning (#14497)<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 <string.h> // for strdup #include <algorithm> #include <stdexcept> #include <string> #include "paddle/fluid/framework/operator.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/cpu_info.h" #ifdef PADDLE_WITH_CUDA #include "paddle/fluid/platform/cuda_device_guard.h" #endif #include "paddle/fluid/platform/device_context.h" #include "paddle/fluid/platform/init.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/string/piece.h" DEFINE_int32(paddle_num_threads, 1, "Number of threads for each paddle instance."); namespace paddle { namespace framework { std::once_flag gflags_init_flag; std::once_flag p2p_init_flag; void InitGflags(std::vector<std::string> argv) { std::call_once(gflags_init_flag, [&]() { FLAGS_logtostderr = true; argv.insert(argv.begin(), "dummy"); int argc = argv.size(); char **arr = new char *[argv.size()]; std::string line; for (size_t i = 0; i < argv.size(); i++) { arr[i] = &argv[i][0]; line += argv[i]; line += ' '; } google::ParseCommandLineFlags(&argc, &arr, true); VLOG(10) << "Init commandline: " << line; }); } void InitP2P(std::vector<int> devices) { #ifdef PADDLE_WITH_CUDA std::call_once(p2p_init_flag, [&]() { int count = devices.size(); for (int i = 0; i < count; ++i) { for (int j = 0; j < count; ++j) { if (devices[i] == devices[j]) continue; int can_acess = -1; PADDLE_ENFORCE( cudaDeviceCanAccessPeer(&can_acess, devices[i], devices[j]), "Failed to test P2P access."); if (can_acess != 1) { LOG(WARNING) << "Cannot enable P2P access from " << devices[i] << " to " << devices[j]; } else { platform::CUDADeviceGuard guard(devices[i]); cudaDeviceEnablePeerAccess(devices[j], 0); } } } }); #endif } void InitDevices(bool init_p2p) { /*Init all available devices by default */ std::vector<int> devices; #ifdef PADDLE_WITH_CUDA try { int count = platform::GetCUDADeviceCount(); for (int i = 0; i < count; ++i) { devices.push_back(i); } } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif InitDevices(init_p2p, devices); } void InitDevices(bool init_p2p, const std::vector<int> devices) { std::vector<platform::Place> places; int count = 0; #ifdef PADDLE_WITH_CUDA try { count = platform::GetCUDADeviceCount(); } catch (const std::exception &exp) { LOG(WARNING) << "Compiled with WITH_GPU, but no GPU found in runtime."; } #endif for (size_t i = 0; i < devices.size(); ++i) { if (devices[i] >= count || devices[i] < 0) { LOG(WARNING) << "Invalid devices id."; continue; } places.emplace_back(platform::CUDAPlace(devices[i])); } if (init_p2p) { InitP2P(devices); } places.emplace_back(platform::CPUPlace()); platform::DeviceContextPool::Init(places); // windows has no support for openblas multi-thread #ifdef _WIN32 if (FLAGS_paddle_num_threads > 1) { FLAGS_paddle_num_threads = 1; } #endif #ifndef PADDLE_WITH_MKLDNN platform::SetNumThreads(FLAGS_paddle_num_threads); #endif #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__OSX__) if (platform::jit::MayIUse(platform::jit::avx)) { #ifndef __AVX__ LOG(WARNING) << "AVX is available, Please re-compile on local machine"; #endif } // Throw some informations when CPU instructions mismatch. #define AVX_GUIDE(compiletime, runtime) \ LOG(FATAL) \ << "This version is compiled on higher instruction(" #compiletime \ ") system, you may encounter illegal instruction error running on" \ " your local CPU machine. Please reinstall the " #runtime \ " version or compile from source code." #ifdef __AVX512F__ if (!platform::jit::MayIUse(platform::jit::avx512f)) { if (platform::jit::MayIUse(platform::jit::avx2)) { AVX_GUIDE(AVX512, AVX2); } else if (platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX512, AVX); } else { AVX_GUIDE(AVX512, NonAVX); } } #endif #ifdef __AVX2__ if (!platform::jit::MayIUse(platform::jit::avx2)) { if (platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX2, AVX); } else { AVX_GUIDE(AVX2, NonAVX); } } #endif #ifdef __AVX__ if (!platform::jit::MayIUse(platform::jit::avx)) { AVX_GUIDE(AVX, NonAVX); } #endif #undef AVX_GUIDE #endif } void InitGLOG(const std::string &prog_name) { // glog will not hold the ARGV[0] inside. // Use strdup to alloc a new string. google::InitGoogleLogging(strdup(prog_name.c_str())); #ifndef _WIN32 google::InstallFailureSignalHandler(); #endif } } // namespace framework } // namespace paddle <|endoftext|>
<commit_before>#ifndef ENTT_SIGNAL_DELEGATE_HPP #define ENTT_SIGNAL_DELEGATE_HPP #include <tuple> #include <cstddef> #include <utility> #include <functional> #include <type_traits> #include "../config/config.h" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename Ret, typename... Args> auto function_pointer(Ret(*)(Args...)) -> Ret(*)(Args...); template<typename Ret, typename Type, typename... Args, typename Other> auto function_pointer(Ret(*)(Type, Args...), Other &&) -> Ret(*)(Args...); template<typename Class, typename Ret, typename... Args, typename... Other> auto function_pointer(Ret(Class:: *)(Args...), Other &&...) -> Ret(*)(Args...); template<typename Class, typename Ret, typename... Args, typename... Other> auto function_pointer(Ret(Class:: *)(Args...) const, Other &&...) -> Ret(*)(Args...); template<typename Class, typename Type, typename... Other> auto function_pointer(Type Class:: *, Other &&...) -> Type(*)(); template<typename... Type> using function_pointer_t = decltype(internal::function_pointer(std::declval<Type>()...)); template<typename... Class, typename Ret, typename... Args> constexpr auto index_sequence_for(Ret(*)(Args...)) { return std::index_sequence_for<Class..., Args...>{}; } } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ /*! @brief Used to wrap a function or a member of a specified type. */ template<auto> struct connect_arg_t {}; /*! @brief Constant of type connect_arg_t used to disambiguate calls. */ template<auto Func> constexpr connect_arg_t<Func> connect_arg{}; /** * @brief Basic delegate implementation. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. */ template<typename> class delegate; /** * @brief Utility class to use to send around functions and members. * * Unmanaged delegate for function pointers and members. Users of this class are * in charge of disconnecting instances before deleting them. * * A delegate can be used as a general purpose invoker without memory overhead * for free functions possibly with payloads and bound or unbound members. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. */ template<typename Ret, typename... Args> class delegate<Ret(Args...)> { using proto_fn_type = Ret(const void *, Args...); template<auto Candidate, std::size_t... Index> auto wrap(std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); return Ret(std::invoke(Candidate, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } template<auto Candidate, typename Type, std::size_t... Index> auto wrap(Type &value_or_instance, std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *payload, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, *curr, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } template<auto Candidate, typename Type, std::size_t... Index> auto wrap(Type *value_or_instance, std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *payload, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, curr, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } public: /*! @brief Function type of the delegate. */ using function_type = Ret(Args...); /*! @brief Default constructor. */ delegate() ENTT_NOEXCEPT : fn{nullptr}, data{nullptr} {} /** * @brief Constructs a delegate and connects a free function or an unbound * member. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> delegate(connect_arg_t<Candidate>) ENTT_NOEXCEPT : delegate{} { connect<Candidate>(); } /** * @brief Constructs a delegate and connects a free function with payload or * a bound member. * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid object that fits the purpose. */ template<auto Candidate, typename Type> delegate(connect_arg_t<Candidate>, Type &&value_or_instance) ENTT_NOEXCEPT : delegate{} { connect<Candidate>(std::forward<Type>(value_or_instance)); } /** * @brief Connects a free function or an unbound member to a delegate. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> void connect() ENTT_NOEXCEPT { data = nullptr; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) { fn = [](const void *, Args... args) -> Ret { return Ret(std::invoke(Candidate, std::forward<Args>(args)...)); }; } else if constexpr(std::is_member_pointer_v<decltype(Candidate)>) { fn = wrap<Candidate>(internal::index_sequence_for<std::tuple_element_t<0, std::tuple<Args...>>>(internal::function_pointer_t<decltype(Candidate)>{})); } else { fn = wrap<Candidate>(internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate)>{})); } } /** * @brief Connects a free function with payload or a bound member to a * delegate. * * The delegate isn't responsible for the connected object or the payload. * Users must always guarantee that the lifetime of the instance overcomes * the one of the delegate.<br/> * When used to connect a free function with payload, its signature must be * such that the instance is the first argument before the ones used to * define the delegate itself. * * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid reference that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type &value_or_instance) ENTT_NOEXCEPT { data = &value_or_instance; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Type &, Args...>) { fn = [](const void *payload, Args... args) -> Ret { Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, *curr, std::forward<Args>(args)...)); }; } else { fn = wrap<Candidate>(value_or_instance, internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate), Type>{})); } } /** * @brief Connects a free function with payload or a bound member to a * delegate. * * @sa connect(Type &) * * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type *value_or_instance) ENTT_NOEXCEPT { data = value_or_instance; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Type *, Args...>) { fn = [](const void *payload, Args... args) -> Ret { Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, curr, std::forward<Args>(args)...)); }; } else { fn = wrap<Candidate>(value_or_instance, internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate), Type>{})); } } /** * @brief Resets a delegate. * * After a reset, a delegate cannot be invoked anymore. */ void reset() ENTT_NOEXCEPT { fn = nullptr; data = nullptr; } /** * @brief Returns the instance or the payload linked to a delegate, if any. * @return An opaque pointer to the underlying data. */ const void * instance() const ENTT_NOEXCEPT { return data; } /** * @brief Triggers a delegate. * * The delegate invokes the underlying function and returns the result. * * @warning * Attempting to trigger an invalid delegate results in undefined * behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * delegate has not yet been set. * * @param args Arguments to use to invoke the underlying function. * @return The value returned by the underlying function. */ Ret operator()(Args... args) const { ENTT_ASSERT(fn); return fn(data, std::forward<Args>(args)...); } /** * @brief Checks whether a delegate actually stores a listener. * @return False if the delegate is empty, true otherwise. */ explicit operator bool() const ENTT_NOEXCEPT { // no need to test also data return fn; } /** * @brief Compares the contents of two delegates. * @param other Delegate with which to compare. * @return False if the two contents differ, true otherwise. */ bool operator==(const delegate<Ret(Args...)> &other) const ENTT_NOEXCEPT { return fn == other.fn && data == other.data; } private: proto_fn_type *fn; const void *data; }; /** * @brief Compares the contents of two delegates. * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. * @param lhs A valid delegate object. * @param rhs A valid delegate object. * @return True if the two contents differ, false otherwise. */ template<typename Ret, typename... Args> bool operator!=(const delegate<Ret(Args...)> &lhs, const delegate<Ret(Args...)> &rhs) ENTT_NOEXCEPT { return !(lhs == rhs); } /** * @brief Deduction guide. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> delegate(connect_arg_t<Candidate>) ENTT_NOEXCEPT -> delegate<std::remove_pointer_t<internal::function_pointer_t<decltype(Candidate)>>>; /** * @brief Deduction guide. * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. */ template<auto Candidate, typename Type> delegate(connect_arg_t<Candidate>, Type &&) ENTT_NOEXCEPT -> delegate<std::remove_pointer_t<internal::function_pointer_t<decltype(Candidate), Type>>>; } #endif <commit_msg>delegate: suppress warnings on parameters used for tag dispatching<commit_after>#ifndef ENTT_SIGNAL_DELEGATE_HPP #define ENTT_SIGNAL_DELEGATE_HPP #include <tuple> #include <cstddef> #include <utility> #include <functional> #include <type_traits> #include "../config/config.h" namespace entt { /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { template<typename Ret, typename... Args> auto function_pointer(Ret(*)(Args...)) -> Ret(*)(Args...); template<typename Ret, typename Type, typename... Args, typename Other> auto function_pointer(Ret(*)(Type, Args...), Other &&) -> Ret(*)(Args...); template<typename Class, typename Ret, typename... Args, typename... Other> auto function_pointer(Ret(Class:: *)(Args...), Other &&...) -> Ret(*)(Args...); template<typename Class, typename Ret, typename... Args, typename... Other> auto function_pointer(Ret(Class:: *)(Args...) const, Other &&...) -> Ret(*)(Args...); template<typename Class, typename Type, typename... Other> auto function_pointer(Type Class:: *, Other &&...) -> Type(*)(); template<typename... Type> using function_pointer_t = decltype(internal::function_pointer(std::declval<Type>()...)); template<typename... Class, typename Ret, typename... Args> constexpr auto index_sequence_for(Ret(*)(Args...)) { return std::index_sequence_for<Class..., Args...>{}; } } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ /*! @brief Used to wrap a function or a member of a specified type. */ template<auto> struct connect_arg_t {}; /*! @brief Constant of type connect_arg_t used to disambiguate calls. */ template<auto Func> constexpr connect_arg_t<Func> connect_arg{}; /** * @brief Basic delegate implementation. * * Primary template isn't defined on purpose. All the specializations give a * compile-time error unless the template parameter is a function type. */ template<typename> class delegate; /** * @brief Utility class to use to send around functions and members. * * Unmanaged delegate for function pointers and members. Users of this class are * in charge of disconnecting instances before deleting them. * * A delegate can be used as a general purpose invoker without memory overhead * for free functions possibly with payloads and bound or unbound members. * * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. */ template<typename Ret, typename... Args> class delegate<Ret(Args...)> { using proto_fn_type = Ret(const void *, Args...); template<auto Candidate, std::size_t... Index> auto wrap(std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); return Ret(std::invoke(Candidate, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } template<auto Candidate, typename Type, std::size_t... Index> auto wrap(Type &, std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *payload, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, *curr, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } template<auto Candidate, typename Type, std::size_t... Index> auto wrap(Type *, std::index_sequence<Index...>) ENTT_NOEXCEPT { return [](const void *payload, Args... args) -> Ret { const auto arguments = std::forward_as_tuple(std::forward<Args>(args)...); Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, curr, std::forward<std::tuple_element_t<Index, std::tuple<Args...>>>(std::get<Index>(arguments))...)); }; } public: /*! @brief Function type of the delegate. */ using function_type = Ret(Args...); /*! @brief Default constructor. */ delegate() ENTT_NOEXCEPT : fn{nullptr}, data{nullptr} {} /** * @brief Constructs a delegate and connects a free function or an unbound * member. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> delegate(connect_arg_t<Candidate>) ENTT_NOEXCEPT : delegate{} { connect<Candidate>(); } /** * @brief Constructs a delegate and connects a free function with payload or * a bound member. * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid object that fits the purpose. */ template<auto Candidate, typename Type> delegate(connect_arg_t<Candidate>, Type &&value_or_instance) ENTT_NOEXCEPT : delegate{} { connect<Candidate>(std::forward<Type>(value_or_instance)); } /** * @brief Connects a free function or an unbound member to a delegate. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> void connect() ENTT_NOEXCEPT { data = nullptr; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) { fn = [](const void *, Args... args) -> Ret { return Ret(std::invoke(Candidate, std::forward<Args>(args)...)); }; } else if constexpr(std::is_member_pointer_v<decltype(Candidate)>) { fn = wrap<Candidate>(internal::index_sequence_for<std::tuple_element_t<0, std::tuple<Args...>>>(internal::function_pointer_t<decltype(Candidate)>{})); } else { fn = wrap<Candidate>(internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate)>{})); } } /** * @brief Connects a free function with payload or a bound member to a * delegate. * * The delegate isn't responsible for the connected object or the payload. * Users must always guarantee that the lifetime of the instance overcomes * the one of the delegate.<br/> * When used to connect a free function with payload, its signature must be * such that the instance is the first argument before the ones used to * define the delegate itself. * * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid reference that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type &value_or_instance) ENTT_NOEXCEPT { data = &value_or_instance; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Type &, Args...>) { fn = [](const void *payload, Args... args) -> Ret { Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, *curr, std::forward<Args>(args)...)); }; } else { fn = wrap<Candidate>(value_or_instance, internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate), Type>{})); } } /** * @brief Connects a free function with payload or a bound member to a * delegate. * * @sa connect(Type &) * * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. * @param value_or_instance A valid pointer that fits the purpose. */ template<auto Candidate, typename Type> void connect(Type *value_or_instance) ENTT_NOEXCEPT { data = value_or_instance; if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Type *, Args...>) { fn = [](const void *payload, Args... args) -> Ret { Type *curr = static_cast<Type *>(const_cast<std::conditional_t<std::is_const_v<Type>, const void *, void *>>(payload)); return Ret(std::invoke(Candidate, curr, std::forward<Args>(args)...)); }; } else { fn = wrap<Candidate>(value_or_instance, internal::index_sequence_for(internal::function_pointer_t<decltype(Candidate), Type>{})); } } /** * @brief Resets a delegate. * * After a reset, a delegate cannot be invoked anymore. */ void reset() ENTT_NOEXCEPT { fn = nullptr; data = nullptr; } /** * @brief Returns the instance or the payload linked to a delegate, if any. * @return An opaque pointer to the underlying data. */ const void * instance() const ENTT_NOEXCEPT { return data; } /** * @brief Triggers a delegate. * * The delegate invokes the underlying function and returns the result. * * @warning * Attempting to trigger an invalid delegate results in undefined * behavior.<br/> * An assertion will abort the execution at runtime in debug mode if the * delegate has not yet been set. * * @param args Arguments to use to invoke the underlying function. * @return The value returned by the underlying function. */ Ret operator()(Args... args) const { ENTT_ASSERT(fn); return fn(data, std::forward<Args>(args)...); } /** * @brief Checks whether a delegate actually stores a listener. * @return False if the delegate is empty, true otherwise. */ explicit operator bool() const ENTT_NOEXCEPT { // no need to test also data return fn; } /** * @brief Compares the contents of two delegates. * @param other Delegate with which to compare. * @return False if the two contents differ, true otherwise. */ bool operator==(const delegate<Ret(Args...)> &other) const ENTT_NOEXCEPT { return fn == other.fn && data == other.data; } private: proto_fn_type *fn; const void *data; }; /** * @brief Compares the contents of two delegates. * @tparam Ret Return type of a function type. * @tparam Args Types of arguments of a function type. * @param lhs A valid delegate object. * @param rhs A valid delegate object. * @return True if the two contents differ, false otherwise. */ template<typename Ret, typename... Args> bool operator!=(const delegate<Ret(Args...)> &lhs, const delegate<Ret(Args...)> &rhs) ENTT_NOEXCEPT { return !(lhs == rhs); } /** * @brief Deduction guide. * @tparam Candidate Function or member to connect to the delegate. */ template<auto Candidate> delegate(connect_arg_t<Candidate>) ENTT_NOEXCEPT -> delegate<std::remove_pointer_t<internal::function_pointer_t<decltype(Candidate)>>>; /** * @brief Deduction guide. * @tparam Candidate Function or member to connect to the delegate. * @tparam Type Type of class or type of payload. */ template<auto Candidate, typename Type> delegate(connect_arg_t<Candidate>, Type &&) ENTT_NOEXCEPT -> delegate<std::remove_pointer_t<internal::function_pointer_t<decltype(Candidate), Type>>>; } #endif <|endoftext|>
<commit_before>/* * substitutionMap.cpp * */ #include "SubstitutionMap.h" #include "simplifier.h" #include "../AST/ArrayTransformer.h" namespace BEEV { SubstitutionMap::~SubstitutionMap() { delete SolverMap; } // if false. Don't simplify while creating the substitution map. // This makes it easier to spot how long is spent in the simplifier. const bool simplify_during_create_subM = false; //if a is READ(Arr,const) and b is BVCONST then return 1. //if a is a symbol SYMBOL, return 1. //if b is READ(Arr,const) and a is BVCONST then return -1 // if b is a symbol return -1. // //else return 0 by default int TermOrder(const ASTNode& a, const ASTNode& b) { const Kind k1 = a.GetKind(); const Kind k2 = b.GetKind(); if (k1 == SYMBOL) return 1; if (k2 == SYMBOL) return -1; //a is of the form READ(Arr,const), and b is const, or if ((k1 == READ && a[0].GetKind() == SYMBOL && a[1].GetKind() == BVCONST && (k2 == BVCONST))) return 1; //b is of the form READ(Arr,const), and a is const, or //b is of the form var, and a is const if ((k1 == BVCONST) && ((k2 == READ && b[0].GetKind() == SYMBOL && b[1].GetKind() == BVCONST))) return -1; return 0; } //End of TermOrder() //This finds conjuncts which are one of: (= SYMBOL BVCONST), (= BVCONST (READ SYMBOL BVCONST)), // (IFF SYMBOL TRUE), (IFF SYMBOL FALSE), (IFF SYMBOL SYMBOL), (=SYMBOL SYMBOL) // or (=SYMBOL BVCONST). // It tries to remove the conjunct, storing it in the substitutionmap. It replaces it in the // formula by true. // The bvsolver puts expressions of the form (= SYMBOL TERM) into the solverMap. ASTNode SubstitutionMap::CreateSubstitutionMap(const ASTNode& a, ArrayTransformer*at) { if (!bm->UserFlags.wordlevel_solve_flag) return a; ASTNode output; //if the variable has been solved for, then simply return it if (CheckSubstitutionMap(a, output)) return output; if (!alreadyVisited.insert(a.GetNodeNum()).second) { return a; } output = a; //traverse a and populate the SubstitutionMap const Kind k = a.GetKind(); if (SYMBOL == k && BOOLEAN_TYPE == a.GetType()) { bool updated = UpdateSubstitutionMap(a, ASTTrue); output = updated ? ASTTrue : a; } else if (NOT == k && SYMBOL == a[0].GetKind()) { bool updated = UpdateSubstitutionMap(a[0], ASTFalse); output = updated ? ASTTrue : a; } else if (IFF == k || EQ == k) { ASTVec c = a.GetChildren(); if (simplify_during_create_subM) SortByArith(c); if (c[0] == c[1]) return ASTTrue; ASTNode c1; if (EQ == k) c1 = simplify_during_create_subM ? simp->SimplifyTerm(c[1]) : c[1]; else// (IFF == k ) c1= simplify_during_create_subM ? simp->SimplifyFormula_NoRemoveWrites(c[1], false) : c[1]; bool updated = UpdateSubstitutionMap(c[0], c1); output = updated ? ASTTrue : a; if (updated) { //fill the arrayname readindices vector if e0 is a //READ(Arr,index) and index is a BVCONST int to; if ((to =TermOrder(c[0],c1))==1 && c[0].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[0], c1); else if (to ==-1 && c1.GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c1,c[0]); } } else if (XOR == k) { if (a.Degree() !=2) return output; int to = TermOrder(a[0],a[1]); if (0 == to) return output; ASTNode symbol,rhs; if (to==1) { symbol = a[0]; rhs = a[1]; } else { symbol = a[0]; rhs = a[1]; } assert(symbol.GetKind() == SYMBOL); // If either side is already solved for. if (CheckSubstitutionMap(symbol) || CheckSubstitutionMap(rhs)) {} else if (UpdateSolverMap(symbol, bm->CreateNode(NOT, rhs))) output = ASTTrue; } else if (AND == k) { const ASTVec& c = a.GetChildren(); ASTVec o; o.reserve(c.size()); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { simp->UpdateAlwaysTrueFormSet(*it); ASTNode aaa = CreateSubstitutionMap(*it,at); if (ASTTrue != aaa) { if (ASTFalse == aaa) return ASTFalse; else o.push_back(aaa); } } if (o.size() == 0) output = ASTTrue; else if (o.size() == 1) output = o[0]; else if (o != c) output = bm->CreateNode(AND, o); else output = a; } return output; } //end of CreateSubstitutionMap() ASTNode SubstitutionMap::applySubstitutionMap(const ASTNode& n) { bm->GetRunTimes()->start(RunTimes::ApplyingSubstitutions); ASTNodeMap cache; SimplifyingNodeFactory nf(*bm->hashingNodeFactory, *bm); ASTNode result = replace(n,*SolverMap,cache,&nf, false); bm->GetRunTimes()->stop(RunTimes::ApplyingSubstitutions); return result; } ASTNode SubstitutionMap::applySubstitutionMapUntilArrays(const ASTNode& n) { bm->GetRunTimes()->start(RunTimes::ApplyingSubstitutions); ASTNodeMap cache; SimplifyingNodeFactory nf(*bm->hashingNodeFactory, *bm); ASTNode result = replace(n,*SolverMap,cache,&nf, true); bm->GetRunTimes()->stop(RunTimes::ApplyingSubstitutions); return result; } ASTNode SubstitutionMap::replace(const ASTNode& n, ASTNodeMap& fromTo, ASTNodeMap& cache, NodeFactory * nf) { return replace(n,fromTo,cache,nf,false); } // NOTE the fromTo map is changed as we traverse downwards. // We call replace on each of the things in the fromTo map aswell. // This is in case we have a fromTo map: (x maps to y), (y maps to 5), // and pass the replace() function the node "x" to replace, then it // will return 5, rather than y. // NB: You can't use this to map from "5" to the symbol "x" say. // It's optimised for the symbol to something case. ASTNode SubstitutionMap::replace(const ASTNode& n, ASTNodeMap& fromTo, ASTNodeMap& cache, NodeFactory * nf, bool stopAtArrays) { const Kind k = n.GetKind(); if (k == BVCONST || k == TRUE || k == FALSE) return n; ASTNodeMap::const_iterator it; if ((it = cache.find(n)) != cache.end()) return it->second; if ((it = fromTo.find(n)) != fromTo.end()) { const ASTNode& r = it->second; assert(r.GetIndexWidth() == n.GetIndexWidth()); ASTNode replaced = replace(r, fromTo, cache,nf,stopAtArrays); if (replaced != r) fromTo[n] = replaced; cache.insert(make_pair(n,replaced)); return replaced; } // These can't be created like regular nodes are if (k == SYMBOL ) return n; const unsigned int indexWidth = n.GetIndexWidth(); if (stopAtArrays && indexWidth > 0) // is an array. { return n; } const ASTVec& children = n.GetChildren(); assert(children.size() > 0); // Should have no leaves left here. ASTVec new_children; new_children.reserve(children.size()); for (ASTVec::const_iterator it = children.begin(); it != children.end(); it++) { new_children.push_back(replace(*it, fromTo, cache,nf,stopAtArrays)); } assert(new_children.size() == children.size()); // This code short-cuts if the children are the same. Nodes with the same children, // won't have necessarily given the same node if the simplifyingNodeFactory is enabled // now, but wasn't enabled when the node was created. Shortcutting saves lots of time. if (new_children == children) { cache.insert(make_pair(n,n)); return n; } ASTNode result; const unsigned int valueWidth = n.GetValueWidth(); if (valueWidth == 0 ) // n.GetType() == BOOLEAN_TYPE { result = nf->CreateNode(k, new_children); } else { // If the index and value width aren't saved, they are reset sometimes (??) result = nf->CreateArrayTerm(k,indexWidth, valueWidth,new_children); } assert(result.GetValueWidth() == valueWidth); assert(result.GetIndexWidth() == indexWidth); cache.insert(make_pair(n,result)); return result; } // Adds to the dependency graph that n0 depends on the variables in n1. // It's not the transitive closure of the dependencies. Just the variables in the expression "n1". // This is only needed as long as all the substitution rules haven't been written through. void SubstitutionMap::buildDepends(const ASTNode& n0, const ASTNode& n1) { if (n0.GetKind() != SYMBOL) return; if (n1.isConstant()) return; vector<Symbols*> av; vars.VarSeenInTerm(vars.getSymbol(n1), rhs_visited, rhs, av); sort(av.begin(), av.end()); for (int i =0; i < av.size();i++) { if (i!=0 && av[i] == av[i-1]) continue; // Treat it like a set of Symbol* in effect. ASTNodeSet* sym = (vars.TermsAlreadySeenMap.find(av[i])->second); if(rhsAlreadyAdded.find(sym) != rhsAlreadyAdded.end()) continue; rhsAlreadyAdded.insert(sym); //cout << loopCount++ << " "; //cout << "initial" << rhs.size() << " Adding: " <<sym->size(); rhs.insert(sym->begin(), sym->end()); //cout << "final:" << rhs.size(); //cout << "added:" << sym << endl; } assert (dependsOn.find(n0) == dependsOn.end()); dependsOn.insert(make_pair(n0,vars.getSymbol(n1))); } // Take the transitive closure of the varsToCheck. Storing the result in visited. void SubstitutionMap::loops_helper(const set<ASTNode>& varsToCheck, set<ASTNode>& visited) { set<ASTNode>::const_iterator visitedIt = visited.begin(); set<ASTNode> toVisit; vector<ASTNode> visitedN; // for each variable. for (set<ASTNode>::const_iterator varIt = varsToCheck.begin(); varIt != varsToCheck.end(); varIt++) { while (*visitedIt < *varIt && visitedIt != visited.end()) visitedIt++; if (*visitedIt == *varIt) continue; visitedN.push_back(*varIt); DependsType::iterator it; if ((it = dependsOn.find(*varIt)) != dependsOn.end()) { Symbols* s= it->second; bool destruct; ASTNodeSet* varsSeen = vars.SetofVarsSeenInTerm(s,destruct); toVisit.insert(varsSeen->begin(), varsSeen->end()); if (destruct) delete varsSeen; } } visited.insert(visitedN.begin(), visitedN.end()); visitedN.clear(); if (toVisit.size() !=0) loops_helper(toVisit, visited); } // If n0 is replaced by n1 in the substitution map. Will it cause a loop? // i.e. will the dependency graph be an acyclic graph still. // For example, if we have x = F(y,z,w), it would make the substitutionMap loop // if there's already z = F(x). bool SubstitutionMap::loops(const ASTNode& n0, const ASTNode& n1) { if (n0.GetKind() != SYMBOL) return false; // sometimes this function is called with constants on the lhs. if (n1.isConstant()) return false; // constants contain no variables. Can't loop. // We are adding an edge FROM n0, so unless there is already an edge TO n0, // there is no change it can loop. Unless adding this would add a TO and FROM edge. if (rhs.find(n0) == rhs.end()) { return vars.VarSeenInTerm(n0,n1); } if (n1.GetKind() == SYMBOL && dependsOn.find(n1) == dependsOn.end() ) return false; // The rhs is a symbol and doesn't appear. if (debug_substn) cout << loopCount++ << endl; bool destruct = true; ASTNodeSet* dependN = vars.SetofVarsSeenInTerm(n1,destruct); if (debug_substn) { cout << n0 << " " << n1.GetNodeNum(); //<< " Expression size:" << bm->NodeSize(n1,true); cout << "Variables in expression: "<< dependN->size() << endl; } set<ASTNode> depend(dependN->begin(), dependN->end()); if (destruct) delete dependN; set<ASTNode> visited; loops_helper(depend,visited); bool loops = visited.find(n0) != visited.end(); if (debug_substn) cout << "Visited:" << visited.size() << "Loops:" << loops << endl; return (loops); } }; <commit_msg>Make applySubstitutionMap idempotent (I hope).<commit_after>/* * substitutionMap.cpp * */ #include "SubstitutionMap.h" #include "simplifier.h" #include "../AST/ArrayTransformer.h" namespace BEEV { SubstitutionMap::~SubstitutionMap() { delete SolverMap; } // if false. Don't simplify while creating the substitution map. // This makes it easier to spot how long is spent in the simplifier. const bool simplify_during_create_subM = false; //if a is READ(Arr,const) and b is BVCONST then return 1. //if a is a symbol SYMBOL, return 1. //if b is READ(Arr,const) and a is BVCONST then return -1 // if b is a symbol return -1. // //else return 0 by default int TermOrder(const ASTNode& a, const ASTNode& b) { const Kind k1 = a.GetKind(); const Kind k2 = b.GetKind(); if (k1 == SYMBOL) return 1; if (k2 == SYMBOL) return -1; //a is of the form READ(Arr,const), and b is const, or if ((k1 == READ && a[0].GetKind() == SYMBOL && a[1].GetKind() == BVCONST && (k2 == BVCONST))) return 1; //b is of the form READ(Arr,const), and a is const, or //b is of the form var, and a is const if ((k1 == BVCONST) && ((k2 == READ && b[0].GetKind() == SYMBOL && b[1].GetKind() == BVCONST))) return -1; return 0; } //End of TermOrder() //This finds conjuncts which are one of: (= SYMBOL BVCONST), (= BVCONST (READ SYMBOL BVCONST)), // (IFF SYMBOL TRUE), (IFF SYMBOL FALSE), (IFF SYMBOL SYMBOL), (=SYMBOL SYMBOL) // or (=SYMBOL BVCONST). // It tries to remove the conjunct, storing it in the substitutionmap. It replaces it in the // formula by true. // The bvsolver puts expressions of the form (= SYMBOL TERM) into the solverMap. ASTNode SubstitutionMap::CreateSubstitutionMap(const ASTNode& a, ArrayTransformer*at) { if (!bm->UserFlags.wordlevel_solve_flag) return a; ASTNode output; //if the variable has been solved for, then simply return it if (CheckSubstitutionMap(a, output)) return output; if (!alreadyVisited.insert(a.GetNodeNum()).second) { return a; } output = a; //traverse a and populate the SubstitutionMap const Kind k = a.GetKind(); if (SYMBOL == k && BOOLEAN_TYPE == a.GetType()) { bool updated = UpdateSubstitutionMap(a, ASTTrue); output = updated ? ASTTrue : a; } else if (NOT == k && SYMBOL == a[0].GetKind()) { bool updated = UpdateSubstitutionMap(a[0], ASTFalse); output = updated ? ASTTrue : a; } else if (IFF == k || EQ == k) { ASTVec c = a.GetChildren(); if (simplify_during_create_subM) SortByArith(c); if (c[0] == c[1]) return ASTTrue; ASTNode c1; if (EQ == k) c1 = simplify_during_create_subM ? simp->SimplifyTerm(c[1]) : c[1]; else// (IFF == k ) c1= simplify_during_create_subM ? simp->SimplifyFormula_NoRemoveWrites(c[1], false) : c[1]; bool updated = UpdateSubstitutionMap(c[0], c1); output = updated ? ASTTrue : a; if (updated) { //fill the arrayname readindices vector if e0 is a //READ(Arr,index) and index is a BVCONST int to; if ((to =TermOrder(c[0],c1))==1 && c[0].GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c[0], c1); else if (to ==-1 && c1.GetKind() == READ) at->FillUp_ArrReadIndex_Vec(c1,c[0]); } } else if (XOR == k) { if (a.Degree() !=2) return output; int to = TermOrder(a[0],a[1]); if (0 == to) return output; ASTNode symbol,rhs; if (to==1) { symbol = a[0]; rhs = a[1]; } else { symbol = a[0]; rhs = a[1]; } assert(symbol.GetKind() == SYMBOL); // If either side is already solved for. if (CheckSubstitutionMap(symbol) || CheckSubstitutionMap(rhs)) {} else if (UpdateSolverMap(symbol, bm->CreateNode(NOT, rhs))) output = ASTTrue; } else if (AND == k) { const ASTVec& c = a.GetChildren(); ASTVec o; o.reserve(c.size()); for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend; it++) { simp->UpdateAlwaysTrueFormSet(*it); ASTNode aaa = CreateSubstitutionMap(*it,at); if (ASTTrue != aaa) { if (ASTFalse == aaa) return ASTFalse; else o.push_back(aaa); } } if (o.size() == 0) output = ASTTrue; else if (o.size() == 1) output = o[0]; else if (o != c) output = bm->CreateNode(AND, o); else output = a; } return output; } //end of CreateSubstitutionMap() // idempotent. ASTNode SubstitutionMap::applySubstitutionMap(const ASTNode& n) { bm->GetRunTimes()->start(RunTimes::ApplyingSubstitutions); ASTNodeMap cache; SimplifyingNodeFactory nf(*bm->hashingNodeFactory, *bm); ASTNode result = replace(n,*SolverMap,cache,&nf, false); // NB. This is an expensive check. Remove it after it's been idempotent // for a while. #ifndef NDEBUG cache.clear(); assert( result == replace(result,*SolverMap,cache,&nf, false)); #endif bm->GetRunTimes()->stop(RunTimes::ApplyingSubstitutions); return result; } // not always idempotent. ASTNode SubstitutionMap::applySubstitutionMapUntilArrays(const ASTNode& n) { bm->GetRunTimes()->start(RunTimes::ApplyingSubstitutions); ASTNodeMap cache; SimplifyingNodeFactory nf(*bm->hashingNodeFactory, *bm); ASTNode result = replace(n,*SolverMap,cache,&nf, true); bm->GetRunTimes()->stop(RunTimes::ApplyingSubstitutions); return result; } ASTNode SubstitutionMap::replace(const ASTNode& n, ASTNodeMap& fromTo, ASTNodeMap& cache, NodeFactory * nf) { return replace(n,fromTo,cache,nf,false); } // NOTE the fromTo map is changed as we traverse downwards. // We call replace on each of the things in the fromTo map aswell. // This is in case we have a fromTo map: (x maps to y), (y maps to 5), // and pass the replace() function the node "x" to replace, then it // will return 5, rather than y. // NB: You can't use this to map from "5" to the symbol "x" say. // It's optimised for the symbol to something case. ASTNode SubstitutionMap::replace(const ASTNode& n, ASTNodeMap& fromTo, ASTNodeMap& cache, NodeFactory * nf, bool stopAtArrays) { const Kind k = n.GetKind(); if (k == BVCONST || k == TRUE || k == FALSE) return n; ASTNodeMap::const_iterator it; if ((it = cache.find(n)) != cache.end()) return it->second; if ((it = fromTo.find(n)) != fromTo.end()) { const ASTNode& r = it->second; assert(r.GetIndexWidth() == n.GetIndexWidth()); ASTNode replaced = replace(r, fromTo, cache,nf,stopAtArrays); if (replaced != r) fromTo[n] = replaced; cache.insert(make_pair(n,replaced)); return replaced; } // These can't be created like regular nodes are if (k == SYMBOL ) return n; const unsigned int indexWidth = n.GetIndexWidth(); if (stopAtArrays && indexWidth > 0) // is an array. { return n; } const ASTVec& children = n.GetChildren(); assert(children.size() > 0); // Should have no leaves left here. ASTVec new_children; new_children.reserve(children.size()); for (ASTVec::const_iterator it = children.begin(); it != children.end(); it++) { new_children.push_back(replace(*it, fromTo, cache,nf,stopAtArrays)); } assert(new_children.size() == children.size()); // This code short-cuts if the children are the same. Nodes with the same children, // won't have necessarily given the same node if the simplifyingNodeFactory is enabled // now, but wasn't enabled when the node was created. Shortcutting saves lots of time. if (new_children == children) { cache.insert(make_pair(n,n)); return n; } ASTNode result; const unsigned int valueWidth = n.GetValueWidth(); if (valueWidth == 0 ) // n.GetType() == BOOLEAN_TYPE { result = nf->CreateNode(k, new_children); } else { // If the index and value width aren't saved, they are reset sometimes (??) result = nf->CreateArrayTerm(k,indexWidth, valueWidth,new_children); } // We may have created something that should be mapped. For instance, // if n is READ(A, x), and the fromTo is: {x==0, READ(A,0) == 1}, then // by here the result will be READ(A,0). Which needs to be mapped again.. // I hope that this makes it idempotent. if (fromTo.find(result) != fromTo.end()) result = replace(result, fromTo, cache,nf,stopAtArrays); assert(result.GetValueWidth() == valueWidth); assert(result.GetIndexWidth() == indexWidth); cache.insert(make_pair(n,result)); return result; } // Adds to the dependency graph that n0 depends on the variables in n1. // It's not the transitive closure of the dependencies. Just the variables in the expression "n1". // This is only needed as long as all the substitution rules haven't been written through. void SubstitutionMap::buildDepends(const ASTNode& n0, const ASTNode& n1) { if (n0.GetKind() != SYMBOL) return; if (n1.isConstant()) return; vector<Symbols*> av; vars.VarSeenInTerm(vars.getSymbol(n1), rhs_visited, rhs, av); sort(av.begin(), av.end()); for (int i =0; i < av.size();i++) { if (i!=0 && av[i] == av[i-1]) continue; // Treat it like a set of Symbol* in effect. ASTNodeSet* sym = (vars.TermsAlreadySeenMap.find(av[i])->second); if(rhsAlreadyAdded.find(sym) != rhsAlreadyAdded.end()) continue; rhsAlreadyAdded.insert(sym); //cout << loopCount++ << " "; //cout << "initial" << rhs.size() << " Adding: " <<sym->size(); rhs.insert(sym->begin(), sym->end()); //cout << "final:" << rhs.size(); //cout << "added:" << sym << endl; } assert (dependsOn.find(n0) == dependsOn.end()); dependsOn.insert(make_pair(n0,vars.getSymbol(n1))); } // Take the transitive closure of the varsToCheck. Storing the result in visited. void SubstitutionMap::loops_helper(const set<ASTNode>& varsToCheck, set<ASTNode>& visited) { set<ASTNode>::const_iterator visitedIt = visited.begin(); set<ASTNode> toVisit; vector<ASTNode> visitedN; // for each variable. for (set<ASTNode>::const_iterator varIt = varsToCheck.begin(); varIt != varsToCheck.end(); varIt++) { while (*visitedIt < *varIt && visitedIt != visited.end()) visitedIt++; if (*visitedIt == *varIt) continue; visitedN.push_back(*varIt); DependsType::iterator it; if ((it = dependsOn.find(*varIt)) != dependsOn.end()) { Symbols* s= it->second; bool destruct; ASTNodeSet* varsSeen = vars.SetofVarsSeenInTerm(s,destruct); toVisit.insert(varsSeen->begin(), varsSeen->end()); if (destruct) delete varsSeen; } } visited.insert(visitedN.begin(), visitedN.end()); visitedN.clear(); if (toVisit.size() !=0) loops_helper(toVisit, visited); } // If n0 is replaced by n1 in the substitution map. Will it cause a loop? // i.e. will the dependency graph be an acyclic graph still. // For example, if we have x = F(y,z,w), it would make the substitutionMap loop // if there's already z = F(x). bool SubstitutionMap::loops(const ASTNode& n0, const ASTNode& n1) { if (n0.GetKind() != SYMBOL) return false; // sometimes this function is called with constants on the lhs. if (n1.isConstant()) return false; // constants contain no variables. Can't loop. // We are adding an edge FROM n0, so unless there is already an edge TO n0, // there is no change it can loop. Unless adding this would add a TO and FROM edge. if (rhs.find(n0) == rhs.end()) { return vars.VarSeenInTerm(n0,n1); } if (n1.GetKind() == SYMBOL && dependsOn.find(n1) == dependsOn.end() ) return false; // The rhs is a symbol and doesn't appear. if (debug_substn) cout << loopCount++ << endl; bool destruct = true; ASTNodeSet* dependN = vars.SetofVarsSeenInTerm(n1,destruct); if (debug_substn) { cout << n0 << " " << n1.GetNodeNum(); //<< " Expression size:" << bm->NodeSize(n1,true); cout << "Variables in expression: "<< dependN->size() << endl; } set<ASTNode> depend(dependN->begin(), dependN->end()); if (destruct) delete dependN; set<ASTNode> visited; loops_helper(depend,visited); bool loops = visited.find(n0) != visited.end(); if (debug_substn) cout << "Visited:" << visited.size() << "Loops:" << loops << endl; return (loops); } }; <|endoftext|>
<commit_before><commit_msg>Update known conformance version for SC 1.0.1.0<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_MM #define MFEM_MM #include <list> #include <cstddef> // for size_t #include <unordered_map> using std::size_t; #include "occa.hpp" // for OccaMemory namespace mfem { // ***************************************************************************** // * Memory Manager Singleton // ***************************************************************************** class mm { public: // ************************************************************************** struct alias; // TODO: Change this to ptr struct memory { const size_t bytes; void *const h_ptr; void *d_ptr; OccaMemory o_ptr; std::list<const alias *> aliases; bool host; bool padding[7]; memory(void* const h, const size_t b): bytes(b), h_ptr(h), d_ptr(nullptr), aliases(), host(true) {} }; struct alias { memory *const mem; const long offset; }; // ************************************************************************** typedef std::unordered_map<const void*, memory> memory_map; typedef std::unordered_map<const void*, const alias*> alias_map; struct ledger { memory_map memories; alias_map aliases; }; // ************************************************************************** // * Main malloc template function // * Allocates n*size bytes and returns a pointer to the allocated memory // ************************************************************************** template<class T> static inline T* malloc(const size_t n, const size_t size = sizeof(T)) { return static_cast<T*>(MM().Insert(::new T[n], n*size)); } // ************************************************************************** // * Frees the memory space pointed to by ptr, which must have been // * returned by a previous call to mm::malloc // ************************************************************************** template<class T> static inline void free(void *ptr) { if (!ptr) { return; } ::delete[] static_cast<T*>(ptr); mm::MM().Erase(ptr); } // ************************************************************************** // * Translates ptr to host or device address, // * depending on config::Cuda() and the ptr' state // ************************************************************************** static inline void *ptr(void *a) { return MM().Ptr(a); } static inline const void* ptr(const void *a) { return MM().Ptr(a); } static inline OccaMemory occaPtr(const void *a) { return MM().Memory(a); } // ************************************************************************** static inline void push(const void *ptr, const size_t bytes = 0) { return MM().Push(ptr, bytes); } // ************************************************************************** static inline void pull(const void *ptr, const size_t bytes = 0) { return MM().Pull(ptr, bytes); } // ************************************************************************** static void* memcpy(void *dst, const void *src, size_t bytes, const bool async = false); // ************************************************************************** static inline bool known(const void *a) { return MM().Known(a); } // ************************************************************************** template<class T> static inline void RegisterHostPtr(T * ptr_host, const size_t size) { MM().Insert(ptr_host, size*sizeof(T)); } // ************************************************************************** template<class T> static void RegisterHostAndDevicePtr(T * ptr_host, T * ptr_device, const size_t size) { MM().Insert(ptr_host, size*sizeof(T)); mm::memory &base = MM().maps.memories.at(ptr_host); base.d_ptr = ptr_device; base.host = false; } private: ledger maps; mm() {} mm(mm const&) = delete; void operator=(mm const&) = delete; static inline mm& MM() { static mm *singleton = new mm(); return *singleton; } // ************************************************************************** void *Insert(void *ptr, const size_t bytes); void *Erase(void *ptr); void *Ptr(void *ptr); const void *Ptr(const void *ptr); bool Known(const void *ptr); bool Alias(const void *ptr); OccaMemory Memory(const void *ptr); // ************************************************************************** void Push(const void *ptr, const size_t bytes = 0); void Pull(const void *ptr, const size_t bytes = 0); }; //Check if method has been registered void RegisterCheck(void *ptr); } // namespace mfem #endif <commit_msg>comment fix<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_MM #define MFEM_MM #include <list> #include <cstddef> // for size_t #include <unordered_map> using std::size_t; #include "occa.hpp" // for OccaMemory namespace mfem { // ***************************************************************************** // * Memory Manager Singleton // ***************************************************************************** class mm { public: // ************************************************************************** struct alias; // TODO: Change this to ptr struct memory { const size_t bytes; void *const h_ptr; void *d_ptr; OccaMemory o_ptr; std::list<const alias *> aliases; bool host; bool padding[7]; memory(void* const h, const size_t b): bytes(b), h_ptr(h), d_ptr(nullptr), aliases(), host(true) {} }; struct alias { memory *const mem; const long offset; }; // ************************************************************************** typedef std::unordered_map<const void*, memory> memory_map; typedef std::unordered_map<const void*, const alias*> alias_map; struct ledger { memory_map memories; alias_map aliases; }; // ************************************************************************** // * Main malloc template function // * Allocates n*size bytes and returns a pointer to the allocated memory // ************************************************************************** template<class T> static inline T* malloc(const size_t n, const size_t size = sizeof(T)) { return static_cast<T*>(MM().Insert(::new T[n], n*size)); } // ************************************************************************** // * Frees the memory space pointed to by ptr, which must have been // * returned by a previous call to mm::malloc // ************************************************************************** template<class T> static inline void free(void *ptr) { if (!ptr) { return; } ::delete[] static_cast<T*>(ptr); mm::MM().Erase(ptr); } // ************************************************************************** // * Translates ptr to host or device address, // * depending on config::Cuda() and the ptr' state // ************************************************************************** static inline void *ptr(void *a) { return MM().Ptr(a); } static inline const void* ptr(const void *a) { return MM().Ptr(a); } static inline OccaMemory occaPtr(const void *a) { return MM().Memory(a); } // ************************************************************************** static inline void push(const void *ptr, const size_t bytes = 0) { return MM().Push(ptr, bytes); } // ************************************************************************** static inline void pull(const void *ptr, const size_t bytes = 0) { return MM().Pull(ptr, bytes); } // ************************************************************************** static void* memcpy(void *dst, const void *src, size_t bytes, const bool async = false); // ************************************************************************** static inline bool known(const void *a) { return MM().Known(a); } // ************************************************************************** template<class T> static inline void RegisterHostPtr(T * ptr_host, const size_t size) { MM().Insert(ptr_host, size*sizeof(T)); } // ************************************************************************** template<class T> static void RegisterHostAndDevicePtr(T * ptr_host, T * ptr_device, const size_t size) { MM().Insert(ptr_host, size*sizeof(T)); mm::memory &base = MM().maps.memories.at(ptr_host); base.d_ptr = ptr_device; base.host = false; } private: ledger maps; mm() {} mm(mm const&) = delete; void operator=(mm const&) = delete; static inline mm& MM() { static mm *singleton = new mm(); return *singleton; } // ************************************************************************** void *Insert(void *ptr, const size_t bytes); void *Erase(void *ptr); void *Ptr(void *ptr); const void *Ptr(const void *ptr); bool Known(const void *ptr); bool Alias(const void *ptr); OccaMemory Memory(const void *ptr); // ************************************************************************** void Push(const void *ptr, const size_t bytes = 0); void Pull(const void *ptr, const size_t bytes = 0); }; //Check if pointer has been registered with the okina memory manager void RegisterCheck(void *ptr); } // namespace mfem #endif <|endoftext|>
<commit_before>/* * CommonCrypto Hash Functions * (C) 2018 Jose Pereira * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/commoncrypto.h> #include <botan/hash.h> #include <unordered_map> #include <CommonCrypto/CommonCrypto.h> namespace Botan { namespace { template <class CTX> class CommonCrypto_HashFunction final : public HashFunction { public: struct digest_config_t { std::string name; size_t digestLength; size_t blockSize; int (*init)(CTX *); int (*update)(CTX *, const void *, CC_LONG len); int (*final)(unsigned char *, CTX*); }; void clear() override { if(m_info.init(&m_ctx) != 1) throw CommonCrypto_Error("CC_" + m_info.name + "_Init"); } std::string provider() const override { return "commoncrypto"; } std::string name() const override { return m_info.name; } HashFunction* clone() const override { return new CommonCrypto_HashFunction(m_info); } std::unique_ptr<HashFunction> copy_state() const override { return std::unique_ptr<CommonCrypto_HashFunction>( new CommonCrypto_HashFunction(m_info, m_ctx)); } size_t output_length() const override { return m_info.digestLength; } size_t hash_block_size() const override { return m_info.blockSize; } CommonCrypto_HashFunction(const digest_config_t& info) : m_info(info) { clear(); } CommonCrypto_HashFunction(const digest_config_t& info, const CTX &ctx) : m_ctx(ctx), m_info(info) {} private: void add_data(const uint8_t input[], size_t length) override { /* update len parameter is 32 bit unsigned integer, feed input in parts */ while (length > 0) { CC_LONG update_len = (length > 0xFFFFFFFFUL) ? 0xFFFFFFFFUL : static_cast<CC_LONG>(length); m_info.update(&m_ctx, input, update_len); input += update_len; length -= update_len; } } void final_result(uint8_t output[]) override { if(m_info.final(output, &m_ctx) != 1) throw CommonCrypto_Error("CC_" + m_info.name + "_Final"); clear(); } CTX m_ctx; digest_config_t m_info; }; } std::unique_ptr<HashFunction> make_commoncrypto_hash(const std::string& name) { #define MAKE_COMMONCRYPTO_HASH_3(name, hash, ctx) \ std::unique_ptr<HashFunction>( \ new CommonCrypto_HashFunction<CC_ ## ctx ## _CTX >({ \ name, \ CC_ ## hash ## _DIGEST_LENGTH, \ CC_ ## hash ## _BLOCK_BYTES, \ CC_ ## hash ## _Init, \ CC_ ## hash ## _Update, \ CC_ ## hash ## _Final \ })); #define MAKE_COMMONCRYPTO_HASH_2(name, id) \ MAKE_COMMONCRYPTO_HASH_3(name, id, id) #define MAKE_COMMONCRYPTO_HASH_1(id) \ MAKE_COMMONCRYPTO_HASH_2(#id, id) #if defined(BOTAN_HAS_SHA2_32) if(name == "SHA-224") return MAKE_COMMONCRYPTO_HASH_3(name, SHA224, SHA256); if(name == "SHA-256") return MAKE_COMMONCRYPTO_HASH_2(name, SHA256); #endif #if defined(BOTAN_HAS_SHA2_64) if(name == "SHA-384") return MAKE_COMMONCRYPTO_HASH_3(name, SHA384, SHA512); if(name == "SHA-512") return MAKE_COMMONCRYPTO_HASH_2(name, SHA512); #endif #if defined(BOTAN_HAS_SHA1) if(name == "SHA-160" || name == "SHA-1" || name == "SHA1") return MAKE_COMMONCRYPTO_HASH_2(name, SHA1); #endif #if defined(BOTAN_HAS_MD5) if(name == "MD5") return MAKE_COMMONCRYPTO_HASH_1(MD5); #endif #if defined(BOTAN_HAS_MD4) if(name == "MD4") return MAKE_COMMONCRYPTO_HASH_1(MD4); #endif return nullptr; } } <commit_msg>Disable MD4/MD5 support in CommonCrypto<commit_after>/* * CommonCrypto Hash Functions * (C) 2018 Jose Pereira * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/commoncrypto.h> #include <botan/hash.h> #include <unordered_map> #include <CommonCrypto/CommonCrypto.h> namespace Botan { namespace { template <class CTX> class CommonCrypto_HashFunction final : public HashFunction { public: struct digest_config_t { std::string name; size_t digestLength; size_t blockSize; int (*init)(CTX *); int (*update)(CTX *, const void *, CC_LONG len); int (*final)(unsigned char *, CTX*); }; void clear() override { if(m_info.init(&m_ctx) != 1) throw CommonCrypto_Error("CC_" + m_info.name + "_Init"); } std::string provider() const override { return "commoncrypto"; } std::string name() const override { return m_info.name; } HashFunction* clone() const override { return new CommonCrypto_HashFunction(m_info); } std::unique_ptr<HashFunction> copy_state() const override { return std::unique_ptr<CommonCrypto_HashFunction>( new CommonCrypto_HashFunction(m_info, m_ctx)); } size_t output_length() const override { return m_info.digestLength; } size_t hash_block_size() const override { return m_info.blockSize; } CommonCrypto_HashFunction(const digest_config_t& info) : m_info(info) { clear(); } CommonCrypto_HashFunction(const digest_config_t& info, const CTX &ctx) : m_ctx(ctx), m_info(info) {} private: void add_data(const uint8_t input[], size_t length) override { /* update len parameter is 32 bit unsigned integer, feed input in parts */ while (length > 0) { CC_LONG update_len = (length > 0xFFFFFFFFUL) ? 0xFFFFFFFFUL : static_cast<CC_LONG>(length); m_info.update(&m_ctx, input, update_len); input += update_len; length -= update_len; } } void final_result(uint8_t output[]) override { if(m_info.final(output, &m_ctx) != 1) throw CommonCrypto_Error("CC_" + m_info.name + "_Final"); clear(); } CTX m_ctx; digest_config_t m_info; }; } std::unique_ptr<HashFunction> make_commoncrypto_hash(const std::string& name) { #define MAKE_COMMONCRYPTO_HASH_3(name, hash, ctx) \ std::unique_ptr<HashFunction>( \ new CommonCrypto_HashFunction<CC_ ## ctx ## _CTX >({ \ name, \ CC_ ## hash ## _DIGEST_LENGTH, \ CC_ ## hash ## _BLOCK_BYTES, \ CC_ ## hash ## _Init, \ CC_ ## hash ## _Update, \ CC_ ## hash ## _Final \ })); #define MAKE_COMMONCRYPTO_HASH_2(name, id) \ MAKE_COMMONCRYPTO_HASH_3(name, id, id) #define MAKE_COMMONCRYPTO_HASH_1(id) \ MAKE_COMMONCRYPTO_HASH_2(#id, id) #if defined(BOTAN_HAS_SHA2_32) if(name == "SHA-224") return MAKE_COMMONCRYPTO_HASH_3(name, SHA224, SHA256); if(name == "SHA-256") return MAKE_COMMONCRYPTO_HASH_2(name, SHA256); #endif #if defined(BOTAN_HAS_SHA2_64) if(name == "SHA-384") return MAKE_COMMONCRYPTO_HASH_3(name, SHA384, SHA512); if(name == "SHA-512") return MAKE_COMMONCRYPTO_HASH_2(name, SHA512); #endif #if defined(BOTAN_HAS_SHA1) if(name == "SHA-160" || name == "SHA-1" || name == "SHA1") return MAKE_COMMONCRYPTO_HASH_2(name, SHA1); #endif return nullptr; } } <|endoftext|>
<commit_before>// Authors: see AUTHORS.md at project root. // CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root. // URL: https://github.com/asrob-uc3m/robotDevastation #include "YarpNetworkManager.hpp" #include <sstream> #include <cstring> // strcmp() #include <yarp/os/Network.h> #include <ColorDebug.hpp> #include "Vocabs.hpp" //-- Initialize static members rd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL; const std::string rd::YarpNetworkManager::id = "YARP"; const int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000; bool rd::YarpNetworkManager::RegisterManager() { if (uniqueInstance == NULL) { uniqueInstance = new YarpNetworkManager(); } return Register( uniqueInstance, id); } rd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS) { started = false; } void rd::YarpNetworkManager::run() { keepAlive(); } rd::YarpNetworkManager::~YarpNetworkManager() { uniqueInstance = NULL; } bool rd::YarpNetworkManager::start() { if (player.getId() == -1) { CD_ERROR("NetworkManager not initialized, player id not set\n"); return false; } if (started) { CD_ERROR("NetworkManager already started\n"); return false; } yarp::os::NetworkBase::initMinimum(); if ( ! yarp::os::NetworkBase::checkNetwork() ) { CD_ERROR("Found no yarp network to connect to rdServer (try running 'yarpserver &'). Bye!\n"); return false; } //-- Open the rcpClient port with this player's id std::ostringstream rpc_str; rpc_str << "/robotDevastation/"; rpc_str << player.getId(); rpc_str << "/rdServer/rpc:c"; if( ! rpcClient.open( rpc_str.str() ) ) { CD_ERROR("Could not open '%s'. Bye!\n",rpc_str.str().c_str()); return false; } //-- Open the callback port with this player's id std::ostringstream callback_str; callback_str << "/robotDevastation/"; callback_str << player.getId(); callback_str << "/rdServer/info:i"; if( ! callbackPort.open( callback_str.str() ) ) { CD_ERROR("Could not open '%s'. Bye!\n",callback_str.str().c_str()); return false; } //-- Connect robotDevastation RpcClient to rdServer RpcServer if( ! yarp::os::Network::connect( rpc_str.str() , "/rdServer/rpc:s" ) ) { CD_ERROR("Could not connect robotDevastation RpcClient to rdServer RpcServer (launch 'rdServer' if not already launched).\n"); return false; } CD_SUCCESS("Connected robotDevastation RpcClient to rdServer RpcServer!\n"); //-- Connect from rdServer info to robotDevastation callbackPort if ( !yarp::os::Network::connect( "/rdServer/info:o", callback_str.str() )) { CD_ERROR("Could not connect from rdServer info to robotDevastation callbackPort (launch 'rdServer' if not already launched).\n"); return false; } CD_SUCCESS("Connected from rdServer info to robotDevastation callbackPort!\n"); callbackPort.useCallback(*this); RateThread::start(); started = true; return true; } void rd::YarpNetworkManager::onRead(yarp::os::Bottle &b) { //CD_INFO("Got %s\n", b.toString().c_str()); if ((b.get(0).asString() == "players")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { // players // //CD_INFO("Number of players: %d\n",b.size()-1); // -1 because of vocab. std::vector< Player > players; for (int i = 1; i < b.size(); i++) { Player rdPlayer(b.get(i).asList()->get(0).asInt(), b.get(i).asList()->get(1).asString().c_str(), b.get(i).asList()->get(2).asInt(), b.get(i).asList()->get(3).asInt(), b.get(i).asList()->get(4).asInt(), b.get(i).asList()->get(5).asInt() ); players.push_back(rdPlayer); } //-- Notify listeners for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it) { (*it)->onDataArrived(players); } } else { CD_ERROR("What?\n"); } } bool rd::YarpNetworkManager::stop() { if (!started) { CD_ERROR("Already stopped\n"); return false; } RateThread::askToStop(); rpcClient.close(); callbackPort.disableCallback(); callbackPort.interrupt(); callbackPort.close(); yarp::os::NetworkBase::finiMinimum(); started = false; return true; } bool rd::YarpNetworkManager::isStopped() const { return !started; } bool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value) { if (parameter.compare("player") == 0) { player = value; return true; } return NetworkManager::configure(parameter, value); } bool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage) { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } //-- Send a message to the server with the player Id and the damage done: yarp::os::Bottle msg_player_hit, response; msg_player_hit.addVocab(VOCAB_RD_HIT); msg_player_hit.addInt(player.getId()); msg_player_hit.addInt(damage); rpcClient.write(msg_player_hit,response); CD_INFO("rdServer response from hit: %s\n",response.toString().c_str()); //-- Check response if (std::strcmp(response.toString().c_str(), "[ok]") == 0) return true; else return false; } bool rd::YarpNetworkManager::login() { if (!started) { CD_WARNING("NetworkManager has not been started\n"); if(!start()) { CD_ERROR("NetworkManager could not be started for player %d\n", player.getId() ); return false; } } //-- Start network system std::stringstream ss; ss << player.getId(); //-- Send login message yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_LOGIN); msgRdPlayer.addInt(player.getId()); msgRdPlayer.addString(player.getName().c_str()); msgRdPlayer.addInt(player.getTeamId()); rpcClient.write(msgRdPlayer,res); CD_INFO("rdServer response from login: %s\n",res.toString().c_str()); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) return true; else return false; } bool rd::YarpNetworkManager::logout() { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } CD_INFO("Logout...\n"); yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_LOGOUT); msgRdPlayer.addInt(player.getId()); rpcClient.write(msgRdPlayer,res); CD_INFO("rdServer response from logout: %s\n",res.toString().c_str()); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) { CD_SUCCESS("Logout ok\n"); return true; } else { CD_ERROR("Logout failed\n"); return false; } } bool rd::YarpNetworkManager::keepAlive() { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } CD_INFO("Keep alive...\n"); yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE); msgRdPlayer.addInt(player.getId()); rpcClient.write(msgRdPlayer,res); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) { return true; } else { CD_ERROR("Keep alive failed\n"); return false; } } <commit_msg>match syntax of main<commit_after>// Authors: see AUTHORS.md at project root. // CopyPolicy: released under the terms of the LGPLv2.1, see LICENSE at project root. // URL: https://github.com/asrob-uc3m/robotDevastation #include "YarpNetworkManager.hpp" #include <sstream> #include <cstring> // strcmp() #include <yarp/os/Network.h> #include <ColorDebug.hpp> #include "Vocabs.hpp" //-- Initialize static members rd::YarpNetworkManager * rd::YarpNetworkManager::uniqueInstance = NULL; const std::string rd::YarpNetworkManager::id = "YARP"; const int rd::YarpNetworkManager::KEEPALIVE_RATE_MS = 1000; bool rd::YarpNetworkManager::RegisterManager() { if (uniqueInstance == NULL) { uniqueInstance = new YarpNetworkManager(); } return Register( uniqueInstance, id); } rd::YarpNetworkManager::YarpNetworkManager() : RateThread(KEEPALIVE_RATE_MS) { started = false; } void rd::YarpNetworkManager::run() { keepAlive(); } rd::YarpNetworkManager::~YarpNetworkManager() { uniqueInstance = NULL; } bool rd::YarpNetworkManager::start() { if (player.getId() == -1) { CD_ERROR("NetworkManager not initialized, player id not set\n"); return false; } if (started) { CD_ERROR("NetworkManager already started\n"); return false; } yarp::os::Network::initMinimum(); if ( ! yarp::os::Network::checkNetwork() ) { CD_ERROR("Found no yarp network to connect to rdServer (try running 'yarpserver &'). Bye!\n"); return false; } //-- Open the rcpClient port with this player's id std::ostringstream rpc_str; rpc_str << "/robotDevastation/"; rpc_str << player.getId(); rpc_str << "/rdServer/rpc:c"; if( ! rpcClient.open( rpc_str.str() ) ) { CD_ERROR("Could not open '%s'. Bye!\n",rpc_str.str().c_str()); return false; } //-- Open the callback port with this player's id std::ostringstream callback_str; callback_str << "/robotDevastation/"; callback_str << player.getId(); callback_str << "/rdServer/info:i"; if( ! callbackPort.open( callback_str.str() ) ) { CD_ERROR("Could not open '%s'. Bye!\n",callback_str.str().c_str()); return false; } //-- Connect robotDevastation RpcClient to rdServer RpcServer if( ! yarp::os::Network::connect( rpc_str.str() , "/rdServer/rpc:s" ) ) { CD_ERROR("Could not connect robotDevastation RpcClient to rdServer RpcServer (launch 'rdServer' if not already launched).\n"); return false; } CD_SUCCESS("Connected robotDevastation RpcClient to rdServer RpcServer!\n"); //-- Connect from rdServer info to robotDevastation callbackPort if ( !yarp::os::Network::connect( "/rdServer/info:o", callback_str.str() )) { CD_ERROR("Could not connect from rdServer info to robotDevastation callbackPort (launch 'rdServer' if not already launched).\n"); return false; } CD_SUCCESS("Connected from rdServer info to robotDevastation callbackPort!\n"); callbackPort.useCallback(*this); RateThread::start(); started = true; return true; } void rd::YarpNetworkManager::onRead(yarp::os::Bottle &b) { //CD_INFO("Got %s\n", b.toString().c_str()); if ((b.get(0).asString() == "players")||(b.get(0).asVocab() == VOCAB_RD_PLAYERS)) { // players // //CD_INFO("Number of players: %d\n",b.size()-1); // -1 because of vocab. std::vector< Player > players; for (int i = 1; i < b.size(); i++) { Player rdPlayer(b.get(i).asList()->get(0).asInt(), b.get(i).asList()->get(1).asString().c_str(), b.get(i).asList()->get(2).asInt(), b.get(i).asList()->get(3).asInt(), b.get(i).asList()->get(4).asInt(), b.get(i).asList()->get(5).asInt() ); players.push_back(rdPlayer); } //-- Notify listeners for (std::vector<NetworkEventListener *>::iterator it = listeners.begin(); it != listeners.end(); ++it) { (*it)->onDataArrived(players); } } else { CD_ERROR("What?\n"); } } bool rd::YarpNetworkManager::stop() { if (!started) { CD_ERROR("Already stopped\n"); return false; } RateThread::askToStop(); rpcClient.close(); callbackPort.disableCallback(); callbackPort.interrupt(); callbackPort.close(); yarp::os::NetworkBase::finiMinimum(); started = false; return true; } bool rd::YarpNetworkManager::isStopped() const { return !started; } bool rd::YarpNetworkManager::configure(const std::string & parameter, const Player & value) { if (parameter.compare("player") == 0) { player = value; return true; } return NetworkManager::configure(parameter, value); } bool rd::YarpNetworkManager::sendPlayerHit(const Player & player, int damage) { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } //-- Send a message to the server with the player Id and the damage done: yarp::os::Bottle msg_player_hit, response; msg_player_hit.addVocab(VOCAB_RD_HIT); msg_player_hit.addInt(player.getId()); msg_player_hit.addInt(damage); rpcClient.write(msg_player_hit,response); CD_INFO("rdServer response from hit: %s\n",response.toString().c_str()); //-- Check response if (std::strcmp(response.toString().c_str(), "[ok]") == 0) return true; else return false; } bool rd::YarpNetworkManager::login() { if (!started) { CD_WARNING("NetworkManager has not been started\n"); if(!start()) { CD_ERROR("NetworkManager could not be started for player %d\n", player.getId() ); return false; } } //-- Start network system std::stringstream ss; ss << player.getId(); //-- Send login message yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_LOGIN); msgRdPlayer.addInt(player.getId()); msgRdPlayer.addString(player.getName().c_str()); msgRdPlayer.addInt(player.getTeamId()); rpcClient.write(msgRdPlayer,res); CD_INFO("rdServer response from login: %s\n",res.toString().c_str()); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) return true; else return false; } bool rd::YarpNetworkManager::logout() { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } CD_INFO("Logout...\n"); yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_LOGOUT); msgRdPlayer.addInt(player.getId()); rpcClient.write(msgRdPlayer,res); CD_INFO("rdServer response from logout: %s\n",res.toString().c_str()); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) { CD_SUCCESS("Logout ok\n"); return true; } else { CD_ERROR("Logout failed\n"); return false; } } bool rd::YarpNetworkManager::keepAlive() { if (!started) { CD_ERROR("NetworkManager has not been started\n"); return false; } CD_INFO("Keep alive...\n"); yarp::os::Bottle msgRdPlayer,res; msgRdPlayer.addVocab(VOCAB_RD_KEEPALIVE); msgRdPlayer.addInt(player.getId()); rpcClient.write(msgRdPlayer,res); //-- Check response if (std::strcmp(res.toString().c_str(), "[ok]") == 0) { return true; } else { CD_ERROR("Keep alive failed\n"); return false; } } <|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 "base/command_line.h" #include "base/message_loop_proxy.h" #include "base/ref_counted.h" #include "base/thread.h" #include "base/waitable_event.h" #include "chrome/common/net/url_fetcher_protect.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/service/service_process.h" #include "chrome/service/cloud_print/cloud_print_url_fetcher.h" #include "googleurl/src/gurl.h" #include "net/test/test_server.h" #include "net/url_request/url_request_unittest.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; namespace { const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data"); int g_request_context_getter_instances = 0; class TestURLRequestContextGetter : public URLRequestContextGetter { public: explicit TestURLRequestContextGetter( base::MessageLoopProxy* io_message_loop_proxy) : io_message_loop_proxy_(io_message_loop_proxy) { g_request_context_getter_instances++; } virtual URLRequestContext* GetURLRequestContext() { if (!context_) context_ = new TestURLRequestContext(); return context_; } virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const { return io_message_loop_proxy_; } protected: scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; private: ~TestURLRequestContextGetter() { g_request_context_getter_instances--; } scoped_refptr<URLRequestContext> context_; }; class TestCloudPrintURLFetcher : public CloudPrintURLFetcher { public: explicit TestCloudPrintURLFetcher( base::MessageLoopProxy* io_message_loop_proxy) : io_message_loop_proxy_(io_message_loop_proxy) { } virtual URLRequestContextGetter* GetRequestContextGetter() { return new TestURLRequestContextGetter(io_message_loop_proxy_.get()); } private: scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; }; class CloudPrintURLFetcherTest : public testing::Test, public CloudPrintURLFetcher::Delegate { public: CloudPrintURLFetcherTest() : fetcher_(NULL) { } // Creates a URLFetcher, using the program's main thread to do IO. virtual void CreateFetcher(const GURL& url, const std::string& retry_policy); // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); virtual void OnRequestAuthError() { ADD_FAILURE(); } scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy() { return io_message_loop_proxy_; } protected: virtual void SetUp() { testing::Test::SetUp(); io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread(); } virtual void TearDown() { fetcher_ = NULL; // Deleting the fetcher causes a task to be posted to the IO thread to // release references to the URLRequestContextGetter. We need to run all // pending tasks to execute that (this is the IO thread). MessageLoop::current()->RunAllPending(); EXPECT_EQ(0, g_request_context_getter_instances); } // URLFetcher is designed to run on the main UI thread, but in our tests // we assume that the current thread is the IO thread where the URLFetcher // dispatches its requests to. When we wish to simulate being used from // a UI thread, we dispatch a worker thread to do so. MessageLoopForIO io_loop_; scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; std::string retry_policy_; Time start_time_; scoped_refptr<CloudPrintURLFetcher> fetcher_; }; class CloudPrintURLFetcherBasicTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherBasicTest() : handle_raw_response_(false), handle_raw_data_(false) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); virtual CloudPrintURLFetcher::ResponseAction HandleJSONData( const URLFetcher* source, const GURL& url, DictionaryValue* json_data, bool succeeded); void SetHandleRawResponse(bool handle_raw_response) { handle_raw_response_ = handle_raw_response; } void SetHandleRawData(bool handle_raw_data) { handle_raw_data_ = handle_raw_data; } private: bool handle_raw_response_; bool handle_raw_data_; }; // Version of CloudPrintURLFetcherTest that tests overload protection. class CloudPrintURLFetcherOverloadTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherOverloadTest() : response_count_(0) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); private: int response_count_; }; // Version of CloudPrintURLFetcherTest that tests backoff protection. class CloudPrintURLFetcherRetryBackoffTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherRetryBackoffTest() : response_count_(0) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); virtual void OnRequestGiveUp(); private: int response_count_; }; void CloudPrintURLFetcherTest::CreateFetcher(const GURL& url, const std::string& retry_policy) { fetcher_ = new TestCloudPrintURLFetcher(io_message_loop_proxy()); retry_policy_ = retry_policy; start_time_ = Time::Now(); fetcher_->StartGetRequest(url, this, "", retry_policy_); } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherTest::HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { EXPECT_TRUE(status.is_success()); EXPECT_EQ(200, response_code); // HTTP OK EXPECT_FALSE(data.empty()); return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { EXPECT_TRUE(status.is_success()); EXPECT_EQ(200, response_code); // HTTP OK EXPECT_FALSE(data.empty()); if (handle_raw_response_) { // If the current message loop is not the IO loop, it will be shut down when // the main loop returns and this thread subsequently goes out of scope. io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data) { // We should never get here if we returned true in HandleRawResponse EXPECT_FALSE(handle_raw_response_); if (handle_raw_data_) { io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleJSONData( const URLFetcher* source, const GURL& url, DictionaryValue* json_data, bool succeeded) { // We should never get here if we returned true in one of the above methods. EXPECT_FALSE(handle_raw_response_); EXPECT_FALSE(handle_raw_data_); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherOverloadTest::HandleRawData(const URLFetcher* source, const GURL& url, const std::string& data) { const TimeDelta one_second = TimeDelta::FromMilliseconds(1000); response_count_++; if (response_count_ < 20) { fetcher_->StartGetRequest(url, this, "", retry_policy_); } else { // We have already sent 20 requests continuously. And we expect that // it takes more than 1 second due to the overload pretection settings. EXPECT_TRUE(Time::Now() - start_time_ >= one_second); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherRetryBackoffTest::HandleRawData(const URLFetcher* source, const GURL& url, const std::string& data) { response_count_++; // First attempt + 11 retries = 12 total responses. EXPECT_LE(response_count_, 12); return CloudPrintURLFetcher::RETRY_REQUEST; } void CloudPrintURLFetcherRetryBackoffTest::OnRequestGiveUp() { const TimeDelta one_second = TimeDelta::FromMilliseconds(1000); // It takes more than 1 second to finish all 11 requests. EXPECT_TRUE(Time::Now() - start_time_ >= one_second); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } TEST_F(CloudPrintURLFetcherBasicTest, HandleRawResponse) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); SetHandleRawResponse(true); CreateFetcher(test_server.GetURL("echo"), "DummyRetryPolicy"); MessageLoop::current()->Run(); } TEST_F(CloudPrintURLFetcherBasicTest, HandleRawData) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); SetHandleRawData(true); CreateFetcher(test_server.GetURL("echo"), "DummyRetryPolicy"); MessageLoop::current()->Run(); } TEST_F(CloudPrintURLFetcherOverloadTest, Protect) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); GURL url(test_server.GetURL("defaultresponse")); // Registers an entry for test url. It only allows 3 requests to be sent // in 200 milliseconds. std::string retry_policy = "OverloadTestPolicy"; URLFetcherProtectManager* manager = URLFetcherProtectManager::GetInstance(); URLFetcherProtectEntry* entry = new URLFetcherProtectEntry(200, 3, 11, 1, 2.0, 0, 256); manager->Register(retry_policy, entry); CreateFetcher(url, retry_policy); MessageLoop::current()->Run(); } TEST_F(CloudPrintURLFetcherRetryBackoffTest, GiveUp) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); GURL url(test_server.GetURL("defaultresponse")); // Registers an entry for test url. The backoff time is calculated by: // new_backoff = 2.0 * old_backoff + 0 // and maximum backoff time is 256 milliseconds. // Maximum retries allowed is set to 11. std::string retry_policy = "BackoffTestPolicy"; URLFetcherProtectManager* manager = URLFetcherProtectManager::GetInstance(); URLFetcherProtectEntry* entry = new URLFetcherProtectEntry(200, 3, 11, 1, 2.0, 0, 256); manager->Register(retry_policy, entry); CreateFetcher(url, retry_policy); MessageLoop::current()->Run(); } } // namespace. <commit_msg>Mark the CloudPrintURLFetcherBasicTest.HandleRawData and CloudPrintURLFetcherRetryBackoffTest.GiveUp tests as flaky.<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 "base/command_line.h" #include "base/message_loop_proxy.h" #include "base/ref_counted.h" #include "base/thread.h" #include "base/waitable_event.h" #include "chrome/common/net/url_fetcher_protect.h" #include "chrome/common/net/url_request_context_getter.h" #include "chrome/service/service_process.h" #include "chrome/service/cloud_print/cloud_print_url_fetcher.h" #include "googleurl/src/gurl.h" #include "net/test/test_server.h" #include "net/url_request/url_request_unittest.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; namespace { const FilePath::CharType kDocRoot[] = FILE_PATH_LITERAL("chrome/test/data"); int g_request_context_getter_instances = 0; class TestURLRequestContextGetter : public URLRequestContextGetter { public: explicit TestURLRequestContextGetter( base::MessageLoopProxy* io_message_loop_proxy) : io_message_loop_proxy_(io_message_loop_proxy) { g_request_context_getter_instances++; } virtual URLRequestContext* GetURLRequestContext() { if (!context_) context_ = new TestURLRequestContext(); return context_; } virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const { return io_message_loop_proxy_; } protected: scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; private: ~TestURLRequestContextGetter() { g_request_context_getter_instances--; } scoped_refptr<URLRequestContext> context_; }; class TestCloudPrintURLFetcher : public CloudPrintURLFetcher { public: explicit TestCloudPrintURLFetcher( base::MessageLoopProxy* io_message_loop_proxy) : io_message_loop_proxy_(io_message_loop_proxy) { } virtual URLRequestContextGetter* GetRequestContextGetter() { return new TestURLRequestContextGetter(io_message_loop_proxy_.get()); } private: scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; }; class CloudPrintURLFetcherTest : public testing::Test, public CloudPrintURLFetcher::Delegate { public: CloudPrintURLFetcherTest() : fetcher_(NULL) { } // Creates a URLFetcher, using the program's main thread to do IO. virtual void CreateFetcher(const GURL& url, const std::string& retry_policy); // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); virtual void OnRequestAuthError() { ADD_FAILURE(); } scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy() { return io_message_loop_proxy_; } protected: virtual void SetUp() { testing::Test::SetUp(); io_message_loop_proxy_ = base::MessageLoopProxy::CreateForCurrentThread(); } virtual void TearDown() { fetcher_ = NULL; // Deleting the fetcher causes a task to be posted to the IO thread to // release references to the URLRequestContextGetter. We need to run all // pending tasks to execute that (this is the IO thread). MessageLoop::current()->RunAllPending(); EXPECT_EQ(0, g_request_context_getter_instances); } // URLFetcher is designed to run on the main UI thread, but in our tests // we assume that the current thread is the IO thread where the URLFetcher // dispatches its requests to. When we wish to simulate being used from // a UI thread, we dispatch a worker thread to do so. MessageLoopForIO io_loop_; scoped_refptr<base::MessageLoopProxy> io_message_loop_proxy_; std::string retry_policy_; Time start_time_; scoped_refptr<CloudPrintURLFetcher> fetcher_; }; class CloudPrintURLFetcherBasicTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherBasicTest() : handle_raw_response_(false), handle_raw_data_(false) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data); virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); virtual CloudPrintURLFetcher::ResponseAction HandleJSONData( const URLFetcher* source, const GURL& url, DictionaryValue* json_data, bool succeeded); void SetHandleRawResponse(bool handle_raw_response) { handle_raw_response_ = handle_raw_response; } void SetHandleRawData(bool handle_raw_data) { handle_raw_data_ = handle_raw_data; } private: bool handle_raw_response_; bool handle_raw_data_; }; // Version of CloudPrintURLFetcherTest that tests overload protection. class CloudPrintURLFetcherOverloadTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherOverloadTest() : response_count_(0) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); private: int response_count_; }; // Version of CloudPrintURLFetcherTest that tests backoff protection. class CloudPrintURLFetcherRetryBackoffTest : public CloudPrintURLFetcherTest { public: CloudPrintURLFetcherRetryBackoffTest() : response_count_(0) { } // CloudPrintURLFetcher::Delegate virtual CloudPrintURLFetcher::ResponseAction HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data); virtual void OnRequestGiveUp(); private: int response_count_; }; void CloudPrintURLFetcherTest::CreateFetcher(const GURL& url, const std::string& retry_policy) { fetcher_ = new TestCloudPrintURLFetcher(io_message_loop_proxy()); retry_policy_ = retry_policy; start_time_ = Time::Now(); fetcher_->StartGetRequest(url, this, "", retry_policy_); } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherTest::HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { EXPECT_TRUE(status.is_success()); EXPECT_EQ(200, response_code); // HTTP OK EXPECT_FALSE(data.empty()); return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleRawResponse( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { EXPECT_TRUE(status.is_success()); EXPECT_EQ(200, response_code); // HTTP OK EXPECT_FALSE(data.empty()); if (handle_raw_response_) { // If the current message loop is not the IO loop, it will be shut down when // the main loop returns and this thread subsequently goes out of scope. io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleRawData( const URLFetcher* source, const GURL& url, const std::string& data) { // We should never get here if we returned true in HandleRawResponse EXPECT_FALSE(handle_raw_response_); if (handle_raw_data_) { io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } return CloudPrintURLFetcher::CONTINUE_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherBasicTest::HandleJSONData( const URLFetcher* source, const GURL& url, DictionaryValue* json_data, bool succeeded) { // We should never get here if we returned true in one of the above methods. EXPECT_FALSE(handle_raw_response_); EXPECT_FALSE(handle_raw_data_); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherOverloadTest::HandleRawData(const URLFetcher* source, const GURL& url, const std::string& data) { const TimeDelta one_second = TimeDelta::FromMilliseconds(1000); response_count_++; if (response_count_ < 20) { fetcher_->StartGetRequest(url, this, "", retry_policy_); } else { // We have already sent 20 requests continuously. And we expect that // it takes more than 1 second due to the overload pretection settings. EXPECT_TRUE(Time::Now() - start_time_ >= one_second); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } return CloudPrintURLFetcher::STOP_PROCESSING; } CloudPrintURLFetcher::ResponseAction CloudPrintURLFetcherRetryBackoffTest::HandleRawData(const URLFetcher* source, const GURL& url, const std::string& data) { response_count_++; // First attempt + 11 retries = 12 total responses. EXPECT_LE(response_count_, 12); return CloudPrintURLFetcher::RETRY_REQUEST; } void CloudPrintURLFetcherRetryBackoffTest::OnRequestGiveUp() { const TimeDelta one_second = TimeDelta::FromMilliseconds(1000); // It takes more than 1 second to finish all 11 requests. EXPECT_TRUE(Time::Now() - start_time_ >= one_second); io_message_loop_proxy()->PostTask(FROM_HERE, new MessageLoop::QuitTask()); } TEST_F(CloudPrintURLFetcherBasicTest, HandleRawResponse) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); SetHandleRawResponse(true); CreateFetcher(test_server.GetURL("echo"), "DummyRetryPolicy"); MessageLoop::current()->Run(); } // http://code.google.com/p/chromium/issues/detail?id=62758 TEST_F(CloudPrintURLFetcherBasicTest, FLAKY_HandleRawData) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); SetHandleRawData(true); CreateFetcher(test_server.GetURL("echo"), "DummyRetryPolicy"); MessageLoop::current()->Run(); } TEST_F(CloudPrintURLFetcherOverloadTest, Protect) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); GURL url(test_server.GetURL("defaultresponse")); // Registers an entry for test url. It only allows 3 requests to be sent // in 200 milliseconds. std::string retry_policy = "OverloadTestPolicy"; URLFetcherProtectManager* manager = URLFetcherProtectManager::GetInstance(); URLFetcherProtectEntry* entry = new URLFetcherProtectEntry(200, 3, 11, 1, 2.0, 0, 256); manager->Register(retry_policy, entry); CreateFetcher(url, retry_policy); MessageLoop::current()->Run(); } // http://code.google.com/p/chromium/issues/detail?id=62758 TEST_F(CloudPrintURLFetcherRetryBackoffTest, FLAKY_GiveUp) { net::TestServer test_server(net::TestServer::TYPE_HTTP, FilePath(kDocRoot)); ASSERT_TRUE(test_server.Start()); GURL url(test_server.GetURL("defaultresponse")); // Registers an entry for test url. The backoff time is calculated by: // new_backoff = 2.0 * old_backoff + 0 // and maximum backoff time is 256 milliseconds. // Maximum retries allowed is set to 11. std::string retry_policy = "BackoffTestPolicy"; URLFetcherProtectManager* manager = URLFetcherProtectManager::GetInstance(); URLFetcherProtectEntry* entry = new URLFetcherProtectEntry(200, 3, 11, 1, 2.0, 0, 256); manager->Register(retry_policy, entry); CreateFetcher(url, retry_policy); MessageLoop::current()->Run(); } } // namespace. <|endoftext|>
<commit_before>// $Id: fe_hermite_shape_3D.C,v 1.4 2006-02-22 22:30:53 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ inlcludes // Local includes #include "fe.h" #include "elem.h" // Anonymous namespace for persistant variables. // This allows us to cache the global-to-local mapping transformation // FIXME: This should also screw up multithreading royally namespace { static unsigned int old_elem_id = libMesh::invalid_uint; static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0)); #ifdef DEBUG static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2); static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2); #endif // Compute the static coefficients for an element void hermite_compute_coefs(const Elem* elem) { // Coefficients are cached from old elements if (elem->id() == old_elem_id) return; old_elem_id = elem->id(); const Order mapping_order (elem->default_order()); const ElemType mapping_elem_type (elem->type()); const int n_mapping_shape_functions = FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type, mapping_order); std::vector<Point> dofpt; dofpt.push_back(Point(-1,-1,-1)); dofpt.push_back(Point(1,1,1)); for (int p = 0; p != 2; ++p) { dxdxi[0][p] = 0; dxdxi[1][p] = 0; dxdxi[2][p] = 0; #ifdef DEBUG dydxi[p] = 0; dzdeta[p] = 0; dxdzeta[p] = 0; dzdxi[p] = 0; dxdeta[p] = 0; dydzeta[p] = 0; #endif for (int i = 0; i != n_mapping_shape_functions; ++i) { const Real ddxi = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, dofpt[p]); const Real ddeta = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, dofpt[p]); const Real ddzeta = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 2, dofpt[p]); // dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all // be 0! dxdxi[0][p] += elem->point(i)(0) * ddxi; dxdxi[1][p] += elem->point(i)(1) * ddeta; dxdxi[2][p] += elem->point(i)(2) * ddzeta; #ifdef DEBUG dydxi[p] += elem->point(i)(1) * ddxi; dzdeta[p] += elem->point(i)(2) * ddeta; dxdzeta[p] += elem->point(i)(0) * ddzeta; dzdxi[p] += elem->point(i)(2) * ddxi; dxdeta[p] += elem->point(i)(0) * ddeta; dydzeta[p] += elem->point(i)(1) * ddzeta; #endif } // No singular elements! assert(dxdxi[0][p]); assert(dxdxi[1][p]); assert(dxdxi[2][p]); // No non-rectilinear or non-axis-aligned elements! #ifdef DEBUG assert(std::abs(dydxi[p]) < 1e-9); assert(std::abs(dzdeta[p]) < 1e-9); assert(std::abs(dxdzeta[p]) < 1e-9); assert(std::abs(dzdxi[p]) < 1e-9); assert(std::abs(dxdeta[p]) < 1e-9); assert(std::abs(dydzeta[p]) < 1e-9); #endif } } } // end anonymous namespace template <> Real FE<3,HERMITE>::shape(const ElemType, const Order, const unsigned int, const Point&) { std::cerr << "Hermite elements require the real element\n" << "to construct gradient-based degrees of freedom." << std::endl; error(); return 0.; } template <> Real FE<3,HERMITE>::shape(const Elem* elem, const Order order, const unsigned int i, const Point& p) { assert (elem != NULL); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } template <> Real FE<3,HERMITE>::shape_deriv(const ElemType, const Order, const unsigned int, const unsigned int, const Point&) { std::cerr << "Hermite elements require the real element\n" << "to construct gradient-based degrees of freedom." << std::endl; error(); return 0.; } template <> Real FE<3,HERMITE>::shape_deriv(const Elem* elem, const Order order, const unsigned int i, const unsigned int j, const Point& p) { assert (elem != NULL); assert (j == 0 || j == 1 || j == 2); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); switch (j) // Derivative type { case 0: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 1: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 2: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; } } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } template <> Real FE<3,HERMITE>::shape_second_deriv(const Elem* elem, const Order order, const unsigned int i, const unsigned int j, const Point& p) { assert (elem != NULL); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); switch (j) // Derivative type { case 0: return coef * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 1: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 2: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 3: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; case 4: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; case 5: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2)); break; } } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } <commit_msg>Make rectilinearity assertions less sensitive and tolerance-dependent<commit_after>// $Id: fe_hermite_shape_3D.C,v 1.5 2006-03-01 22:48:28 roystgnr Exp $ // The libMesh Finite Element Library. // Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // C++ inlcludes // Local includes #include "fe.h" #include "elem.h" // Anonymous namespace for persistant variables. // This allows us to cache the global-to-local mapping transformation // FIXME: This should also screw up multithreading royally namespace { static unsigned int old_elem_id = libMesh::invalid_uint; static std::vector<std::vector<Real> > dxdxi(3, std::vector<Real>(2, 0)); #ifdef DEBUG static std::vector<Real> dydxi(2), dzdeta(2), dxdzeta(2); static std::vector<Real> dzdxi(2), dxdeta(2), dydzeta(2); #endif // Compute the static coefficients for an element void hermite_compute_coefs(const Elem* elem) { // Coefficients are cached from old elements if (elem->id() == old_elem_id) return; old_elem_id = elem->id(); const Order mapping_order (elem->default_order()); const ElemType mapping_elem_type (elem->type()); const int n_mapping_shape_functions = FE<3,LAGRANGE>::n_shape_functions(mapping_elem_type, mapping_order); std::vector<Point> dofpt; dofpt.push_back(Point(-1,-1,-1)); dofpt.push_back(Point(1,1,1)); for (int p = 0; p != 2; ++p) { dxdxi[0][p] = 0; dxdxi[1][p] = 0; dxdxi[2][p] = 0; #ifdef DEBUG dydxi[p] = 0; dzdeta[p] = 0; dxdzeta[p] = 0; dzdxi[p] = 0; dxdeta[p] = 0; dydzeta[p] = 0; #endif for (int i = 0; i != n_mapping_shape_functions; ++i) { const Real ddxi = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 0, dofpt[p]); const Real ddeta = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 1, dofpt[p]); const Real ddzeta = FE<3,LAGRANGE>::shape_deriv (mapping_elem_type, mapping_order, i, 2, dofpt[p]); // dxdeta, dxdzeta, dydxi, dydzeta, dzdxi, dzdeta should all // be 0! dxdxi[0][p] += elem->point(i)(0) * ddxi; dxdxi[1][p] += elem->point(i)(1) * ddeta; dxdxi[2][p] += elem->point(i)(2) * ddzeta; #ifdef DEBUG dydxi[p] += elem->point(i)(1) * ddxi; dzdeta[p] += elem->point(i)(2) * ddeta; dxdzeta[p] += elem->point(i)(0) * ddzeta; dzdxi[p] += elem->point(i)(2) * ddxi; dxdeta[p] += elem->point(i)(0) * ddeta; dydzeta[p] += elem->point(i)(1) * ddzeta; #endif } // No singular elements! assert(dxdxi[0][p]); assert(dxdxi[1][p]); assert(dxdxi[2][p]); // No non-rectilinear or non-axis-aligned elements! #ifdef DEBUG assert(std::abs(dydxi[p]) < TOLERANCE); assert(std::abs(dzdeta[p]) < TOLERANCE); assert(std::abs(dxdzeta[p]) < TOLERANCE); assert(std::abs(dzdxi[p]) < TOLERANCE); assert(std::abs(dxdeta[p]) < TOLERANCE); assert(std::abs(dydzeta[p]) < TOLERANCE); #endif } } } // end anonymous namespace template <> Real FE<3,HERMITE>::shape(const ElemType, const Order, const unsigned int, const Point&) { std::cerr << "Hermite elements require the real element\n" << "to construct gradient-based degrees of freedom." << std::endl; error(); return 0.; } template <> Real FE<3,HERMITE>::shape(const Elem* elem, const Order order, const unsigned int i, const Point& p) { assert (elem != NULL); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } template <> Real FE<3,HERMITE>::shape_deriv(const ElemType, const Order, const unsigned int, const unsigned int, const Point&) { std::cerr << "Hermite elements require the real element\n" << "to construct gradient-based degrees of freedom." << std::endl; error(); return 0.; } template <> Real FE<3,HERMITE>::shape_deriv(const Elem* elem, const Order order, const unsigned int i, const unsigned int j, const Point& p) { assert (elem != NULL); assert (j == 0 || j == 1 || j == 2); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); switch (j) // Derivative type { case 0: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 1: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 2: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; } } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } template <> Real FE<3,HERMITE>::shape_second_deriv(const Elem* elem, const Order order, const unsigned int i, const unsigned int j, const Point& p) { assert (elem != NULL); hermite_compute_coefs(elem); const ElemType type = elem->type(); switch (order) { // 3rd-order tricubic Hermite functions case THIRD: { switch (type) { case HEX8: case HEX20: case HEX27: { assert (i<64); std::vector<unsigned int> bases1D; Real coef = FEHermite<1>::hermite_bases(bases1D, dxdxi, i, 3); switch (j) // Derivative type { case 0: return coef * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 1: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 2: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape(bases1D[2],p(2)); break; case 3: return coef * FEHermite<1>::hermite_raw_shape_deriv(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; case 4: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_deriv(bases1D[2],p(2)); break; case 5: return coef * FEHermite<1>::hermite_raw_shape(bases1D[0],p(0)) * FEHermite<1>::hermite_raw_shape(bases1D[1],p(1)) * FEHermite<1>::hermite_raw_shape_second_deriv(bases1D[2],p(2)); break; } } default: std::cerr << "ERROR: Unsupported element type!" << std::endl; error(); } } // by default throw an error default: std::cerr << "ERROR: Unsupported polynomial order!" << std::endl; error(); } error(); return 0.; } <|endoftext|>
<commit_before>// $Id: NMRSpectrum.C,v 1.7 2000/09/22 14:14:59 amoll Exp $ #include<BALL/NMR/NMRSpectrum.h> #include<BALL/FORMAT/PDBFile.h> #include<BALL/KERNEL/PTE.h> #include<BALL/COMMON/limits.h> /////////////////////////////////////////////////////////////////////////// /* shift Module sind alle von Prozessoren abgeleitet NMRSpectrum verwaltet eine Liste mit Prozessoren verbesserung : eine von Prozessor abgeleitete gemeinsame Basisklasse der shift Module entwerfen und die Liste darauf definieren stellt sicher das nur shift module in der Liste abgelegt werden koennen. Shift Module koennen ueber Strings definiert werden. neue Module erforden eine neue Zeile in insert_shift_module(CBallString) und dementsprechung eine neu compilierung. besser waere es die Neucompilierung auf das neue Modulzu beschraenken. !!! korrigieren : Fehler wenn nur ein peak vorhanden : stepSize = 0 und Schleife terminiert nicht bei Ausgabe in file */ /////////////////////////////////////////////////////////////////////////// using namespace std; namespace BALL { typedef struct { String name; float shift; } name_shift; NMRSpectrum::NMRSpectrum() : system_(0), density_(100), is_sorted_(false) { } NMRSpectrum::~NMRSpectrum() { } void NMRSpectrum::setSystem(System* s) { system_ = s; } const System* NMRSpectrum::getSystem() const { return system_; } void NMRSpectrum::calculateShifts() { system_->apply(shift_model_); } void NMRSpectrum::createSpectrum() { system_->apply(create_spectrum_); spectrum_ = create_spectrum_.getPeakList(); spectrum_.sort(); } const list<Peak1D>& NMRSpectrum::getPeakList() const { return spectrum_; } void NMRSpectrum::setPeakList(const list<Peak1D>& peak_list) { spectrum_ = peak_list; is_sorted_ = false; } float NMRSpectrum::getSpectrumMin() const { if (is_sorted_) { return spectrum_.begin()->getValue(); } float min = Limits<float>::max(); list<Peak1D>::const_iterator it = spectrum_.begin(); while (it != spectrum_.end()) { if (it->getValue() < min) { min = it->getValue(); } it++; } return min; } float NMRSpectrum::getSpectrumMax() const { if (is_sorted_) { return spectrum_.rbegin()->getValue(); } float max = Limits<float>::min(); list<Peak1D>::const_iterator it = spectrum_.begin(); while (it != spectrum_.end()) { if (it->getValue() > max) { max = it->getValue(); } it++; } return max; } void NMRSpectrum::sortSpectrum() { spectrum_.sort(); is_sorted_ = true; } void NMRSpectrum::setDensity(Size density) { density_ = density; } Size NMRSpectrum::getDensity() const { return density_; } void NMRSpectrum::plotPeaks(const String& filename) const { ofstream outfile(filename.c_str (), ios::out); list<Peak1D>::const_iterator peak_iter = spectrum_.begin(); for (; peak_iter != spectrum_.end(); ++peak_iter) { outfile << peak_iter->getValue() << " " << peak_iter->getHeight() << endl; } } void NMRSpectrum::writePeaks(const String& filename) const { float shift; ofstream outfile (filename.c_str(), ios::out); AtomIterator atom_iter = system_->beginAtom(); for (; atom_iter != system_->endAtom(); ++atom_iter) { shift = (*atom_iter).getProperty ("chemical_shift").getFloat(); if (shift != 0 && shift < 100) { outfile << (*atom_iter).getFullName() << " " << shift << endl; } } outfile << "END" << " " << 0.0 << endl; } void NMRSpectrum::plotSpectrum(const String& filename) const { // berechnet die peak Daten und schreibt sie in das file : filename list<Peak1D>::const_iterator peak_iter1; list<Peak1D>::const_iterator peak_iter2; ofstream outfile(filename.c_str(), ios::out); // Berechnung der Dichteverteilung: float omega, ts, gs; const float& min = getSpectrumMin(); const float& max = getSpectrumMax(); const float stepSize = max - min / density_; float y = stepSize; float value = peak_iter1->getValue(); float value_old = value; peak_iter1 = spectrum_.begin(); for (float x = min; x <= max; x += y) { if (x < value) { omega = x; } else { omega = value; ++peak_iter1; value_old = value; value = (*peak_iter1).getValue(); x -= y; } gs = 0; for (peak_iter2 = spectrum_.begin(); peak_iter2 != spectrum_.end(); ++peak_iter2) { const float number = peak_iter2->getValue() * 2 * Constants::PI * 1e6 - omega * 2 * Constants::PI * 1e6; ts = peak_iter2->getHeight() / (1 + (number * number * 4 / peak_iter2->getWidth())); gs += ts; } outfile << omega << " " << gs << endl; if (((x - value) < stepSize && (x - value) > -stepSize) || ((x - value_old) < stepSize && (x - value_old) > -stepSize) ) { y = stepSize / 10; } else { y = stepSize; } } } void makeDifference(const float& diff, const String &a, const String& b, const String& out) { std::list<name_shift> liste_b; std::list<name_shift>::iterator iter; String atom_name; float shift; name_shift *eintrag; ifstream infile_b (b.c_str(), ios::in); while (atom_name != "END"); { infile_b >> atom_name; infile_b >> shift; eintrag = new name_shift; eintrag->name = atom_name; eintrag->shift = shift; liste_b.push_back (*eintrag); } ifstream infile_a (a.c_str(), ios::in); ofstream outfile (out.c_str(), ios::out); bool found; do { found = false; infile_a >> atom_name; infile_a >> shift; for (iter = liste_b.begin(); iter != liste_b.end(); ++iter) { if ((atom_name == (*iter).name) && ((shift - (*iter).shift < diff) && (shift - (*iter).shift > -diff))) { found = true; break; } } if (!found) { outfile << atom_name << " " << shift << endl; } } while (atom_name != "END"); outfile << "END" << " " << 0.0 << endl; } void setDifference(NMRSpectrum* a, NMRSpectrum* b, const String& outpdb, const String& out) { const System& system_a = *a->getSystem(); const System& system_b = *b->getSystem(); StringHashMap<Atom*> table_b; AtomIterator atom_iter = system_b.beginAtom(); for (; +atom_iter; ++atom_iter) { if ((*atom_iter).getElement() == PTE[Element::H]) { table_b[(*atom_iter).getFullName()] = &(*atom_iter); } } PDBAtom* patom_a; Atom* atom_b; ofstream dfile(out.c_str(), ios::out); float shift_a, shift_b, difference; atom_iter = system_a.beginAtom(); for (; +atom_iter; ++atom_iter) { patom_a = RTTI::castTo<PDBAtom>((*atom_iter)); patom_a->setOccupancy(0.5); if ((*atom_iter).getElement() == PTE[Element::H] && table_b.has((*atom_iter).getFullName())) { atom_b = table_b[(*atom_iter).getFullName()]; shift_a = patom_a->getProperty ("chemical_shift").getFloat(); shift_b = atom_b->getProperty ("chemical_shift").getFloat(); difference = shift_a - shift_b; if (shift_a > 100) { difference = 0.5; } patom_a->setOccupancy(patom_a->getOccupancy() + difference); dfile << (*atom_iter).getFullName() << " " << shift_a << " " << difference << endl; } } PDBFile outfile(outpdb, ios::out); //outfile.open; outfile << system_a; outfile.close(); } } // namespace Ball <commit_msg>changed: rewrite of the plotSpectrum method<commit_after>// $Id: NMRSpectrum.C,v 1.8 2000/09/27 07:21:10 oliver Exp $ #include<BALL/NMR/NMRSpectrum.h> #include<BALL/FORMAT/PDBFile.h> #include<BALL/KERNEL/PTE.h> #include<BALL/COMMON/limits.h> /////////////////////////////////////////////////////////////////////////// /* shift Module sind alle von Prozessoren abgeleitet NMRSpectrum verwaltet eine Liste mit Prozessoren verbesserung : eine von Prozessor abgeleitete gemeinsame Basisklasse der shift Module entwerfen und die Liste darauf definieren stellt sicher das nur shift module in der Liste abgelegt werden koennen. Shift Module koennen ueber Strings definiert werden. neue Module erforden eine neue Zeile in insert_shift_module(CBallString) und dementsprechung eine neu compilierung. besser waere es die Neucompilierung auf das neue Modulzu beschraenken. !!! korrigieren : Fehler wenn nur ein peak vorhanden : stepSize = 0 und Schleife terminiert nicht bei Ausgabe in file */ /////////////////////////////////////////////////////////////////////////// using namespace std; namespace BALL { typedef struct { String name; float shift; } name_shift; NMRSpectrum::NMRSpectrum() : system_(0), density_(100), is_sorted_(false) { } NMRSpectrum::~NMRSpectrum() { } void NMRSpectrum::setSystem(System* s) { system_ = s; } const System* NMRSpectrum::getSystem() const { return system_; } void NMRSpectrum::calculateShifts() { system_->apply(shift_model_); } void NMRSpectrum::createSpectrum() { create_spectrum_.init(); system_->apply(create_spectrum_); spectrum_ = create_spectrum_.getPeakList(); spectrum_.sort(); } const ShiftModel& NMRSpectrum::getShiftModel() const { return shift_model_; } void NMRSpectrum::setShiftModel(const ShiftModel& model) { shift_model_ = model; } const list<Peak1D>& NMRSpectrum::getPeakList() const { return spectrum_; } void NMRSpectrum::setPeakList(const list<Peak1D>& peak_list) { spectrum_ = peak_list; is_sorted_ = false; } float NMRSpectrum::getSpectrumMin() const { if (is_sorted_) { return spectrum_.begin()->getValue(); } float min = Limits<float>::max(); list<Peak1D>::const_iterator it = spectrum_.begin(); while (it != spectrum_.end()) { if (it->getValue() < min) { min = it->getValue(); } it++; } return min; } float NMRSpectrum::getSpectrumMax() const { if (is_sorted_) { return spectrum_.rbegin()->getValue(); } float max = Limits<float>::min(); list<Peak1D>::const_iterator it = spectrum_.begin(); while (it != spectrum_.end()) { if (it->getValue() > max) { max = it->getValue(); } it++; } return max; } void NMRSpectrum::sortSpectrum() { spectrum_.sort(); is_sorted_ = true; } void NMRSpectrum::setDensity(Size density) { density_ = density; } Size NMRSpectrum::getDensity() const { return density_; } void NMRSpectrum::plotPeaks(const String& filename) const { ofstream outfile(filename.c_str (), ios::out); list<Peak1D>::const_iterator peak_it = spectrum_.begin(); for (; peak_it != spectrum_.end(); ++peak_it) { outfile << peak_it->getValue() << " " << peak_it->getHeight() << " " << peak_it->getAtom()->getFullName()<< endl; } } void NMRSpectrum::writePeaks(const String& filename) const { float shift; ofstream outfile (filename.c_str(), ios::out); AtomIterator atom_iter = system_->beginAtom(); for (; atom_iter != system_->endAtom(); ++atom_iter) { shift = (*atom_iter).getProperty(ShiftModule::PROPERTY__SHIFT).getFloat(); if (shift != 0.0) { outfile << (*atom_iter).getFullName() << " " << shift << endl; } } outfile << "END" << " " << 0.0 << endl; } void NMRSpectrum::plotSpectrum(const String& filename) const { // berechnet die peak Daten und schreibt sie in das file : filename ofstream outfile(filename.c_str(), ios::out); // Berechnung der Dichteverteilung: float min = getSpectrumMin(); float max = getSpectrumMax(); float step_size = (max - min) / density_; if (step_size <= 0.0) { Log.error() << "NMRSpectrum:plotSpectrum: spectrum has empty range. Aborted." << endl; } else { Log.info() << " min = " << min << " max = " << max << " density_ = " << density_ << " step_size = " << step_size << endl; List<Peak1D>::const_iterator peak_it; for (float x = min; x <= max; x += step_size) { float y = 0; for (peak_it = spectrum_.begin(); peak_it != spectrum_.end(); ++peak_it) { float number = peak_it->getValue() * 2 * Constants::PI - x * 2 * Constants::PI; y += peak_it->getHeight() / (1 + (number * number * 4 / (peak_it->getWidth() / 10.0))); } outfile << x << " " << y << endl; } } outfile.close(); } void makeDifference(const float& diff, const String &a, const String& b, const String& out) { std::list<name_shift> liste_b; std::list<name_shift>::iterator iter; String atom_name; float shift; name_shift *eintrag; ifstream infile_b (b.c_str(), ios::in); while (atom_name != "END"); { infile_b >> atom_name; infile_b >> shift; eintrag = new name_shift; eintrag->name = atom_name; eintrag->shift = shift; liste_b.push_back (*eintrag); } ifstream infile_a (a.c_str(), ios::in); ofstream outfile (out.c_str(), ios::out); bool found; do { found = false; infile_a >> atom_name; infile_a >> shift; for (iter = liste_b.begin(); iter != liste_b.end(); ++iter) { if ((atom_name == (*iter).name) && ((shift - (*iter).shift < diff) && (shift - (*iter).shift > -diff))) { found = true; break; } } if (!found) { outfile << atom_name << " " << shift << endl; } } while (atom_name != "END"); outfile << "END" << " " << 0.0 << endl; } } // namespace Ball <|endoftext|>
<commit_before>#include "ScriptWrapper.h" #include "MagnetiteCore.h" #include "World.h" #include "BaseBlock.h" #include "BlockFactory.h" #include <fstream> using namespace v8; std::string strize( Handle<Value> s ) { String::Utf8Value v(s); return *v ? *v : ""; } void report( TryCatch* handler ) { HandleScope scope; if(handler->Message().IsEmpty()) { // No message Util::log( strize( handler->Exception() ) ); } else { Handle<Message> message = handler->Message(); std::string file = strize( message->GetScriptResourceName() ); int lnnum = message->GetLineNumber(); Util::log( file + ":" + Util::toString(lnnum) + " " + strize( handler->Exception() ) ); } } typedef std::map<BaseBlock*,PersistentObject> WrappedBlocks; WrappedBlocks gWrappedBlocks; Persistent<ObjectTemplate> blockTemplate; ValueHandle wrapBlock( BaseBlock* block ) { if( !block ) return Undefined(); WrappedBlocks::iterator it = gWrappedBlocks.find( block ); if( it != gWrappedBlocks.end() ) { return it->second; } if( blockTemplate.IsEmpty() ) { blockTemplate = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); blockTemplate->Set( String::New( "type" ), String::New( block->getType().c_str() ) ); } PersistentObject obj = Persistent<Object>::New(blockTemplate->NewInstance()); gWrappedBlocks.insert( WrappedBlocks::value_type( block, obj) ); return obj; } ValueHandle runFile( std::string filename ) { std::ifstream is(filename.c_str(), std::ios_base::in); if(is.is_open()) { std::string source; std::string line; while( !is.eof() ) { std::getline(is, line); source.append(line); } HandleScope scope; TryCatch try_catch; Handle<Script> script = Script::Compile( String::New(source.c_str()), String::New(filename.c_str()) ); if( script.IsEmpty() ) { if(try_catch.HasCaught()) { report(&try_catch); return Undefined(); } } ValueHandle result = script->Run(); if(try_catch.HasCaught()) { report(&try_catch); return Undefined(); } return scope.Close(result); } else { Util::log("Unable to open: " + filename); } return Undefined(); } ValueHandle log(const Arguments& args) { for( size_t i = 0; i < args.Length(); i++ ) { Util::log( strize(args[i]->ToString() )); } } ValueHandle import(const Arguments& args) { if( args.Length() >= 1 ) { return runFile( strize( args[0]->ToString() ) ); } return Undefined(); } /*=========== World Object functions ===========*/ ValueHandle world_getBlock(const Arguments& args) { if( args.Length() >= 3 ) { return wrapBlock(CoreSingleton->getWorld()->getBlockAt( args[0]->Int32Value(), args[1]->Int32Value(), args[2]->Int32Value() )); } return Undefined(); } ValueHandle world_removeBlock(const Arguments& args) { if( args.Length() >= 3 ) { CoreSingleton->getWorld()->removeBlockAt( args[0]->Int32Value(), args[1]->Int32Value(), args[2]->Int32Value() ); } return Undefined(); } ValueHandle world_createBlock(const Arguments& args) { if( args.Length() >= 1 ) { BaseBlock* block = FactoryManager::getManager().createBlock( strize(args[0]) ); if( block == NULL ) return Undefined(); if( args.Length() >= 4 ) { CoreSingleton->getWorld()->setBlockAt(block, args[1]->Int32Value(), args[2]->Int32Value(), args[3]->Int32Value() ); } return wrapBlock(block); } return Undefined(); } void ScriptWrapper::init() { HandleScope scope; Handle<ObjectTemplate> global = ObjectTemplate::New(); global->Set(String::New("import"), FunctionTemplate::New(import)); Handle<ObjectTemplate> console = ObjectTemplate::New(); console->Set(String::New("log"), FunctionTemplate::New(log)); Handle<ObjectTemplate> world = ObjectTemplate::New(); world->Set(String::New("getBlock"), FunctionTemplate::New(world_getBlock)); world->Set(String::New("removeBlock"), FunctionTemplate::New(world_removeBlock)); world->Set(String::New("createBlock"), FunctionTemplate::New(world_createBlock)); global->Set(String::New("console"), console); global->Set(String::New("world"), world); mContext = Context::New(NULL, global); Context::Scope ctx_scope(mContext); runFile("../scripts/main.js"); } <commit_msg>move scripts folder<commit_after>#include "ScriptWrapper.h" #include "MagnetiteCore.h" #include "World.h" #include "BaseBlock.h" #include "BlockFactory.h" #include <fstream> using namespace v8; std::string strize( Handle<Value> s ) { String::Utf8Value v(s); return *v ? *v : ""; } void report( TryCatch* handler ) { HandleScope scope; if(handler->Message().IsEmpty()) { // No message Util::log( strize( handler->Exception() ) ); } else { Handle<Message> message = handler->Message(); std::string file = strize( message->GetScriptResourceName() ); int lnnum = message->GetLineNumber(); Util::log( file + ":" + Util::toString(lnnum) + " " + strize( handler->Exception() ) ); } } typedef std::map<BaseBlock*,PersistentObject> WrappedBlocks; WrappedBlocks gWrappedBlocks; Persistent<ObjectTemplate> blockTemplate; ValueHandle wrapBlock( BaseBlock* block ) { if( !block ) return Undefined(); WrappedBlocks::iterator it = gWrappedBlocks.find( block ); if( it != gWrappedBlocks.end() ) { return it->second; } if( blockTemplate.IsEmpty() ) { blockTemplate = Persistent<ObjectTemplate>::New(ObjectTemplate::New()); blockTemplate->Set( String::New( "type" ), String::New( block->getType().c_str() ) ); } PersistentObject obj = Persistent<Object>::New(blockTemplate->NewInstance()); gWrappedBlocks.insert( WrappedBlocks::value_type( block, obj) ); return obj; } ValueHandle runFile( std::string filename ) { std::ifstream is(filename.c_str(), std::ios_base::in); if(is.is_open()) { std::string source; std::string line; while( !is.eof() ) { std::getline(is, line); source.append(line); } HandleScope scope; TryCatch try_catch; Handle<Script> script = Script::Compile( String::New(source.c_str()), String::New(filename.c_str()) ); if( script.IsEmpty() ) { if(try_catch.HasCaught()) { report(&try_catch); return Undefined(); } } ValueHandle result = script->Run(); if(try_catch.HasCaught()) { report(&try_catch); return Undefined(); } return scope.Close(result); } else { Util::log("Unable to open: " + filename); } return Undefined(); } ValueHandle log(const Arguments& args) { for( size_t i = 0; i < args.Length(); i++ ) { Util::log( strize(args[i]->ToString() )); } } ValueHandle import(const Arguments& args) { if( args.Length() >= 1 ) { return runFile( strize( args[0]->ToString() ) ); } return Undefined(); } /*=========== World Object functions ===========*/ ValueHandle world_getBlock(const Arguments& args) { if( args.Length() >= 3 ) { return wrapBlock(CoreSingleton->getWorld()->getBlockAt( args[0]->Int32Value(), args[1]->Int32Value(), args[2]->Int32Value() )); } return Undefined(); } ValueHandle world_removeBlock(const Arguments& args) { if( args.Length() >= 3 ) { CoreSingleton->getWorld()->removeBlockAt( args[0]->Int32Value(), args[1]->Int32Value(), args[2]->Int32Value() ); } return Undefined(); } ValueHandle world_createBlock(const Arguments& args) { if( args.Length() >= 1 ) { BaseBlock* block = FactoryManager::getManager().createBlock( strize(args[0]) ); if( block == NULL ) return Undefined(); if( args.Length() >= 4 ) { CoreSingleton->getWorld()->setBlockAt(block, args[1]->Int32Value(), args[2]->Int32Value(), args[3]->Int32Value() ); } return wrapBlock(block); } return Undefined(); } void ScriptWrapper::init() { HandleScope scope; Handle<ObjectTemplate> global = ObjectTemplate::New(); global->Set(String::New("import"), FunctionTemplate::New(import)); Handle<ObjectTemplate> console = ObjectTemplate::New(); console->Set(String::New("log"), FunctionTemplate::New(log)); Handle<ObjectTemplate> world = ObjectTemplate::New(); world->Set(String::New("getBlock"), FunctionTemplate::New(world_getBlock)); world->Set(String::New("removeBlock"), FunctionTemplate::New(world_removeBlock)); world->Set(String::New("createBlock"), FunctionTemplate::New(world_createBlock)); global->Set(String::New("console"), console); global->Set(String::New("world"), world); mContext = Context::New(NULL, global); Context::Scope ctx_scope(mContext); runFile("./scripts/main.js"); } <|endoftext|>
<commit_before>#include "ValueProcessor.h" #include <sstream> #include <iostream> template <class T> inline std::string to_string (const T& t) { std::stringstream ss; ss << t; return ss.str(); } ValueProcessor::ValueProcessor() { pushScope(); } ValueProcessor::~ValueProcessor() { popScope(); } TokenList* ValueProcessor::processValue(TokenList* value) { TokenList newvalue; Value* v; TokenList* var; Token* token; TokenList* variable; while (value->size() > 0) { v = processStatement(value); if (v != NULL) { if (newvalue.size() > 0) newvalue.push(new Token(" ", Token::WHITESPACE)); newvalue.push(v->getTokens()); delete v; } else if (value->size() > 0) { if (newvalue.size() > 0) newvalue.push(new Token(" ", Token::WHITESPACE)); if (value->front()->type == Token::ATKEYWORD && (variable = getVariable(value->front()->str)) != NULL) { newvalue.push(variable); delete value->shift(); } else if (value->front()->type == Token::STRING || value->front()->type == Token::URL) { processString(value->front()); newvalue.push(value->shift()); } else { if ((var = processDeepVariable(value)) != NULL) { newvalue.push(var); delete var; delete value->shift(); delete value->shift(); } else if ((token = processEscape(value)) != NULL) newvalue.push(token); else newvalue.push(value->shift()); } } } value->push(&newvalue); return value; } void ValueProcessor::putVariable(string key, TokenList* value) { scopes.back()->insert(pair<string, TokenList*>(key, value)); } TokenList* ValueProcessor::getVariable(string key) { list<map<string, TokenList*>*>::reverse_iterator it; map<string, TokenList*>::iterator mit; for (it = scopes.rbegin(); it != scopes.rend(); it++) { mit = (*it)->find(key); if (mit != (*it)->end()) return mit->second; } return NULL; } void ValueProcessor::pushScope() { scopes.push_back(new map<string, TokenList*>()); } void ValueProcessor::popScope() { // delete tokenlists in scope delete scopes.back(); scopes.pop_back(); } Value* ValueProcessor::processStatement(TokenList* value) { Value* op, *v = processConstant(value); if (v != NULL) { while ((op = processOperator(value, v))) v = op; return v; } else return NULL; } Value* ValueProcessor::processOperator(TokenList* value, Value* v1, Token* lastop) { Value* v2, *tmp; Token* op; string operators("+-*/"); while (value->size() > 0 && value->front()->type == Token::WHITESPACE) { delete value->shift(); } if (value->size() == 0 || operators.find(value->front()->str) == string::npos) return NULL; if (lastop != NULL && operators.find(lastop->str) > operators.find(value->front()->str)) { return NULL; } op = value->shift(); v2 = processConstant(value); if (v2 == NULL) { if (value->size() > 0) throw new ParseException(value->front()->str, "Constant or @-variable"); else throw new ParseException("end of line", "Constant or @-variable"); } while ((tmp = processOperator(value, v2, op))) v2 = tmp; if (v2->type == Value::COLOR && v1->type != Value::COLOR) { if (op->str == "-" || op->str == "/") throw new ValueException("Cannot substract or divide a color \ from a number"); tmp = v1; v1 = v2; v2 = tmp; } if (op->str == "+") v1->add(v2); else if (op->str == "-") v1->substract(v2); else if (op->str == "*") v1->multiply(v2); else if (op->str == "/") v1->divide(v2); delete v2; return v1; } Value* ValueProcessor::processConstant(TokenList* value) { Token* token; Value* ret; vector<Value*> arguments; TokenList* variable; while (value->size() > 0 && value->front()->type == Token::WHITESPACE) { delete value->shift(); } if (value->size() == 0) return NULL; token = value->front(); switch(token->type) { case Token::HASH: // generate color from hex value return new Color(value->shift()); case Token::NUMBER: case Token::PERCENTAGE: case Token::DIMENSION: return new Value(value->shift()); case Token::FUNCTION: value->shift(); if (value->front()->type != Token::PAREN_CLOSED) arguments.push_back(processConstant(value)); while (value->front()->str == ",") { delete value->shift(); arguments.push_back(processConstant(value)); } if (value->front()->type != Token::PAREN_CLOSED) throw new ParseException(value->front()->str, ")"); delete value->shift(); return processFunction(token, arguments); case Token::ATKEYWORD: if ((variable = getVariable(token->str)) != NULL) { TokenList* var = variable->clone(); ret = processConstant(var); while(!var->empty() && var->front()->type == Token::WHITESPACE) delete var->shift(); if (!var->empty()) { delete ret; ret = NULL; } else delete value->shift(); delete var; return ret; } else return NULL; case Token::PAREN_OPEN: delete value->shift(); ret = processStatement(value); if (value->front()->type == Token::PAREN_CLOSED) delete value->shift(); return ret; default: TokenList* var = processDeepVariable(value); if (var != NULL) { ret = processConstant(var); if (ret != NULL) { delete value->shift(); delete value->shift(); } delete var; return ret; } else return NULL; } } TokenList* ValueProcessor::processDeepVariable (TokenList* value) { Token* first, *second; TokenList* var; string key = "@"; if (value->size() < 2) return NULL; first = value->front(); second = value->at(1); if (first->type != Token::OTHER || first->str != "@" || second->type != Token::ATKEYWORD || (var = getVariable(second->str)) == NULL) return NULL; if (var->size() > 1 || var->front()->type != Token::STRING) return NULL; // generate key with '@' + var without quotes key.append(var->front()-> str.substr(1, var->front()->str.size() - 2)); var = getVariable(key); if (var == NULL) return NULL; return var->clone(); } Value* ValueProcessor::processFunction(Token* function, vector<Value*> arguments) { Color* color; string percentage; if(function->str == "rgb(") { // Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER) if (arguments.size() == 3 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::NUMBER && arguments[2]->type == Value::NUMBER) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue()); } } else if(function->str == "rgba(") { // Color rgba(@red: NUMBER, @green: NUMBER, @blue: NUMBER, // @alpha: NUMBER) if (arguments.size() == 4 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::NUMBER && arguments[2]->type == Value::NUMBER) { if (arguments[3]->type == Value::NUMBER) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue(), arguments[3]->getValue()); } else if (arguments[3]->type == Value::PERCENTAGE) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue(), arguments[3]->getValue() * .01); } } } else if (function->str == "lighten(") { // Color lighten(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->lighten(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "darken(") { // Color darken(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->darken(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "saturate(") { // Color saturate(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->saturate(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "desaturate(") { // Color desaturate(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "fadein(") { // Color fadein(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->fadein(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "fadeout(") { // Color fadeout(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "spin(") { // Color fadein(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::NUMBER) { static_cast<Color*>(arguments[0])->spin(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "hsl(") { // Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE) if (arguments.size() == 3 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::PERCENTAGE && arguments[2]->type == Value::PERCENTAGE) { color = new Color(0,0,0); color->setHSL(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue()); return color; } } else if (function->str == "hue(") { // NUMBER hue(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue())); return new Value(new Token(percentage, Token::NUMBER)); } } else if (function->str == "saturation(") { // PERCENTAGE saturation(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation())); percentage.append("%"); return new Value(new Token(percentage, Token::PERCENTAGE)); } } else if (function->str == "lightness(") { // PERCENTAGE lightness(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness())); percentage.append("%"); return new Value(new Token(percentage, Token::PERCENTAGE)); } } else return NULL; return NULL; } void ValueProcessor::processString(Token* token) { size_t start, end; string key = "@", value; TokenList* var; if ((start = token->str.find("@{")) == string::npos || (end = token->str.find("}", start)) == string::npos) return; key.append(token->str.substr(start + 2, end - (start + 2))); var = getVariable(key); if (var == NULL) return; value = *var->toString(); // Remove quotes of strings. if (var->size() == 1 && var->front()->type == Token::STRING) value = value.substr(1, value.size() - 2); token->str.replace(start, (end + 1) - start, value); } Token* ValueProcessor::processEscape (TokenList* value) { Token* first, *second; if (value->size() < 2) return NULL; first = value->front(); second = value->at(1); if (first->str != "~" || second->type != Token::STRING) return NULL; delete value->shift(); second->str = second->str.substr(1, second->str.size() - 2); return value->shift(); } <commit_msg>Added more exceptions for invalid syntax.<commit_after>#include "ValueProcessor.h" #include <sstream> #include <iostream> template <class T> inline std::string to_string (const T& t) { std::stringstream ss; ss << t; return ss.str(); } ValueProcessor::ValueProcessor() { pushScope(); } ValueProcessor::~ValueProcessor() { popScope(); } TokenList* ValueProcessor::processValue(TokenList* value) { TokenList newvalue; Value* v; TokenList* var; Token* token; TokenList* variable; while (value->size() > 0) { v = processStatement(value); if (v != NULL) { if (newvalue.size() > 0) newvalue.push(new Token(" ", Token::WHITESPACE)); newvalue.push(v->getTokens()); delete v; } else if (value->size() > 0) { if (newvalue.size() > 0) newvalue.push(new Token(" ", Token::WHITESPACE)); if (value->front()->type == Token::ATKEYWORD && (variable = getVariable(value->front()->str)) != NULL) { newvalue.push(variable); delete value->shift(); } else if (value->front()->type == Token::STRING || value->front()->type == Token::URL) { processString(value->front()); newvalue.push(value->shift()); } else { if ((var = processDeepVariable(value)) != NULL) { newvalue.push(var); delete var; delete value->shift(); delete value->shift(); } else if ((token = processEscape(value)) != NULL) newvalue.push(token); else newvalue.push(value->shift()); } } } value->push(&newvalue); return value; } void ValueProcessor::putVariable(string key, TokenList* value) { scopes.back()->insert(pair<string, TokenList*>(key, value)); } TokenList* ValueProcessor::getVariable(string key) { list<map<string, TokenList*>*>::reverse_iterator it; map<string, TokenList*>::iterator mit; for (it = scopes.rbegin(); it != scopes.rend(); it++) { mit = (*it)->find(key); if (mit != (*it)->end()) return mit->second; } return NULL; } void ValueProcessor::pushScope() { scopes.push_back(new map<string, TokenList*>()); } void ValueProcessor::popScope() { // delete tokenlists in scope delete scopes.back(); scopes.pop_back(); } Value* ValueProcessor::processStatement(TokenList* value) { Value* op, *v = processConstant(value); if (v != NULL) { while ((op = processOperator(value, v))) v = op; return v; } else return NULL; } Value* ValueProcessor::processOperator(TokenList* value, Value* v1, Token* lastop) { Value* v2, *tmp; Token* op; string operators("+-*/"); while (value->size() > 0 && value->front()->type == Token::WHITESPACE) { delete value->shift(); } if (value->size() == 0 || operators.find(value->front()->str) == string::npos) return NULL; if (lastop != NULL && operators.find(lastop->str) > operators.find(value->front()->str)) { return NULL; } op = value->shift(); v2 = processConstant(value); if (v2 == NULL) { if (value->size() > 0) throw new ParseException(value->front()->str, "Constant or @-variable"); else throw new ParseException("end of line", "Constant or @-variable"); } while ((tmp = processOperator(value, v2, op))) v2 = tmp; if (v2->type == Value::COLOR && v1->type != Value::COLOR) { if (op->str == "-" || op->str == "/") throw new ValueException("Cannot substract or divide a color \ from a number"); tmp = v1; v1 = v2; v2 = tmp; } if (op->str == "+") v1->add(v2); else if (op->str == "-") v1->substract(v2); else if (op->str == "*") v1->multiply(v2); else if (op->str == "/") v1->divide(v2); delete v2; return v1; } Value* ValueProcessor::processConstant(TokenList* value) { Token* token; Value* ret; vector<Value*> arguments; TokenList* variable; while (value->size() > 0 && value->front()->type == Token::WHITESPACE) { delete value->shift(); } if (value->size() == 0) return NULL; token = value->front(); switch(token->type) { case Token::HASH: // generate color from hex value return new Color(value->shift()); case Token::NUMBER: case Token::PERCENTAGE: case Token::DIMENSION: return new Value(value->shift()); case Token::FUNCTION: value->shift(); // TODO: Check if the function can be processed before parsing // arguments. Right now the arguments are lost if the function // isn't reckognized. if (value->front()->type != Token::PAREN_CLOSED) arguments.push_back(processConstant(value)); while (value->front()->str == ",") { delete value->shift(); arguments.push_back(processConstant(value)); } if (value->front()->type != Token::PAREN_CLOSED) throw new ParseException(value->front()->str, ")"); delete value->shift(); return processFunction(token, arguments); case Token::ATKEYWORD: if ((variable = getVariable(token->str)) != NULL) { TokenList* var = variable->clone(); ret = processConstant(var); while(!var->empty() && var->front()->type == Token::WHITESPACE) delete var->shift(); if (!var->empty()) { delete ret; ret = NULL; } else delete value->shift(); delete var; return ret; } else return NULL; case Token::PAREN_OPEN: delete value->shift(); ret = processStatement(value); if (ret == NULL) throw new ValueException("Expecting a valid expression in \ parentheses. Something like '(5 + @x)'. Alternatively, one of the \ variables in the expression may not contain a proper value like 5, \ 5%, 5em or #555555."); if (value->size() == 0) throw new ParseException("end of line", ")"); else if (value->front()->type == Token::PAREN_CLOSED) delete value->shift(); else throw new ParseException(value->front()->str, ")"); return ret; default: TokenList* var = processDeepVariable(value); if (var != NULL) { ret = processConstant(var); if (ret != NULL) { delete value->shift(); delete value->shift(); } delete var; return ret; } else return NULL; } } TokenList* ValueProcessor::processDeepVariable (TokenList* value) { Token* first, *second; TokenList* var; string key = "@"; if (value->size() < 2) return NULL; first = value->front(); second = value->at(1); if (first->type != Token::OTHER || first->str != "@" || second->type != Token::ATKEYWORD || (var = getVariable(second->str)) == NULL) return NULL; if (var->size() > 1 || var->front()->type != Token::STRING) return NULL; // generate key with '@' + var without quotes key.append(var->front()-> str.substr(1, var->front()->str.size() - 2)); var = getVariable(key); if (var == NULL) return NULL; return var->clone(); } Value* ValueProcessor::processFunction(Token* function, vector<Value*> arguments) { Color* color; string percentage; if(function->str == "rgb(") { // Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER) if (arguments.size() == 3 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::NUMBER && arguments[2]->type == Value::NUMBER) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue()); } } else if(function->str == "rgba(") { // Color rgba(@red: NUMBER, @green: NUMBER, @blue: NUMBER, // @alpha: NUMBER) if (arguments.size() == 4 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::NUMBER && arguments[2]->type == Value::NUMBER) { if (arguments[3]->type == Value::NUMBER) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue(), arguments[3]->getValue()); } else if (arguments[3]->type == Value::PERCENTAGE) { return new Color(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue(), arguments[3]->getValue() * .01); } } } else if (function->str == "lighten(") { // Color lighten(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->lighten(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "darken(") { // Color darken(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->darken(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "saturate(") { // Color saturate(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->saturate(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "desaturate(") { // Color desaturate(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "fadein(") { // Color fadein(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->fadein(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "fadeout(") { // Color fadeout(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::PERCENTAGE) { static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "spin(") { // Color fadein(Color, PERCENTAGE) if (arguments.size() == 2 && arguments[0]->type == Value::COLOR && arguments[1]->type == Value::NUMBER) { static_cast<Color*>(arguments[0])->spin(arguments[1]->getValue()); return arguments[0]; } } else if (function->str == "hsl(") { // Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE) if (arguments.size() == 3 && arguments[0]->type == Value::NUMBER && arguments[1]->type == Value::PERCENTAGE && arguments[2]->type == Value::PERCENTAGE) { color = new Color(0,0,0); color->setHSL(arguments[0]->getValue(), arguments[1]->getValue(), arguments[2]->getValue()); return color; } } else if (function->str == "hue(") { // NUMBER hue(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue())); return new Value(new Token(percentage, Token::NUMBER)); } } else if (function->str == "saturation(") { // PERCENTAGE saturation(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation())); percentage.append("%"); return new Value(new Token(percentage, Token::PERCENTAGE)); } } else if (function->str == "lightness(") { // PERCENTAGE lightness(Color) if (arguments.size() == 1 && arguments[0]->type == Value::COLOR) { percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness())); percentage.append("%"); return new Value(new Token(percentage, Token::PERCENTAGE)); } } else return NULL; return NULL; } void ValueProcessor::processString(Token* token) { size_t start, end; string key = "@", value; TokenList* var; if ((start = token->str.find("@{")) == string::npos || (end = token->str.find("}", start)) == string::npos) return; key.append(token->str.substr(start + 2, end - (start + 2))); var = getVariable(key); if (var == NULL) return; value = *var->toString(); // Remove quotes of strings. if (var->size() == 1 && var->front()->type == Token::STRING) value = value.substr(1, value.size() - 2); token->str.replace(start, (end + 1) - start, value); } Token* ValueProcessor::processEscape (TokenList* value) { Token* first, *second; if (value->size() < 2) return NULL; first = value->front(); second = value->at(1); if (first->str != "~" || second->type != Token::STRING) return NULL; delete value->shift(); second->str = second->str.substr(1, second->str.size() - 2); return value->shift(); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2017 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Track.h" #include "math/Constants.h" #include "math/Spline.h" #include "mesh/Mesh.h" #include "splinesonic/Constants.h" #include <glm/gtx/norm.hpp> #include <glm/gtx/projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <random> namespace SplineSonic { namespace TrackGen { constexpr float ThetaMax = 0.8f * Reaper::Math::HalfPi; constexpr float PhiMax = 1.0f * Reaper::Math::Pi; constexpr float RollMax = 0.25f * Reaper::Math::Pi; constexpr float WidthMin = 20.0f * MeterInGameUnits; constexpr float WidthMax = 50.0f * MeterInGameUnits; constexpr float RadiusMin = 100.0f * MeterInGameUnits; constexpr float RadiusMax = 300.0f * MeterInGameUnits; constexpr u32 MinLength = 5; constexpr u32 MaxLength = 1000; constexpr u32 MaxTryCount = 10000; constexpr u32 SplineOrder = 3; constexpr float SplineInnerWeight = 0.5f; constexpr u32 BoneCountPerChunk = 4; using RNG = std::mt19937; using Reaper::Math::UnitXAxis; using Reaper::Math::UnitYAxis; using Reaper::Math::UnitZAxis; namespace { glm::quat GenerateChunkEndLocalSpace(const GenerationInfo& genInfo, RNG& rng) { const glm::vec2 thetaBounds = glm::vec2(0.0f, ThetaMax) * genInfo.chaos; const glm::vec2 phiBounds = glm::vec2(-PhiMax, PhiMax) * genInfo.chaos; const glm::vec2 rollBounds = glm::vec2(-RollMax, RollMax) * genInfo.chaos; std::uniform_real_distribution<float> thetaDistribution(thetaBounds.x, thetaBounds.y); std::uniform_real_distribution<float> phiDistribution(phiBounds.x, phiBounds.y); std::uniform_real_distribution<float> rollDistribution(rollBounds.x, rollBounds.y); const float theta = thetaDistribution(rng); const float phi = phiDistribution(rng); const float roll = rollDistribution(rng); glm::quat deviation = glm::angleAxis(phi, UnitXAxis) * glm::angleAxis(theta, UnitZAxis); glm::quat rollFixup = glm::angleAxis(-phi + roll, deviation * UnitXAxis); return rollFixup * deviation; } bool IsNodeSelfColliding(const std::vector<TrackSkeletonNode>& nodes, const TrackSkeletonNode& currentNode, u32& outputNodeIdx) { for (u32 i = 0; (i + 1) < nodes.size(); i++) { const float distanceSq = glm::distance2(currentNode.positionWS, nodes[i].positionWS); const float minRadius = currentNode.radius + nodes[i].radius; if (distanceSq < (minRadius * minRadius)) { outputNodeIdx = i; return true; } } return false; } TrackSkeletonNode GenerateNode(const GenerationInfo& genInfo, const std::vector<TrackSkeletonNode>& skeletonNodes, RNG& rng) { std::uniform_real_distribution<float> widthDistribution(WidthMin, WidthMax); std::uniform_real_distribution<float> radiusDistribution(RadiusMin, RadiusMax); TrackSkeletonNode node; node.radius = radiusDistribution(rng); if (skeletonNodes.empty()) { node.orientationWS = glm::quat(); node.inWidth = widthDistribution(rng); node.positionWS = glm::vec3(0.f); } else { const TrackSkeletonNode& previousNode = skeletonNodes.back(); node.orientationWS = previousNode.orientationWS * previousNode.rotationLS; node.inWidth = previousNode.outWidth; const glm::vec3 offsetMS = UnitXAxis * (previousNode.radius + node.radius); const glm::vec3 offsetWS = node.orientationWS * offsetMS; node.positionWS = previousNode.positionWS + offsetWS; } node.rotationLS = GenerateChunkEndLocalSpace(genInfo, rng); node.outWidth = widthDistribution(rng); return node; } } void GenerateTrackSkeleton(const GenerationInfo& genInfo, std::vector<TrackSkeletonNode>& skeletonNodes) { Assert(genInfo.length >= MinLength); Assert(genInfo.length <= MaxLength); skeletonNodes.resize(0); skeletonNodes.reserve(genInfo.length); std::random_device rd; RNG rng(rd()); u32 tryCount = 0; while (skeletonNodes.size() < genInfo.length && tryCount < MaxTryCount) { const TrackSkeletonNode node = GenerateNode(genInfo, skeletonNodes, rng); u32 colliderIdx = 0; if (IsNodeSelfColliding(skeletonNodes, node, colliderIdx)) skeletonNodes.resize(colliderIdx + 1); // Shrink the vector and generate from collider else skeletonNodes.push_back(node); ++tryCount; } Assert(tryCount < MaxTryCount, "something is majorly FUBAR"); } void GenerateTrackSplines(const std::vector<TrackSkeletonNode>& skeletonNodes, std::vector<Reaper::Math::Spline>& splines) { std::vector<glm::vec4> controlPoints(4); const u32 trackChunkCount = static_cast<u32>(skeletonNodes.size()); Assert(trackChunkCount > 0); Assert(trackChunkCount == skeletonNodes.size()); splines.resize(trackChunkCount); for (u32 i = 0; i < trackChunkCount; i++) { const TrackSkeletonNode& node = skeletonNodes[i]; // Laying down 1 control point at each end and 2 in the center of the sphere // seems to work pretty well. controlPoints[0] = glm::vec4(UnitXAxis * -node.radius, 1.0f); controlPoints[1] = glm::vec4(glm::vec3(0.0f), SplineInnerWeight); controlPoints[2] = glm::vec4(glm::vec3(0.0f), SplineInnerWeight); controlPoints[3] = glm::vec4(node.rotationLS * UnitXAxis * node.radius, 1.0f); splines[i] = Reaper::Math::ConstructSpline(SplineOrder, controlPoints); } } namespace { void GenerateTrackSkinningForChunk(const TrackSkeletonNode& node, const Reaper::Math::Spline& spline, TrackSkinning& skinningInfo) { skinningInfo.bones.resize(BoneCountPerChunk); // Fill bone positions skinningInfo.bones[0].root = EvalSpline(spline, 0.0f); skinningInfo.bones[BoneCountPerChunk - 1].end = EvalSpline(spline, 1.0f); // Compute bone start and end positions for (u32 i = 1; i < BoneCountPerChunk; i++) { const float param = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const glm::vec3 anchorPos = EvalSpline(spline, param); skinningInfo.bones[i - 1].end = anchorPos; skinningInfo.bones[i].root = anchorPos; } skinningInfo.invBindTransforms.resize(BoneCountPerChunk); // Compute inverse bind pose matrix for (u32 i = 0; i < BoneCountPerChunk; i++) { const float t = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const float param = t * 2.0f - 1.0f; const glm::vec3 offset = UnitXAxis * (param * node.radius); // Inverse of a translation is the translation by the opposite vector skinningInfo.invBindTransforms[i] = glm::translate(glm::mat4(1.0f), -offset); } skinningInfo.poseTransforms.resize(BoneCountPerChunk); // Compute current pose matrix by reconstructing an ortho-base // We only have roll information at chunk boundary, so we have to // use tricks to get the correct bone rotation for (u32 i = 0; i < BoneCountPerChunk; i++) { const float t = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const glm::fquat interpolatedOrientation = glm::slerp(glm::quat(), node.rotationLS, t); const Bone& bone = skinningInfo.bones[i]; const glm::fvec3 plusX = glm::normalize(bone.end - bone.root); const glm::fvec3 interpolatedPlusY = interpolatedOrientation * UnitYAxis; const glm::fvec3 plusY = glm::normalize(interpolatedPlusY - glm::proj(interpolatedPlusY, plusX)); // Trick to get a correct-ish roll along the spline const glm::fvec3 plusZ = glm::cross(plusX, plusY); // Should already be normalized at this point (write assert) // Convert to a matrix const glm::fmat4 rotation = glm::fmat3(plusX, plusY, plusZ); const glm::fmat4 translation = glm::translate(glm::fmat4(1.0f), bone.root); skinningInfo.poseTransforms[i] = translation * rotation; } } } void GenerateTrackSkinning(const std::vector<TrackSkeletonNode>& skeletonNodes, const std::vector<Reaper::Math::Spline>& splines, std::vector<TrackSkinning>& skinning) { const u32 trackChunkCount = static_cast<u32>(splines.size()); Assert(trackChunkCount > 0); skinning.resize(trackChunkCount); for (u32 chunkIdx = 0; chunkIdx < splines.size(); chunkIdx++) { GenerateTrackSkinningForChunk(skeletonNodes[chunkIdx], splines[chunkIdx], skinning[chunkIdx]); } } namespace { glm::fvec4 ComputeBoneWeights(glm::vec3 position) { static_cast<void>(position); return glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); // FIXME } } void SkinTrackChunkMesh(const TrackSkeletonNode& node, const TrackSkinning& trackSkinning, Mesh& mesh, float meshLength) { const u32 vertexCount = static_cast<u32>(mesh.vertices.size()); const u32 boneCount = 4; // FIXME std::vector<glm::fvec3> skinnedVertices(vertexCount); Assert(vertexCount > 0); const float scaleX = node.radius / (meshLength * 0.5f); for (u32 i = 0; i < vertexCount; i++) { const glm::fvec3 vertex = mesh.vertices[i] * glm::fvec3(scaleX, 1.0f, 1.0f); const glm::fvec4 boneWeights = ComputeBoneWeights(vertex); skinnedVertices[i] = glm::fvec3(0.0f); for (u32 j = 0; j < boneCount; j++) { const glm::fmat4 boneTransform = trackSkinning.poseTransforms[j] * trackSkinning.invBindTransforms[j]; const glm::fvec4 skinnedVertex = (boneTransform * glm::fvec4(vertex, 1.0f)) * boneWeights[j]; Assert(skinnedVertex.w > 0.0f); skinnedVertices[i] += glm::fvec3(skinnedVertex) / skinnedVertex.w; } } mesh.vertices = skinnedVertices; } }} // namespace SplineSonic::TrackGen <commit_msg>skinning: fix division by zero<commit_after>//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2017 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Track.h" #include "math/Constants.h" #include "math/Spline.h" #include "mesh/Mesh.h" #include "splinesonic/Constants.h" #include <glm/gtx/norm.hpp> #include <glm/gtx/projection.hpp> #include <glm/gtc/matrix_transform.hpp> #include <random> namespace SplineSonic { namespace TrackGen { constexpr float ThetaMax = 0.8f * Reaper::Math::HalfPi; constexpr float PhiMax = 1.0f * Reaper::Math::Pi; constexpr float RollMax = 0.25f * Reaper::Math::Pi; constexpr float WidthMin = 20.0f * MeterInGameUnits; constexpr float WidthMax = 50.0f * MeterInGameUnits; constexpr float RadiusMin = 100.0f * MeterInGameUnits; constexpr float RadiusMax = 300.0f * MeterInGameUnits; constexpr u32 MinLength = 5; constexpr u32 MaxLength = 1000; constexpr u32 MaxTryCount = 10000; constexpr u32 SplineOrder = 3; constexpr float SplineInnerWeight = 0.5f; constexpr u32 BoneCountPerChunk = 4; using RNG = std::mt19937; using Reaper::Math::UnitXAxis; using Reaper::Math::UnitYAxis; using Reaper::Math::UnitZAxis; namespace { glm::quat GenerateChunkEndLocalSpace(const GenerationInfo& genInfo, RNG& rng) { const glm::vec2 thetaBounds = glm::vec2(0.0f, ThetaMax) * genInfo.chaos; const glm::vec2 phiBounds = glm::vec2(-PhiMax, PhiMax) * genInfo.chaos; const glm::vec2 rollBounds = glm::vec2(-RollMax, RollMax) * genInfo.chaos; std::uniform_real_distribution<float> thetaDistribution(thetaBounds.x, thetaBounds.y); std::uniform_real_distribution<float> phiDistribution(phiBounds.x, phiBounds.y); std::uniform_real_distribution<float> rollDistribution(rollBounds.x, rollBounds.y); const float theta = thetaDistribution(rng); const float phi = phiDistribution(rng); const float roll = rollDistribution(rng); glm::quat deviation = glm::angleAxis(phi, UnitXAxis) * glm::angleAxis(theta, UnitZAxis); glm::quat rollFixup = glm::angleAxis(-phi + roll, deviation * UnitXAxis); return rollFixup * deviation; } bool IsNodeSelfColliding(const std::vector<TrackSkeletonNode>& nodes, const TrackSkeletonNode& currentNode, u32& outputNodeIdx) { for (u32 i = 0; (i + 1) < nodes.size(); i++) { const float distanceSq = glm::distance2(currentNode.positionWS, nodes[i].positionWS); const float minRadius = currentNode.radius + nodes[i].radius; if (distanceSq < (minRadius * minRadius)) { outputNodeIdx = i; return true; } } return false; } TrackSkeletonNode GenerateNode(const GenerationInfo& genInfo, const std::vector<TrackSkeletonNode>& skeletonNodes, RNG& rng) { std::uniform_real_distribution<float> widthDistribution(WidthMin, WidthMax); std::uniform_real_distribution<float> radiusDistribution(RadiusMin, RadiusMax); TrackSkeletonNode node; node.radius = radiusDistribution(rng); if (skeletonNodes.empty()) { node.orientationWS = glm::quat(); node.inWidth = widthDistribution(rng); node.positionWS = glm::vec3(0.f); } else { const TrackSkeletonNode& previousNode = skeletonNodes.back(); node.orientationWS = previousNode.orientationWS * previousNode.rotationLS; node.inWidth = previousNode.outWidth; const glm::vec3 offsetMS = UnitXAxis * (previousNode.radius + node.radius); const glm::vec3 offsetWS = node.orientationWS * offsetMS; node.positionWS = previousNode.positionWS + offsetWS; } node.rotationLS = GenerateChunkEndLocalSpace(genInfo, rng); node.outWidth = widthDistribution(rng); return node; } } void GenerateTrackSkeleton(const GenerationInfo& genInfo, std::vector<TrackSkeletonNode>& skeletonNodes) { Assert(genInfo.length >= MinLength); Assert(genInfo.length <= MaxLength); skeletonNodes.resize(0); skeletonNodes.reserve(genInfo.length); std::random_device rd; RNG rng(rd()); u32 tryCount = 0; while (skeletonNodes.size() < genInfo.length && tryCount < MaxTryCount) { const TrackSkeletonNode node = GenerateNode(genInfo, skeletonNodes, rng); u32 colliderIdx = 0; if (IsNodeSelfColliding(skeletonNodes, node, colliderIdx)) skeletonNodes.resize(colliderIdx + 1); // Shrink the vector and generate from collider else skeletonNodes.push_back(node); ++tryCount; } Assert(tryCount < MaxTryCount, "something is majorly FUBAR"); } void GenerateTrackSplines(const std::vector<TrackSkeletonNode>& skeletonNodes, std::vector<Reaper::Math::Spline>& splines) { std::vector<glm::vec4> controlPoints(4); const u32 trackChunkCount = static_cast<u32>(skeletonNodes.size()); Assert(trackChunkCount > 0); Assert(trackChunkCount == skeletonNodes.size()); splines.resize(trackChunkCount); for (u32 i = 0; i < trackChunkCount; i++) { const TrackSkeletonNode& node = skeletonNodes[i]; // Laying down 1 control point at each end and 2 in the center of the sphere // seems to work pretty well. controlPoints[0] = glm::vec4(UnitXAxis * -node.radius, 1.0f); controlPoints[1] = glm::vec4(glm::vec3(0.0f), SplineInnerWeight); controlPoints[2] = glm::vec4(glm::vec3(0.0f), SplineInnerWeight); controlPoints[3] = glm::vec4(node.rotationLS * UnitXAxis * node.radius, 1.0f); splines[i] = Reaper::Math::ConstructSpline(SplineOrder, controlPoints); } } namespace { void GenerateTrackSkinningForChunk(const TrackSkeletonNode& node, const Reaper::Math::Spline& spline, TrackSkinning& skinningInfo) { skinningInfo.bones.resize(BoneCountPerChunk); // Fill bone positions skinningInfo.bones[0].root = EvalSpline(spline, 0.0f); skinningInfo.bones[BoneCountPerChunk - 1].end = EvalSpline(spline, 1.0f); // Compute bone start and end positions for (u32 i = 1; i < BoneCountPerChunk; i++) { const float param = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const glm::vec3 anchorPos = EvalSpline(spline, param); skinningInfo.bones[i - 1].end = anchorPos; skinningInfo.bones[i].root = anchorPos; } skinningInfo.invBindTransforms.resize(BoneCountPerChunk); // Compute inverse bind pose matrix for (u32 i = 0; i < BoneCountPerChunk; i++) { const float t = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const float param = t * 2.0f - 1.0f; const glm::vec3 offset = UnitXAxis * (param * node.radius); // Inverse of a translation is the translation by the opposite vector skinningInfo.invBindTransforms[i] = glm::translate(glm::mat4(1.0f), -offset); } skinningInfo.poseTransforms.resize(BoneCountPerChunk); // Compute current pose matrix by reconstructing an ortho-base // We only have roll information at chunk boundary, so we have to // use tricks to get the correct bone rotation for (u32 i = 0; i < BoneCountPerChunk; i++) { const float t = static_cast<float>(i) / static_cast<float>(BoneCountPerChunk); const glm::fquat interpolatedOrientation = glm::slerp(glm::quat(), node.rotationLS, t); const Bone& bone = skinningInfo.bones[i]; const glm::fvec3 plusX = glm::normalize(bone.end - bone.root); const glm::fvec3 interpolatedPlusY = interpolatedOrientation * UnitYAxis; const glm::fvec3 plusY = glm::normalize(interpolatedPlusY - glm::proj(interpolatedPlusY, plusX)); // Trick to get a correct-ish roll along the spline const glm::fvec3 plusZ = glm::cross(plusX, plusY); // Should already be normalized at this point (write assert) // Convert to a matrix const glm::fmat4 rotation = glm::fmat3(plusX, plusY, plusZ); const glm::fmat4 translation = glm::translate(glm::fmat4(1.0f), bone.root); skinningInfo.poseTransforms[i] = translation * rotation; } } } void GenerateTrackSkinning(const std::vector<TrackSkeletonNode>& skeletonNodes, const std::vector<Reaper::Math::Spline>& splines, std::vector<TrackSkinning>& skinning) { const u32 trackChunkCount = static_cast<u32>(splines.size()); Assert(trackChunkCount > 0); skinning.resize(trackChunkCount); for (u32 chunkIdx = 0; chunkIdx < splines.size(); chunkIdx++) { GenerateTrackSkinningForChunk(skeletonNodes[chunkIdx], splines[chunkIdx], skinning[chunkIdx]); } } namespace { glm::fvec4 ComputeBoneWeights(glm::vec3 position) { static_cast<void>(position); return glm::vec4(1.0f, 0.0f, 0.0f, 0.0f); // FIXME } } void SkinTrackChunkMesh(const TrackSkeletonNode& node, const TrackSkinning& trackSkinning, Mesh& mesh, float meshLength) { const u32 vertexCount = static_cast<u32>(mesh.vertices.size()); const u32 boneCount = 4; // FIXME std::vector<glm::fvec3> skinnedVertices(vertexCount); Assert(vertexCount > 0); const float scaleX = node.radius / (meshLength * 0.5f); for (u32 i = 0; i < vertexCount; i++) { const glm::fvec3 vertex = mesh.vertices[i] * glm::fvec3(scaleX, 1.0f, 1.0f); const glm::fvec4 boneWeights = ComputeBoneWeights(vertex); skinnedVertices[i] = glm::fvec3(0.0f); for (u32 j = 0; j < boneCount; j++) { const glm::fmat4 boneTransform = trackSkinning.poseTransforms[j] * trackSkinning.invBindTransforms[j]; const glm::fvec4 skinnedVertex = (boneTransform * glm::fvec4(vertex, 1.0f)) * boneWeights[j]; if (glm::abs(skinnedVertex.w) > 0.0f) skinnedVertices[i] += glm::fvec3(skinnedVertex) / skinnedVertex.w; } } mesh.vertices = skinnedVertices; } }} // namespace SplineSonic::TrackGen <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dllinit.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2007-07-18 12:15:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #pragma warning(push,1) // disable warnings within system headers #include <windows.h> #pragma warning(pop) void dso_init(void); void dso_exit(void); extern "C" BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpvReserved) { switch(dwReason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); dso_init(); break; case DLL_PROCESS_DETACH: if (!lpvReserved) dso_exit(); break; } return TRUE; } <commit_msg>INTEGRATION: CWS changefileheader (1.2.48); FILE MERGED 2008/03/28 16:30:38 rt 1.2.48.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dllinit.cxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #pragma warning(push,1) // disable warnings within system headers #include <windows.h> #pragma warning(pop) void dso_init(void); void dso_exit(void); extern "C" BOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpvReserved) { switch(dwReason) { case DLL_PROCESS_ATTACH: DisableThreadLibraryCalls(hModule); dso_init(); break; case DLL_PROCESS_DETACH: if (!lpvReserved) dso_exit(); break; } return TRUE; } <|endoftext|>
<commit_before>#include "photoeffects.hpp" #include <math.h> using namespace cv; #define MAX_KERNELSIZE 15 int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft) { CV_Assert(src.type() == CV_8UC3); dst.create(src.size(), src.type()); Mat image = src.getMat(), outputImage = dst.getMat(); CV_Assert(indentTop >= 0 && indentTop <= (image.rows / 2 - 10)); CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols / 2 - 10)); float halfWidth = (image.cols / 2.0f) * (image.cols / 2.0f); float halfHeight = (image.rows / 2.0f) * (image.rows / 2.0f); float a = (image.cols / 2.0f - indentLeft) * (image.cols / 2.0f - indentLeft); float b = (image.rows / 2.0f - indentTop) * (image.rows / 2.0f - indentTop); int kSizeEdges = halfWidth / a + halfHeight / b; kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE); Mat bearingImage(image.rows + 2 * kSizeEdges, image.cols + 2 * kSizeEdges, CV_8UC3); copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges, kSizeEdges, kSizeEdges, BORDER_REPLICATE); for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++) { for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++) { int size; Vec3f sumF; Vec3b Color; float sumC = 0.0f, coeff; float bearHalfWidth = bearingImage.cols / 2.0f; float bearHalfHeight = bearingImage.rows / 2.0f; float radius = (bearHalfHeight - i) * (bearHalfHeight - i) / b + (bearHalfWidth - j) * (bearHalfWidth - j) / a; if (radius < 1.0f) { outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = bearingImage.at<Vec3b>(i, j); continue; } size = radius; radius = 2.0f * (radius - 0.5f) * (radius - 0.5f); size = MIN(size, kSizeEdges); for (int x = -size; x <= size; x++) { for (int y = -size; y <= size; y++) { coeff = 1.0f / (CV_PI * radius) * exp(- (x * x + y * y) / radius); Color = bearingImage.at<Vec3b>(x + i, y + j); sumF += coeff * Color; sumC += coeff; } } sumF *= (1.0f / sumC); outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF; } } return 0; } <commit_msg>Corrected<commit_after>#include "photoeffects.hpp" #include <math.h> using namespace cv; #define MAX_KERNELSIZE 15 int edgeBlur(InputArray src, OutputArray dst, int indentTop, int indentLeft) { CV_Assert(src.type() == CV_8UC3); dst.create(src.size(), src.type()); Mat image = src.getMat(), outputImage = dst.getMat(); CV_Assert(indentTop >= 0 && indentTop <= (image.rows / 2 - 10)); CV_Assert(indentLeft >= 0 && indentLeft <= (image.cols / 2 - 10)); float halfWidth = image.cols / 2.0f; float halfHeight = image.rows / 2.0f; float a = (image.cols / 2.0f - indentLeft) * (image.cols / 2.0f - indentLeft); float b = (image.rows / 2.0f - indentTop) * (image.rows / 2.0f - indentTop); int kSizeEdges = halfWidth * halfWidth / a + halfHeight * halfHeight / b; kSizeEdges = MIN(kSizeEdges, MAX_KERNELSIZE); Mat bearingImage(image.rows + 2 * kSizeEdges, image.cols + 2 * kSizeEdges, CV_8UC3); copyMakeBorder(image, bearingImage, kSizeEdges, kSizeEdges, kSizeEdges, kSizeEdges, BORDER_REPLICATE); for (int i = kSizeEdges; i < bearingImage.rows - kSizeEdges; i++) { for (int j = kSizeEdges; j < bearingImage.cols - kSizeEdges; j++) { int size; Vec3f sumF; Vec3b Color; float sumC = 0.0f, coeff; float radius = (halfHeight - i) * (halfHeight- i) / b + (halfWidth - j) * (halfHeight - j) / a; if (radius < 1.0f) { outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = bearingImage.at<Vec3b>(i, j); continue; } size = radius; radius = 2.0f * (radius - 0.5f) * (radius - 0.5f); size = MIN(size, kSizeEdges); for (int x = -size; x <= size; x++) { for (int y = -size; y <= size; y++) { coeff = 1.0f / (CV_PI * radius) * exp(- (x * x + y * y) / radius); Color = bearingImage.at<Vec3b>(x + i, y + j); sumF += coeff * (Vec3f)Color; sumC += coeff; } } sumF *= (1.0f / sumC); outputImage.at<Vec3b>(i - kSizeEdges, j - kSizeEdges) = sumF; } } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS 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 GOOGLE INC. * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/xml/XMLErrors.h" #include "HTMLNames.h" #include "SVGNames.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Text.h" #include "wtf/text/WTFString.h" namespace WebCore { using namespace HTMLNames; const int maxErrors = 25; XMLErrors::XMLErrors(Document* document) : m_document(document) , m_errorCount(0) , m_lastErrorPosition(TextPosition::belowRangePosition()) { } void XMLErrors::handleError(ErrorType type, const char* message, int lineNumber, int columnNumber) { handleError(type, message, TextPosition(OrdinalNumber::fromOneBasedInt(lineNumber), OrdinalNumber::fromOneBasedInt(columnNumber))); } void XMLErrors::handleError(ErrorType type, const char* message, TextPosition position) { if (type == fatal || (m_errorCount < maxErrors && m_lastErrorPosition.m_line != position.m_line && m_lastErrorPosition.m_column != position.m_column)) { switch (type) { case warning: appendErrorMessage("warning", position, message); break; case fatal: case nonFatal: appendErrorMessage("error", position, message); } m_lastErrorPosition = position; ++m_errorCount; } } void XMLErrors::appendErrorMessage(const String& typeString, TextPosition position, const char* message) { // <typeString> on line <lineNumber> at column <columnNumber>: <message> m_errorMessages.append(typeString); m_errorMessages.appendLiteral(" on line "); m_errorMessages.appendNumber(position.m_line.oneBasedInt()); m_errorMessages.appendLiteral(" at column "); m_errorMessages.appendNumber(position.m_column.oneBasedInt()); m_errorMessages.appendLiteral(": "); m_errorMessages.append(message); } static inline PassRefPtr<Element> createXHTMLParserErrorHeader(Document* doc, const String& errorMessages) { RefPtr<Element> reportElement = doc->createElement(QualifiedName(nullAtom, "parsererror", xhtmlNamespaceURI), true); Vector<Attribute> reportAttributes; reportAttributes.append(Attribute(styleAttr, "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black")); reportElement->parserSetAttributes(reportAttributes); RefPtr<Element> h3 = doc->createElement(h3Tag, true); reportElement->parserAppendChild(h3.get()); h3->parserAppendChild(doc->createTextNode("This page contains the following errors:")); RefPtr<Element> fixed = doc->createElement(divTag, true); Vector<Attribute> fixedAttributes; fixedAttributes.append(Attribute(styleAttr, "font-family:monospace;font-size:12px")); fixed->parserSetAttributes(fixedAttributes); reportElement->parserAppendChild(fixed.get()); fixed->parserAppendChild(doc->createTextNode(errorMessages)); h3 = doc->createElement(h3Tag, true); reportElement->parserAppendChild(h3.get()); h3->parserAppendChild(doc->createTextNode("Below is a rendering of the page up to the first error.")); return reportElement.release(); } void XMLErrors::insertErrorMessageBlock() { // One or more errors occurred during parsing of the code. Display an error block to the user above // the normal content (the DOM tree is created manually and includes line/col info regarding // where the errors are located) // Create elements for display RefPtr<Element> documentElement = m_document->documentElement(); if (!documentElement) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); rootElement->parserAppendChild(body); m_document->parserAppendChild(rootElement); rootElement->lazyAttach(); documentElement = body.get(); } else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); rootElement->parserAppendChild(body); if (documentElement->attached()) documentElement->detach(); m_document->parserRemoveChild(documentElement.get()); body->parserAppendChild(documentElement); m_document->parserAppendChild(rootElement); rootElement->lazyAttach(); documentElement = body.get(); } String errorMessages = m_errorMessages.toString(); RefPtr<Element> reportElement = createXHTMLParserErrorHeader(m_document, errorMessages); if (m_document->transformSourceDocument()) { Vector<Attribute> attributes; attributes.append(Attribute(styleAttr, "white-space: normal")); RefPtr<Element> paragraph = m_document->createElement(pTag, true); paragraph->parserSetAttributes(attributes); paragraph->parserAppendChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result.")); reportElement->parserAppendChild(paragraph.release()); } Node* firstChild = documentElement->firstChild(); if (firstChild) documentElement->parserInsertBefore(reportElement, documentElement->firstChild()); else documentElement->parserAppendChild(reportElement); reportElement->lazyAttach(); // FIXME: Why do we need to call this manually? m_document->updateStyleIfNeeded(); } } // namespace WebCore <commit_msg>XMLErrors::insertErrorMessageBlock does not need to call detach<commit_after>/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. AND ITS 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 GOOGLE INC. * OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/xml/XMLErrors.h" #include "HTMLNames.h" #include "SVGNames.h" #include "core/dom/Document.h" #include "core/dom/Element.h" #include "core/dom/Text.h" #include "wtf/text/WTFString.h" namespace WebCore { using namespace HTMLNames; const int maxErrors = 25; XMLErrors::XMLErrors(Document* document) : m_document(document) , m_errorCount(0) , m_lastErrorPosition(TextPosition::belowRangePosition()) { } void XMLErrors::handleError(ErrorType type, const char* message, int lineNumber, int columnNumber) { handleError(type, message, TextPosition(OrdinalNumber::fromOneBasedInt(lineNumber), OrdinalNumber::fromOneBasedInt(columnNumber))); } void XMLErrors::handleError(ErrorType type, const char* message, TextPosition position) { if (type == fatal || (m_errorCount < maxErrors && m_lastErrorPosition.m_line != position.m_line && m_lastErrorPosition.m_column != position.m_column)) { switch (type) { case warning: appendErrorMessage("warning", position, message); break; case fatal: case nonFatal: appendErrorMessage("error", position, message); } m_lastErrorPosition = position; ++m_errorCount; } } void XMLErrors::appendErrorMessage(const String& typeString, TextPosition position, const char* message) { // <typeString> on line <lineNumber> at column <columnNumber>: <message> m_errorMessages.append(typeString); m_errorMessages.appendLiteral(" on line "); m_errorMessages.appendNumber(position.m_line.oneBasedInt()); m_errorMessages.appendLiteral(" at column "); m_errorMessages.appendNumber(position.m_column.oneBasedInt()); m_errorMessages.appendLiteral(": "); m_errorMessages.append(message); } static inline PassRefPtr<Element> createXHTMLParserErrorHeader(Document* doc, const String& errorMessages) { RefPtr<Element> reportElement = doc->createElement(QualifiedName(nullAtom, "parsererror", xhtmlNamespaceURI), true); Vector<Attribute> reportAttributes; reportAttributes.append(Attribute(styleAttr, "display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black")); reportElement->parserSetAttributes(reportAttributes); RefPtr<Element> h3 = doc->createElement(h3Tag, true); reportElement->parserAppendChild(h3.get()); h3->parserAppendChild(doc->createTextNode("This page contains the following errors:")); RefPtr<Element> fixed = doc->createElement(divTag, true); Vector<Attribute> fixedAttributes; fixedAttributes.append(Attribute(styleAttr, "font-family:monospace;font-size:12px")); fixed->parserSetAttributes(fixedAttributes); reportElement->parserAppendChild(fixed.get()); fixed->parserAppendChild(doc->createTextNode(errorMessages)); h3 = doc->createElement(h3Tag, true); reportElement->parserAppendChild(h3.get()); h3->parserAppendChild(doc->createTextNode("Below is a rendering of the page up to the first error.")); return reportElement.release(); } void XMLErrors::insertErrorMessageBlock() { // One or more errors occurred during parsing of the code. Display an error block to the user above // the normal content (the DOM tree is created manually and includes line/col info regarding // where the errors are located) // Create elements for display RefPtr<Element> documentElement = m_document->documentElement(); if (!documentElement) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); rootElement->parserAppendChild(body); m_document->parserAppendChild(rootElement); rootElement->lazyAttach(); documentElement = body.get(); } else if (documentElement->namespaceURI() == SVGNames::svgNamespaceURI) { RefPtr<Element> rootElement = m_document->createElement(htmlTag, true); RefPtr<Element> body = m_document->createElement(bodyTag, true); rootElement->parserAppendChild(body); m_document->parserRemoveChild(documentElement.get()); body->parserAppendChild(documentElement); m_document->parserAppendChild(rootElement); rootElement->lazyAttach(); documentElement = body.get(); } String errorMessages = m_errorMessages.toString(); RefPtr<Element> reportElement = createXHTMLParserErrorHeader(m_document, errorMessages); if (m_document->transformSourceDocument()) { Vector<Attribute> attributes; attributes.append(Attribute(styleAttr, "white-space: normal")); RefPtr<Element> paragraph = m_document->createElement(pTag, true); paragraph->parserSetAttributes(attributes); paragraph->parserAppendChild(m_document->createTextNode("This document was created as the result of an XSL transformation. The line and column numbers given are from the transformed result.")); reportElement->parserAppendChild(paragraph.release()); } Node* firstChild = documentElement->firstChild(); if (firstChild) documentElement->parserInsertBefore(reportElement, documentElement->firstChild()); else documentElement->parserAppendChild(reportElement); reportElement->lazyAttach(); // FIXME: Why do we need to call this manually? m_document->updateStyleIfNeeded(); } } // namespace WebCore <|endoftext|>
<commit_before>#include <core/stdafx.h> #include <core/smartview/AdditionalRenEntryIDs.h> #include <core/interpret/flags.h> #include <core/mapi/extraPropTags.h> namespace smartview { PersistElement::PersistElement(std::shared_ptr<binaryParser> parser) { wElementID = blockT<WORD>::parse(parser); wElementDataSize = blockT<WORD>::parse(parser); if (wElementID != PersistElement::ELEMENT_SENTINEL) { // Since this is a word, the size will never be too large lpbElementData = blockBytes::parse(parser, wElementDataSize->getData()); } } void AdditionalRenEntryIDs::Parse() { WORD wPersistDataCount = 0; // Run through the parser once to count the number of PersistData structs while (m_Parser->RemainingBytes() >= 2 * sizeof(WORD)) { const auto& wPersistID = blockT<WORD>::parse(m_Parser); const auto& wDataElementSize = blockT<WORD>::parse(m_Parser); // Must have at least wDataElementSize bytes left to be a valid data element if (m_Parser->RemainingBytes() < wDataElementSize->getData()) break; m_Parser->advance(wDataElementSize->getData()); wPersistDataCount++; if (wPersistID == PersistData::PERISIST_SENTINEL) break; } // Now we parse for real m_Parser->rewind(); if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall) { m_ppdPersistData.reserve(wPersistDataCount); for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++) { m_ppdPersistData.emplace_back(std::make_shared<PersistData>(m_Parser)); } } } PersistData::PersistData(std::shared_ptr<binaryParser> parser) { WORD wDataElementCount = 0; wPersistID = blockT<WORD>::parse(parser); wDataElementsSize = blockT<WORD>::parse(parser); if (wPersistID != PERISIST_SENTINEL && parser->RemainingBytes() >= wDataElementsSize->getData()) { // Build a new parser to preread and count our elements // This new parser will only contain as much space as suggested in wDataElementsSize auto DataElementParser = std::make_shared<binaryParser>(wDataElementsSize->getData(), parser->GetCurrentAddress()); for (;;) { if (DataElementParser->RemainingBytes() < 2 * sizeof(WORD)) break; const auto& wElementID = blockT<WORD>::parse(DataElementParser); const auto& wElementDataSize = blockT<WORD>::parse(DataElementParser); // Must have at least wElementDataSize bytes left to be a valid element data if (DataElementParser->RemainingBytes() < wElementDataSize->getData()) break; DataElementParser->advance(wElementDataSize->getData()); wDataElementCount++; if (wElementID == PersistElement::ELEMENT_SENTINEL) break; } } if (wDataElementCount && wDataElementCount < _MaxEntriesSmall) { ppeDataElement.reserve(wDataElementCount); for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++) { ppeDataElement.emplace_back(std::make_shared<PersistElement>(parser)); } } // We'll trust wDataElementsSize to dictate our record size. // Count the 2 WORD size header fields too. const auto cbRecordSize = wDataElementsSize->getData() + sizeof(WORD) * 2; // Junk data remains - can't use GetRemainingData here since it would eat the whole buffer if (parser->GetCurrentOffset() < cbRecordSize) { JunkData = blockBytes::parse(parser, cbRecordSize - parser->GetCurrentOffset()); } } void AdditionalRenEntryIDs::ParseBlocks() { setRoot(L"Additional Ren Entry IDs\r\n"); addHeader(L"PersistDataCount = %1!d!", m_ppdPersistData.size()); if (!m_ppdPersistData.empty()) { auto iPersistElement = 0; for (const auto& persistData : m_ppdPersistData) { terminateBlock(); addBlankLine(); auto element = std::make_shared<block>(); element->setText(L"Persist Element %1!d!:\r\n", iPersistElement); element->addChild( persistData->wPersistID, L"PersistID = 0x%1!04X! = %2!ws!\r\n", persistData->wPersistID->getData(), flags::InterpretFlags(flagPersistID, persistData->wPersistID->getData()).c_str()); element->addChild( persistData->wDataElementsSize, L"DataElementsSize = 0x%1!04X!", persistData->wDataElementsSize->getData()); if (!persistData->ppeDataElement.empty()) { auto iDataElement = 0; for (const auto& dataElement : persistData->ppeDataElement) { element->terminateBlock(); element->addHeader(L"DataElement: %1!d!\r\n", iDataElement); element->addChild( dataElement->wElementID, L"\tElementID = 0x%1!04X! = %2!ws!\r\n", dataElement->wElementID->getData(), flags::InterpretFlags(flagElementID, dataElement->wElementID->getData()).c_str()); element->addChild( dataElement->wElementDataSize, L"\tElementDataSize = 0x%1!04X!\r\n", dataElement->wElementDataSize->getData()); element->addHeader(L"\tElementData = "); element->addChild(dataElement->lpbElementData); iDataElement++; } } if (!persistData->JunkData->empty()) { element->terminateBlock(); element->addHeader(L"Unparsed data size = 0x%1!08X!\r\n", persistData->JunkData->size()); element->addChild(persistData->JunkData); } addChild(element); iPersistElement++; } } } } // namespace smartview<commit_msg>Slight tweaks to AdditionalRenEntryIDs<commit_after>#include <core/stdafx.h> #include <core/smartview/AdditionalRenEntryIDs.h> #include <core/interpret/flags.h> #include <core/mapi/extraPropTags.h> namespace smartview { PersistElement::PersistElement(std::shared_ptr<binaryParser> parser) { wElementID = blockT<WORD>::parse(parser); wElementDataSize = blockT<WORD>::parse(parser); if (wElementID != PersistElement::ELEMENT_SENTINEL) { // Since this is a word, the size will never be too large lpbElementData = blockBytes::parse(parser, wElementDataSize->getData()); } } void AdditionalRenEntryIDs::Parse() { WORD wPersistDataCount = 0; // Run through the parser once to count the number of PersistData structs while (m_Parser->RemainingBytes() >= 2 * sizeof(WORD)) { const auto& wPersistID = blockT<WORD>::parse(m_Parser); const auto& wDataElementSize = blockT<WORD>::parse(m_Parser); // Must have at least wDataElementSize bytes left to be a valid data element if (m_Parser->RemainingBytes() < *wDataElementSize) break; m_Parser->advance(*wDataElementSize); wPersistDataCount++; if (wPersistID == PersistData::PERISIST_SENTINEL) break; } // Now we parse for real m_Parser->rewind(); if (wPersistDataCount && wPersistDataCount < _MaxEntriesSmall) { m_ppdPersistData.reserve(wPersistDataCount); for (WORD iPersistElement = 0; iPersistElement < wPersistDataCount; iPersistElement++) { m_ppdPersistData.emplace_back(std::make_shared<PersistData>(m_Parser)); } } } PersistData::PersistData(std::shared_ptr<binaryParser> parser) { WORD wDataElementCount = 0; wPersistID = blockT<WORD>::parse(parser); wDataElementsSize = blockT<WORD>::parse(parser); if (wPersistID != PERISIST_SENTINEL && parser->RemainingBytes() >= *wDataElementsSize) { // Build a new parser to preread and count our elements // This new parser will only contain as much space as suggested in wDataElementsSize auto DataElementParser = std::make_shared<binaryParser>(*wDataElementsSize, parser->GetCurrentAddress()); for (;;) { if (DataElementParser->RemainingBytes() < 2 * sizeof(WORD)) break; const auto& wElementID = blockT<WORD>::parse(DataElementParser); const auto& wElementDataSize = blockT<WORD>::parse(DataElementParser); // Must have at least wElementDataSize bytes left to be a valid element data if (DataElementParser->RemainingBytes() < *wElementDataSize) break; DataElementParser->advance(*wElementDataSize); wDataElementCount++; if (wElementID == PersistElement::ELEMENT_SENTINEL) break; } } if (wDataElementCount && wDataElementCount < _MaxEntriesSmall) { ppeDataElement.reserve(wDataElementCount); for (WORD iDataElement = 0; iDataElement < wDataElementCount; iDataElement++) { ppeDataElement.emplace_back(std::make_shared<PersistElement>(parser)); } } // We'll trust wDataElementsSize to dictate our record size. // Count the 2 WORD size header fields too. const auto cbRecordSize = *wDataElementsSize + sizeof(WORD) * 2; // Junk data remains - can't use GetRemainingData here since it would eat the whole buffer if (parser->GetCurrentOffset() < cbRecordSize) { JunkData = blockBytes::parse(parser, cbRecordSize - parser->GetCurrentOffset()); } } void AdditionalRenEntryIDs::ParseBlocks() { setRoot(L"Additional Ren Entry IDs\r\n"); addHeader(L"PersistDataCount = %1!d!", m_ppdPersistData.size()); if (!m_ppdPersistData.empty()) { auto iPersistElement = 0; for (const auto& persistData : m_ppdPersistData) { terminateBlock(); addBlankLine(); auto element = std::make_shared<block>(); addChild(element); element->setText(L"Persist Element %1!d!:\r\n", iPersistElement); element->addChild( persistData->wPersistID, L"PersistID = 0x%1!04X! = %2!ws!\r\n", persistData->wPersistID->getData(), flags::InterpretFlags(flagPersistID, persistData->wPersistID->getData()).c_str()); element->addChild( persistData->wDataElementsSize, L"DataElementsSize = 0x%1!04X!", persistData->wDataElementsSize->getData()); if (!persistData->ppeDataElement.empty()) { auto iDataElement = 0; for (const auto& dataElement : persistData->ppeDataElement) { element->terminateBlock(); element->addHeader(L"DataElement: %1!d!\r\n", iDataElement); element->addChild( dataElement->wElementID, L"\tElementID = 0x%1!04X! = %2!ws!\r\n", dataElement->wElementID->getData(), flags::InterpretFlags(flagElementID, dataElement->wElementID->getData()).c_str()); element->addChild( dataElement->wElementDataSize, L"\tElementDataSize = 0x%1!04X!\r\n", dataElement->wElementDataSize->getData()); element->addHeader(L"\tElementData = "); element->addChild(dataElement->lpbElementData); iDataElement++; } } if (!persistData->JunkData->empty()) { element->terminateBlock(); element->addHeader(L"Unparsed data size = 0x%1!08X!\r\n", persistData->JunkData->size()); element->addChild(persistData->JunkData); } iPersistElement++; } } } } // namespace smartview<|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS ([email protected]) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "Application.hpp" #include <QMessageBox> #include <QDir> #include <QFileInfo> #include <QFileInfoList> Application::Application(int& argc, char** argv) : QApplication(argc, argv) { if (argc > 1) { QStringList args{QCoreApplication::arguments()}; if (args[1] == "compile") { if (args[2] == "theme") { if (!compile(args[3], args[4] + QLatin1String(".snthm"))) QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("Failed to compile theme: ") + m_errors); else QMessageBox::information(nullptr, QApplication::tr("Success"), QApplication::tr("Theme compiled with success")); } else QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("%1 is not a valid Sielo format").arg(args[2])); } else if (args[1] == "decompile") { if (!decompile(args[2], args[3])) QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("Failed to decompile: ") + m_errors); else if (args.count() == 5) { QMessageBox::information(nullptr, QApplication::tr("Success"), args[4]); } } else QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("The action you want to do is unknown...")); } QCoreApplication::instance()->exit(0); } Application::~Application() { // Empty } bool Application::compile(const QString& srcFolder, const QString& fileDestination) { QDir src{srcFolder}; if (!src.exists()) { m_errors = QApplication::tr("The folder to compile doesn't exist."); return false; } m_file.setFileName(fileDestination); if (!m_file.open(QIODevice::WriteOnly)) { m_errors = QApplication::tr("The destination file can't be open."); return false; } m_stream.setDevice(&m_file); bool success{compress(srcFolder, "")}; m_file.close(); return success; } bool Application::decompile(const QString& srcFile, const QString& filesDestination) { QFile src{srcFile}; QFileInfo name{}; if (!src.exists()) { m_errors = QApplication::tr("Sources to decompile don't exists."); return false; } QDir dir{}; if (!dir.mkpath(filesDestination)) { m_errors = QApplication::tr("Can't create folder to receive decompiled files"); return false; } if (!src.open(QIODevice::ReadOnly)) { m_errors = QApplication::tr("Failed to read compiled file."); return false; } QDataStream stream{&src}; while (!stream.atEnd()) { QString fileName{}; QByteArray data{}; stream >> fileName >> data; QString subFolder{}; for (int i{fileName.length() - 1}; i > 0; --i) { if ((QString(fileName[i]) == QString("\\")) || (QString(fileName[i]) == QString("/"))) { subFolder = fileName.left(i); dir.mkpath(filesDestination + QLatin1Char('/') + subFolder); break; } } QFile outFile{filesDestination + QLatin1Char('/') + fileName}; if (!outFile.open(QIODevice::WriteOnly)) { src.close(); m_errors = QApplication::tr("Failed to write decompiled files."); return false; } outFile.write(qUncompress(data)); outFile.close(); } src.close(); return true; } bool Application::compress(const QString& srcFolder, const QString& prefexe) { QDir dir{srcFolder}; dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs); QFileInfoList folderList{dir.entryInfoList()}; for (int i{0}; i < folderList.length(); ++i) { QString folderName{folderList[i].fileName()}; QString folderPath{dir.absolutePath() + QLatin1Char('/') + folderName}; QString newPrefexe{prefexe + QLatin1Char('/') + folderName}; compress(folderPath, newPrefexe); } dir.setFilter(QDir::NoDotAndDotDot | QDir::Files); QFileInfoList filesList{dir.entryInfoList()}; for (int i{0}; i < filesList.length(); ++i) { QFile file{dir.absolutePath() + QLatin1Char('/') + filesList[i].fileName()}; if (!file.open(QIODevice::ReadOnly)) { m_errors = QApplication::tr("Failed to read ") + filesList[i].fileName(); return false; } m_stream << QString(prefexe + QLatin1Char('/') + filesList[i].fileName()); m_stream << qCompress(file.readAll()); file.close(); } return true; }<commit_msg>[Add] An help argument to sielo-compiler<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS ([email protected]) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "Application.hpp" #include <QMessageBox> #include <QDir> #include <QFileInfo> #include <QFileInfoList> #include <iostream> Application::Application(int& argc, char** argv) : QApplication(argc, argv) { if (argc > 1) { QStringList args{QCoreApplication::arguments()}; if (args[1] == "compile") { if (args[2] == "theme") { if (!compile(args[3], args[4] + QLatin1String(".snthm"))) QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("Failed to compile theme: ") + m_errors); else QMessageBox::information(nullptr, QApplication::tr("Success"), QApplication::tr("Theme compiled with success")); } else QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("%1 is not a valid Sielo format").arg(args[2])); } else if (args[1] == "decompile") { if (!decompile(args[2], args[3])) QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("Failed to decompile: ") + m_errors); else if (args.count() == 5) { QMessageBox::information(nullptr, QApplication::tr("Success"), args[4]); } } else if (args[1] == "-h" || args[1] == "--help") { std::cout << QApplication::tr("Their is two ways to use this command:").toStdString() << std::endl << std::endl; std::cout << QApplication::tr("$ sielo-compiler compile theme (path to the theme folder) (name of the theme)").toStdString() << std::endl; std::cout << " -> " << QApplication::tr("This will compile your theme in a basic \".sntm\" file. The output is in the theme folder directory.").toStdString() << std::endl << std::endl; std::cout << QApplication::tr("$ sielo-compiler decompile (path to the theme file) (path where the theme must be decompiled)").toStdString() << std::endl; std::cout << " -> " << QApplication::tr("This will decompile your theme in the directory you choose.").toStdString() << std::endl << std::endl; } else QMessageBox::critical(nullptr, QApplication::tr("Error"), QApplication::tr("The action you want to do is unknown...")); } QCoreApplication::instance()->exit(0); } Application::~Application() { // Empty } bool Application::compile(const QString& srcFolder, const QString& fileDestination) { QDir src{srcFolder}; if (!src.exists()) { m_errors = QApplication::tr("The folder to compile doesn't exist."); return false; } m_file.setFileName(fileDestination); if (!m_file.open(QIODevice::WriteOnly)) { m_errors = QApplication::tr("The destination file can't be open."); return false; } m_stream.setDevice(&m_file); bool success{compress(srcFolder, "")}; m_file.close(); return success; } bool Application::decompile(const QString& srcFile, const QString& filesDestination) { QFile src{srcFile}; QFileInfo name{}; if (!src.exists()) { m_errors = QApplication::tr("Sources to decompile don't exists."); return false; } QDir dir{}; if (!dir.mkpath(filesDestination)) { m_errors = QApplication::tr("Can't create folder to receive decompiled files"); return false; } if (!src.open(QIODevice::ReadOnly)) { m_errors = QApplication::tr("Failed to read compiled file."); return false; } QDataStream stream{&src}; while (!stream.atEnd()) { QString fileName{}; QByteArray data{}; stream >> fileName >> data; QString subFolder{}; for (int i{fileName.length() - 1}; i > 0; --i) { if ((QString(fileName[i]) == QString("\\")) || (QString(fileName[i]) == QString("/"))) { subFolder = fileName.left(i); dir.mkpath(filesDestination + QLatin1Char('/') + subFolder); break; } } QFile outFile{filesDestination + QLatin1Char('/') + fileName}; if (!outFile.open(QIODevice::WriteOnly)) { src.close(); m_errors = QApplication::tr("Failed to write decompiled files."); return false; } outFile.write(qUncompress(data)); outFile.close(); } src.close(); return true; } bool Application::compress(const QString& srcFolder, const QString& prefexe) { QDir dir{srcFolder}; dir.setFilter(QDir::NoDotAndDotDot | QDir::Dirs); QFileInfoList folderList{dir.entryInfoList()}; for (int i{0}; i < folderList.length(); ++i) { QString folderName{folderList[i].fileName()}; QString folderPath{dir.absolutePath() + QLatin1Char('/') + folderName}; QString newPrefexe{prefexe + QLatin1Char('/') + folderName}; compress(folderPath, newPrefexe); } dir.setFilter(QDir::NoDotAndDotDot | QDir::Files); QFileInfoList filesList{dir.entryInfoList()}; for (int i{0}; i < filesList.length(); ++i) { QFile file{dir.absolutePath() + QLatin1Char('/') + filesList[i].fileName()}; if (!file.open(QIODevice::ReadOnly)) { m_errors = QApplication::tr("Failed to read ") + filesList[i].fileName(); return false; } m_stream << QString(prefexe + QLatin1Char('/') + filesList[i].fileName()); m_stream << qCompress(file.readAll()); file.close(); } return true; }<|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { bool DeviceType::operator<(const DeviceType& other) const { return type_ < other.type_; } bool DeviceType::operator==(const DeviceType& other) const { return type_ == other.type_; } std::ostream& operator<<(std::ostream& os, const DeviceType& d) { os << d.type(); return os; } const char* const DEVICE_CPU = "CPU"; const char* const DEVICE_GPU = "GPU"; const char* const DEVICE_SYCL = "SYCL"; string DataTypeString(DataType dtype) { if (IsRefType(dtype)) { DataType non_ref = static_cast<DataType>(dtype - kDataTypeRefOffset); return strings::StrCat(DataTypeString(non_ref), "_ref"); } switch (dtype) { case DT_INVALID: return "INVALID"; case DT_FLOAT: return "float"; case DT_DOUBLE: return "double"; case DT_INT32: return "int32"; case DT_UINT8: return "uint8"; case DT_UINT16: return "uint16"; case DT_INT16: return "int16"; case DT_INT8: return "int8"; case DT_STRING: return "string"; case DT_COMPLEX64: return "complex64"; case DT_COMPLEX128: return "complex128"; case DT_INT64: return "int64"; case DT_BOOL: return "bool"; case DT_QINT8: return "qint8"; case DT_QUINT8: return "quint8"; case DT_QUINT16: return "quint16"; case DT_QINT16: return "qint16"; case DT_QINT32: return "qint32"; case DT_BFLOAT16: return "bfloat16"; case DT_HALF: return "half"; case DT_RESOURCE: return "resource"; default: LOG(FATAL) << "Unrecognized DataType enum value " << dtype; return ""; } } bool DataTypeFromString(StringPiece sp, DataType* dt) { if (sp.ends_with("_ref")) { sp.remove_suffix(4); DataType non_ref; if (DataTypeFromString(sp, &non_ref) && !IsRefType(non_ref)) { *dt = static_cast<DataType>(non_ref + kDataTypeRefOffset); return true; } else { return false; } } if (sp == "float" || sp == "float32") { *dt = DT_FLOAT; return true; } else if (sp == "double" || sp == "float64") { *dt = DT_DOUBLE; return true; } else if (sp == "int32") { *dt = DT_INT32; return true; } else if (sp == "uint8") { *dt = DT_UINT8; return true; } else if (sp == "uint16") { *dt = DT_UINT16; return true; } else if (sp == "int16") { *dt = DT_INT16; return true; } else if (sp == "int8") { *dt = DT_INT8; return true; } else if (sp == "string") { *dt = DT_STRING; return true; } else if (sp == "complex64") { *dt = DT_COMPLEX64; return true; } else if (sp == "complex128") { *dt = DT_COMPLEX128; return true; } else if (sp == "int64") { *dt = DT_INT64; return true; } else if (sp == "bool") { *dt = DT_BOOL; return true; } else if (sp == "qint8") { *dt = DT_QINT8; return true; } else if (sp == "quint8") { *dt = DT_QUINT8; return true; } else if (sp == "qint16") { *dt = DT_QINT16; return true; } else if (sp == "quint16") { *dt = DT_QUINT16; return true; } else if (sp == "qint32") { *dt = DT_QINT32; return true; } else if (sp == "bfloat16") { *dt = DT_BFLOAT16; return true; } else if (sp == "half" || sp == "float16") { *dt = DT_HALF; return true; } else if (sp == "resource") { *dt = DT_RESOURCE; return true; } return false; } string DeviceTypeString(DeviceType device_type) { return device_type.type(); } string DataTypeSliceString(const DataTypeSlice types) { string out; for (auto it = types.begin(); it != types.end(); ++it) { strings::StrAppend(&out, ((it == types.begin()) ? "" : ", "), DataTypeString(*it)); } return out; } DataTypeVector AllTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, DT_UINT16, DT_INT8, DT_STRING, DT_COMPLEX64, DT_COMPLEX128, DT_INT64, DT_BOOL, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF, DT_RESOURCE}; } #if !defined(IS_MOBILE_PLATFORM) || defined(SUPPORT_SELECTIVE_REGISTRATION) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_UINT8, DT_INT16, DT_INT8, DT_UINT16, DT_HALF}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_UINT8, DT_UINT16, DT_UINT16, DT_INT8, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT64, DT_INT32, DT_UINT8, DT_UINT16, DT_INT16, DT_INT8, DT_COMPLEX64, DT_COMPLEX128, DT_QINT8, DT_QUINT8, DT_QINT32, DT_HALF}; } #elif defined(__ANDROID_TYPES_FULL__) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_HALF}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_QINT8, DT_QUINT8, DT_QINT32, DT_HALF}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF}; } #else // defined(IS_MOBILE_PLATFORM) && !defined(__ANDROID_TYPES_FULL__) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT32}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } #endif // defined(IS_MOBILE_PLATFORM) // TODO(jeff): Maybe unify this with Tensor::CanUseDMA, or the underlying // is_simple<T> in tensor.cc (and possible choose a more general name?) bool DataTypeCanUseMemcpy(DataType dt) { switch (dt) { case DT_FLOAT: case DT_DOUBLE: case DT_INT32: case DT_UINT8: case DT_UINT16: case DT_INT16: case DT_INT8: case DT_COMPLEX64: case DT_COMPLEX128: case DT_INT64: case DT_BOOL: case DT_QINT8: case DT_QUINT8: case DT_QINT16: case DT_QUINT16: case DT_QINT32: case DT_BFLOAT16: case DT_HALF: return true; default: return false; } } bool DataTypeIsQuantized(DataType dt) { switch (dt) { case DT_QINT8: case DT_QUINT8: case DT_QINT16: case DT_QUINT16: case DT_QINT32: return true; default: return false; } } bool DataTypeIsInteger(DataType dt) { switch (dt) { case DT_INT8: case DT_UINT8: case DT_INT16: case DT_UINT16: case DT_INT32: case DT_INT64: return true; default: return false; } } int DataTypeSize(DataType dt) { #define CASE(T) \ case DataTypeToEnum<T>::value: \ return sizeof(T); switch (dt) { TF_CALL_POD_TYPES(CASE); TF_CALL_QUANTIZED_TYPES(CASE); default: return 0; } #undef CASE } } // namespace tensorflow <commit_msg>Don't FATAL when asked for the name of an unknown type. (Leaving it as an error for now while I check some of the invocations to see if there's really a need for the diagnostic message). Current fatal prevents some helpful error messages from propagating back to the caller. Change: 142870362<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/types.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { bool DeviceType::operator<(const DeviceType& other) const { return type_ < other.type_; } bool DeviceType::operator==(const DeviceType& other) const { return type_ == other.type_; } std::ostream& operator<<(std::ostream& os, const DeviceType& d) { os << d.type(); return os; } const char* const DEVICE_CPU = "CPU"; const char* const DEVICE_GPU = "GPU"; const char* const DEVICE_SYCL = "SYCL"; string DataTypeString(DataType dtype) { if (IsRefType(dtype)) { DataType non_ref = static_cast<DataType>(dtype - kDataTypeRefOffset); return strings::StrCat(DataTypeString(non_ref), "_ref"); } switch (dtype) { case DT_INVALID: return "INVALID"; case DT_FLOAT: return "float"; case DT_DOUBLE: return "double"; case DT_INT32: return "int32"; case DT_UINT8: return "uint8"; case DT_UINT16: return "uint16"; case DT_INT16: return "int16"; case DT_INT8: return "int8"; case DT_STRING: return "string"; case DT_COMPLEX64: return "complex64"; case DT_COMPLEX128: return "complex128"; case DT_INT64: return "int64"; case DT_BOOL: return "bool"; case DT_QINT8: return "qint8"; case DT_QUINT8: return "quint8"; case DT_QUINT16: return "quint16"; case DT_QINT16: return "qint16"; case DT_QINT32: return "qint32"; case DT_BFLOAT16: return "bfloat16"; case DT_HALF: return "half"; case DT_RESOURCE: return "resource"; default: LOG(ERROR) << "Unrecognized DataType enum value " << dtype; return strings::StrCat("unknown dtype enum (", dtype, ")"); } } bool DataTypeFromString(StringPiece sp, DataType* dt) { if (sp.ends_with("_ref")) { sp.remove_suffix(4); DataType non_ref; if (DataTypeFromString(sp, &non_ref) && !IsRefType(non_ref)) { *dt = static_cast<DataType>(non_ref + kDataTypeRefOffset); return true; } else { return false; } } if (sp == "float" || sp == "float32") { *dt = DT_FLOAT; return true; } else if (sp == "double" || sp == "float64") { *dt = DT_DOUBLE; return true; } else if (sp == "int32") { *dt = DT_INT32; return true; } else if (sp == "uint8") { *dt = DT_UINT8; return true; } else if (sp == "uint16") { *dt = DT_UINT16; return true; } else if (sp == "int16") { *dt = DT_INT16; return true; } else if (sp == "int8") { *dt = DT_INT8; return true; } else if (sp == "string") { *dt = DT_STRING; return true; } else if (sp == "complex64") { *dt = DT_COMPLEX64; return true; } else if (sp == "complex128") { *dt = DT_COMPLEX128; return true; } else if (sp == "int64") { *dt = DT_INT64; return true; } else if (sp == "bool") { *dt = DT_BOOL; return true; } else if (sp == "qint8") { *dt = DT_QINT8; return true; } else if (sp == "quint8") { *dt = DT_QUINT8; return true; } else if (sp == "qint16") { *dt = DT_QINT16; return true; } else if (sp == "quint16") { *dt = DT_QUINT16; return true; } else if (sp == "qint32") { *dt = DT_QINT32; return true; } else if (sp == "bfloat16") { *dt = DT_BFLOAT16; return true; } else if (sp == "half" || sp == "float16") { *dt = DT_HALF; return true; } else if (sp == "resource") { *dt = DT_RESOURCE; return true; } return false; } string DeviceTypeString(DeviceType device_type) { return device_type.type(); } string DataTypeSliceString(const DataTypeSlice types) { string out; for (auto it = types.begin(); it != types.end(); ++it) { strings::StrAppend(&out, ((it == types.begin()) ? "" : ", "), DataTypeString(*it)); } return out; } DataTypeVector AllTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_UINT8, DT_INT16, DT_UINT16, DT_INT8, DT_STRING, DT_COMPLEX64, DT_COMPLEX128, DT_INT64, DT_BOOL, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF, DT_RESOURCE}; } #if !defined(IS_MOBILE_PLATFORM) || defined(SUPPORT_SELECTIVE_REGISTRATION) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_UINT8, DT_INT16, DT_INT8, DT_UINT16, DT_HALF}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_UINT8, DT_UINT16, DT_UINT16, DT_INT8, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_DOUBLE, DT_INT64, DT_INT32, DT_UINT8, DT_UINT16, DT_INT16, DT_INT8, DT_COMPLEX64, DT_COMPLEX128, DT_QINT8, DT_QUINT8, DT_QINT32, DT_HALF}; } #elif defined(__ANDROID_TYPES_FULL__) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_HALF}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_QINT8, DT_QUINT8, DT_QINT32, DT_HALF}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_INT32, DT_INT64, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32, DT_HALF}; } #else // defined(IS_MOBILE_PLATFORM) && !defined(__ANDROID_TYPES_FULL__) DataTypeVector RealNumberTypes() { return {DT_FLOAT, DT_INT32}; } DataTypeVector NumberTypes() { return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT32}; } DataTypeVector QuantizedTypes() { return {DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } DataTypeVector RealAndQuantizedTypes() { return {DT_FLOAT, DT_INT32, DT_QINT8, DT_QUINT8, DT_QINT16, DT_QUINT16, DT_QINT32}; } #endif // defined(IS_MOBILE_PLATFORM) // TODO(jeff): Maybe unify this with Tensor::CanUseDMA, or the underlying // is_simple<T> in tensor.cc (and possible choose a more general name?) bool DataTypeCanUseMemcpy(DataType dt) { switch (dt) { case DT_FLOAT: case DT_DOUBLE: case DT_INT32: case DT_UINT8: case DT_UINT16: case DT_INT16: case DT_INT8: case DT_COMPLEX64: case DT_COMPLEX128: case DT_INT64: case DT_BOOL: case DT_QINT8: case DT_QUINT8: case DT_QINT16: case DT_QUINT16: case DT_QINT32: case DT_BFLOAT16: case DT_HALF: return true; default: return false; } } bool DataTypeIsQuantized(DataType dt) { switch (dt) { case DT_QINT8: case DT_QUINT8: case DT_QINT16: case DT_QUINT16: case DT_QINT32: return true; default: return false; } } bool DataTypeIsInteger(DataType dt) { switch (dt) { case DT_INT8: case DT_UINT8: case DT_INT16: case DT_UINT16: case DT_INT32: case DT_INT64: return true; default: return false; } } int DataTypeSize(DataType dt) { #define CASE(T) \ case DataTypeToEnum<T>::value: \ return sizeof(T); switch (dt) { TF_CALL_POD_TYPES(CASE); TF_CALL_QUANTIZED_TYPES(CASE); default: return 0; } #undef CASE } } // namespace tensorflow <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFeedback.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTransformFeedback.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkShaderProgram.h" #include "vtk_glew.h" vtkStandardNewMacro(vtkTransformFeedback) //------------------------------------------------------------------------------ void vtkTransformFeedback::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ size_t vtkTransformFeedback::GetBytesPerVertex() const { size_t result = 0; typedef std::vector<VaryingMetaData>::const_iterator IterT; for (IterT it = this->Varyings.begin(), itEnd = this->Varyings.end(); it != itEnd; ++it) { result += this->GetBytesPerVertex(it->Role); } return result; } //------------------------------------------------------------------------------ void vtkTransformFeedback::ClearVaryings() { this->Varyings.clear(); this->VaryingsBound = false; } //------------------------------------------------------------------------------ void vtkTransformFeedback::AddVarying(VaryingRole role, const std::string &var) { this->Varyings.push_back(VaryingMetaData(role, var)); this->VaryingsBound = false; } //------------------------------------------------------------------------------ void vtkTransformFeedback::SetNumberOfVertices(int drawMode, size_t inputVerts) { switch (static_cast<GLenum>(drawMode)) { case GL_POINTS: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_POINTS); return; case GL_LINE_STRIP: this->SetNumberOfVertices(inputVerts < 2 ? 0 : (2 * (inputVerts - 1))); this->SetPrimitiveMode(GL_LINES); return; case GL_LINE_LOOP: this->SetNumberOfVertices(2 * inputVerts); this->SetPrimitiveMode(GL_LINES); return; case GL_LINES: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_LINES); return; case GL_TRIANGLE_STRIP: this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2))); this->SetPrimitiveMode(GL_TRIANGLES); return; case GL_TRIANGLE_FAN: this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2))); this->SetPrimitiveMode(GL_TRIANGLES); return; case GL_TRIANGLES: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_TRIANGLES); return; } vtkErrorMacro("Unknown draw mode enum value: " << drawMode); this->SetNumberOfVertices(0); this->SetPrimitiveMode(GL_POINTS); } //------------------------------------------------------------------------------ size_t vtkTransformFeedback::GetBufferSize() const { return this->GetBytesPerVertex() * this->NumberOfVertices; } //------------------------------------------------------------------------------ void vtkTransformFeedback::BindVaryings(vtkShaderProgram *prog) { if (this->Varyings.empty()) { vtkErrorMacro(<<"No capture varyings specified."); return; } vtkOpenGLClearErrorMacro(); std::vector<const char*> vars; vars.reserve(this->Varyings.size()); for (size_t i = 0; i < this->Varyings.size(); ++i) { vars.push_back(this->Varyings[i].Identifier.c_str()); } glTransformFeedbackVaryings(static_cast<GLuint>(prog->GetHandle()), static_cast<GLsizei>(vars.size()), &vars[0], static_cast<GLenum>(this->BufferMode)); this->VaryingsBound = true; vtkOpenGLCheckErrorMacro("OpenGL errors detected after " "glTransformFeedbackVaryings."); } //------------------------------------------------------------------------------ void vtkTransformFeedback::BindBuffer() { if (!this->VaryingsBound) { vtkErrorMacro("Varyings not yet bound!"); return; } vtkOpenGLClearErrorMacro(); this->ReleaseGraphicsResources(); GLuint tbo; glGenBuffers(1, &tbo); this->BufferHandle = static_cast<int>(tbo); glBindBuffer(GL_ARRAY_BUFFER, tbo); glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(this->GetBufferSize()), NULL, GL_STATIC_READ); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo); glBeginTransformFeedback(static_cast<GLenum>(this->PrimitiveMode)); vtkOpenGLCheckErrorMacro("OpenGL errors detected."); } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReadBuffer() { if (this->BufferHandle == 0) { vtkErrorMacro("BufferHandle not set by BindBuffer()."); return; } glEndTransformFeedback(); glFlush(); size_t bufferSize = this->GetBufferSize(); this->ReleaseBufferData(); this->BufferData = new unsigned char[bufferSize]; glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufferSize, static_cast<void*>(this->BufferData)); this->ReleaseGraphicsResources(); vtkOpenGLCheckErrorMacro("OpenGL errors detected."); } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReleaseGraphicsResources() { if (this->BufferHandle) { GLuint tbo = static_cast<GLuint>(this->BufferHandle); glDeleteBuffers(1, &tbo); this->BufferHandle = 0; } } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReleaseBufferData(bool freeBuffer) { if (freeBuffer) { delete [] this->BufferData; } this->BufferData = NULL; } //------------------------------------------------------------------------------ vtkTransformFeedback::vtkTransformFeedback() : VaryingsBound(false), Varyings(), NumberOfVertices(0), BufferMode(GL_INTERLEAVED_ATTRIBS), BufferHandle(0), PrimitiveMode(GL_POINTS), BufferData(NULL) { } //------------------------------------------------------------------------------ vtkTransformFeedback::~vtkTransformFeedback() { this->ReleaseGraphicsResources(); this->ReleaseBufferData(); } <commit_msg>Disable vtkTransformFeedback on ES 2.0.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkTransformFeedback.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkTransformFeedback.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkShaderProgram.h" #include "vtk_glew.h" // Many of the OpenGL features used here are available in ES3, but not ES2. // All non-embedded OpenGL versions for this backend should support this class. #if !defined(GL_ES_VERSION_2_0) || defined(GL_ES_VERSION_3_0) #define GL_SUPPORTED // Not on an embedded system, or ES >= 3.0 #endif #ifdef GL_SUPPORTED vtkStandardNewMacro(vtkTransformFeedback) #else // GL_SUPPORTED vtkTransformFeedback* vtkTransformFeedback::New() { // We return null on non-supported platforms. Since we only instantiate // this class when an instance of vtkOpenGLGL2PSHelper exists and no valid // implementation of that class exists on embedded systems, this shouldn't // cause problems. vtkGenericWarningMacro("TransformFeedback is unsupported on this platform."); return NULL; } #endif // GL_SUPPORTED //------------------------------------------------------------------------------ void vtkTransformFeedback::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //------------------------------------------------------------------------------ size_t vtkTransformFeedback::GetBytesPerVertex() const { size_t result = 0; typedef std::vector<VaryingMetaData>::const_iterator IterT; for (IterT it = this->Varyings.begin(), itEnd = this->Varyings.end(); it != itEnd; ++it) { result += this->GetBytesPerVertex(it->Role); } return result; } //------------------------------------------------------------------------------ void vtkTransformFeedback::ClearVaryings() { this->Varyings.clear(); this->VaryingsBound = false; } //------------------------------------------------------------------------------ void vtkTransformFeedback::AddVarying(VaryingRole role, const std::string &var) { this->Varyings.push_back(VaryingMetaData(role, var)); this->VaryingsBound = false; } //------------------------------------------------------------------------------ void vtkTransformFeedback::SetNumberOfVertices(int drawMode, size_t inputVerts) { #ifdef GL_SUPPORTED switch (static_cast<GLenum>(drawMode)) { case GL_POINTS: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_POINTS); return; case GL_LINE_STRIP: this->SetNumberOfVertices(inputVerts < 2 ? 0 : (2 * (inputVerts - 1))); this->SetPrimitiveMode(GL_LINES); return; case GL_LINE_LOOP: this->SetNumberOfVertices(2 * inputVerts); this->SetPrimitiveMode(GL_LINES); return; case GL_LINES: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_LINES); return; case GL_TRIANGLE_STRIP: this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2))); this->SetPrimitiveMode(GL_TRIANGLES); return; case GL_TRIANGLE_FAN: this->SetNumberOfVertices(inputVerts < 3 ? 0 : (3 * (inputVerts - 2))); this->SetPrimitiveMode(GL_TRIANGLES); return; case GL_TRIANGLES: this->SetNumberOfVertices(inputVerts); this->SetPrimitiveMode(GL_TRIANGLES); return; } vtkErrorMacro("Unknown draw mode enum value: " << drawMode); this->SetNumberOfVertices(0); this->SetPrimitiveMode(GL_POINTS); #else // GL_SUPPORTED (void)drawMode; (void)inputVerts; #endif // GL_SUPPORTED } //------------------------------------------------------------------------------ size_t vtkTransformFeedback::GetBufferSize() const { return this->GetBytesPerVertex() * this->NumberOfVertices; } //------------------------------------------------------------------------------ void vtkTransformFeedback::BindVaryings(vtkShaderProgram *prog) { #ifdef GL_SUPPORTED if (this->Varyings.empty()) { vtkErrorMacro(<<"No capture varyings specified."); return; } vtkOpenGLClearErrorMacro(); std::vector<const char*> vars; vars.reserve(this->Varyings.size()); for (size_t i = 0; i < this->Varyings.size(); ++i) { vars.push_back(this->Varyings[i].Identifier.c_str()); } glTransformFeedbackVaryings(static_cast<GLuint>(prog->GetHandle()), static_cast<GLsizei>(vars.size()), &vars[0], static_cast<GLenum>(this->BufferMode)); this->VaryingsBound = true; vtkOpenGLCheckErrorMacro("OpenGL errors detected after " "glTransformFeedbackVaryings."); #else // GL_SUPPORTED (void)prog; #endif // GL_SUPPORTED } //------------------------------------------------------------------------------ void vtkTransformFeedback::BindBuffer() { #ifdef GL_SUPPORTED if (!this->VaryingsBound) { vtkErrorMacro("Varyings not yet bound!"); return; } vtkOpenGLClearErrorMacro(); this->ReleaseGraphicsResources(); GLuint tbo; glGenBuffers(1, &tbo); this->BufferHandle = static_cast<int>(tbo); glBindBuffer(GL_ARRAY_BUFFER, tbo); glBufferData(GL_ARRAY_BUFFER, static_cast<GLsizeiptr>(this->GetBufferSize()), NULL, GL_STATIC_READ); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo); glBeginTransformFeedback(static_cast<GLenum>(this->PrimitiveMode)); vtkOpenGLCheckErrorMacro("OpenGL errors detected."); #endif // GL_SUPPORTED } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReadBuffer() { #ifdef GL_SUPPORTED if (this->BufferHandle == 0) { vtkErrorMacro("BufferHandle not set by BindBuffer()."); return; } glEndTransformFeedback(); glFlush(); size_t bufferSize = this->GetBufferSize(); this->ReleaseBufferData(); this->BufferData = new unsigned char[bufferSize]; glGetBufferSubData(GL_TRANSFORM_FEEDBACK_BUFFER, 0, bufferSize, static_cast<void*>(this->BufferData)); this->ReleaseGraphicsResources(); vtkOpenGLCheckErrorMacro("OpenGL errors detected."); #endif // GL_SUPPORTED } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReleaseGraphicsResources() { #ifdef GL_SUPPORTED if (this->BufferHandle) { GLuint tbo = static_cast<GLuint>(this->BufferHandle); glDeleteBuffers(1, &tbo); this->BufferHandle = 0; } #endif // GL_SUPPORTED } //------------------------------------------------------------------------------ void vtkTransformFeedback::ReleaseBufferData(bool freeBuffer) { if (freeBuffer) { delete [] this->BufferData; } this->BufferData = NULL; } //------------------------------------------------------------------------------ vtkTransformFeedback::vtkTransformFeedback() : VaryingsBound(false), Varyings(), NumberOfVertices(0), #ifdef GL_SUPPORTED BufferMode(GL_INTERLEAVED_ATTRIBS), #else // GL_SUPPORTED BufferMode(0), #endif // GL_SUPPORTED BufferHandle(0), PrimitiveMode(GL_POINTS), BufferData(NULL) { } //------------------------------------------------------------------------------ vtkTransformFeedback::~vtkTransformFeedback() { this->ReleaseGraphicsResources(); this->ReleaseBufferData(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkSampleFunction.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkSampleFunction.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkGarbageCollector.h" #include "vtkImageData.h" #include "vtkImplicitFunction.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkSampleFunction, "1.74"); vtkStandardNewMacro(vtkSampleFunction); vtkCxxSetObjectMacro(vtkSampleFunction,ImplicitFunction,vtkImplicitFunction); // Construct with ModelBounds=(-1,1,-1,1,-1,1), SampleDimensions=(50,50,50), // Capping turned off, and normal generation on. vtkSampleFunction::vtkSampleFunction() { this->ModelBounds[0] = -1.0; this->ModelBounds[1] = 1.0; this->ModelBounds[2] = -1.0; this->ModelBounds[3] = 1.0; this->ModelBounds[4] = -1.0; this->ModelBounds[5] = 1.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->Capping = 0; this->CapValue = VTK_LARGE_FLOAT; this->ImplicitFunction = NULL; this->ComputeNormals = 1; this->OutputScalarType = VTK_DOUBLE; this->SetNumberOfInputPorts(0); } vtkSampleFunction::~vtkSampleFunction() { this->SetImplicitFunction(NULL); } // Specify the dimensions of the data on which to sample. void vtkSampleFunction::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Specify the dimensions of the data on which to sample. void vtkSampleFunction::SetSampleDimensions(int dim[3]) { vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { for ( int i=0; i<3; i++) { this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1); } this->Modified(); } } int vtkSampleFunction::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed( inputVector ), vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); int i; double ar[3], origin[3]; int wExt[6]; wExt[0] = 0; wExt[2] = 0; wExt[4] = 0; wExt[1] = this->SampleDimensions[0]-1; wExt[3] = this->SampleDimensions[1]-1; wExt[5] = this->SampleDimensions[2]-1; outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6); for (i=0; i < 3; i++) { origin[i] = this->ModelBounds[2*i]; if ( this->SampleDimensions[i] <= 1 ) { ar[i] = 1; } else { ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } } outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),ar,3); vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_DOUBLE, 1); return 1; } void vtkSampleFunction::ExecuteData(vtkDataObject *outp) { vtkIdType idx, i, j, k; vtkFloatArray *newNormals=NULL; vtkIdType numPts; double p[3], s; vtkImageData *output=this->GetOutput(); output->SetExtent(output->GetUpdateExtent()); output = this->AllocateOutputData(outp); vtkDoubleArray *newScalars = vtkDoubleArray::SafeDownCast(output->GetPointData()->GetScalars()); vtkDebugMacro(<< "Sampling implicit function"); // Initialize self; create output objects // if ( !this->ImplicitFunction ) { vtkErrorMacro(<<"No implicit function specified"); return; } numPts = newScalars->GetNumberOfTuples(); // Traverse all points evaluating implicit function at each point // int extent[6]; output->GetUpdateExtent(extent); double spacing[3]; output->GetSpacing(spacing); for ( idx=0, k=extent[4]; k <= extent[5]; k++ ) { p[2] = this->ModelBounds[4] + k*spacing[2]; for ( j=extent[2]; j <= extent[3]; j++ ) { p[1] = this->ModelBounds[2] + j*spacing[1]; for ( i=extent[0]; i <= extent[1]; i++ ) { p[0] = this->ModelBounds[0] + i*spacing[0]; s = this->ImplicitFunction->FunctionValue(p); newScalars->SetTuple1(idx++,s); } } } // If normal computation turned on, compute them // if ( this->ComputeNormals ) { double n[3]; newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->SetNumberOfTuples(numPts); for ( idx=0, k=extent[4]; k <= extent[5]; k++ ) { p[2] = this->ModelBounds[4] + k*spacing[2]; for ( j=extent[2]; j <= extent[3]; j++ ) { p[1] = this->ModelBounds[2] + j*spacing[1]; for ( i=extent[0]; i <= extent[1]; i++ ) { p[0] = this->ModelBounds[0] + i*spacing[0]; this->ImplicitFunction->FunctionGradient(p, n); n[0] *= -1; n[1] *= -1; n[2] *= -1; vtkMath::Normalize(n); newNormals->SetTuple(idx++,n); } } } } // If capping is turned on, set the distances of the outside of the volume // to the CapValue. // if ( this->Capping ) { this->Cap(newScalars); } // Update self // if (newNormals) { output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); } } unsigned long vtkSampleFunction::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); unsigned long impFuncMTime; if ( this->ImplicitFunction != NULL ) { impFuncMTime = this->ImplicitFunction->GetMTime(); mTime = ( impFuncMTime > mTime ? impFuncMTime : mTime ); } return mTime; } void vtkSampleFunction::Cap(vtkDataArray *s) { int i,j,k,extent[6]; vtkIdType idx; int d01=this->SampleDimensions[0]*this->SampleDimensions[1]; vtkImageData *output = this->GetOutput(); output->GetUpdateExtent(extent); // i-j planes //k = extent[4]; for (j=extent[2]; j<=extent[3]; j++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(i+j*this->SampleDimensions[0], 0, this->CapValue); } } k = extent[5]; idx = k*d01; for (j=extent[2]; j<=extent[3]; j++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(idx+i+j*this->SampleDimensions[0], 0, this->CapValue); } } // j-k planes //i = extent[0]; for (k=extent[4]; k<=extent[5]; k++) { for (j=extent[2]; j<=extent[3]; j++) { s->SetComponent(j*this->SampleDimensions[0]+k*d01, 0, this->CapValue); } } i = extent[1]; for (k=extent[4]; k<=extent[5]; k++) { for (j=extent[2]; j<=extent[3]; j++) { s->SetComponent(i+j*this->SampleDimensions[0]+k*d01, 0, this->CapValue); } } // i-k planes //j = extent[2]; for (k=extent[4]; k<=extent[5]; k++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(i+k*d01, 0, this->CapValue); } } j = extent[3]; idx = j*this->SampleDimensions[0]; for (k=extent[4]; k<=extent[5]; k++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(idx+i+k*d01, 0, this->CapValue); } } } void vtkSampleFunction::SetScalars(vtkDataArray *da) { if (da) { this->SetOutputScalarType(da->GetDataType()); } } void vtkSampleFunction::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "OutputScalarType: " << this->OutputScalarType << "\n"; if ( this->ImplicitFunction ) { os << indent << "Implicit Function: " << this->ImplicitFunction << "\n"; } else { os << indent << "No Implicit function defined\n"; } os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Cap Value: " << this->CapValue << "\n"; os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); } //---------------------------------------------------------------------------- void vtkSampleFunction::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->ImplicitFunction, "ImplicitFunction"); } <commit_msg>BUG:Fixed a line missed by the convertion to double.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkSampleFunction.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/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 notice for more information. =========================================================================*/ #include "vtkSampleFunction.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkGarbageCollector.h" #include "vtkImageData.h" #include "vtkImplicitFunction.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkSampleFunction, "1.75"); vtkStandardNewMacro(vtkSampleFunction); vtkCxxSetObjectMacro(vtkSampleFunction,ImplicitFunction,vtkImplicitFunction); vtkSampleFunction::vtkSampleFunction() { this->ModelBounds[0] = -1.0; this->ModelBounds[1] = 1.0; this->ModelBounds[2] = -1.0; this->ModelBounds[3] = 1.0; this->ModelBounds[4] = -1.0; this->ModelBounds[5] = 1.0; this->SampleDimensions[0] = 50; this->SampleDimensions[1] = 50; this->SampleDimensions[2] = 50; this->Capping = 0; this->CapValue = VTK_DOUBLE_MAX; this->ImplicitFunction = NULL; this->ComputeNormals = 1; this->OutputScalarType = VTK_DOUBLE; this->SetNumberOfInputPorts(0); } vtkSampleFunction::~vtkSampleFunction() { this->SetImplicitFunction(NULL); } // Specify the dimensions of the data on which to sample. void vtkSampleFunction::SetSampleDimensions(int i, int j, int k) { int dim[3]; dim[0] = i; dim[1] = j; dim[2] = k; this->SetSampleDimensions(dim); } // Specify the dimensions of the data on which to sample. void vtkSampleFunction::SetSampleDimensions(int dim[3]) { vtkDebugMacro(<< " setting SampleDimensions to (" << dim[0] << "," << dim[1] << "," << dim[2] << ")"); if ( dim[0] != this->SampleDimensions[0] || dim[1] != this->SampleDimensions[1] || dim[2] != this->SampleDimensions[2] ) { for ( int i=0; i<3; i++) { this->SampleDimensions[i] = (dim[i] > 0 ? dim[i] : 1); } this->Modified(); } } int vtkSampleFunction::RequestInformation ( vtkInformation * vtkNotUsed(request), vtkInformationVector ** vtkNotUsed( inputVector ), vtkInformationVector *outputVector) { // get the info objects vtkInformation* outInfo = outputVector->GetInformationObject(0); int i; double ar[3], origin[3]; int wExt[6]; wExt[0] = 0; wExt[2] = 0; wExt[4] = 0; wExt[1] = this->SampleDimensions[0]-1; wExt[3] = this->SampleDimensions[1]-1; wExt[5] = this->SampleDimensions[2]-1; outInfo->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), wExt, 6); for (i=0; i < 3; i++) { origin[i] = this->ModelBounds[2*i]; if ( this->SampleDimensions[i] <= 1 ) { ar[i] = 1; } else { ar[i] = (this->ModelBounds[2*i+1] - this->ModelBounds[2*i]) / (this->SampleDimensions[i] - 1); } } outInfo->Set(vtkDataObject::ORIGIN(),origin,3); outInfo->Set(vtkDataObject::SPACING(),ar,3); vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_DOUBLE, 1); return 1; } void vtkSampleFunction::ExecuteData(vtkDataObject *outp) { vtkIdType idx, i, j, k; vtkFloatArray *newNormals=NULL; vtkIdType numPts; double p[3], s; vtkImageData *output=this->GetOutput(); output->SetExtent(output->GetUpdateExtent()); output = this->AllocateOutputData(outp); vtkDoubleArray *newScalars = vtkDoubleArray::SafeDownCast(output->GetPointData()->GetScalars()); vtkDebugMacro(<< "Sampling implicit function"); // Initialize self; create output objects // if ( !this->ImplicitFunction ) { vtkErrorMacro(<<"No implicit function specified"); return; } numPts = newScalars->GetNumberOfTuples(); // Traverse all points evaluating implicit function at each point // int extent[6]; output->GetUpdateExtent(extent); double spacing[3]; output->GetSpacing(spacing); for ( idx=0, k=extent[4]; k <= extent[5]; k++ ) { p[2] = this->ModelBounds[4] + k*spacing[2]; for ( j=extent[2]; j <= extent[3]; j++ ) { p[1] = this->ModelBounds[2] + j*spacing[1]; for ( i=extent[0]; i <= extent[1]; i++ ) { p[0] = this->ModelBounds[0] + i*spacing[0]; s = this->ImplicitFunction->FunctionValue(p); newScalars->SetTuple1(idx++,s); } } } // If normal computation turned on, compute them // if ( this->ComputeNormals ) { double n[3]; newNormals = vtkFloatArray::New(); newNormals->SetNumberOfComponents(3); newNormals->SetNumberOfTuples(numPts); for ( idx=0, k=extent[4]; k <= extent[5]; k++ ) { p[2] = this->ModelBounds[4] + k*spacing[2]; for ( j=extent[2]; j <= extent[3]; j++ ) { p[1] = this->ModelBounds[2] + j*spacing[1]; for ( i=extent[0]; i <= extent[1]; i++ ) { p[0] = this->ModelBounds[0] + i*spacing[0]; this->ImplicitFunction->FunctionGradient(p, n); n[0] *= -1; n[1] *= -1; n[2] *= -1; vtkMath::Normalize(n); newNormals->SetTuple(idx++,n); } } } } // If capping is turned on, set the distances of the outside of the volume // to the CapValue. // if ( this->Capping ) { this->Cap(newScalars); } // Update self // if (newNormals) { output->GetPointData()->SetNormals(newNormals); newNormals->Delete(); } } unsigned long vtkSampleFunction::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); unsigned long impFuncMTime; if ( this->ImplicitFunction != NULL ) { impFuncMTime = this->ImplicitFunction->GetMTime(); mTime = ( impFuncMTime > mTime ? impFuncMTime : mTime ); } return mTime; } void vtkSampleFunction::Cap(vtkDataArray *s) { int i,j,k,extent[6]; vtkIdType idx; int d01=this->SampleDimensions[0]*this->SampleDimensions[1]; vtkImageData *output = this->GetOutput(); output->GetUpdateExtent(extent); // i-j planes //k = extent[4]; for (j=extent[2]; j<=extent[3]; j++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(i+j*this->SampleDimensions[0], 0, this->CapValue); } } k = extent[5]; idx = k*d01; for (j=extent[2]; j<=extent[3]; j++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(idx+i+j*this->SampleDimensions[0], 0, this->CapValue); } } // j-k planes //i = extent[0]; for (k=extent[4]; k<=extent[5]; k++) { for (j=extent[2]; j<=extent[3]; j++) { s->SetComponent(j*this->SampleDimensions[0]+k*d01, 0, this->CapValue); } } i = extent[1]; for (k=extent[4]; k<=extent[5]; k++) { for (j=extent[2]; j<=extent[3]; j++) { s->SetComponent(i+j*this->SampleDimensions[0]+k*d01, 0, this->CapValue); } } // i-k planes //j = extent[2]; for (k=extent[4]; k<=extent[5]; k++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(i+k*d01, 0, this->CapValue); } } j = extent[3]; idx = j*this->SampleDimensions[0]; for (k=extent[4]; k<=extent[5]; k++) { for (i=extent[0]; i<=extent[1]; i++) { s->SetComponent(idx+i+k*d01, 0, this->CapValue); } } } void vtkSampleFunction::SetScalars(vtkDataArray *da) { if (da) { this->SetOutputScalarType(da->GetDataType()); } } void vtkSampleFunction::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Sample Dimensions: (" << this->SampleDimensions[0] << ", " << this->SampleDimensions[1] << ", " << this->SampleDimensions[2] << ")\n"; os << indent << "ModelBounds: \n"; os << indent << " Xmin,Xmax: (" << this->ModelBounds[0] << ", " << this->ModelBounds[1] << ")\n"; os << indent << " Ymin,Ymax: (" << this->ModelBounds[2] << ", " << this->ModelBounds[3] << ")\n"; os << indent << " Zmin,Zmax: (" << this->ModelBounds[4] << ", " << this->ModelBounds[5] << ")\n"; os << indent << "OutputScalarType: " << this->OutputScalarType << "\n"; if ( this->ImplicitFunction ) { os << indent << "Implicit Function: " << this->ImplicitFunction << "\n"; } else { os << indent << "No Implicit function defined\n"; } os << indent << "Capping: " << (this->Capping ? "On\n" : "Off\n"); os << indent << "Cap Value: " << this->CapValue << "\n"; os << indent << "Compute Normals: " << (this->ComputeNormals ? "On\n" : "Off\n"); } //---------------------------------------------------------------------------- void vtkSampleFunction::ReportReferences(vtkGarbageCollector* collector) { this->Superclass::ReportReferences(collector); vtkGarbageCollectorReport(collector, this->ImplicitFunction, "ImplicitFunction"); } <|endoftext|>
<commit_before>// // JdCoreL2.h // Jigidesign // // Created by Steven Massey on 9/4/15. // Copyright (c) 2015 Jigidesign. All rights reserved. // #ifndef __Jigidesign__JdCoreL2__ #define __Jigidesign__JdCoreL2__ #include <sstream> #include "JdNucleus.hpp" namespace Jd { i32 HashCString31 (const char *i_string); u64 HashString64 (const string & i_string); template <class X> X* SingletonHelper (bool i_create) { static X * lonely = new X; static i64 usageCount = 0; if (i_create) { ++usageCount; } else { if (--usageCount <= 0) { delete lonely; lonely = nullptr; usageCount = 0; } } return lonely; } template <class X> X* AcquireSingleton () // X * should be subsequently released with the ReleaseSingleton () call, if you want the singleton to be eventually shutdown { return SingletonHelper <X> (true); } } #endif /* defined(__Jigidesign__JdCoreL2__) */ <commit_msg>no message<commit_after>// // JdCoreL2.h // Jigidesign // // Created by Steven Massey on 9/4/15. // Copyright (c) 2015 Jigidesign. All rights reserved. // #ifndef __Jigidesign__JdCoreL2__ #define __Jigidesign__JdCoreL2__ #include <sstream> #include "JdNucleus.hpp" namespace Jd { i32 HashCString31 (const char *i_string); u64 HashString64 (const string & i_string); template <class X> X* SingletonHelper (bool i_create) { static X * lonely = new X; static i64 usageCount = 0; if (i_create) { ++usageCount; } else { if (--usageCount <= 0) { delete lonely; lonely = nullptr; usageCount = 0; } } return lonely; } template <class X> X* AcquireSingleton () // X * should be subsequently released with the ReleaseSingleton () call, if you want the singleton to be eventually shutdown { return SingletonHelper <X> (true); } template <class X> void ReleaseSingleton (X * i_singleton) { if (i_singleton) SingletonHelper <X> (false); } template <typename X> struct Singleton { Singleton () { m_lonely = Jd::AcquireSingleton <X> (); } ~Singleton () { Jd::ReleaseSingleton (m_lonely); } X * operator -> () const { return m_lonely; } operator X * () const { return m_lonely; } X * m_lonely; }; } #endif /* defined(__Jigidesign__JdCoreL2__) */ <|endoftext|>
<commit_before> #include "precompiled.h" void WarpZone::setDistination(ofVec2f& pos) { destPos_ = pos; x_.animateFromTo(pos_.x, destPos_.x); y_.animateFromTo(pos_.y, destPos_.y); x_.setDuration(1); y_.setDuration(1); x_.setCurve(EASE_IN); y_.setCurve(EASE_IN); } WarpZone::WarpZone() { name_ = "WarpZone"; tag_ = WARPZONE; color_ = ofFloatColor(1, 0, 0); size_ = ofVec2f(40, 40); } void WarpZone::setup() { enableCollision(); } void WarpZone::update(float deltaTime) { x_.update(deltaTime); y_.update(deltaTime); player_->setPos(ofVec2f(x_, y_)); if (destPos_ == ofVec2f(x_, y_)) { destroy(); } } void WarpZone::draw() { ofSetColor(color_); ofDrawRectangle(getRectangle()); } void WarpZone::onCollision(Actor* c_actor) { if (c_actor->getTag() == PLAYER) { color_ = ofFloatColor(0, 0, 0, 0); player_ = dynamic_cast<Player*>(c_actor); enableUpdate(); } }<commit_msg>warpZone.cpp update()とonCollision()を少し書き換えました<commit_after> #include "precompiled.h" void WarpZone::setDistination(ofVec2f& pos) { destPos_ = pos; x_.animateFromTo(pos_.x, destPos_.x); y_.animateFromTo(pos_.y, destPos_.y); x_.setDuration(1); y_.setDuration(1); x_.setCurve(EASE_IN); y_.setCurve(EASE_IN); } WarpZone::WarpZone() { name_ = "WarpZone"; tag_ = WARPZONE; color_ = ofFloatColor(1, 0, 0); size_ = ofVec2f(40, 40); } void WarpZone::setup() { enableCollision(); } void WarpZone::update(float deltaTime) { if (!player_) { return; } x_.update(deltaTime); y_.update(deltaTime); player_->setPos(ofVec2f(x_, y_)); if (destPos_ == ofVec2f(x_, y_)) { destroy(); } } void WarpZone::draw() { ofSetColor(color_); ofDrawRectangle(getRectangle()); } void WarpZone::onCollision(Actor* c_actor) { if (player_) { return; } if (c_actor->getTag() == PLAYER) { color_ = ofFloatColor(0, 0, 0, 0); player_ = dynamic_cast<Player*>(c_actor); enableUpdate(); } }<|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright © 2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "layout.h++" #include <utility> namespace skui { namespace gui { layout::~layout() = default; layout::layout(element_ptrs children) : children{std::move(children)} , spacing{0} { spacing.value_changed.connect(this, &element::invalidate); } void layout::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const { auto child_offsets = calculate_child_offsets(canvas); for(std::size_t i = 0; i < children.size(); ++i) { children[i]->draw(canvas, position + child_offsets[i]); } } } } <commit_msg>Take padding into account in layout<commit_after>/** * The MIT License (MIT) * * Copyright © 2018 Ruben Van Boxem * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. **/ #include "layout.h++" #include <utility> namespace skui { namespace gui { layout::~layout() = default; layout::layout(element_ptrs children) : children{std::move(children)} , spacing{0} { spacing.value_changed.connect(this, &element::invalidate); } void layout::draw(graphics::canvas& canvas, const graphics::scalar_position& position) const { auto child_offsets = calculate_child_offsets(canvas); const auto padded_position = position + graphics::scalar_position{padding.left, padding.right}; std::for_each(child_offsets.begin(), child_offsets.end(), [&padded_position](auto& offset) { offset += padded_position; }); for(std::size_t i = 0; i < children.size(); ++i) { children[i]->draw(canvas, child_offsets[i]); } } } } <|endoftext|>
<commit_before>//$Id$ #include <streambuf> #include <sstream> #include <cstdlib> #include <iostream> #include <vector> #include "zmq.hpp" #include <map> #include <chrono> #include "Messages.h" #include "MessageUtilities.h" #ifdef _WIN32 #include <windows.h> #include <tchar.h> #else #include <unistd.h> #include <signal.h> #include <spawn.h> #include <sys/wait.h> #endif using namespace std; using namespace std::chrono; extern char **environ; class WorkerInfo { public: int numThreads; #ifdef _WIN32 PROCESS_INFORMATION pi; #else pid_t pid; #endif }; class ServerConfig { public: int mControlPort = 23300; string mControlPortStr = "23300"; int mMaxNumSlots = 4; }; ServerConfig gServerConfig; size_t nTakenSlots=0; #ifdef _WIN32 zmq::context_t gContext(1, 63); #else zmq::context_t gContext(1); #endif #define PRINTSERVER "HopsanServer@"+gServerConfig.mControlPortStr+"; " std::string nowDateTime() { std::time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buff[64]; std::strftime(buff, sizeof(buff), "%b %d %H:%M:%S", std::localtime(&now_time)); return string(&buff[0]); } bool receiveAckNackMessage(zmq::socket_t &rSocket, long timeout, string &rNackReason) { zmq::message_t response; if(receiveWithTimeout(rSocket, timeout, response)) { size_t offset=0; bool parseOK; size_t id = getMessageId(response, offset, parseOK); //cout << "id: " << id << endl; if (id == Ack) { return true; } else if (id == NotAck) { rNackReason = unpackMessage<std::string>(response, offset, parseOK); } else if (!parseOK) { rNackReason = "Exception in msgpack:unpack!"; } else { rNackReason = "Got neither Ack nor Nack"; } } else { rNackReason = "Got either timeout or exception in zmq::recv()"; } return false; } void reportToAddressServer(std::string addressIP, std::string addressPort, std::string myIP, std::string myPort, std::string myDescription, bool isOnline) { try { zmq::socket_t addressServerSocket (gContext, ZMQ_REQ); int linger_ms = 1000; addressServerSocket.setsockopt(ZMQ_LINGER, &linger_ms, sizeof(int)); addressServerSocket.connect(makeZMQAddress(addressIP, addressPort).c_str()); //! @todo check if ok infomsg_Available_t message; message.ip = myIP; message.port = myPort; message.description = myDescription; message.numTotalSlots = gServerConfig.mMaxNumSlots; message.identity = 0; // Identity should allways be 0 when a server starts, relay servers may set other values if (isOnline) { sendMessage(addressServerSocket, Available, message); std::string nackreason; bool ack = receiveAckNackMessage(addressServerSocket, 5000, nackreason); if (ack) { cout << PRINTSERVER << nowDateTime() << " Successfully registered in address server" << endl; } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not register in master server: " << nackreason << endl; } } else { sendMessage(addressServerSocket, ServerClosing, message); std::string nackreason; bool ack = receiveAckNackMessage(addressServerSocket, 5000, nackreason); if (ack) { cout << PRINTSERVER << nowDateTime() << " Successfully unregistered in address server" << endl; } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not unregister in master server: " << nackreason << endl; } } addressServerSocket.disconnect(makeZMQAddress(addressIP, addressPort).c_str()); } catch(zmq::error_t e) { cout << PRINTSERVER << nowDateTime() << " Error: Preparing addressServerSocket: " << e.what() << endl; } } static int s_interrupted = 0; #ifdef _WIN32 BOOL WINAPI consoleCtrlHandler( DWORD dwCtrlType ) { // what to do here? s_interrupted = 1; return TRUE; } #else static void s_signal_handler(int signal_value) { s_interrupted = 1; } static void s_catch_signals(void) { struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset (&action.sa_mask); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); } #endif map<int, WorkerInfo> workerMap; int main(int argc, char* argv[]) { if (argc < 3) { cout << PRINTSERVER << nowDateTime() << " Error: you must specify what number of threads to use and what base port to use!" << endl; return 1; } string numThreadsToUse = argv[1]; gServerConfig.mMaxNumSlots = atoi(numThreadsToUse.c_str()); string myPort = argv[2]; gServerConfig.mControlPortStr = myPort; gServerConfig.mControlPort = atoi(myPort.c_str()); std::string masterserverip, masterserverport; steady_clock::time_point lastStatusRequestTime; if (argc >= 5) { masterserverip = argv[3]; masterserverport = argv[4]; } string myExternalIP = "127.0.0.1"; if (argc >= 6) { myExternalIP = argv[5]; } string myDescription; if (argc >= 7) { myDescription = argv[6]; } cout << PRINTSERVER << nowDateTime() << " Starting with: " << gServerConfig.mMaxNumSlots << " slots, Listening on port: " << gServerConfig.mControlPort << endl; // Prepare our context and socket try { zmq::socket_t socket (gContext, ZMQ_REP); int linger_ms = 1000; socket.setsockopt(ZMQ_LINGER, &linger_ms, sizeof(int)); socket.bind( makeZMQAddress("*", myPort).c_str() ); if (!masterserverip.empty()) { //! @todo somehow automatically figure out my ip reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, true); } #ifdef _WIN32 SetConsoleCtrlHandler( consoleCtrlHandler, TRUE ); #else s_catch_signals(); #endif while (true) { // Wait for next request from client zmq::message_t request; if(receiveWithTimeout(socket, 30000, request)) { size_t offset=0; bool idParseOK; size_t msg_id = getMessageId(request, offset, idParseOK); //cout << PRINTSERVER << nowDateTime() << " Received message with length: " << request.size() << " msg_id: " << msg_id << endl; if (msg_id == RequestServerSlots) { bool parseOK; reqmsg_ReqServerSlots_t msg = unpackMessage<reqmsg_ReqServerSlots_t>(request, offset, parseOK); int requestNumThreads = msg.numThreads; cout << PRINTSERVER << nowDateTime() << " Client is requesting: " << requestNumThreads << " slots... " << endl; if (nTakenSlots+requestNumThreads <= gServerConfig.mMaxNumSlots) { size_t workerPort = gServerConfig.mControlPort+nTakenSlots+1; // Generate unique worker Id int uid = rand(); while (workerMap.count(uid) != 0) { uid = rand(); } #ifdef _WIN32 PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; memset(&processInformation, 0, sizeof(processInformation)); memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); string scport = to_string(gServerConfig.mControlPort); string swport = to_string(workerPort); string nthreads = to_string(requestNumThreads); string uidstr = to_string(uid); std::string appName("HopsanServerWorker.exe"); std::string cmdLine("HopsanServerWorker "+uidstr+" "+scport+" "+swport+" "+nthreads); TCHAR tempCmdLine[cmdLine.size()*2]; strcpy_s(tempCmdLine, cmdLine.size()*2, cmdLine.c_str()); BOOL result = CreateProcess(appName.c_str(), tempCmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation); if (result == 0) { std::cout << PRINTSERVER << "Error: Failed to launch worker process!"<<endl; sendMessage(socket, "Failed to launch worker process!"); } else { std::cout << PRINTSERVER << "Launched Worker Process, pid: "<< processInformation.dwProcessId << " port: " << workerPort << " uid: " << uid << " nThreads: " << requestNumThreads << endl; workerMap.insert({uid, {requestNumThreads, processInformation}}); SM_ReqSlot_Reply_t msg = {workerPort}; sendMessage<SM_ReqSlot_Reply_t>(socket, ReplyServerSlots, msg); nTakenSlots++; } #else char sport_buff[64], wport_buff[64], thread_buff[64], uid_buff[64]; // Write port as char in buffer sprintf(sport_buff, "%d", gServerConfig.mControlPort); sprintf(wport_buff, "%d", int(workerPort)); // Write num threads as char in buffer sprintf(thread_buff, "%d", requestNumThreads); // Write id as char in buffer sprintf(uid_buff, "%d", uid); char *argv[] = {"HopsanServerWorker", uid_buff, sport_buff, wport_buff, thread_buff, nullptr}; pid_t pid; int status = posix_spawn(&pid,"./HopsanServerWorker",nullptr,nullptr,argv,environ); if(status == 0) { std::cout << PRINTSERVER << nowDateTime() << " Launched Worker Process, pid: "<< pid << " port: " << workerPort << " uid: " << uid << " nThreads: " << requestNumThreads << endl; workerMap.insert({uid,{requestNumThreads,pid}}); replymsg_ReplyServerSlots_t msg = {workerPort}; sendMessage(socket, ReplyServerSlots, msg); nTakenSlots+=requestNumThreads; std::cout << PRINTSERVER << nowDateTime() << " Remaining slots: " << gServerConfig.mMaxNumSlots-nTakenSlots << endl; } else { std::cout << PRINTSERVER << nowDateTime() << " Error: Failed to launch worker process!"<<endl; sendMessage(socket, NotAck, "Failed to launch worker process!"); } #endif } else if (nTakenSlots == gServerConfig.mMaxNumSlots) { sendMessage(socket, NotAck, "All slots taken"); cout << PRINTSERVER << nowDateTime() << " Denied! All slots taken." << endl; } else { sendMessage(socket, NotAck, "To few free slots"); cout << PRINTSERVER << nowDateTime() << " Denied! To few free slots." << endl; } } else if (msg_id == WorkerFinished) { bool parseOK; string id_string = unpackMessage<std::string>(request,offset,parseOK); if (parseOK) { int id = atoi(id_string.c_str()); cout << PRINTSERVER << nowDateTime() << " Worker " << id_string << " Finished!" << endl; auto it = workerMap.find(id); if (it != workerMap.end()) { sendShortMessage(socket, Ack); // Wait for process to stop (to avoid zombies) #ifdef _WIN32 PROCESS_INFORMATION pi = it->second.pi; WaitForSingleObject( pi.hProcess, INFINITE ); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); #else pid_t pid = it->second.pid; int stat_loc; pid_t status = waitpid(pid, &stat_loc, WUNTRACED); #endif int nThreads = it->second.numThreads; //! @todo check returncodes maybe workerMap.erase(it); nTakenSlots -= nThreads; std::cout << PRINTSERVER << nowDateTime() << " Open slots: " << gServerConfig.mMaxNumSlots-nTakenSlots << endl; } else { sendMessage(socket, NotAck, "Wrong worker id specified"); } } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not server id string" << endl; } } else if (msg_id == RequestServerStatus) { cout << PRINTSERVER << nowDateTime() << " Client is requesting status" << endl; replymsg_ReplyServerStatus_t status; status.numTotalSlots = gServerConfig.mMaxNumSlots; status.numFreeSlots = gServerConfig.mMaxNumSlots-nTakenSlots; status.isReady = true; sendMessage(socket, ReplyServerStatus, status); lastStatusRequestTime = chrono::steady_clock::now(); } // Ignore the following messages silently else if (msg_id == ClientClosing) { sendShortMessage(socket, Ack); } else if (!idParseOK) { cout << PRINTSERVER << nowDateTime() << " Error: Could not parse message id" << endl; } else { stringstream ss; ss << PRINTSERVER << nowDateTime() << " Warning: Unhandled message id " << msg_id << endl; cout << ss.str() << endl; sendMessage(socket, NotAck, ss.str()); } } else { // Handle timeout / exception } duration<double> time_span = duration_cast<duration<double>>(steady_clock::now() - lastStatusRequestTime); if (time_span.count() > 180) { cout << PRINTSERVER << nowDateTime() << " Too long since status check: " << time_span.count() << endl; // If noone has requested status for this long (and we have a master server) we assume that the master server // has gone down, lets reconnect to it to make sure it knows that we still exist //! @todo maybe this should be handled in the server by saving known servers to file instead if (!masterserverip.empty()) { reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, true); } } // Do some 'work' #ifndef _WIN32 //sleep(1); #else //Sleep (1); #endif if (s_interrupted) { cout << PRINTSERVER << nowDateTime() << " Interrupt signal received, killing server" << std::endl; break; } } // Tell master server we are closing if (!masterserverip.empty()) { //! @todo somehow automatically figure out my ip reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, false); } } catch(zmq::error_t e) { cout << PRINTSERVER << nowDateTime() << " Error: Preparing our context and socket: " << e.what() << endl; } cout << PRINTSERVER << nowDateTime() << " Closed!" << endl; } <commit_msg>Fixed win32 ifdefed code<commit_after>//$Id$ #include <streambuf> #include <sstream> #include <cstdlib> #include <iostream> #include <vector> #include "zmq.hpp" #include <map> #include <chrono> #include "Messages.h" #include "MessageUtilities.h" #ifdef _WIN32 #include <windows.h> #include <tchar.h> #else #include <unistd.h> #include <signal.h> #include <spawn.h> #include <sys/wait.h> #endif using namespace std; using namespace std::chrono; extern char **environ; class WorkerInfo { public: int numThreads; #ifdef _WIN32 PROCESS_INFORMATION pi; #else pid_t pid; #endif }; class ServerConfig { public: int mControlPort = 23300; string mControlPortStr = "23300"; int mMaxNumSlots = 4; }; ServerConfig gServerConfig; size_t nTakenSlots=0; #ifdef _WIN32 zmq::context_t gContext(1, 63); #else zmq::context_t gContext(1); #endif #define PRINTSERVER "HopsanServer@"+gServerConfig.mControlPortStr+"; " std::string nowDateTime() { std::time_t now_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); char buff[64]; std::strftime(buff, sizeof(buff), "%b %d %H:%M:%S", std::localtime(&now_time)); return string(&buff[0]); } bool receiveAckNackMessage(zmq::socket_t &rSocket, long timeout, string &rNackReason) { zmq::message_t response; if(receiveWithTimeout(rSocket, timeout, response)) { size_t offset=0; bool parseOK; size_t id = getMessageId(response, offset, parseOK); //cout << "id: " << id << endl; if (id == Ack) { return true; } else if (id == NotAck) { rNackReason = unpackMessage<std::string>(response, offset, parseOK); } else if (!parseOK) { rNackReason = "Exception in msgpack:unpack!"; } else { rNackReason = "Got neither Ack nor Nack"; } } else { rNackReason = "Got either timeout or exception in zmq::recv()"; } return false; } void reportToAddressServer(std::string addressIP, std::string addressPort, std::string myIP, std::string myPort, std::string myDescription, bool isOnline) { try { zmq::socket_t addressServerSocket (gContext, ZMQ_REQ); int linger_ms = 1000; addressServerSocket.setsockopt(ZMQ_LINGER, &linger_ms, sizeof(int)); addressServerSocket.connect(makeZMQAddress(addressIP, addressPort).c_str()); //! @todo check if ok infomsg_Available_t message; message.ip = myIP; message.port = myPort; message.description = myDescription; message.numTotalSlots = gServerConfig.mMaxNumSlots; message.identity = 0; // Identity should allways be 0 when a server starts, relay servers may set other values if (isOnline) { sendMessage(addressServerSocket, Available, message); std::string nackreason; bool ack = receiveAckNackMessage(addressServerSocket, 5000, nackreason); if (ack) { cout << PRINTSERVER << nowDateTime() << " Successfully registered in address server" << endl; } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not register in master server: " << nackreason << endl; } } else { sendMessage(addressServerSocket, ServerClosing, message); std::string nackreason; bool ack = receiveAckNackMessage(addressServerSocket, 5000, nackreason); if (ack) { cout << PRINTSERVER << nowDateTime() << " Successfully unregistered in address server" << endl; } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not unregister in master server: " << nackreason << endl; } } addressServerSocket.disconnect(makeZMQAddress(addressIP, addressPort).c_str()); } catch(zmq::error_t e) { cout << PRINTSERVER << nowDateTime() << " Error: Preparing addressServerSocket: " << e.what() << endl; } } static int s_interrupted = 0; #ifdef _WIN32 BOOL WINAPI consoleCtrlHandler( DWORD dwCtrlType ) { // what to do here? s_interrupted = 1; return TRUE; } #else static void s_signal_handler(int signal_value) { s_interrupted = 1; } static void s_catch_signals(void) { struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset (&action.sa_mask); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); } #endif map<int, WorkerInfo> workerMap; int main(int argc, char* argv[]) { if (argc < 3) { cout << PRINTSERVER << nowDateTime() << " Error: you must specify what number of threads to use and what base port to use!" << endl; return 1; } string numThreadsToUse = argv[1]; gServerConfig.mMaxNumSlots = atoi(numThreadsToUse.c_str()); string myPort = argv[2]; gServerConfig.mControlPortStr = myPort; gServerConfig.mControlPort = atoi(myPort.c_str()); std::string masterserverip, masterserverport; steady_clock::time_point lastStatusRequestTime; if (argc >= 5) { masterserverip = argv[3]; masterserverport = argv[4]; } string myExternalIP = "127.0.0.1"; if (argc >= 6) { myExternalIP = argv[5]; } string myDescription; if (argc >= 7) { myDescription = argv[6]; } cout << PRINTSERVER << nowDateTime() << " Starting with: " << gServerConfig.mMaxNumSlots << " slots, Listening on port: " << gServerConfig.mControlPort << endl; // Prepare our context and socket try { zmq::socket_t socket (gContext, ZMQ_REP); int linger_ms = 1000; socket.setsockopt(ZMQ_LINGER, &linger_ms, sizeof(int)); socket.bind( makeZMQAddress("*", myPort).c_str() ); if (!masterserverip.empty()) { //! @todo somehow automatically figure out my ip reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, true); } #ifdef _WIN32 SetConsoleCtrlHandler( consoleCtrlHandler, TRUE ); #else s_catch_signals(); #endif while (true) { // Wait for next request from client zmq::message_t request; if(receiveWithTimeout(socket, 30000, request)) { size_t offset=0; bool idParseOK; size_t msg_id = getMessageId(request, offset, idParseOK); //cout << PRINTSERVER << nowDateTime() << " Received message with length: " << request.size() << " msg_id: " << msg_id << endl; if (msg_id == RequestServerSlots) { bool parseOK; reqmsg_ReqServerSlots_t msg = unpackMessage<reqmsg_ReqServerSlots_t>(request, offset, parseOK); int requestNumThreads = msg.numThreads; cout << PRINTSERVER << nowDateTime() << " Client is requesting: " << requestNumThreads << " slots... " << endl; if (nTakenSlots+requestNumThreads <= gServerConfig.mMaxNumSlots) { size_t workerPort = gServerConfig.mControlPort+nTakenSlots+1; // Generate unique worker Id int uid = rand(); while (workerMap.count(uid) != 0) { uid = rand(); } #ifdef _WIN32 PROCESS_INFORMATION processInformation; STARTUPINFO startupInfo; memset(&processInformation, 0, sizeof(processInformation)); memset(&startupInfo, 0, sizeof(startupInfo)); startupInfo.cb = sizeof(startupInfo); string scport = to_string(gServerConfig.mControlPort); string swport = to_string(workerPort); string nthreads = to_string(requestNumThreads); string uidstr = to_string(uid); std::string appName("HopsanServerWorker.exe"); std::string cmdLine("HopsanServerWorker "+uidstr+" "+scport+" "+swport+" "+nthreads); TCHAR tempCmdLine[cmdLine.size()*2]; strcpy_s(tempCmdLine, cmdLine.size()*2, cmdLine.c_str()); BOOL result = CreateProcess(appName.c_str(), tempCmdLine, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &processInformation); if (result == 0) { std::cout << PRINTSERVER << "Error: Failed to launch worker process!"<<endl; sendMessage(socket, NotAck, "Failed to launch worker process!"); } else { std::cout << PRINTSERVER << "Launched Worker Process, pid: "<< processInformation.dwProcessId << " port: " << workerPort << " uid: " << uid << " nThreads: " << requestNumThreads << endl; workerMap.insert({uid, {requestNumThreads, processInformation}}); replymsg_ReplyServerSlots_t msg = {workerPort}; sendMessage<replymsg_ReplyServerSlots_t>(socket, ReplyServerSlots, msg); nTakenSlots++; } #else char sport_buff[64], wport_buff[64], thread_buff[64], uid_buff[64]; // Write port as char in buffer sprintf(sport_buff, "%d", gServerConfig.mControlPort); sprintf(wport_buff, "%d", int(workerPort)); // Write num threads as char in buffer sprintf(thread_buff, "%d", requestNumThreads); // Write id as char in buffer sprintf(uid_buff, "%d", uid); char *argv[] = {"HopsanServerWorker", uid_buff, sport_buff, wport_buff, thread_buff, nullptr}; pid_t pid; int status = posix_spawn(&pid,"./HopsanServerWorker",nullptr,nullptr,argv,environ); if(status == 0) { std::cout << PRINTSERVER << nowDateTime() << " Launched Worker Process, pid: "<< pid << " port: " << workerPort << " uid: " << uid << " nThreads: " << requestNumThreads << endl; workerMap.insert({uid,{requestNumThreads,pid}}); replymsg_ReplyServerSlots_t msg = {workerPort}; sendMessage(socket, ReplyServerSlots, msg); nTakenSlots+=requestNumThreads; std::cout << PRINTSERVER << nowDateTime() << " Remaining slots: " << gServerConfig.mMaxNumSlots-nTakenSlots << endl; } else { std::cout << PRINTSERVER << nowDateTime() << " Error: Failed to launch worker process!"<<endl; sendMessage(socket, NotAck, "Failed to launch worker process!"); } #endif } else if (nTakenSlots == gServerConfig.mMaxNumSlots) { sendMessage(socket, NotAck, "All slots taken"); cout << PRINTSERVER << nowDateTime() << " Denied! All slots taken." << endl; } else { sendMessage(socket, NotAck, "To few free slots"); cout << PRINTSERVER << nowDateTime() << " Denied! To few free slots." << endl; } } else if (msg_id == WorkerFinished) { bool parseOK; string id_string = unpackMessage<std::string>(request,offset,parseOK); if (parseOK) { int id = atoi(id_string.c_str()); cout << PRINTSERVER << nowDateTime() << " Worker " << id_string << " Finished!" << endl; auto it = workerMap.find(id); if (it != workerMap.end()) { sendShortMessage(socket, Ack); // Wait for process to stop (to avoid zombies) #ifdef _WIN32 PROCESS_INFORMATION pi = it->second.pi; WaitForSingleObject( pi.hProcess, INFINITE ); CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); #else pid_t pid = it->second.pid; int stat_loc; pid_t status = waitpid(pid, &stat_loc, WUNTRACED); #endif int nThreads = it->second.numThreads; //! @todo check returncodes maybe workerMap.erase(it); nTakenSlots -= nThreads; std::cout << PRINTSERVER << nowDateTime() << " Open slots: " << gServerConfig.mMaxNumSlots-nTakenSlots << endl; } else { sendMessage(socket, NotAck, "Wrong worker id specified"); } } else { cout << PRINTSERVER << nowDateTime() << " Error: Could not server id string" << endl; } } else if (msg_id == RequestServerStatus) { cout << PRINTSERVER << nowDateTime() << " Client is requesting status" << endl; replymsg_ReplyServerStatus_t status; status.numTotalSlots = gServerConfig.mMaxNumSlots; status.numFreeSlots = gServerConfig.mMaxNumSlots-nTakenSlots; status.isReady = true; sendMessage(socket, ReplyServerStatus, status); lastStatusRequestTime = chrono::steady_clock::now(); } // Ignore the following messages silently else if (msg_id == ClientClosing) { sendShortMessage(socket, Ack); } else if (!idParseOK) { cout << PRINTSERVER << nowDateTime() << " Error: Could not parse message id" << endl; } else { stringstream ss; ss << PRINTSERVER << nowDateTime() << " Warning: Unhandled message id " << msg_id << endl; cout << ss.str() << endl; sendMessage(socket, NotAck, ss.str()); } } else { // Handle timeout / exception } duration<double> time_span = duration_cast<duration<double>>(steady_clock::now() - lastStatusRequestTime); if (time_span.count() > 180) { cout << PRINTSERVER << nowDateTime() << " Too long since status check: " << time_span.count() << endl; // If noone has requested status for this long (and we have a master server) we assume that the master server // has gone down, lets reconnect to it to make sure it knows that we still exist //! @todo maybe this should be handled in the server by saving known servers to file instead if (!masterserverip.empty()) { reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, true); } } // Do some 'work' #ifndef _WIN32 //sleep(1); #else //Sleep (1); #endif if (s_interrupted) { cout << PRINTSERVER << nowDateTime() << " Interrupt signal received, killing server" << std::endl; break; } } // Tell master server we are closing if (!masterserverip.empty()) { //! @todo somehow automatically figure out my ip reportToAddressServer(masterserverip, masterserverport, myExternalIP, myPort, myDescription, false); } } catch(zmq::error_t e) { cout << PRINTSERVER << nowDateTime() << " Error: Preparing our context and socket: " << e.what() << endl; } cout << PRINTSERVER << nowDateTime() << " Closed!" << endl; } <|endoftext|>
<commit_before>#include "Object.h" #include "Math.h" using namespace std; using namespace Intersection; using namespace Rendering; using namespace Math; using namespace Rendering::Light; using namespace Core; #define _child _vector Object::Object(const std::string& name, Object* parent /* = NULL */) : _culled(false), _parent(parent), _use(true), _hasMesh(false), _name(name), _radius(0.0f) { _boundBox.SetMinMax(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, 0.0f)); _transform = new Transform( this ); _root = parent ? parent->_root : this; if(parent) parent->AddChild(this); } Object::~Object(void) { SAFE_DELETE(_transform); DeleteAllChild(); DeleteAllComponent(); } void Object::DeleteAllChild() { for(auto iter = _vector.begin(); iter != _vector.end(); ++iter) { (*iter)->DeleteAllComponent(); (*iter)->DeleteAllChild(); SAFE_DELETE((*iter)); } DeleteAll(); } void Object::AddChild(Object *child) { ASSERT_COND_MSG( (child->_parent == nullptr) || (child->_parent == this), "Error, Invalid parent"); if(FindChild(child->GetName()) == nullptr) { Add(child->_name, child); child->_parent = this; _transform->AddChild(child->GetName(), child->_transform); } else { ASSERT_MSG("Duplicated child. plz check your code."); } } Object* Object::FindChild(const std::string& key) { Object** ret = Find(key, nullptr); return ret ? (*ret) : nullptr; } bool Object::CompareIsChildOfParent(Object *parent) { return (parent == _parent); } void Object::Culling(const Intersection::Frustum *frustum) { if(_use == false) return; Vector3 wp; _transform->FetchWorldPosition(wp); _culled = !frustum->In(wp, _radius); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->Culling(frustum); } void Object::Update(float delta) { if(_use == false) return; for(auto iter = _components.begin(); iter != _components.end(); ++iter) (*iter)->OnUpdate(delta); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->Update(delta); } void Object::UpdateTransformCB_With_ComputeSceneMinMaxPos( const Device::DirectX*& dx, Math::Vector3& refWorldPosMin, Math::Vector3& refWorldPosMax, const Math::Matrix& parentWorldMat) { if(_use == false) return; Math::Matrix localMat; _transform->FetchLocalMatrix(localMat); Math::Matrix worldMat = localMat * parentWorldMat; if(_hasMesh) { Vector3 extents = _boundBox.GetExtents(); Vector3 boxCenter = _boundBox.GetCenter(); Vector3 worldPos = Vector3(worldMat._41, worldMat._42, worldMat._43) + boxCenter; Vector3 worldScale; Transform::FetchWorldScale(worldScale, worldMat); Vector3 minPos = (worldPos - extents) * worldScale; Vector3 maxPos = (worldPos + extents) * worldScale; if(refWorldPosMin.x > minPos.x) refWorldPosMin.x = minPos.x; if(refWorldPosMin.y > minPos.y) refWorldPosMin.y = minPos.y; if(refWorldPosMin.z > minPos.z) refWorldPosMin.z = minPos.z; if(refWorldPosMax.x < maxPos.x) refWorldPosMax.x = maxPos.x; if(refWorldPosMax.y < maxPos.y) refWorldPosMax.y = maxPos.y; if(refWorldPosMax.z < maxPos.z) refWorldPosMax.z = maxPos.z; } Rendering::TransformCB transformCB; Matrix& transposedWM = transformCB.world; Matrix::Transpose(transposedWM, worldMat); Matrix& worldInvTranspose = transformCB.worldInvTranspose; { Matrix::Inverse(worldInvTranspose, transposedWM); Matrix::Transpose(worldInvTranspose, worldInvTranspose); } bool changedWorldMat = memcmp(&_prevWorldMat, &worldMat, sizeof(Math::Matrix)) != 0; if(changedWorldMat) _prevWorldMat = worldMat; for(auto iter = _components.begin(); iter != _components.end(); ++iter) { if(changedWorldMat) (*iter)->OnUpdateTransformCB(dx, transformCB); (*iter)->OnRenderPreview(); } for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->UpdateTransformCB_With_ComputeSceneMinMaxPos(dx, refWorldPosMin, refWorldPosMax, worldMat); } bool Object::Intersects(Intersection::Sphere &sphere) { Vector3 wp; _transform->FetchWorldPosition(wp); return sphere.Intersects(wp, _radius); } void Object::DeleteComponent(Component *component) { for(auto iter = _components.begin(); iter != _components.end(); ++iter) { if((*iter) == component) { (*iter)->OnDestroy(); _components.erase(iter); delete (*iter); return; } } } void Object::DeleteAllComponent() { for(auto iter = _components.begin(); iter != _components.end(); ++iter) delete (*iter); _components.clear(); } Object* Object::Clone() const { Object* newObject = new Object(_name + "-Clone", nullptr); newObject->_transform->UpdateTransform(*_transform); newObject->_hasMesh = _hasMesh; newObject->_use = _use; newObject->_radius = _radius; newObject->_boundBox = _boundBox; for(auto iter = _components.begin(); iter != _components.end(); ++iter) newObject->_components.push_back( (*iter)->Clone() ); for(auto iter = _child.begin(); iter != _child.end(); ++iter) newObject->AddChild( (*iter)->Clone() ); return newObject; } void Object::SetUse(bool b) { _use = b; Geometry::Mesh* mesh = GetComponent<Geometry::Mesh>(); if(mesh) mesh->SetShow(b); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->SetUse(b); }<commit_msg>Object.cpp - _prevWorldMat -> _prevTransposedWorldMat #53<commit_after>#include "Object.h" #include "Math.h" using namespace std; using namespace Intersection; using namespace Rendering; using namespace Math; using namespace Rendering::Light; using namespace Core; #define _child _vector Object::Object(const std::string& name, Object* parent /* = NULL */) : _culled(false), _parent(parent), _use(true), _hasMesh(false), _name(name), _radius(0.0f) { _boundBox.SetMinMax(Vector3(0.0f, 0.0f, 0.0f), Vector3(0.0f, 0.0f, 0.0f)); _transform = new Transform( this ); _root = parent ? parent->_root : this; if(parent) parent->AddChild(this); } Object::~Object(void) { SAFE_DELETE(_transform); DeleteAllChild(); DeleteAllComponent(); } void Object::DeleteAllChild() { for(auto iter = _vector.begin(); iter != _vector.end(); ++iter) { (*iter)->DeleteAllComponent(); (*iter)->DeleteAllChild(); SAFE_DELETE((*iter)); } DeleteAll(); } void Object::AddChild(Object *child) { ASSERT_COND_MSG( (child->_parent == nullptr) || (child->_parent == this), "Error, Invalid parent"); if(FindChild(child->GetName()) == nullptr) { Add(child->_name, child); child->_parent = this; _transform->AddChild(child->GetName(), child->_transform); } else { ASSERT_MSG("Duplicated child. plz check your code."); } } Object* Object::FindChild(const std::string& key) { Object** ret = Find(key, nullptr); return ret ? (*ret) : nullptr; } bool Object::CompareIsChildOfParent(Object *parent) { return (parent == _parent); } void Object::Culling(const Intersection::Frustum *frustum) { if(_use == false) return; Vector3 wp; _transform->FetchWorldPosition(wp); _culled = !frustum->In(wp, _radius); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->Culling(frustum); } void Object::Update(float delta) { if(_use == false) return; for(auto iter = _components.begin(); iter != _components.end(); ++iter) (*iter)->OnUpdate(delta); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->Update(delta); } void Object::UpdateTransformCB_With_ComputeSceneMinMaxPos( const Device::DirectX*& dx, Math::Vector3& refWorldPosMin, Math::Vector3& refWorldPosMax, const Math::Matrix& parentWorldMat) { if(_use == false) return; Math::Matrix localMat; _transform->FetchLocalMatrix(localMat); Math::Matrix worldMat = localMat * parentWorldMat; if(_hasMesh) { Vector3 extents = _boundBox.GetExtents(); Vector3 boxCenter = _boundBox.GetCenter(); Vector3 worldPos = Vector3(worldMat._41, worldMat._42, worldMat._43) + boxCenter; Vector3 worldScale; Transform::FetchWorldScale(worldScale, worldMat); Vector3 minPos = (worldPos - extents) * worldScale; Vector3 maxPos = (worldPos + extents) * worldScale; if(refWorldPosMin.x > minPos.x) refWorldPosMin.x = minPos.x; if(refWorldPosMin.y > minPos.y) refWorldPosMin.y = minPos.y; if(refWorldPosMin.z > minPos.z) refWorldPosMin.z = minPos.z; if(refWorldPosMax.x < maxPos.x) refWorldPosMax.x = maxPos.x; if(refWorldPosMax.y < maxPos.y) refWorldPosMax.y = maxPos.y; if(refWorldPosMax.z < maxPos.z) refWorldPosMax.z = maxPos.z; } Rendering::TransformCB transformCB; Matrix& transposedWM = transformCB.world; Matrix::Transpose(transposedWM, worldMat); Matrix& worldInvTranspose = transformCB.worldInvTranspose; { Matrix::Inverse(worldInvTranspose, transposedWM); Matrix::Transpose(worldInvTranspose, worldInvTranspose); } bool changedWorldMat = memcmp(&_prevTransposedWorldMat, &transposedWM, sizeof(Math::Matrix)) != 0; if(changedWorldMat) _prevTransposedWorldMat = transposedWM; for(auto iter = _components.begin(); iter != _components.end(); ++iter) { if(changedWorldMat) (*iter)->OnUpdateTransformCB(dx, transformCB); (*iter)->OnRenderPreview(); } for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->UpdateTransformCB_With_ComputeSceneMinMaxPos(dx, refWorldPosMin, refWorldPosMax, worldMat); } bool Object::Intersects(Intersection::Sphere &sphere) { Vector3 wp; _transform->FetchWorldPosition(wp); return sphere.Intersects(wp, _radius); } void Object::DeleteComponent(Component *component) { for(auto iter = _components.begin(); iter != _components.end(); ++iter) { if((*iter) == component) { (*iter)->OnDestroy(); _components.erase(iter); delete (*iter); return; } } } void Object::DeleteAllComponent() { for(auto iter = _components.begin(); iter != _components.end(); ++iter) delete (*iter); _components.clear(); } Object* Object::Clone() const { Object* newObject = new Object(_name + "-Clone", nullptr); newObject->_transform->UpdateTransform(*_transform); newObject->_hasMesh = _hasMesh; newObject->_use = _use; newObject->_radius = _radius; newObject->_boundBox = _boundBox; for(auto iter = _components.begin(); iter != _components.end(); ++iter) newObject->_components.push_back( (*iter)->Clone() ); for(auto iter = _child.begin(); iter != _child.end(); ++iter) newObject->AddChild( (*iter)->Clone() ); return newObject; } void Object::SetUse(bool b) { _use = b; Geometry::Mesh* mesh = GetComponent<Geometry::Mesh>(); if(mesh) mesh->SetShow(b); for(auto iter = _child.begin(); iter != _child.end(); ++iter) (*iter)->SetUse(b); } <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "ipc/ipc_server.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_asio.h" #include "base/strings/string_printf.h" #include "base/strings/unicode.h" #include "base/win/scoped_object.h" #include "base/win/security_helpers.h" #include "crypto/random.h" #include "ipc/ipc_channel.h" #include <asio/post.hpp> #include <asio/windows/overlapped_ptr.hpp> #include <asio/windows/stream_handle.hpp> namespace ipc { namespace { const DWORD kAcceptTimeout = 5000; // ms const DWORD kPipeBufferSize = 512 * 1024; // 512 kB } // namespace class Server::Listener : public std::enable_shared_from_this<Listener> { public: Listener(Server* server, size_t index); void dettach() { server_ = nullptr; } bool listen(asio::io_context& io_context, std::u16string_view channel_name); void onNewConnetion(const std::error_code& error_code, size_t bytes_transferred); private: Server* server_; const size_t index_; std::unique_ptr<asio::windows::stream_handle> handle_; std::unique_ptr<asio::windows::overlapped_ptr> overlapped_; DISALLOW_COPY_AND_ASSIGN(Listener); }; Server::Listener::Listener(Server* server, size_t index) : server_(server), index_(index) { // Nothing } bool Server::Listener::listen(asio::io_context& io_context, std::u16string_view channel_name) { std::wstring user_sid; if (!base::win::userSidString(&user_sid)) { LOG(LS_ERROR) << "Failed to query the current user SID"; return nullptr; } // Create a security descriptor that gives full access to the caller and authenticated users // and denies access by anyone else. std::wstring security_descriptor = base::stringPrintf(L"O:%sG:%sD:(A;;GA;;;%s)(A;;GA;;;AU)", user_sid.c_str(), user_sid.c_str(), user_sid.c_str()); base::win::ScopedSd sd = base::win::convertSddlToSd(security_descriptor); if (!sd.get()) { LOG(LS_ERROR) << "Failed to create a security descriptor"; return nullptr; } SECURITY_ATTRIBUTES security_attributes = { 0 }; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = sd.get(); security_attributes.bInheritHandle = FALSE; base::win::ScopedHandle handle( CreateNamedPipeW(reinterpret_cast<const wchar_t*>(channel_name.data()), FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS, PIPE_UNLIMITED_INSTANCES, kPipeBufferSize, kPipeBufferSize, kAcceptTimeout, &security_attributes)); if (!handle.isValid()) { PLOG(LS_WARNING) << "CreateNamedPipeW failed"; return nullptr; } handle_ = std::make_unique<asio::windows::stream_handle>(io_context, handle.release()); overlapped_ = std::make_unique<asio::windows::overlapped_ptr>( io_context, std::bind(&Server::Listener::onNewConnetion, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); if (!ConnectNamedPipe(handle_->native_handle(), overlapped_->get())) { DWORD last_error = GetLastError(); switch (last_error) { case ERROR_PIPE_CONNECTED: break; case ERROR_IO_PENDING: overlapped_->release(); return true; default: overlapped_->complete( std::error_code(last_error, asio::error::get_system_category()), 0); return false; } } overlapped_->complete(std::error_code(), 0); return true; } void Server::Listener::onNewConnetion( const std::error_code& error_code, size_t /* bytes_transferred */) { if (!server_) return; if (error_code) { server_->onErrorOccurred(FROM_HERE); return; } std::unique_ptr<Channel> channel = std::unique_ptr<Channel>(new Channel(server_->channel_name_, std::move(*handle_))); server_->onNewConnection(index_, std::move(channel)); } Server::Server() : io_context_(base::MessageLoop::current()->pumpAsio()->ioContext()) { for (size_t i = 0; i < listeners_.size(); ++i) listeners_[i] = std::make_shared<Listener>(this, i); } Server::~Server() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); stop(); } // static std::u16string Server::createUniqueId() { static std::atomic_uint32_t last_channel_id = 0; uint32_t channel_id = last_channel_id++; uint32_t process_id = GetCurrentProcessId(); uint32_t random_number = crypto::Random::number32(); return base::utf16FromAscii( base::stringPrintf("%lu.%lu.%lu", process_id, channel_id, random_number)); } bool Server::start(std::u16string_view channel_id, Delegate* delegate) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(delegate); if (channel_id.empty()) { DLOG(LS_ERROR) << "Empty channel id"; return false; } channel_name_ = Channel::channelName(channel_id); delegate_ = delegate; for (size_t i = 0; i < listeners_.size(); ++i) { if (!runListener(i)) return false; } return true; } void Server::stop() { delegate_ = nullptr; for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i]) { listeners_[i]->dettach(); listeners_[i].reset(); } } } bool Server::runListener(size_t index) { return listeners_[index]->listen(io_context_, channel_name_); } void Server::onNewConnection(size_t index, std::unique_ptr<Channel> channel) { if (delegate_) { delegate_->onNewConnection(std::move(channel)); runListener(index); } } void Server::onErrorOccurred(const base::Location& location) { LOG(LS_WARNING) << "Error in IPC server with name: " << channel_name_ << " (" << location.toString() << ")"; if (delegate_) delegate_->onErrorOccurred(); } } // namespace ipc <commit_msg>- Added null pointer check. - Other minor changes.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "ipc/ipc_server.h" #include "base/location.h" #include "base/logging.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_pump_asio.h" #include "base/strings/string_printf.h" #include "base/strings/unicode.h" #include "base/win/scoped_object.h" #include "base/win/security_helpers.h" #include "crypto/random.h" #include "ipc/ipc_channel.h" #include <asio/post.hpp> #include <asio/windows/overlapped_ptr.hpp> #include <asio/windows/stream_handle.hpp> namespace ipc { namespace { const DWORD kAcceptTimeout = 5000; // ms const DWORD kPipeBufferSize = 512 * 1024; // 512 kB } // namespace class Server::Listener : public std::enable_shared_from_this<Listener> { public: Listener(Server* server, size_t index); ~Listener(); void dettach() { server_ = nullptr; } bool listen(asio::io_context& io_context, std::u16string_view channel_name); void onNewConnetion(const std::error_code& error_code, size_t bytes_transferred); private: Server* server_; const size_t index_; std::unique_ptr<asio::windows::stream_handle> handle_; std::unique_ptr<asio::windows::overlapped_ptr> overlapped_; DISALLOW_COPY_AND_ASSIGN(Listener); }; Server::Listener::Listener(Server* server, size_t index) : server_(server), index_(index) { // Nothing } Server::Listener::~Listener() = default; bool Server::Listener::listen(asio::io_context& io_context, std::u16string_view channel_name) { std::wstring user_sid; if (!base::win::userSidString(&user_sid)) { LOG(LS_ERROR) << "Failed to query the current user SID"; return false; } // Create a security descriptor that gives full access to the caller and authenticated users // and denies access by anyone else. std::wstring security_descriptor = base::stringPrintf(L"O:%sG:%sD:(A;;GA;;;%s)(A;;GA;;;AU)", user_sid.c_str(), user_sid.c_str(), user_sid.c_str()); base::win::ScopedSd sd = base::win::convertSddlToSd(security_descriptor); if (!sd.get()) { LOG(LS_ERROR) << "Failed to create a security descriptor"; return false; } SECURITY_ATTRIBUTES security_attributes = { 0 }; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = sd.get(); security_attributes.bInheritHandle = FALSE; base::win::ScopedHandle handle( CreateNamedPipeW(reinterpret_cast<const wchar_t*>(channel_name.data()), FILE_FLAG_OVERLAPPED | PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_REJECT_REMOTE_CLIENTS, PIPE_UNLIMITED_INSTANCES, kPipeBufferSize, kPipeBufferSize, kAcceptTimeout, &security_attributes)); if (!handle.isValid()) { PLOG(LS_WARNING) << "CreateNamedPipeW failed"; return false; } handle_ = std::make_unique<asio::windows::stream_handle>(io_context, handle.release()); overlapped_ = std::make_unique<asio::windows::overlapped_ptr>( io_context, std::bind(&Server::Listener::onNewConnetion, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); if (!ConnectNamedPipe(handle_->native_handle(), overlapped_->get())) { DWORD last_error = GetLastError(); switch (last_error) { case ERROR_PIPE_CONNECTED: break; case ERROR_IO_PENDING: overlapped_->release(); return true; default: overlapped_->complete( std::error_code(last_error, asio::error::get_system_category()), 0); return false; } } overlapped_->complete(std::error_code(), 0); return true; } void Server::Listener::onNewConnetion( const std::error_code& error_code, size_t /* bytes_transferred */) { if (!server_) return; if (error_code) { server_->onErrorOccurred(FROM_HERE); return; } std::unique_ptr<Channel> channel = std::unique_ptr<Channel>(new Channel(server_->channel_name_, std::move(*handle_))); server_->onNewConnection(index_, std::move(channel)); } Server::Server() : io_context_(base::MessageLoop::current()->pumpAsio()->ioContext()) { for (size_t i = 0; i < listeners_.size(); ++i) listeners_[i] = std::make_shared<Listener>(this, i); } Server::~Server() { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); stop(); } // static std::u16string Server::createUniqueId() { static std::atomic_uint32_t last_channel_id = 0; uint32_t channel_id = last_channel_id++; uint32_t process_id = GetCurrentProcessId(); uint32_t random_number = crypto::Random::number32(); return base::utf16FromAscii( base::stringPrintf("%lu.%lu.%lu", process_id, channel_id, random_number)); } bool Server::start(std::u16string_view channel_id, Delegate* delegate) { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DCHECK(delegate); if (channel_id.empty()) { DLOG(LS_ERROR) << "Empty channel id"; return false; } channel_name_ = Channel::channelName(channel_id); delegate_ = delegate; for (size_t i = 0; i < listeners_.size(); ++i) { if (!runListener(i)) return false; } return true; } void Server::stop() { delegate_ = nullptr; for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i]) { listeners_[i]->dettach(); listeners_[i].reset(); } } } bool Server::runListener(size_t index) { std::shared_ptr<Listener> listener = listeners_[index]; if (!listener) return false; return listener->listen(io_context_, channel_name_); } void Server::onNewConnection(size_t index, std::unique_ptr<Channel> channel) { if (delegate_) { delegate_->onNewConnection(std::move(channel)); runListener(index); } } void Server::onErrorOccurred(const base::Location& location) { LOG(LS_WARNING) << "Error in IPC server with name: " << channel_name_ << " (" << location.toString() << ")"; if (delegate_) delegate_->onErrorOccurred(); } } // namespace ipc <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2016 The DarkNet developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionrecord.h" #include "base58.h" #include "timedata.h" #include "wallet.h" #include "obfuscation.h" #include "swifttx.h" #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (wtx.IsCoinStake()) { CTxDestination address; if (!ExtractDestination(wtx.vout[1].scriptPubKey, address)) return parts; if(!IsMine(*wallet, address)) //if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx { for(unsigned int i = 0; i < wtx.vout.size(); i++) { if(i == 0) continue; // first tx is blank CTxDestination outAddress; if(ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) { if(IsMine(*wallet, outAddress)) { TransactionRecord txrMasternodeRec = TransactionRecord(hash, nTime, TransactionRecord::MNReward, CBitcoinAddress(outAddress).ToString(), wtx.vout[i].nValue, 0); parts.append(txrMasternodeRec); } } } } else { //stake reward TransactionRecord txrCoinStake = TransactionRecord(hash, nTime, TransactionRecord::StakeMint, CBitcoinAddress(address).ToString(), nNet, 0); parts.append(txrCoinStake); } } else if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { isminetype mine = wallet->IsMine(txout); if(mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; sub.involvesWatchAddress = mine == ISMINE_WATCH_ONLY; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by DarkNet Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { bool fAllFromMeDenom = true; int nFromMe = 0; bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { if(wallet->IsMine(txin)) { fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin); nFromMe++; } isminetype mine = wallet->IsMine(txin); if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; bool fAllToMeDenom = true; int nToMe = 0; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue); nToMe++; } isminetype mine = wallet->IsMine(txout); if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } if(fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) { parts.append(TransactionRecord(hash, nTime, TransactionRecord::ObfuscationDenominate, "", -nDebit, nCredit)); parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe && fAllToMe) { // Payment to self // TODO: this section still not accurate but covers most cases, // might need some additional work however TransactionRecord sub(hash, nTime); // Payment to self by default sub.type = TransactionRecord::SendToSelf; sub.address = ""; if(mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; CTxDestination address; if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) { // Sent to DarkNet Address sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.address = mapValue["to"]; } } else { for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; sub.idx = parts.size(); if(wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationMakeCollaterals; if(wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationCreateDenominations; if(nDebit - wtx.GetValueOut() == OBFUSCATION_COLLATERAL) sub.type = TransactionRecord::ObfuscationCollateralPayment; } } CAmount nChange = wtx.GetChange(); sub.debit = -(nDebit - nChange); sub.credit = nCredit - nChange; parts.append(sub); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // CAmount nTxFee = nDebit - wtx.GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); sub.involvesWatchAddress = involvesWatchAddress; if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to DarkNet Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } if(mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; } CAmount nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { AssertLockHeld(cs_main); // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = chainActive.Height(); status.cur_num_ix_locks = nCompleteTXLocks; if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - chainActive.Height(); } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated || type == TransactionRecord::StakeMint) { if (wtx.GetBlocksToMaturity() > 0) { status.status = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.status = TransactionStatus::MaturesWarning; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } } bool TransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks; } QString TransactionRecord::getTxID() const { return formatSubTxId(hash, idx); } QString TransactionRecord::formatSubTxId(const uint256 &hash, int vout) { return QString::fromStdString(hash.ToString() + strprintf("-%03d", vout)); } <commit_msg>fix masternode rewards showing as confirmed prematurely in transaction tab<commit_after>// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2016 The DarkNet developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionrecord.h" #include "base58.h" #include "timedata.h" #include "wallet.h" #include "obfuscation.h" #include "swifttx.h" #include <stdint.h> /* Return positive answer if transaction should be shown in list. */ bool TransactionRecord::showTransaction(const CWalletTx &wtx) { if (wtx.IsCoinBase()) { // Ensures we show generated coins / mined transactions at depth 1 if (!wtx.IsInMainChain()) { return false; } } return true; } /* * Decompose CWallet transaction to model transaction records. */ QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx) { QList<TransactionRecord> parts; int64_t nTime = wtx.GetTxTime(); CAmount nCredit = wtx.GetCredit(ISMINE_ALL); CAmount nDebit = wtx.GetDebit(ISMINE_ALL); CAmount nNet = nCredit - nDebit; uint256 hash = wtx.GetHash(); std::map<std::string, std::string> mapValue = wtx.mapValue; if (wtx.IsCoinStake()) { CTxDestination address; if (!ExtractDestination(wtx.vout[1].scriptPubKey, address)) return parts; if(!IsMine(*wallet, address)) //if the address is not yours then it means you have a tx sent to you in someone elses coinstake tx { for(unsigned int i = 0; i < wtx.vout.size(); i++) { if(i == 0) continue; // first tx is blank CTxDestination outAddress; if(ExtractDestination(wtx.vout[i].scriptPubKey, outAddress)) { if(IsMine(*wallet, outAddress)) { TransactionRecord txrMasternodeRec = TransactionRecord(hash, nTime, TransactionRecord::MNReward, CBitcoinAddress(outAddress).ToString(), wtx.vout[i].nValue, 0); parts.append(txrMasternodeRec); } } } } else { //stake reward TransactionRecord txrCoinStake = TransactionRecord(hash, nTime, TransactionRecord::StakeMint, CBitcoinAddress(address).ToString(), nNet, 0); parts.append(txrCoinStake); } } else if (nNet > 0 || wtx.IsCoinBase()) { // // Credit // BOOST_FOREACH(const CTxOut& txout, wtx.vout) { isminetype mine = wallet->IsMine(txout); if(mine) { TransactionRecord sub(hash, nTime); CTxDestination address; sub.idx = parts.size(); // sequence number sub.credit = txout.nValue; sub.involvesWatchAddress = mine == ISMINE_WATCH_ONLY; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address)) { // Received by DarkNet Address sub.type = TransactionRecord::RecvWithAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Received by IP connection (deprecated features), or a multisignature or other non-simple transaction sub.type = TransactionRecord::RecvFromOther; sub.address = mapValue["from"]; } if (wtx.IsCoinBase()) { // Generated sub.type = TransactionRecord::Generated; } parts.append(sub); } } } else { bool fAllFromMeDenom = true; int nFromMe = 0; bool involvesWatchAddress = false; isminetype fAllFromMe = ISMINE_SPENDABLE; BOOST_FOREACH(const CTxIn& txin, wtx.vin) { if(wallet->IsMine(txin)) { fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin); nFromMe++; } isminetype mine = wallet->IsMine(txin); if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllFromMe > mine) fAllFromMe = mine; } isminetype fAllToMe = ISMINE_SPENDABLE; bool fAllToMeDenom = true; int nToMe = 0; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if(wallet->IsMine(txout)) { fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue); nToMe++; } isminetype mine = wallet->IsMine(txout); if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true; if(fAllToMe > mine) fAllToMe = mine; } if(fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) { parts.append(TransactionRecord(hash, nTime, TransactionRecord::ObfuscationDenominate, "", -nDebit, nCredit)); parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe && fAllToMe) { // Payment to self // TODO: this section still not accurate but covers most cases, // might need some additional work however TransactionRecord sub(hash, nTime); // Payment to self by default sub.type = TransactionRecord::SendToSelf; sub.address = ""; if(mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; CTxDestination address; if (ExtractDestination(wtx.vout[0].scriptPubKey, address)) { // Sent to DarkNet Address sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.address = mapValue["to"]; } } else { for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; sub.idx = parts.size(); if(wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationMakeCollaterals; if(wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::ObfuscationCreateDenominations; if(nDebit - wtx.GetValueOut() == OBFUSCATION_COLLATERAL) sub.type = TransactionRecord::ObfuscationCollateralPayment; } } CAmount nChange = wtx.GetChange(); sub.debit = -(nDebit - nChange); sub.credit = nCredit - nChange; parts.append(sub); parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument } else if (fAllFromMe) { // // Debit // CAmount nTxFee = nDebit - wtx.GetValueOut(); for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++) { const CTxOut& txout = wtx.vout[nOut]; TransactionRecord sub(hash, nTime); sub.idx = parts.size(); sub.involvesWatchAddress = involvesWatchAddress; if(wallet->IsMine(txout)) { // Ignore parts sent to self, as this is usually the change // from a transaction sent back to our own address. continue; } CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address)) { // Sent to DarkNet Address sub.type = TransactionRecord::SendToAddress; sub.address = CBitcoinAddress(address).ToString(); } else { // Sent to IP, or other non-address transaction like OP_EVAL sub.type = TransactionRecord::SendToOther; sub.address = mapValue["to"]; } if(mapValue["DS"] == "1") { sub.type = TransactionRecord::Obfuscated; } CAmount nValue = txout.nValue; /* Add fee to first output */ if (nTxFee > 0) { nValue += nTxFee; nTxFee = 0; } sub.debit = -nValue; parts.append(sub); } } else { // // Mixed debit transaction, can't break down payees // parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0)); parts.last().involvesWatchAddress = involvesWatchAddress; } } return parts; } void TransactionRecord::updateStatus(const CWalletTx &wtx) { AssertLockHeld(cs_main); // Determine transaction status // Find the block the tx is in CBlockIndex* pindex = NULL; BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock); if (mi != mapBlockIndex.end()) pindex = (*mi).second; // Sort order, unrecorded transactions sort to the top status.sortKey = strprintf("%010d-%01d-%010u-%03d", (pindex ? pindex->nHeight : std::numeric_limits<int>::max()), (wtx.IsCoinBase() ? 1 : 0), wtx.nTimeReceived, idx); status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0); status.depth = wtx.GetDepthInMainChain(); status.cur_num_blocks = chainActive.Height(); status.cur_num_ix_locks = nCompleteTXLocks; if (!IsFinalTx(wtx, chainActive.Height() + 1)) { if (wtx.nLockTime < LOCKTIME_THRESHOLD) { status.status = TransactionStatus::OpenUntilBlock; status.open_for = wtx.nLockTime - chainActive.Height(); } else { status.status = TransactionStatus::OpenUntilDate; status.open_for = wtx.nLockTime; } } // For generated transactions, determine maturity else if(type == TransactionRecord::Generated || type == TransactionRecord::StakeMint || type == TransactionRecord::MNReward) { if (wtx.GetBlocksToMaturity() > 0) { status.status = TransactionStatus::Immature; if (wtx.IsInMainChain()) { status.matures_in = wtx.GetBlocksToMaturity(); // Check if the block was requested by anyone if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) status.status = TransactionStatus::MaturesWarning; } else { status.status = TransactionStatus::NotAccepted; } } else { status.status = TransactionStatus::Confirmed; } } else { if (status.depth < 0) { status.status = TransactionStatus::Conflicted; } else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0) { status.status = TransactionStatus::Offline; } else if (status.depth == 0) { status.status = TransactionStatus::Unconfirmed; } else if (status.depth < RecommendedNumConfirmations) { status.status = TransactionStatus::Confirming; } else { status.status = TransactionStatus::Confirmed; } } } bool TransactionRecord::statusUpdateNeeded() { AssertLockHeld(cs_main); return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks; } QString TransactionRecord::getTxID() const { return formatSubTxId(hash, idx); } QString TransactionRecord::formatSubTxId(const uint256 &hash, int vout) { return QString::fromStdString(hash.ToString() + strprintf("-%03d", vout)); } <|endoftext|>
<commit_before>#include "buffer_cache/alt/evicter.hpp" #include "buffer_cache/alt/page.hpp" #include "buffer_cache/alt/page_cache.hpp" #include "buffer_cache/alt/cache_balancer.hpp" namespace alt { evicter_t::evicter_t(cache_balancer_t *balancer) : balancer_(balancer), bytes_loaded_counter_(0), access_time_counter_(INITIAL_ACCESS_TIME) { guarantee(balancer_ != NULL); memory_limit_ = balancer_->base_mem_per_store(); balancer_->add_evicter(this); } evicter_t::~evicter_t() { assert_thread(); balancer_->remove_evicter(this); } void evicter_t::update_memory_limit(uint64_t new_memory_limit, uint64_t bytes_loaded_accounted_for) { assert_thread(); __sync_sub_and_fetch(&bytes_loaded_counter_, bytes_loaded_accounted_for); memory_limit_ = new_memory_limit; evict_if_necessary(); } uint64_t evicter_t::get_clamped_bytes_loaded() const { __sync_synchronize(); int64_t res = bytes_loaded_counter_; __sync_synchronize(); return std::max<int64_t>(res, 0); } void evicter_t::notify_bytes_loading(int64_t in_memory_buf_change) { assert_thread(); __sync_add_and_fetch(&bytes_loaded_counter_, in_memory_buf_change); balancer_->notify_access(); } void evicter_t::add_deferred_loaded(page_t *page) { assert_thread(); evicted_.add(page, page->hypothetical_memory_usage()); } void evicter_t::catch_up_deferred_load(page_t *page) { assert_thread(); rassert(evicted_.has_page(page)); evicted_.remove(page, page->hypothetical_memory_usage()); unevictable_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::add_not_yet_loaded(page_t *page) { assert_thread(); unevictable_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::reloading_page(page_t *page) { assert_thread(); notify_bytes_loading(page->hypothetical_memory_usage()); } bool evicter_t::page_is_in_unevictable_bag(page_t *page) const { assert_thread(); return unevictable_.has_page(page); } bool evicter_t::page_is_in_evicted_bag(page_t *page) const { assert_thread(); return evicted_.has_page(page); } void evicter_t::add_to_evictable_unbacked(page_t *page) { assert_thread(); evictable_unbacked_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::add_to_evictable_disk_backed(page_t *page) { assert_thread(); evictable_disk_backed_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::move_unevictable_to_evictable(page_t *page) { assert_thread(); rassert(unevictable_.has_page(page)); unevictable_.remove(page, page->hypothetical_memory_usage()); eviction_bag_t *new_bag = correct_eviction_category(page); rassert(new_bag == &evictable_disk_backed_ || new_bag == &evictable_unbacked_); new_bag->add(page, page->hypothetical_memory_usage()); evict_if_necessary(); } void evicter_t::change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page) { assert_thread(); rassert(current_bag->has_page(page)); current_bag->remove(page, page->hypothetical_memory_usage()); eviction_bag_t *new_bag = correct_eviction_category(page); new_bag->add(page, page->hypothetical_memory_usage()); evict_if_necessary(); } eviction_bag_t *evicter_t::correct_eviction_category(page_t *page) { assert_thread(); if (page->is_loading() || page->has_waiters()) { return &unevictable_; } else if (page->is_not_loaded()) { return &evicted_; } else if (page->is_disk_backed()) { return &evictable_disk_backed_; } else { return &evictable_unbacked_; } } void evicter_t::remove_page(page_t *page) { assert_thread(); eviction_bag_t *bag = correct_eviction_category(page); bag->remove(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(-static_cast<int64_t>(page->hypothetical_memory_usage())); } uint64_t evicter_t::in_memory_size() const { assert_thread(); return unevictable_.size() + evictable_disk_backed_.size() + evictable_unbacked_.size(); } void evicter_t::evict_if_necessary() { assert_thread(); // KSI: Implement eviction of unbacked evictables too. When flushing, you // could use the page_t::eviction_index_ field to identify pages that are // currently in the process of being evicted, to avoid reflushing a page // currently being written for the purpose of eviction. page_t *page; while (in_memory_size() > memory_limit_ && evictable_disk_backed_.remove_oldish(&page, access_time_counter_)) { evicted_.add(page, page->hypothetical_memory_usage()); page->evict_self(); } } } // namespace alt <commit_msg>Made catch_up_deferred_load assert page is unevictable, rather than evicted...<commit_after>#include "buffer_cache/alt/evicter.hpp" #include "buffer_cache/alt/page.hpp" #include "buffer_cache/alt/page_cache.hpp" #include "buffer_cache/alt/cache_balancer.hpp" namespace alt { evicter_t::evicter_t(cache_balancer_t *balancer) : balancer_(balancer), bytes_loaded_counter_(0), access_time_counter_(INITIAL_ACCESS_TIME) { guarantee(balancer_ != NULL); memory_limit_ = balancer_->base_mem_per_store(); balancer_->add_evicter(this); } evicter_t::~evicter_t() { assert_thread(); balancer_->remove_evicter(this); } void evicter_t::update_memory_limit(uint64_t new_memory_limit, uint64_t bytes_loaded_accounted_for) { assert_thread(); __sync_sub_and_fetch(&bytes_loaded_counter_, bytes_loaded_accounted_for); memory_limit_ = new_memory_limit; evict_if_necessary(); } uint64_t evicter_t::get_clamped_bytes_loaded() const { __sync_synchronize(); int64_t res = bytes_loaded_counter_; __sync_synchronize(); return std::max<int64_t>(res, 0); } void evicter_t::notify_bytes_loading(int64_t in_memory_buf_change) { assert_thread(); __sync_add_and_fetch(&bytes_loaded_counter_, in_memory_buf_change); balancer_->notify_access(); } void evicter_t::add_deferred_loaded(page_t *page) { assert_thread(); evicted_.add(page, page->hypothetical_memory_usage()); } void evicter_t::catch_up_deferred_load(page_t *page) { assert_thread(); rassert(unevictable_.has_page(page)); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::add_not_yet_loaded(page_t *page) { assert_thread(); unevictable_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::reloading_page(page_t *page) { assert_thread(); notify_bytes_loading(page->hypothetical_memory_usage()); } bool evicter_t::page_is_in_unevictable_bag(page_t *page) const { assert_thread(); return unevictable_.has_page(page); } bool evicter_t::page_is_in_evicted_bag(page_t *page) const { assert_thread(); return evicted_.has_page(page); } void evicter_t::add_to_evictable_unbacked(page_t *page) { assert_thread(); evictable_unbacked_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::add_to_evictable_disk_backed(page_t *page) { assert_thread(); evictable_disk_backed_.add(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(page->hypothetical_memory_usage()); } void evicter_t::move_unevictable_to_evictable(page_t *page) { assert_thread(); rassert(unevictable_.has_page(page)); unevictable_.remove(page, page->hypothetical_memory_usage()); eviction_bag_t *new_bag = correct_eviction_category(page); rassert(new_bag == &evictable_disk_backed_ || new_bag == &evictable_unbacked_); new_bag->add(page, page->hypothetical_memory_usage()); evict_if_necessary(); } void evicter_t::change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page) { assert_thread(); rassert(current_bag->has_page(page)); current_bag->remove(page, page->hypothetical_memory_usage()); eviction_bag_t *new_bag = correct_eviction_category(page); new_bag->add(page, page->hypothetical_memory_usage()); evict_if_necessary(); } eviction_bag_t *evicter_t::correct_eviction_category(page_t *page) { assert_thread(); if (page->is_loading() || page->has_waiters()) { return &unevictable_; } else if (page->is_not_loaded()) { return &evicted_; } else if (page->is_disk_backed()) { return &evictable_disk_backed_; } else { return &evictable_unbacked_; } } void evicter_t::remove_page(page_t *page) { assert_thread(); eviction_bag_t *bag = correct_eviction_category(page); bag->remove(page, page->hypothetical_memory_usage()); evict_if_necessary(); notify_bytes_loading(-static_cast<int64_t>(page->hypothetical_memory_usage())); } uint64_t evicter_t::in_memory_size() const { assert_thread(); return unevictable_.size() + evictable_disk_backed_.size() + evictable_unbacked_.size(); } void evicter_t::evict_if_necessary() { assert_thread(); // KSI: Implement eviction of unbacked evictables too. When flushing, you // could use the page_t::eviction_index_ field to identify pages that are // currently in the process of being evicted, to avoid reflushing a page // currently being written for the purpose of eviction. page_t *page; while (in_memory_size() > memory_limit_ && evictable_disk_backed_.remove_oldish(&page, access_time_counter_)) { evicted_.add(page, page->hypothetical_memory_usage()); page->evict_self(); } } } // namespace alt <|endoftext|>
<commit_before> #pragma once #include <cppexpose/typed/TypedEnum.hh> #include <cassert> #include <type_traits> namespace cppexpose { template <typename T, typename BASE> TypedEnum<T, BASE>::TypedEnum() { // Create default enum strings this->setStrings(EnumDefaultStrings<T>()()); } template <typename T, typename BASE> TypedEnum<T, BASE>::~TypedEnum() { } template <typename T, typename BASE> std::vector<std::string> TypedEnum<T, BASE>::strings() const { std::vector<std::string> strings; for (auto element : m_stringMap) { strings.push_back(element.second); } return strings; } template <typename T, typename BASE> void TypedEnum<T, BASE>::setStrings(const std::map<T, std::string> & pairs) { // Save map of enum value -> string representation m_stringMap = pairs; // Construct reverse map (string -> enum value) m_enumMap.clear(); for (const std::pair<T, std::string> & pair : pairs) { assert(m_enumMap.count(pair.second) == 0); m_enumMap.insert(std::make_pair(pair.second, pair.first)); } } template <typename T, typename BASE> std::string TypedEnum<T, BASE>::typeName() const { return "enum"; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::isNumber() const { return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::isIntegral() const { return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromVariant(const Variant & variant) { if (variant.hasType<T>()) { this->setValue(variant.value<T>()); } else { this->setValue((T)variant.value<int>()); } return true; } template <typename T, typename BASE> std::string TypedEnum<T, BASE>::toString() const { // Check if value has a string representation const auto it = m_stringMap.find(this->value()); // Return string representation if (it != m_stringMap.cend()) { return it->second; } return ""; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromString(const std::string & value) { // Find enum of string representation auto it = m_enumMap.find(value); // Abort if it is not available if (it == m_enumMap.end()) { return false; } // Set value this->setValue((*it).second); return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::toBool() const { return (bool)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromBool(bool value) { this->setValue((T)value); return true; } template <typename T, typename BASE> long long TypedEnum<T, BASE>::toLongLong() const { return (long long)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromLongLong(long long value) { this->setValue((T)value); return true; } template <typename T, typename BASE> unsigned long long TypedEnum<T, BASE>::toULongLong() const { return (unsigned long long)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromULongLong(unsigned long long value) { this->setValue((T)value); return true; } template <typename T, typename BASE> double TypedEnum<T, BASE>::toDouble() const { return (double)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromDouble(double value) { this->setValue((T)static_cast<typename std::underlying_type<T>::type>(value)); return true; } template <typename T> std::map<T, std::string> EnumDefaultStrings<T>::operator()() { return std::map<T, std::string>(); } } // namespace cppexpose <commit_msg>Add empty line<commit_after> #pragma once #include <cppexpose/typed/TypedEnum.hh> #include <cassert> #include <type_traits> namespace cppexpose { template <typename T, typename BASE> TypedEnum<T, BASE>::TypedEnum() { // Create default enum strings this->setStrings(EnumDefaultStrings<T>()()); } template <typename T, typename BASE> TypedEnum<T, BASE>::~TypedEnum() { } template <typename T, typename BASE> std::vector<std::string> TypedEnum<T, BASE>::strings() const { std::vector<std::string> strings; for (auto element : m_stringMap) { strings.push_back(element.second); } return strings; } template <typename T, typename BASE> void TypedEnum<T, BASE>::setStrings(const std::map<T, std::string> & pairs) { // Save map of enum value -> string representation m_stringMap = pairs; // Construct reverse map (string -> enum value) m_enumMap.clear(); for (const std::pair<T, std::string> & pair : pairs) { assert(m_enumMap.count(pair.second) == 0); m_enumMap.insert(std::make_pair(pair.second, pair.first)); } } template <typename T, typename BASE> std::string TypedEnum<T, BASE>::typeName() const { return "enum"; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::isNumber() const { return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::isIntegral() const { return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromVariant(const Variant & variant) { if (variant.hasType<T>()) { this->setValue(variant.value<T>()); } else { this->setValue((T)variant.value<int>()); } return true; } template <typename T, typename BASE> std::string TypedEnum<T, BASE>::toString() const { // Check if value has a string representation const auto it = m_stringMap.find(this->value()); // Return string representation if (it != m_stringMap.cend()) { return it->second; } return ""; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromString(const std::string & value) { // Find enum of string representation auto it = m_enumMap.find(value); // Abort if it is not available if (it == m_enumMap.end()) { return false; } // Set value this->setValue((*it).second); return true; } template <typename T, typename BASE> bool TypedEnum<T, BASE>::toBool() const { return (bool)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromBool(bool value) { this->setValue((T)value); return true; } template <typename T, typename BASE> long long TypedEnum<T, BASE>::toLongLong() const { return (long long)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromLongLong(long long value) { this->setValue((T)value); return true; } template <typename T, typename BASE> unsigned long long TypedEnum<T, BASE>::toULongLong() const { return (unsigned long long)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromULongLong(unsigned long long value) { this->setValue((T)value); return true; } template <typename T, typename BASE> double TypedEnum<T, BASE>::toDouble() const { return (double)this->value(); } template <typename T, typename BASE> bool TypedEnum<T, BASE>::fromDouble(double value) { this->setValue((T)static_cast<typename std::underlying_type<T>::type>(value)); return true; } template <typename T> std::map<T, std::string> EnumDefaultStrings<T>::operator()() { return std::map<T, std::string>(); } } // namespace cppexpose <|endoftext|>
<commit_before>#include "./JPetSinogram.h" #include <boost/numeric/ublas/matrix.hpp> #include <vector> #include <utility> #include <cmath> //for sin and cos using namespace boost::numeric::ublas; JPetSinogram::JPetSinogram() { } JPetSinogram::~JPetSinogram() { } long long JPetSinogram::forwardProjection(float s, float theta, matrix<int> emissionMatrix) { long long sum = 0; if(s == 0) return sum; // not implemented yet if(theta == 90) { for(unsigned int i = 0; i < emissionMatrix.size1(); i++) { sum += emissionMatrix(i, s); } } else { //prosta prostopadła Ax + By + C = 0 //w zmiennych biegunowych: x * cos(theta) + y * sin(theta) - s = 0 //prostopadła x * (-sin(theta)) + y * cos(theta) + C = 0 int x = std::floor(std::cos(-theta) * s); int y = -std::floor(std::sin(-theta) * s); float theta2 = 90 / emissionMatrix.size1(); std::cout << "x: " << x << " y: " << y << " theta2: " << theta2 << std::endl; while(x >= 0 && y >= 0 && x < emissionMatrix.size1() && y < emissionMatrix.size2()) { sum += emissionMatrix(x, y); s++; x = std::floor(std::cos(-theta) * s); y = -std::round(std::sin(-theta) * s); std::cout << "x: " << x << " y: " << y << std::endl; //float cos = std::cos(theta2 - theta); //float r = s / cos; // //x = std::round(std::cos(theta2) * r); //y = std::round(std::sin(theta2) * r); //std::cout << "x: " << x << " y: " << y << " theta2: " << theta2 << " r: " << r \ //<< " cos " << cos << std::endl; //theta2 += 90 / emissionMatrix.size1(); } } /*if(theta == 0) { for(unsigned int i = 0; i < emissionMatrix.size2(); i++) { sum += emissionMatrix(s, i); } } else if(theta == 90) { for(unsigned int i = 0; i < emissionMatrix.size1(); i++) { sum += emissionMatrix(i, s); } } else if(theta == 45) { unsigned int j = (emissionMatrix.size2() - 1) - s < 0 ? 0 : (emissionMatrix.size2() - 1) - s; unsigned int i = (emissionMatrix.size2() - 1) - s < 0 ? - ((emissionMatrix.size2() - 1 - s)) : 0;// select row, start from upper right corner for(; j < emissionMatrix.size2(); j++) { //-1 bcs matrix start from 0 if(i < emissionMatrix.size1()) { sum += emissionMatrix(i, j); i++; } else { } // exception } }*/ std::cout << "s: " << s << " theta: " << theta << " sum: " << sum << std::endl; return sum; } // std::vector<std::tuple<long long, float, int>> JPetSinogram::sinogram(matrix<int> emissionMatrix) { // std::vector<std::tuple<long long, float, int>> result; // value, theta, s // for(int i = 0; i < emissionMatrix.size1(); i++) { // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 0., emissionMatrix), 0., i)); // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 90., emissionMatrix), 90., i)); // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 45., emissionMatrix), 45., i)); // } // /* // for(int i = 0; i < emissionMatrix.size1() * 2 - 1; i++) { // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 45., emissionMatrix), 45.)); // }*/ // return result; // } typedef std::shared_ptr<double[]> ManagedDouble; typedef std::shared_ptr<ManagedDouble[]> resultType; resultType JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans) { int i; i=0; auto proj = std::shared_ptr<ManagedDouble[]>(new ManagedDouble[views]); //std::shared_ptr<double**> proj(new double*[views]); for(int k = 0; k < views; k++) { (*proj)[k] = ManagedDouble(new double[scans]); } double pos, val, Aleft, Aright; int x, y, Xcenter, Ycenter, Ileft, Iright; std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); int S=0; int inputimgsize = emissionMatrix.size1(); float phi = 0., stepsize = 0.; int ang1 = 0, ang2 = 180; for (phi=ang1;phi<ang2;phi=phi+stepsize){ sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } // Project each pixel in the image Xcenter = inputimgsize / 2; Ycenter = inputimgsize / 2; i=0; //if no. scans is greater than the image width, then scale will be <1 double scale = inputimgsize*1.42/scans; int N=0; val = 0; double weight = 0; double sang = std::sqrt(2)/2; double progr=0; bool fast = false; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i] ; double aa = 1/a; if (std::abs(sintab[i]) > sang){ for (S=0;S<scans;S++){ N = S - scans/2; double b = (N - costab[i] - sintab[i]) / sintab[i]; b = b * scale; for (x = -Xcenter; x < Xcenter; x++){ if (fast == true){ y = (int) std::round(a*x + b); if (y >= -Xcenter && y < Xcenter ) val += emissionMatrix((x+Xcenter),(y+Ycenter)); } else { y = (int) std::round(a*x + b); weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= -Xcenter && y+1 < Xcenter ) val += (1-weight) * emissionMatrix((x+Xcenter),(y+Ycenter)) + weight * emissionMatrix((x+Xcenter), (y+Ycenter+1)); } } (*(*proj)[i])[S] = val/std::abs(sintab[i]); val=0; } } if (std::abs(sintab[i]) <= sang){ for (S=0;S<scans;S++){ N = S - scans/2; double bb = (N - costab[i] - sintab[i]) / costab[i]; bb = bb * scale; //IJ.write("bb="+bb+" "); for (y = -Ycenter; y < Ycenter; y++) { if (fast ==true){ x = (int) std::round(aa*y + bb); if (x >= -Xcenter && x < Xcenter ) val += emissionMatrix(x+Xcenter, y+Ycenter); } else { x = (int) std::round(aa*y + bb); weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb)); if (x >= -Xcenter && x+1 < Xcenter ) val += (1-weight) * emissionMatrix((x+Xcenter), (y+Ycenter)) + weight * emissionMatrix((x+Xcenter+1), (y+Ycenter)); } } (*(*proj)[i])[S] = val/std::abs(costab[i]); val=0; } } i++; } i=0; normalize2DArray(proj, views, scans, 0, 255); return proj; } void JPetSinogram::normalize2DArray(resultType data, int imax, int jmax, double min, double max) { double datamax = (*(*data)[0])[0]; double datamin = (*(*data)[0])[0]; for (int i = 0; i < imax; i++ ) { for ( int j = 0; j < jmax; j++ ) { if((*(*data)[i])[j] < 0) (*(*data)[i])[j] = 0; if((*(*data)[i])[j] > max) datamax = (*(*data)[i])[j]; if ((*(*data)[i])[j] < min) datamin = (*(*data)[i])[j]; } } for ( int i = 0; i < imax; i++ ) { for ( int j = 0; j < jmax; j++ ) { (*(*data)[i])[j] = (double) ((((*(*data)[i])[j]-datamin) * (max))/datamax); } } }<commit_msg>Change smart pointers to vector of vectors<commit_after>#include "./JPetSinogram.h" #include <boost/numeric/ublas/matrix.hpp> #include <vector> #include <utility> #include <cmath> //for sin and cos using namespace boost::numeric::ublas; JPetSinogram::JPetSinogram() { } JPetSinogram::~JPetSinogram() { } long long JPetSinogram::forwardProjection(float s, float theta, matrix<int> emissionMatrix) { long long sum = 0; if(s == 0) return sum; // not implemented yet if(theta == 90) { for(unsigned int i = 0; i < emissionMatrix.size1(); i++) { sum += emissionMatrix(i, s); } } else { //prosta prostopadła Ax + By + C = 0 //w zmiennych biegunowych: x * cos(theta) + y * sin(theta) - s = 0 //prostopadła x * (-sin(theta)) + y * cos(theta) + C = 0 int x = std::floor(std::cos(-theta) * s); int y = -std::floor(std::sin(-theta) * s); float theta2 = 90 / emissionMatrix.size1(); std::cout << "x: " << x << " y: " << y << " theta2: " << theta2 << std::endl; while(x >= 0 && y >= 0 && x < emissionMatrix.size1() && y < emissionMatrix.size2()) { sum += emissionMatrix(x, y); s++; x = std::floor(std::cos(-theta) * s); y = -std::round(std::sin(-theta) * s); std::cout << "x: " << x << " y: " << y << std::endl; //float cos = std::cos(theta2 - theta); //float r = s / cos; // //x = std::round(std::cos(theta2) * r); //y = std::round(std::sin(theta2) * r); //std::cout << "x: " << x << " y: " << y << " theta2: " << theta2 << " r: " << r \ //<< " cos " << cos << std::endl; //theta2 += 90 / emissionMatrix.size1(); } } /*if(theta == 0) { for(unsigned int i = 0; i < emissionMatrix.size2(); i++) { sum += emissionMatrix(s, i); } } else if(theta == 90) { for(unsigned int i = 0; i < emissionMatrix.size1(); i++) { sum += emissionMatrix(i, s); } } else if(theta == 45) { unsigned int j = (emissionMatrix.size2() - 1) - s < 0 ? 0 : (emissionMatrix.size2() - 1) - s; unsigned int i = (emissionMatrix.size2() - 1) - s < 0 ? - ((emissionMatrix.size2() - 1 - s)) : 0;// select row, start from upper right corner for(; j < emissionMatrix.size2(); j++) { //-1 bcs matrix start from 0 if(i < emissionMatrix.size1()) { sum += emissionMatrix(i, j); i++; } else { } // exception } }*/ std::cout << "s: " << s << " theta: " << theta << " sum: " << sum << std::endl; return sum; } // std::vector<std::tuple<long long, float, int>> JPetSinogram::sinogram(matrix<int> emissionMatrix) { // std::vector<std::tuple<long long, float, int>> result; // value, theta, s // for(int i = 0; i < emissionMatrix.size1(); i++) { // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 0., emissionMatrix), 0., i)); // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 90., emissionMatrix), 90., i)); // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 45., emissionMatrix), 45., i)); // } // /* // for(int i = 0; i < emissionMatrix.size1() * 2 - 1; i++) { // result.push_back(std::tuple<long long, float, int>(forwardProjection(i, 45., emissionMatrix), 45.)); // }*/ // return result; // } typedef std::shared_ptr<double[]> ManagedDouble; typedef std::vector<std::vector<double>> resultType; resultType JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans) { int i; i=0; std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); //resultType proj = resultType(new ManagedDouble[views]); //std::shared_ptr<double**> proj(new double*[views]); //for(int k = 0; k < views; k++) { // proj[k] = ManagedDouble(new double[scans]); //} double pos, val, Aleft, Aright; int x, y, Xcenter, Ycenter, Ileft, Iright; std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); int S=0; int inputimgsize = emissionMatrix.size1(); float phi = 0., stepsize = 0.; int ang1 = 0, ang2 = 180; stepsize = (ang2 - ang1) / views; for (phi=ang1;phi<ang2;phi=phi+stepsize){ sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } // Project each pixel in the image Xcenter = inputimgsize / 2; Ycenter = inputimgsize / 2; i=0; //if no. scans is greater than the image width, then scale will be <1 double scale = inputimgsize*1.42/scans; int N=0; val = 0; double weight = 0; double sang = std::sqrt(2)/2; double progr=0; bool fast = false; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i] ; double aa = 1/a; if (std::abs(sintab[i]) > sang){ for (S=0;S<scans;S++){ N = S - scans/2; double b = (N - costab[i] - sintab[i]) / sintab[i]; b = b * scale; for (x = -Xcenter; x < Xcenter; x++){ if (fast == true){ y = (int) std::round(a*x + b); if (y >= -Xcenter && y < Xcenter ) val += emissionMatrix((x+Xcenter),(y+Ycenter)); } else { y = (int) std::round(a*x + b); weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= -Xcenter && y+1 < Xcenter ) val += (1-weight) * emissionMatrix((x+Xcenter),(y+Ycenter)) + weight * emissionMatrix((x+Xcenter), (y+Ycenter+1)); } } proj[i][S] = val/std::abs(sintab[i]); val=0; } } if (std::abs(sintab[i]) <= sang){ for (S=0;S<scans;S++){ N = S - scans/2; double bb = (N - costab[i] - sintab[i]) / costab[i]; bb = bb * scale; //IJ.write("bb="+bb+" "); for (y = -Ycenter; y < Ycenter; y++) { if (fast ==true){ x = (int) std::round(aa*y + bb); if (x >= -Xcenter && x < Xcenter ) val += emissionMatrix(x+Xcenter, y+Ycenter); } else { x = (int) std::round(aa*y + bb); weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb)); if (x >= -Xcenter && x+1 < Xcenter ) val += (1-weight) * emissionMatrix((x+Xcenter), (y+Ycenter)) + weight * emissionMatrix((x+Xcenter+1), (y+Ycenter)); } } proj[i][S] = val/std::abs(costab[i]); val=0; } } i++; } i=0; normalize2DArray(proj, views, scans, 0, 255); return proj; } void JPetSinogram::normalize2DArray(resultType &data, int imax, int jmax, double min, double max) { double datamax = data[0][0]; double datamin = data[0][0]; for (int i = 0; i < imax; i++ ) { for ( int j = 0; j < jmax; j++ ) { if(data[i][j] < 0) data[i][j] = 0; if(data[i][j] > max) datamax = data[i][j]; if(data[i][j] < min) datamin = data[i][j]; } } for ( int i = 0; i < imax; i++ ) { for ( int j = 0; j < jmax; j++ ) { data[i][j] = (double) (((data[i][j]-datamin) * (max))/datamax); } } }<|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOgreTexture.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIOgreTexture.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIImageCodec.h" #include <OgreTextureManager.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal function that reverses all bytes in a buffer void _byteSwap(unsigned char* b, int n) { register int i = 0; register int j = n-1; while (i < j) std::swap(b[i++], b[j--]); } #define byteSwap(x) _byteSwap((unsigned char*) &x,sizeof(x)) //----------------------------------------------------------------------------// uint32 OgreTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// const Size& OgreTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Size& OgreTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2& OgreTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void OgreTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) throw RendererException("OgreTexture::loadFromFile: " "CEGUI::System object has not been created!"); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) throw RendererException("OgreTexture::loadFromFile: " + sys->getImageCodec().getIdentifierString()+ " failed to load image '" + filename + "'."); } //----------------------------------------------------------------------------// void OgreTexture::loadFromMemory(const void* buffer, const Size& buffer_size, PixelFormat pixel_format) { using namespace Ogre; // get rid of old texture freeOgreTexture(); // wrap input buffer with an Ogre data stream const size_t pixel_size = pixel_format == PF_RGBA ? 4 : 3; const size_t byte_size = buffer_size.d_width * buffer_size.d_height * pixel_size; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG // FIXME: I think this leaks memory, though need to check! unsigned char* swapped_buffer = new unsigned char[byte_size]; memcpy(swapped_buffer, buffer, byte_size); for (size_t i = 0; i < byte_size; i += pixel_size) _byteSwap(&swapped_buffer[i], pixel_size); DataStreamPtr odc(new MemoryDataStream(static_cast<void*>(swapped_buffer), byte_size, false)); #else DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer), byte_size, false)); #endif // get pixel type for the target texture. Ogre::PixelFormat target_fmt = (pixel_format == PF_RGBA) ? Ogre::PF_A8B8G8R8 : Ogre::PF_B8G8R8; // try to create a Ogre::Texture from the input data d_texture = TextureManager::getSingleton().loadRawData( getUniqueName(), "General", odc, buffer_size.d_width, buffer_size.d_height, target_fmt, TEX_TYPE_2D, 0, 1.0f); // throw exception if no texture was able to be created if (d_texture.isNull()) throw RendererException("OgreTexture::loadFromMemory: Failed to create " "Texture object from memory."); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = buffer_size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OgreTexture::saveToMemory(void* buffer) { // TODO: } //----------------------------------------------------------------------------// OgreTexture::OgreTexture() : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& filename, const String& resourceGroup) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const Size& sz) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { // TODO: } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(Ogre::TexturePtr& tex, bool take_ownership) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { setOgreTexture(tex, take_ownership); } //----------------------------------------------------------------------------// OgreTexture::~OgreTexture() { freeOgreTexture(); } //----------------------------------------------------------------------------// void OgreTexture::freeOgreTexture() { if (!d_texture.isNull() && !d_isLinked) Ogre::TextureManager::getSingleton().remove(d_texture->getHandle()); d_texture.setNull(); } //----------------------------------------------------------------------------// Ogre::String OgreTexture::getUniqueName() { Ogre::StringUtil::StrStreamType strstream; strstream << "_cegui_ogre_" << d_textureNumber++; return strstream.str(); } //----------------------------------------------------------------------------// void OgreTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership) { freeOgreTexture(); d_texture = texture; d_isLinked = !take_ownership; if (!d_texture.isNull()) { d_size.d_width = d_texture->getWidth(); d_size.d_height= d_texture->getHeight(); d_dataSize = d_size; } else d_size = d_dataSize = Size(0, 0); updateCachedScaleValues(); } //----------------------------------------------------------------------------// Ogre::TexturePtr OgreTexture::getOgreTexture() const { return d_texture; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>ADD: Implement missing parts in Ogre renderer.<commit_after>/*********************************************************************** filename: CEGUIOgreTexture.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIOgreTexture.h" #include "CEGUIExceptions.h" #include "CEGUISystem.h" #include "CEGUIImageCodec.h" #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// // Internal function that reverses all bytes in a buffer void _byteSwap(unsigned char* b, int n) { register int i = 0; register int j = n-1; while (i < j) std::swap(b[i++], b[j--]); } #define byteSwap(x) _byteSwap((unsigned char*) &x,sizeof(x)) //----------------------------------------------------------------------------// uint32 OgreTexture::d_textureNumber = 0; //----------------------------------------------------------------------------// const Size& OgreTexture::getSize() const { return d_size; } //----------------------------------------------------------------------------// const Size& OgreTexture::getOriginalDataSize() const { return d_dataSize; } //----------------------------------------------------------------------------// const Vector2& OgreTexture::getTexelScaling() const { return d_texelScaling; } //----------------------------------------------------------------------------// void OgreTexture::loadFromFile(const String& filename, const String& resourceGroup) { // get and check existence of CEGUI::System object System* sys = System::getSingletonPtr(); if (!sys) throw RendererException("OgreTexture::loadFromFile: " "CEGUI::System object has not been created!"); // load file to memory via resource provider RawDataContainer texFile; sys->getResourceProvider()->loadRawDataContainer(filename, texFile, resourceGroup); Texture* res = sys->getImageCodec().load(texFile, this); // unload file data buffer sys->getResourceProvider()->unloadRawDataContainer(texFile); // throw exception if data was load loaded to texture. if (!res) throw RendererException("OgreTexture::loadFromFile: " + sys->getImageCodec().getIdentifierString()+ " failed to load image '" + filename + "'."); } //----------------------------------------------------------------------------// void OgreTexture::loadFromMemory(const void* buffer, const Size& buffer_size, PixelFormat pixel_format) { using namespace Ogre; // get rid of old texture freeOgreTexture(); // wrap input buffer with an Ogre data stream const size_t pixel_size = pixel_format == PF_RGBA ? 4 : 3; const size_t byte_size = buffer_size.d_width * buffer_size.d_height * pixel_size; #if OGRE_ENDIAN == OGRE_ENDIAN_BIG // FIXME: I think this leaks memory, though need to check! unsigned char* swapped_buffer = new unsigned char[byte_size]; memcpy(swapped_buffer, buffer, byte_size); for (size_t i = 0; i < byte_size; i += pixel_size) _byteSwap(&swapped_buffer[i], pixel_size); DataStreamPtr odc(new MemoryDataStream(static_cast<void*>(swapped_buffer), byte_size, false)); #else DataStreamPtr odc(new MemoryDataStream(const_cast<void*>(buffer), byte_size, false)); #endif // get pixel type for the target texture. Ogre::PixelFormat target_fmt = (pixel_format == PF_RGBA) ? Ogre::PF_A8B8G8R8 : Ogre::PF_B8G8R8; // try to create a Ogre::Texture from the input data d_texture = TextureManager::getSingleton().loadRawData( getUniqueName(), "General", odc, buffer_size.d_width, buffer_size.d_height, target_fmt, TEX_TYPE_2D, 0, 1.0f); // throw exception if no texture was able to be created if (d_texture.isNull()) throw RendererException("OgreTexture::loadFromMemory: Failed to create " "Texture object from memory."); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = buffer_size; updateCachedScaleValues(); } //----------------------------------------------------------------------------// void OgreTexture::saveToMemory(void* buffer) { if (d_texture.isNull()) return; Ogre::HardwarePixelBufferSharedPtr src = d_texture->getBuffer(); if (src.isNull()) throw RendererException("OgreTexture::saveToMemory: unable to obtain " "hardware pixel buffer pointer."); const size_t sz = static_cast<size_t>(d_size.d_width * d_size.d_height) * 4; src->readData(0, sz, buffer); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture() : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const String& filename, const String& resourceGroup) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { loadFromFile(filename, resourceGroup); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(const Size& sz) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { using namespace Ogre; // try to create a Ogre::Texture with given dimensions d_texture = TextureManager::getSingleton().createManual( getUniqueName(), "General", TEX_TYPE_2D, sz.d_width, sz.d_height, 0, Ogre::PF_A8B8G8R8); // throw exception if no texture was able to be created if (d_texture.isNull()) throw RendererException("OgreTexture: Failed to create Texture object " "with spcecified size."); d_size.d_width = d_texture->getWidth(); d_size.d_height = d_texture->getHeight(); d_dataSize = sz; updateCachedScaleValues(); } //----------------------------------------------------------------------------// OgreTexture::OgreTexture(Ogre::TexturePtr& tex, bool take_ownership) : d_isLinked(false), d_size(0, 0), d_dataSize(0, 0), d_texelScaling(0, 0) { setOgreTexture(tex, take_ownership); } //----------------------------------------------------------------------------// OgreTexture::~OgreTexture() { freeOgreTexture(); } //----------------------------------------------------------------------------// void OgreTexture::freeOgreTexture() { if (!d_texture.isNull() && !d_isLinked) Ogre::TextureManager::getSingleton().remove(d_texture->getHandle()); d_texture.setNull(); } //----------------------------------------------------------------------------// Ogre::String OgreTexture::getUniqueName() { Ogre::StringUtil::StrStreamType strstream; strstream << "_cegui_ogre_" << d_textureNumber++; return strstream.str(); } //----------------------------------------------------------------------------// void OgreTexture::updateCachedScaleValues() { // // calculate what to use for x scale // const float orgW = d_dataSize.d_width; const float texW = d_size.d_width; // if texture and original data width are the same, scale is based // on the original size. // if texture is wider (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_x = 1.0f / ((orgW == texW) ? orgW : texW); // // calculate what to use for y scale // const float orgH = d_dataSize.d_height; const float texH = d_size.d_height; // if texture and original data height are the same, scale is based // on the original size. // if texture is taller (and source data was not stretched), scale // is based on the size of the resulting texture. d_texelScaling.d_y = 1.0f / ((orgH == texH) ? orgH : texH); } //----------------------------------------------------------------------------// void OgreTexture::setOgreTexture(Ogre::TexturePtr texture, bool take_ownership) { freeOgreTexture(); d_texture = texture; d_isLinked = !take_ownership; if (!d_texture.isNull()) { d_size.d_width = d_texture->getWidth(); d_size.d_height= d_texture->getHeight(); d_dataSize = d_size; } else d_size = d_dataSize = Size(0, 0); updateCachedScaleValues(); } //----------------------------------------------------------------------------// Ogre::TexturePtr OgreTexture::getOgreTexture() const { return d_texture; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // mapnik #include <mapnik/font_engine_freetype.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <sstream> // icu #include <unicode/ubidi.h> #include <unicode/ushape.h> #include <unicode/schriter.h> #include <unicode/uversion.h> namespace mapnik { freetype_engine::freetype_engine() { FT_Error error = FT_Init_FreeType( &library_ ); if (error) { throw std::runtime_error("can not load FreeType2 library"); } } freetype_engine::~freetype_engine() { FT_Done_FreeType(library_); } bool freetype_engine::is_font_file(std::string const& file_name) { /** only accept files that will be matched by freetype2's `figurefiletype()` */ std::string const& fn = boost::algorithm::to_lower_copy(file_name); return boost::algorithm::ends_with(fn,std::string(".ttf")) || boost::algorithm::ends_with(fn,std::string(".otf")) || boost::algorithm::ends_with(fn,std::string(".ttc")) || boost::algorithm::ends_with(fn,std::string(".pfa")) || boost::algorithm::ends_with(fn,std::string(".pfb")) || boost::algorithm::ends_with(fn,std::string(".ttc")) || /** Plus OSX custom ext */ boost::algorithm::ends_with(fn,std::string(".dfont")); } bool freetype_engine::register_font(std::string const& file_name) { if (!boost::filesystem::is_regular_file(file_name) || !is_font_file(file_name)) return false; #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif FT_Library library; FT_Error error = FT_Init_FreeType(&library); if (error) { throw std::runtime_error("Failed to initialize FreeType2 library"); } FT_Face face; error = FT_New_Face (library,file_name.c_str(),0,&face); if (error) { FT_Done_FreeType(library); return false; } // some fonts can lack names, skip them // http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_FaceRec if (face->family_name && face->style_name) { std::string name = std::string(face->family_name) + " " + std::string(face->style_name); name2file_.insert(std::make_pair(name,file_name)); FT_Done_Face(face); FT_Done_FreeType(library); return true; } else { FT_Done_Face(face); FT_Done_FreeType(library); std::ostringstream s; s << "Error: unable to load invalid font file which lacks identifiable family and style name: '" << file_name << "'"; throw std::runtime_error(s.str()); } return true; } bool freetype_engine::register_fonts(std::string const& dir, bool recurse) { boost::filesystem::path path(dir); if (!boost::filesystem::exists(path)) return false; if (!boost::filesystem::is_directory(path)) return mapnik::freetype_engine::register_font(dir); boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(dir); itr != end_itr; ++itr) { if (boost::filesystem::is_directory(*itr) && recurse) { #if (BOOST_FILESYSTEM_VERSION == 3) if (!register_fonts(itr->path().string(), true)) return false; #else // v2 if (!register_fonts(itr->string(), true)) return false; #endif } else { #if (BOOST_FILESYSTEM_VERSION == 3) mapnik::freetype_engine::register_font(itr->path().string()); #else // v2 mapnik::freetype_engine::register_font(itr->string()); #endif } } return true; } std::vector<std::string> freetype_engine::face_names () { std::vector<std::string> names; std::map<std::string,std::string>::const_iterator itr; for (itr = name2file_.begin();itr!=name2file_.end();++itr) { names.push_back(itr->first); } return names; } std::map<std::string,std::string> const& freetype_engine::get_mapping() { return name2file_; } face_ptr freetype_engine::create_face(std::string const& family_name) { std::map<std::string,std::string>::iterator itr; itr = name2file_.find(family_name); if (itr != name2file_.end()) { FT_Face face; FT_Error error = FT_New_Face (library_,itr->second.c_str(),0,&face); if (!error) { return face_ptr (new font_face(face)); } } return face_ptr(); } stroker_ptr freetype_engine::create_stroker() { FT_Stroker s; FT_Error error = FT_Stroker_New(library_, &s); if (!error) { return stroker_ptr(new stroker(s)); } return stroker_ptr(); } font_face_set::dimension_t font_face_set::character_dimensions(const unsigned c) { std::map<unsigned, dimension_t>::const_iterator itr; itr = dimension_cache_.find(c); if (itr != dimension_cache_.end()) { return itr->second; } FT_Matrix matrix; FT_Vector pen; FT_Error error; pen.x = 0; pen.y = 0; FT_BBox glyph_bbox; FT_Glyph image; glyph_ptr glyph = get_glyph(c); FT_Face face = glyph->get_face()->get_face(); matrix.xx = (FT_Fixed)( 1 * 0x10000L ); matrix.xy = (FT_Fixed)( 0 * 0x10000L ); matrix.yx = (FT_Fixed)( 0 * 0x10000L ); matrix.yy = (FT_Fixed)( 1 * 0x10000L ); FT_Set_Transform(face, &matrix, &pen); error = FT_Load_Glyph (face, glyph->get_index(), FT_LOAD_NO_HINTING); if ( error ) return dimension_t(0, 0, 0); error = FT_Get_Glyph(face->glyph, &image); if ( error ) return dimension_t(0, 0, 0); FT_Glyph_Get_CBox(image, ft_glyph_bbox_pixels, &glyph_bbox); FT_Done_Glyph(image); unsigned tempx = face->glyph->advance.x >> 6; //std::clog << "glyph: " << glyph_index << " x: " << tempx << " y: " << tempy << std::endl; dimension_t dim(tempx, glyph_bbox.yMax, glyph_bbox.yMin); //dimension_cache_[c] = dim; would need an default constructor for dimension_t dimension_cache_.insert(std::pair<unsigned, dimension_t>(c, dim)); return dim; } void font_face_set::get_string_info(string_info & info) { unsigned width = 0; unsigned height = 0; UErrorCode err = U_ZERO_ERROR; UnicodeString reordered; UnicodeString shaped; UnicodeString const& ustr = info.get_string(); int32_t length = ustr.length(); UBiDi *bidi = ubidi_openSized(length, 0, &err); ubidi_setPara(bidi, ustr.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err); ubidi_writeReordered(bidi, reordered.getBuffer(length), length, UBIDI_DO_MIRRORING, &err); reordered.releaseBuffer(length); u_shapeArabic(reordered.getBuffer(), length, shaped.getBuffer(length), length, U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR | U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err); shaped.releaseBuffer(length); if (U_SUCCESS(err)) { StringCharacterIterator iter(shaped); for (iter.setToStart(); iter.hasNext();) { UChar ch = iter.nextPostInc(); dimension_t char_dim = character_dimensions(ch); info.add_info(ch, char_dim.width, char_dim.height); width += char_dim.width; height = (char_dim.height > height) ? char_dim.height : height; } } #if (U_ICU_VERSION_MAJOR_NUM*100 + U_ICU_VERSION_MINOR_NUM >= 406) if (ubidi_getBaseDirection(ustr.getBuffer(), length) == UBIDI_RTL) { info.set_rtl(true); } #endif ubidi_close(bidi); info.set_dimensions(width, height); } #ifdef MAPNIK_THREADSAFE boost::mutex freetype_engine::mutex_; #endif std::map<std::string,std::string> freetype_engine::name2file_; } <commit_msg>adding support for multiple fonts in one font file, for instance .ttc<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ // mapnik #include <mapnik/font_engine_freetype.hpp> // boost #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <sstream> // icu #include <unicode/ubidi.h> #include <unicode/ushape.h> #include <unicode/schriter.h> #include <unicode/uversion.h> namespace mapnik { freetype_engine::freetype_engine() { FT_Error error = FT_Init_FreeType( &library_ ); if (error) { throw std::runtime_error("can not load FreeType2 library"); } } freetype_engine::~freetype_engine() { FT_Done_FreeType(library_); } bool freetype_engine::is_font_file(std::string const& file_name) { /** only accept files that will be matched by freetype2's `figurefiletype()` */ std::string const& fn = boost::algorithm::to_lower_copy(file_name); return boost::algorithm::ends_with(fn,std::string(".ttf")) || boost::algorithm::ends_with(fn,std::string(".otf")) || boost::algorithm::ends_with(fn,std::string(".ttc")) || boost::algorithm::ends_with(fn,std::string(".pfa")) || boost::algorithm::ends_with(fn,std::string(".pfb")) || boost::algorithm::ends_with(fn,std::string(".ttc")) || /** Plus OSX custom ext */ boost::algorithm::ends_with(fn,std::string(".dfont")); } bool freetype_engine::register_font(std::string const& file_name) { if (!boost::filesystem::is_regular_file(file_name) || !is_font_file(file_name)) return false; #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif FT_Library library; FT_Error error = FT_Init_FreeType(&library); if (error) { throw std::runtime_error("Failed to initialize FreeType2 library"); } FT_Face face; // fome font files have multiple fonts in a file // the count is in the 'root' face library[0] // see the FT_FaceRec in freetype.h for ( int i = 0; face == 0 || i < face->num_faces; i++ ) { // if face is null then this is the first face error = FT_New_Face (library,file_name.c_str(),i,&face); if (error) { FT_Done_FreeType(library); return false; } // some fonts can lack names, skip them // http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html#FT_FaceRec if (face->family_name && face->style_name) { std::string name = std::string(face->family_name) + " " + std::string(face->style_name); name2file_.insert(std::make_pair(name,file_name)); FT_Done_Face(face); //FT_Done_FreeType(library); //return true; } else { FT_Done_Face(face); FT_Done_FreeType(library); std::ostringstream s; s << "Error: unable to load invalid font file which lacks identifiable family and style name: '" << file_name << "'"; throw std::runtime_error(s.str()); } } FT_Done_FreeType(library); return true; } bool freetype_engine::register_fonts(std::string const& dir, bool recurse) { boost::filesystem::path path(dir); if (!boost::filesystem::exists(path)) return false; if (!boost::filesystem::is_directory(path)) return mapnik::freetype_engine::register_font(dir); boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator itr(dir); itr != end_itr; ++itr) { if (boost::filesystem::is_directory(*itr) && recurse) { #if (BOOST_FILESYSTEM_VERSION == 3) if (!register_fonts(itr->path().string(), true)) return false; #else // v2 if (!register_fonts(itr->string(), true)) return false; #endif } else { #if (BOOST_FILESYSTEM_VERSION == 3) mapnik::freetype_engine::register_font(itr->path().string()); #else // v2 mapnik::freetype_engine::register_font(itr->string()); #endif } } return true; } std::vector<std::string> freetype_engine::face_names () { std::vector<std::string> names; std::map<std::string,std::string>::const_iterator itr; for (itr = name2file_.begin();itr!=name2file_.end();++itr) { names.push_back(itr->first); } return names; } std::map<std::string,std::string> const& freetype_engine::get_mapping() { return name2file_; } face_ptr freetype_engine::create_face(std::string const& family_name) { std::map<std::string,std::string>::iterator itr; itr = name2file_.find(family_name); if (itr != name2file_.end()) { FT_Face face; FT_Error error = FT_New_Face (library_,itr->second.c_str(),0,&face); if (!error) { return face_ptr (new font_face(face)); } } return face_ptr(); } stroker_ptr freetype_engine::create_stroker() { FT_Stroker s; FT_Error error = FT_Stroker_New(library_, &s); if (!error) { return stroker_ptr(new stroker(s)); } return stroker_ptr(); } font_face_set::dimension_t font_face_set::character_dimensions(const unsigned c) { std::map<unsigned, dimension_t>::const_iterator itr; itr = dimension_cache_.find(c); if (itr != dimension_cache_.end()) { return itr->second; } FT_Matrix matrix; FT_Vector pen; FT_Error error; pen.x = 0; pen.y = 0; FT_BBox glyph_bbox; FT_Glyph image; glyph_ptr glyph = get_glyph(c); FT_Face face = glyph->get_face()->get_face(); matrix.xx = (FT_Fixed)( 1 * 0x10000L ); matrix.xy = (FT_Fixed)( 0 * 0x10000L ); matrix.yx = (FT_Fixed)( 0 * 0x10000L ); matrix.yy = (FT_Fixed)( 1 * 0x10000L ); FT_Set_Transform(face, &matrix, &pen); error = FT_Load_Glyph (face, glyph->get_index(), FT_LOAD_NO_HINTING); if ( error ) return dimension_t(0, 0, 0); error = FT_Get_Glyph(face->glyph, &image); if ( error ) return dimension_t(0, 0, 0); FT_Glyph_Get_CBox(image, ft_glyph_bbox_pixels, &glyph_bbox); FT_Done_Glyph(image); unsigned tempx = face->glyph->advance.x >> 6; //std::clog << "glyph: " << glyph_index << " x: " << tempx << " y: " << tempy << std::endl; dimension_t dim(tempx, glyph_bbox.yMax, glyph_bbox.yMin); //dimension_cache_[c] = dim; would need an default constructor for dimension_t dimension_cache_.insert(std::pair<unsigned, dimension_t>(c, dim)); return dim; } void font_face_set::get_string_info(string_info & info) { unsigned width = 0; unsigned height = 0; UErrorCode err = U_ZERO_ERROR; UnicodeString reordered; UnicodeString shaped; UnicodeString const& ustr = info.get_string(); int32_t length = ustr.length(); UBiDi *bidi = ubidi_openSized(length, 0, &err); ubidi_setPara(bidi, ustr.getBuffer(), length, UBIDI_DEFAULT_LTR, 0, &err); ubidi_writeReordered(bidi, reordered.getBuffer(length), length, UBIDI_DO_MIRRORING, &err); reordered.releaseBuffer(length); u_shapeArabic(reordered.getBuffer(), length, shaped.getBuffer(length), length, U_SHAPE_LETTERS_SHAPE | U_SHAPE_LENGTH_FIXED_SPACES_NEAR | U_SHAPE_TEXT_DIRECTION_VISUAL_LTR, &err); shaped.releaseBuffer(length); if (U_SUCCESS(err)) { StringCharacterIterator iter(shaped); for (iter.setToStart(); iter.hasNext();) { UChar ch = iter.nextPostInc(); dimension_t char_dim = character_dimensions(ch); info.add_info(ch, char_dim.width, char_dim.height); width += char_dim.width; height = (char_dim.height > height) ? char_dim.height : height; } } #if (U_ICU_VERSION_MAJOR_NUM*100 + U_ICU_VERSION_MINOR_NUM >= 406) if (ubidi_getBaseDirection(ustr.getBuffer(), length) == UBIDI_RTL) { info.set_rtl(true); } #endif ubidi_close(bidi); info.set_dimensions(width, height); } #ifdef MAPNIK_THREADSAFE boost::mutex freetype_engine::mutex_; #endif std::map<std::string,std::string> freetype_engine::name2file_; } <|endoftext|>
<commit_before>// Copyright 2011-2012 Google // 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 "base/hash.h" #include "base/map-util.h" #include "base/stl_util.h" #include "base/random.h" #include "constraint_solver/constraint_solveri.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/model.pb.h" namespace operations_research { class OneVarLns : public BaseLNS { public: OneVarLns(const IntVar* const* vars, int size) : BaseLNS(vars, size), index_(0) {} ~OneVarLns() {} virtual void InitFragments() { index_ = 0; } virtual bool NextFragment(std::vector<int>* fragment) { const int size = Size(); if (index_ < size) { fragment->push_back(index_); ++index_; return true; } else { return false; } } private: int index_; }; class MoveOneVar: public IntVarLocalSearchOperator { public: MoveOneVar(const std::vector<IntVar*>& variables) : IntVarLocalSearchOperator(variables.data(), variables.size()), variable_index_(0), move_up_(false) {} virtual ~MoveOneVar() {} protected: // Make a neighbor assigning one variable to its target value. virtual bool MakeOneNeighbor() { const int64 current_value = OldValue(variable_index_); if (move_up_) { SetValue(variable_index_, current_value + 1); variable_index_ = (variable_index_ + 1) % Size(); } else { SetValue(variable_index_, current_value - 1); } move_up_ = !move_up_; return true; } private: virtual void OnStart() { CHECK_GE(variable_index_, 0); CHECK_LT(variable_index_, Size()); } // Index of the next variable to try to restore int64 variable_index_; // Direction of the modification. bool move_up_; }; class SumFilter : public IntVarLocalSearchFilter { public: SumFilter(const IntVar* const* vars, int size) : IntVarLocalSearchFilter(vars, size), sum_(0) {} ~SumFilter() {} virtual void OnSynchronize() { sum_ = 0; for (int index = 0; index < Size(); ++index) { sum_ += Value(index); } } virtual bool Accept(const Assignment* delta, const Assignment* unused_deltadelta) { const Assignment::IntContainer& solution_delta = delta->IntVarContainer(); const int solution_delta_size = solution_delta.Size(); // The input const Assignment* delta given to Accept() may // actually contain "Deactivated" elements, which represent // variables that have been freed -- they are not bound to a // single value anymore. This happens with LNS-type (Large // Neighborhood Search) LocalSearchOperator, which are not used in // this example as of 2012-01; and we refer the reader to // ./routing.cc for an example of such LNS-type operators. // // For didactical purposes, we will assume for a moment that a // LNS-type operator might be applied. The Filter will still be // called, but our filter here won't be able to work, since // it needs every variable to be bound (i.e. have a fixed value), // in the assignment that it considers. Therefore, we include here // a snippet of code that will detect if the input assignment is // not fully bound. For further details, read ./routing.cc -- but // we strongly advise the reader to first try and understand all // of this file. for (int i = 0; i < solution_delta_size; ++i) { if (!solution_delta.Element(i).Activated()) { VLOG(1) << "Element #" << i << " of the delta assignment given to" << " SumFilter::Accept() is not activated (i.e. its variable" << " is not bound to a single value anymore). This means that" << " we are in a LNS phase, and the DobbleFilter won't be able" << " to filter anything. Returning true."; return true; } } int64 new_sum = sum_; VLOG(1) << "No LNS, size = " << solution_delta_size; for (int index = 0; index < solution_delta_size; ++index) { int64 touched_var = -1; FindIndex(solution_delta.Element(index).Var(), &touched_var); const int64 old_value = Value(touched_var); const int64 new_value = solution_delta.Element(index).Value(); new_sum += new_value - old_value; } VLOG(1) << "new sum = " << new_sum << ", old sum = " << sum_; return new_sum < sum_; } private: int64 sum_; }; void BasicLns() { LOG(INFO) << "Basic LNS"; Solver s("Sample"); vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); OneVarLns one_var_lns(vars.data(), vars.size()); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_lns, db); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } void BasicLs() { LOG(INFO) << "Basic LS"; Solver s("Sample"); vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); MoveOneVar one_var_ls(vars); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_ls, db); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } void BasicLsWithFilter() { LOG(INFO) << "Basic LS with Filter"; Solver s("Sample"); vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); MoveOneVar one_var_ls(vars); std::vector<LocalSearchFilter*> filters; filters.push_back(s.RevAlloc(new SumFilter(vars.data(), vars.size()))); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_ls, db, NULL, filters); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } } //namespace operations_research int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); operations_research::BasicLns(); operations_research::BasicLs(); operations_research::BasicLsWithFilter(); return 0; } <commit_msg>compilation fix<commit_after>// Copyright 2011-2012 Google // 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 "base/hash.h" #include "base/map-util.h" #include "base/stl_util.h" #include "base/random.h" #include "constraint_solver/constraint_solveri.h" #include "constraint_solver/constraint_solver.h" #include "constraint_solver/model.pb.h" namespace operations_research { class OneVarLns : public BaseLNS { public: OneVarLns(const IntVar* const* vars, int size) : BaseLNS(vars, size), index_(0) {} ~OneVarLns() {} virtual void InitFragments() { index_ = 0; } virtual bool NextFragment(std::vector<int>* fragment) { const int size = Size(); if (index_ < size) { fragment->push_back(index_); ++index_; return true; } else { return false; } } private: int index_; }; class MoveOneVar: public IntVarLocalSearchOperator { public: MoveOneVar(const std::vector<IntVar*>& variables) : IntVarLocalSearchOperator(variables.data(), variables.size()), variable_index_(0), move_up_(false) {} virtual ~MoveOneVar() {} protected: // Make a neighbor assigning one variable to its target value. virtual bool MakeOneNeighbor() { const int64 current_value = OldValue(variable_index_); if (move_up_) { SetValue(variable_index_, current_value + 1); variable_index_ = (variable_index_ + 1) % Size(); } else { SetValue(variable_index_, current_value - 1); } move_up_ = !move_up_; return true; } private: virtual void OnStart() { CHECK_GE(variable_index_, 0); CHECK_LT(variable_index_, Size()); } // Index of the next variable to try to restore int64 variable_index_; // Direction of the modification. bool move_up_; }; class SumFilter : public IntVarLocalSearchFilter { public: SumFilter(const IntVar* const* vars, int size) : IntVarLocalSearchFilter(vars, size), sum_(0) {} ~SumFilter() {} virtual void OnSynchronize() { sum_ = 0; for (int index = 0; index < Size(); ++index) { sum_ += Value(index); } } virtual bool Accept(const Assignment* delta, const Assignment* unused_deltadelta) { const Assignment::IntContainer& solution_delta = delta->IntVarContainer(); const int solution_delta_size = solution_delta.Size(); // The input const Assignment* delta given to Accept() may // actually contain "Deactivated" elements, which represent // variables that have been freed -- they are not bound to a // single value anymore. This happens with LNS-type (Large // Neighborhood Search) LocalSearchOperator, which are not used in // this example as of 2012-01; and we refer the reader to // ./routing.cc for an example of such LNS-type operators. // // For didactical purposes, we will assume for a moment that a // LNS-type operator might be applied. The Filter will still be // called, but our filter here won't be able to work, since // it needs every variable to be bound (i.e. have a fixed value), // in the assignment that it considers. Therefore, we include here // a snippet of code that will detect if the input assignment is // not fully bound. For further details, read ./routing.cc -- but // we strongly advise the reader to first try and understand all // of this file. for (int i = 0; i < solution_delta_size; ++i) { if (!solution_delta.Element(i).Activated()) { VLOG(1) << "Element #" << i << " of the delta assignment given to" << " SumFilter::Accept() is not activated (i.e. its variable" << " is not bound to a single value anymore). This means that" << " we are in a LNS phase, and the DobbleFilter won't be able" << " to filter anything. Returning true."; return true; } } int64 new_sum = sum_; VLOG(1) << "No LNS, size = " << solution_delta_size; for (int index = 0; index < solution_delta_size; ++index) { int64 touched_var = -1; FindIndex(solution_delta.Element(index).Var(), &touched_var); const int64 old_value = Value(touched_var); const int64 new_value = solution_delta.Element(index).Value(); new_sum += new_value - old_value; } VLOG(1) << "new sum = " << new_sum << ", old sum = " << sum_; return new_sum < sum_; } private: int64 sum_; }; void BasicLns() { LOG(INFO) << "Basic LNS"; Solver s("Sample"); std::vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); OneVarLns one_var_lns(vars.data(), vars.size()); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_lns, db); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } void BasicLs() { LOG(INFO) << "Basic LS"; Solver s("Sample"); std::vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); MoveOneVar one_var_ls(vars); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_ls, db); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } void BasicLsWithFilter() { LOG(INFO) << "Basic LS with Filter"; Solver s("Sample"); std::vector<IntVar*> vars; s.MakeIntVarArray(4, 0, 4, &vars); IntVar* const sum_var = s.MakeSum(vars)->Var(); OptimizeVar* const obj = s.MakeMinimize(sum_var, 1); DecisionBuilder* const db = s.MakePhase(vars, Solver::CHOOSE_FIRST_UNBOUND, Solver::ASSIGN_MAX_VALUE); MoveOneVar one_var_ls(vars); std::vector<LocalSearchFilter*> filters; filters.push_back(s.RevAlloc(new SumFilter(vars.data(), vars.size()))); LocalSearchPhaseParameters* const ls_params = s.MakeLocalSearchPhaseParameters(&one_var_ls, db, NULL, filters); DecisionBuilder* const ls = s.MakeLocalSearchPhase(vars, db, ls_params); SolutionCollector* const collector = s.MakeLastSolutionCollector(); collector->Add(vars); collector->AddObjective(sum_var); SearchMonitor* const log = s.MakeSearchLog(1000, obj); s.Solve(ls, collector, obj, log); LOG(INFO) << "Objective value = " << collector->objective_value(0); } } //namespace operations_research int main(int argc, char** argv) { google::ParseCommandLineFlags(&argc, &argv, true); operations_research::BasicLns(); operations_research::BasicLs(); operations_research::BasicLsWithFilter(); return 0; } <|endoftext|>
<commit_before>#include "testing/testing.h" #include "ParseDatabase.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <string> using namespace openMVG::exif::sensordb; static const std::string sDatabase = "sensor_width_camera_database.txt"; TEST(Matching, InvalidDatabase) { std::vector<Datasheet> vec_database; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), "" ); EXPECT_FALSE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( vec_database.empty() ); } TEST(Matching, ValidDatabase) { std::vector<Datasheet> vec_database; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( !vec_database.empty() ); } TEST(Matching, ParseDatabaseSD900) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon PowerShot SD900"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( "Canon", datasheet._brand ); EXPECT_EQ( "Canon PowerShot SD900", datasheet._model ); EXPECT_EQ( 7.11, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseA710_IS) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon PowerShot A710 IS"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( "Canon", datasheet._brand ); EXPECT_EQ( "Canon PowerShot A710 IS", datasheet._model ); EXPECT_EQ( 5.75, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseNotExist) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "NotExistModel"; const std::string sBrand = "NotExistBrand"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_FALSE( getInfo( sBrand, sModel, vec_database, datasheet ) ); } TEST(Matching, ParseDatabaseCanon_EOS_550D) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 550D"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 22.3, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseCanon_EOS_5D_Mark_II) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 5D Mark II"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 36, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseCanon_EOS_1100D) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 1100D"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 22.2, datasheet._sensorSize ); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <commit_msg>[exif] fix parse database test : Update `Canon EOS 5D Mark II` sensor width<commit_after>#include "testing/testing.h" #include "ParseDatabase.hpp" #include "third_party/stlplus3/filesystemSimplified/file_system.hpp" #include <string> using namespace openMVG::exif::sensordb; static const std::string sDatabase = "sensor_width_camera_database.txt"; TEST(Matching, InvalidDatabase) { std::vector<Datasheet> vec_database; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), "" ); EXPECT_FALSE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( vec_database.empty() ); } TEST(Matching, ValidDatabase) { std::vector<Datasheet> vec_database; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( !vec_database.empty() ); } TEST(Matching, ParseDatabaseSD900) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon PowerShot SD900"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( "Canon", datasheet._brand ); EXPECT_EQ( "Canon PowerShot SD900", datasheet._model ); EXPECT_EQ( 7.11, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseA710_IS) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon PowerShot A710 IS"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( "Canon", datasheet._brand ); EXPECT_EQ( "Canon PowerShot A710 IS", datasheet._model ); EXPECT_EQ( 5.75, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseNotExist) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "NotExistModel"; const std::string sBrand = "NotExistBrand"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_FALSE( getInfo( sBrand, sModel, vec_database, datasheet ) ); } TEST(Matching, ParseDatabaseCanon_EOS_550D) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 550D"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 22.3, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseCanon_EOS_5D_Mark_II) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 5D Mark II"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 35.8, datasheet._sensorSize ); } TEST(Matching, ParseDatabaseCanon_EOS_1100D) { std::vector<Datasheet> vec_database; Datasheet datasheet; const std::string sfileDatabase = stlplus::create_filespec( std::string(THIS_SOURCE_DIR), sDatabase ); const std::string sModel = "Canon EOS 1100D"; const std::string sBrand = "Canon"; EXPECT_TRUE( parseDatabase( sfileDatabase, vec_database ) ); EXPECT_TRUE( getInfo( sBrand, sModel, vec_database, datasheet ) ); EXPECT_EQ( 22.2, datasheet._sensorSize ); } /* ************************************************************************* */ int main() { TestResult tr; return TestRegistry::runAllTests(tr);} /* ************************************************************************* */ <|endoftext|>
<commit_before>namespace factor { // It is up to the caller to fill in the object's fields in a // meaningful fashion! // Allocates memory inline code_block* factor_vm::allot_code_block(cell size, code_block_type type) { cell block_size = size + sizeof(code_block); code_block* block = code->allocator->allot(block_size); if (block == NULL) { // If allocation failed, do a full GC and compact the code heap. // A full GC that occurs as a result of the data heap filling up does not // trigger a compaction. This setup ensures that most GCs do not compact // the code heap, but if the code fills up, it probably means it will be // fragmented after GC anyway, so its best to compact. primitive_compact_gc(); block = code->allocator->allot(block_size); // Insufficient room even after code GC, give up if (block == NULL) { std::cout << "Code heap used: " << code->allocator->occupied_space() << "\n"; std::cout << "Code heap free: " << code->allocator->free_space << "\n"; std::cout << "Request : " << block_size << "\n"; fatal_error("Out of memory in allot_code_block", 0); } } // next time we do a minor GC, we have to trace this code block, since // the fields of the code_block struct might point into nursery or aging this->code->write_barrier(block); block->set_type(type); return block; } // Allocates memory inline object* factor_vm::allot_large_object(cell type, cell size) { // If tenured space does not have enough room, collect and compact cell required_free = size + data->high_water_mark(); if (!data->tenured->can_allot_p(required_free)) { primitive_compact_gc(); // If it still won't fit, grow the heap if (!data->tenured->can_allot_p(required_free)) { gc(COLLECT_GROWING_DATA_HEAP_OP, size); } } object* obj = data->tenured->allot(size); // Allows initialization code to store old->new pointers // without hitting the write barrier in the common case of // a nursery allocation write_barrier(obj, size); obj->initialize(type); return obj; } // Allocates memory inline object* factor_vm::allot_object(cell type, cell size) { FACTOR_ASSERT(!current_gc); bump_allocator *nursery = data->nursery; // If the object is bigger than the nursery, allocate it in tenured space if (size >= nursery->size) return allot_large_object(type, size); // If the object is smaller than the nursery, allocate it in the nursery, // after a GC if needed if (nursery->here + size > nursery->end) primitive_minor_gc(); object* obj = nursery->allot(size); obj->initialize(type); return obj; } } <commit_msg>vm/allot.hpp: Print more room info when allot() fails.<commit_after>namespace factor { // It is up to the caller to fill in the object's fields in a // meaningful fashion! // Allocates memory inline code_block* factor_vm::allot_code_block(cell size, code_block_type type) { cell block_size = size + sizeof(code_block); code_block* block = code->allocator->allot(block_size); if (block == NULL) { // If allocation failed, do a full GC and compact the code heap. // A full GC that occurs as a result of the data heap filling up does not // trigger a compaction. This setup ensures that most GCs do not compact // the code heap, but if the code fills up, it probably means it will be // fragmented after GC anyway, so its best to compact. primitive_compact_gc(); block = code->allocator->allot(block_size); // Insufficient room even after code GC, give up if (block == NULL) { std::cout << "Code heap used: " << code->allocator->occupied_space() << "\n"; std::cout << "Code heap free: " << code->allocator->free_space << "\n"; std::cout << "Code heap free_block_count: " << code->allocator->free_block_count << "\n"; std::cout << "Code heap largest_free_block: " << code->allocator->largest_free_block() << "\n"; std::cout << "Request : " << block_size << "\n"; fatal_error("Out of memory in allot_code_block", 0); } } // next time we do a minor GC, we have to trace this code block, since // the fields of the code_block struct might point into nursery or aging this->code->write_barrier(block); block->set_type(type); return block; } // Allocates memory inline object* factor_vm::allot_large_object(cell type, cell size) { // If tenured space does not have enough room, collect and compact cell required_free = size + data->high_water_mark(); if (!data->tenured->can_allot_p(required_free)) { primitive_compact_gc(); // If it still won't fit, grow the heap if (!data->tenured->can_allot_p(required_free)) { gc(COLLECT_GROWING_DATA_HEAP_OP, size); } } object* obj = data->tenured->allot(size); // Allows initialization code to store old->new pointers // without hitting the write barrier in the common case of // a nursery allocation write_barrier(obj, size); obj->initialize(type); return obj; } // Allocates memory inline object* factor_vm::allot_object(cell type, cell size) { FACTOR_ASSERT(!current_gc); bump_allocator *nursery = data->nursery; // If the object is bigger than the nursery, allocate it in tenured space if (size >= nursery->size) return allot_large_object(type, size); // If the object is smaller than the nursery, allocate it in the nursery, // after a GC if needed if (nursery->here + size > nursery->end) primitive_minor_gc(); object* obj = nursery->allot(size); obj->initialize(type); return obj; } } <|endoftext|>
<commit_before>/* The GC superclass methods, used by both GCs. */ #include "object_utils.hpp" #include "gc/gc.hpp" #include "objectmemory.hpp" #include "gc/object_mark.hpp" #include "builtin/class.hpp" #include "builtin/tuple.hpp" #include "builtin/module.hpp" #include "builtin/symbol.hpp" #include "builtin/weakref.hpp" #include "builtin/compiledcode.hpp" #include "builtin/nativemethod.hpp" #include "call_frame.hpp" #include "builtin/variable_scope.hpp" #include "builtin/constantscope.hpp" #include "builtin/block_environment.hpp" #include "capi/handle.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif #include "instruments/tooling.hpp" #include "arguments.hpp" #include "object_watch.hpp" namespace rubinius { GCData::GCData(VM* state) : roots_(state->globals().roots) , handles_(state->om->capi_handles()) , cached_handles_(state->om->cached_capi_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->om->global_capi_handle_locations()) , gc_token_(0) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GCData::GCData(VM* state, GCToken gct) : roots_(state->globals().roots) , handles_(state->om->capi_handles()) , cached_handles_(state->om->cached_capi_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->om->global_capi_handle_locations()) , gc_token_(&gct) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GarbageCollector::GarbageCollector(ObjectMemory *om) :object_memory_(om), weak_refs_(NULL) { } VM* GarbageCollector::state() { return object_memory_->state(); } /** * Scans the specified Object +obj+ for references to other Objects, and * marks those Objects as reachable. Understands how to read the inside of * an Object and find all references located within. For each reference * found, it marks the object pointed to as live (which may trigger * movement of the object in a copying garbage collector), but does not * recursively scan into the referenced object (since such recursion could * be arbitrarily deep, depending on the object graph, and this could cause * the stack to blow up). * /param obj The Object to be scanned for references to other Objects. */ void GarbageCollector::scan_object(Object* obj) { Object* slot; #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during scan_object.\n"; } #endif slot = saw_object(obj->klass()); if(slot) obj->klass(object_memory_, force_as<Class>(slot)); if(obj->ivars()->reference_p()) { slot = saw_object(obj->ivars()); if(slot) obj->ivars(object_memory_, slot); } // Handle Tuple directly, because it's so common if(Tuple* tup = try_as<Tuple>(obj)) { native_int size = tup->num_fields(); for(native_int i = 0; i < size; i++) { slot = tup->field[i]; if(slot->reference_p()) { Object* moved = saw_object(slot); if(moved && moved != slot) { tup->field[i] = moved; object_memory_->write_barrier(tup, moved); } } } } else { TypeInfo* ti = object_memory_->type_info[obj->type_id()]; ObjectMark mark(this); ti->mark(obj, mark); } } /** * Removes a mature object from the remembered set, ensuring it will not keep * alive any young objects if no other live references to those objects exist. */ void GarbageCollector::delete_object(Object* obj) { if(obj->remembered_p()) { object_memory_->unremember_object(obj); } } void GarbageCollector::saw_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_ = mark_object(scope->self()); scope->block_ = mark_object(scope->block()); scope->module_ = (Module*)mark_object(scope->module()); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); if(local->reference_p()) { scope->set_local(i, mark_object(local)); } } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_ = mark_object(scope->last_match_); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_ = (VariableScope*)mark_object(parent); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_ = (VariableScope*)mark_object(heap); } } void GarbageCollector::verify_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_->validate(); scope->block_->validate(); scope->module_->validate(); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); local->validate(); } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_->validate(); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_->validate(); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_->validate(); } } template <typename T> T displace(T ptr, AddressDisplacement* dis) { if(!dis) return ptr; return dis->displace(ptr); } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::walk_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_ && call_frame->constant_scope_->reference_p()) { call_frame->constant_scope_ = (ConstantScope*)mark_object(call_frame->constant_scope_); } if(call_frame->compiled_code && call_frame->compiled_code->reference_p()) { call_frame->compiled_code = (CompiledCode*)mark_object(call_frame->compiled_code); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; if(obj && obj->reference_p()) { call_frame->stk[i] = mark_object(obj); } } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_ = (VariableScope*)mark_object(call_frame->top_scope_); } if(BlockEnvironment* env = call_frame->block_env()) { call_frame->set_block_env((BlockEnvironment*)mark_object(env)); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->set_recv(mark_object(args->recv())); args->set_block(mark_object(args->block())); if(Tuple* tup = args->argument_container()) { args->update_argument_container((Tuple*)mark_object(tup)); } else { Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i] = mark_object(ary[i]); } } } if(NativeMethodFrame* nmf = call_frame->native_method_frame()) { nmf->handles().gc_scan(this); } #ifdef ENABLE_LLVM if(jit::RuntimeDataHolder* jd = call_frame->jit_data()) { jd->set_mark(); ObjectMark mark(this); jd->mark_all(0, mark); } if(jit::RuntimeData* rd = call_frame->runtime_data()) { rd->method_ = (CompiledCode*)mark_object(rd->method()); rd->name_ = (Symbol*)mark_object(rd->name()); rd->module_ = (Module*)mark_object(rd->module()); } #endif if(call_frame->scope && call_frame->compiled_code) { saw_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::verify_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_) { call_frame->constant_scope_->validate(); } if(call_frame->compiled_code) { call_frame->compiled_code->validate(); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; obj->validate(); } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_->validate(); } if(BlockEnvironment* env = call_frame->block_env()) { env->validate(); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->recv()->validate(); args->block()->validate(); Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i]->validate(); } } if(call_frame->scope && call_frame->compiled_code) { verify_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } } void GarbageCollector::scan(ManagedThread* thr, bool young_only) { for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } scan(thr->variable_root_buffers(), young_only); scan(thr->root_buffers(), young_only); if(VM* vm = thr->as_vm()) { vm->gc_scan(this); } } void GarbageCollector::verify(GCData* data) { if(data->threads()) { for(std::list<ManagedThread*>::iterator i = data->threads()->begin(); i != data->threads()->end(); ++i) { ManagedThread* thr = *i; for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->get()->validate(); } if(VM* vm = thr->as_vm()) { vm->gc_verify(this); } } } } void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { VariableRootBuffer* vrb = displace(buffers.front(), offset); while(vrb) { Object*** buffer = displace(vrb->buffer(), offset); for(int idx = 0; idx < vrb->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp && tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } vrb = displace((VariableRootBuffer*)vrb->next(), offset); } } void GarbageCollector::scan(RootBuffers& buffers, bool young_only) { for(RootBuffers::Iterator i(buffers); i.more(); i.advance()) { Object** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object* tmp = buffer[idx]; if(tmp->reference_p() && (!young_only || tmp->young_object_p())) { buffer[idx] = saw_object(tmp); } } } } void GarbageCollector::scan_fibers(GCData* data, bool marked_only) { if(data->threads()) { for(std::list<ManagedThread*>::iterator i = data->threads()->begin(); i != data->threads()->end(); ++i) { if(VM* vm = (*i)->as_vm()) { vm->gc_fiber_scan(this, marked_only); } } } } void GarbageCollector::clean_weakrefs(bool check_forwards) { if(!weak_refs_) return; for(ObjectArray::iterator i = weak_refs_->begin(); i != weak_refs_->end(); ++i) { WeakRef* ref = try_as<WeakRef>(*i); if(!ref) continue; // WTF. Object* obj = ref->object(); if(!obj->reference_p()) continue; if(check_forwards) { if(obj->young_object_p()) { if(!obj->forwarded_p()) { ref->set_object(object_memory_, cNil); } else { ref->set_object(object_memory_, obj->forward()); } } } else if(!obj->marked_p(object_memory_->mark())) { ref->set_object(object_memory_, cNil); } } delete weak_refs_; weak_refs_ = NULL; } void GarbageCollector::clean_locked_objects(ManagedThread* thr, bool young_only) { LockedObjects& los = thr->locked_objects(); for(LockedObjects::iterator i = los.begin(); i != los.end();) { Object* obj = static_cast<Object*>(*i); if(young_only) { if(obj->young_object_p()) { if(obj->forwarded_p()) { *i = obj->forward(); ++i; } else { i = los.erase(i); } } else { ++i; } } else { if(!obj->marked_p(object_memory_->mark())) { i = los.erase(i); } else { ++i; } } } } } <commit_msg>Don't go through write barrier if not necessary<commit_after>/* The GC superclass methods, used by both GCs. */ #include "object_utils.hpp" #include "gc/gc.hpp" #include "objectmemory.hpp" #include "gc/object_mark.hpp" #include "builtin/class.hpp" #include "builtin/tuple.hpp" #include "builtin/module.hpp" #include "builtin/symbol.hpp" #include "builtin/weakref.hpp" #include "builtin/compiledcode.hpp" #include "builtin/nativemethod.hpp" #include "call_frame.hpp" #include "builtin/variable_scope.hpp" #include "builtin/constantscope.hpp" #include "builtin/block_environment.hpp" #include "capi/handle.hpp" #ifdef ENABLE_LLVM #include "llvm/state.hpp" #endif #include "instruments/tooling.hpp" #include "arguments.hpp" #include "object_watch.hpp" namespace rubinius { GCData::GCData(VM* state) : roots_(state->globals().roots) , handles_(state->om->capi_handles()) , cached_handles_(state->om->cached_capi_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->om->global_capi_handle_locations()) , gc_token_(0) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GCData::GCData(VM* state, GCToken gct) : roots_(state->globals().roots) , handles_(state->om->capi_handles()) , cached_handles_(state->om->cached_capi_handles()) , global_cache_(state->shared.global_cache) , threads_(state->shared.threads()) , global_handle_locations_(state->om->global_capi_handle_locations()) , gc_token_(&gct) #ifdef ENABLE_LLVM , llvm_state_(LLVMState::get_if_set(state)) #endif {} GarbageCollector::GarbageCollector(ObjectMemory *om) :object_memory_(om), weak_refs_(NULL) { } VM* GarbageCollector::state() { return object_memory_->state(); } /** * Scans the specified Object +obj+ for references to other Objects, and * marks those Objects as reachable. Understands how to read the inside of * an Object and find all references located within. For each reference * found, it marks the object pointed to as live (which may trigger * movement of the object in a copying garbage collector), but does not * recursively scan into the referenced object (since such recursion could * be arbitrarily deep, depending on the object graph, and this could cause * the stack to blow up). * /param obj The Object to be scanned for references to other Objects. */ void GarbageCollector::scan_object(Object* obj) { Object* slot; #ifdef ENABLE_OBJECT_WATCH if(watched_p(obj)) { std::cout << "detected " << obj << " during scan_object.\n"; } #endif slot = saw_object(obj->klass()); if(slot && slot != obj->klass()) { obj->klass(object_memory_, force_as<Class>(slot)); } if(obj->ivars()->reference_p()) { slot = saw_object(obj->ivars()); if(slot && slot != obj->ivars()) { obj->ivars(object_memory_, slot); } } // Handle Tuple directly, because it's so common if(Tuple* tup = try_as<Tuple>(obj)) { native_int size = tup->num_fields(); for(native_int i = 0; i < size; i++) { slot = tup->field[i]; if(slot->reference_p()) { Object* moved = saw_object(slot); if(moved && moved != slot) { tup->field[i] = moved; object_memory_->write_barrier(tup, moved); } } } } else { TypeInfo* ti = object_memory_->type_info[obj->type_id()]; ObjectMark mark(this); ti->mark(obj, mark); } } /** * Removes a mature object from the remembered set, ensuring it will not keep * alive any young objects if no other live references to those objects exist. */ void GarbageCollector::delete_object(Object* obj) { if(obj->remembered_p()) { object_memory_->unremember_object(obj); } } void GarbageCollector::saw_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_ = mark_object(scope->self()); scope->block_ = mark_object(scope->block()); scope->module_ = (Module*)mark_object(scope->module()); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); if(local->reference_p()) { scope->set_local(i, mark_object(local)); } } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_ = mark_object(scope->last_match_); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_ = (VariableScope*)mark_object(parent); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_ = (VariableScope*)mark_object(heap); } } void GarbageCollector::verify_variable_scope(CallFrame* call_frame, StackVariables* scope) { scope->self_->validate(); scope->block_->validate(); scope->module_->validate(); int locals = call_frame->compiled_code->machine_code()->number_of_locals; for(int i = 0; i < locals; i++) { Object* local = scope->get_local(i); local->validate(); } if(scope->last_match_ && scope->last_match_->reference_p()) { scope->last_match_->validate(); } VariableScope* parent = scope->parent(); if(parent) { scope->parent_->validate(); } VariableScope* heap = scope->on_heap(); if(heap) { scope->on_heap_->validate(); } } template <typename T> T displace(T ptr, AddressDisplacement* dis) { if(!dis) return ptr; return dis->displace(ptr); } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::walk_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_ && call_frame->constant_scope_->reference_p()) { call_frame->constant_scope_ = (ConstantScope*)mark_object(call_frame->constant_scope_); } if(call_frame->compiled_code && call_frame->compiled_code->reference_p()) { call_frame->compiled_code = (CompiledCode*)mark_object(call_frame->compiled_code); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; if(obj && obj->reference_p()) { call_frame->stk[i] = mark_object(obj); } } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_ = (VariableScope*)mark_object(call_frame->top_scope_); } if(BlockEnvironment* env = call_frame->block_env()) { call_frame->set_block_env((BlockEnvironment*)mark_object(env)); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->set_recv(mark_object(args->recv())); args->set_block(mark_object(args->block())); if(Tuple* tup = args->argument_container()) { args->update_argument_container((Tuple*)mark_object(tup)); } else { Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i] = mark_object(ary[i]); } } } if(NativeMethodFrame* nmf = call_frame->native_method_frame()) { nmf->handles().gc_scan(this); } #ifdef ENABLE_LLVM if(jit::RuntimeDataHolder* jd = call_frame->jit_data()) { jd->set_mark(); ObjectMark mark(this); jd->mark_all(0, mark); } if(jit::RuntimeData* rd = call_frame->runtime_data()) { rd->method_ = (CompiledCode*)mark_object(rd->method()); rd->name_ = (Symbol*)mark_object(rd->name()); rd->module_ = (Module*)mark_object(rd->module()); } #endif if(call_frame->scope && call_frame->compiled_code) { saw_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } } /** * Walks the chain of objects accessible from the specified CallFrame. */ void GarbageCollector::verify_call_frame(CallFrame* top_call_frame, AddressDisplacement* offset) { CallFrame* call_frame = top_call_frame; while(call_frame) { call_frame = displace(call_frame, offset); if(call_frame->custom_constant_scope_p() && call_frame->constant_scope_) { call_frame->constant_scope_->validate(); } if(call_frame->compiled_code) { call_frame->compiled_code->validate(); } if(call_frame->compiled_code && call_frame->stk) { native_int stack_size = call_frame->compiled_code->stack_size()->to_native(); for(native_int i = 0; i < stack_size; i++) { Object* obj = call_frame->stk[i]; obj->validate(); } } if(call_frame->multiple_scopes_p() && call_frame->top_scope_) { call_frame->top_scope_->validate(); } if(BlockEnvironment* env = call_frame->block_env()) { env->validate(); } Arguments* args = displace(call_frame->arguments, offset); if(!call_frame->inline_method_p() && args) { args->recv()->validate(); args->block()->validate(); Object** ary = displace(args->arguments(), offset); for(uint32_t i = 0; i < args->total(); i++) { ary[i]->validate(); } } if(call_frame->scope && call_frame->compiled_code) { verify_variable_scope(call_frame, displace(call_frame->scope, offset)); } call_frame = call_frame->previous; } } void GarbageCollector::scan(ManagedThread* thr, bool young_only) { for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->set(saw_object(ri->get())); } scan(thr->variable_root_buffers(), young_only); scan(thr->root_buffers(), young_only); if(VM* vm = thr->as_vm()) { vm->gc_scan(this); } } void GarbageCollector::verify(GCData* data) { if(data->threads()) { for(std::list<ManagedThread*>::iterator i = data->threads()->begin(); i != data->threads()->end(); ++i) { ManagedThread* thr = *i; for(Roots::Iterator ri(thr->roots()); ri.more(); ri.advance()) { ri->get()->validate(); } if(VM* vm = thr->as_vm()) { vm->gc_verify(this); } } } } void GarbageCollector::scan(VariableRootBuffers& buffers, bool young_only, AddressDisplacement* offset) { VariableRootBuffer* vrb = displace(buffers.front(), offset); while(vrb) { Object*** buffer = displace(vrb->buffer(), offset); for(int idx = 0; idx < vrb->size(); idx++) { Object** var = displace(buffer[idx], offset); Object* tmp = *var; if(tmp && tmp->reference_p() && (!young_only || tmp->young_object_p())) { *var = saw_object(tmp); } } vrb = displace((VariableRootBuffer*)vrb->next(), offset); } } void GarbageCollector::scan(RootBuffers& buffers, bool young_only) { for(RootBuffers::Iterator i(buffers); i.more(); i.advance()) { Object** buffer = i->buffer(); for(int idx = 0; idx < i->size(); idx++) { Object* tmp = buffer[idx]; if(tmp->reference_p() && (!young_only || tmp->young_object_p())) { buffer[idx] = saw_object(tmp); } } } } void GarbageCollector::scan_fibers(GCData* data, bool marked_only) { if(data->threads()) { for(std::list<ManagedThread*>::iterator i = data->threads()->begin(); i != data->threads()->end(); ++i) { if(VM* vm = (*i)->as_vm()) { vm->gc_fiber_scan(this, marked_only); } } } } void GarbageCollector::clean_weakrefs(bool check_forwards) { if(!weak_refs_) return; for(ObjectArray::iterator i = weak_refs_->begin(); i != weak_refs_->end(); ++i) { WeakRef* ref = try_as<WeakRef>(*i); if(!ref) continue; // WTF. Object* obj = ref->object(); if(!obj->reference_p()) continue; if(check_forwards) { if(obj->young_object_p()) { if(!obj->forwarded_p()) { ref->set_object(object_memory_, cNil); } else { ref->set_object(object_memory_, obj->forward()); } } } else if(!obj->marked_p(object_memory_->mark())) { ref->set_object(object_memory_, cNil); } } delete weak_refs_; weak_refs_ = NULL; } void GarbageCollector::clean_locked_objects(ManagedThread* thr, bool young_only) { LockedObjects& los = thr->locked_objects(); for(LockedObjects::iterator i = los.begin(); i != los.end();) { Object* obj = static_cast<Object*>(*i); if(young_only) { if(obj->young_object_p()) { if(obj->forwarded_p()) { *i = obj->forward(); ++i; } else { i = los.erase(i); } } else { ++i; } } else { if(!obj->marked_p(object_memory_->mark())) { i = los.erase(i); } else { ++i; } } } } } <|endoftext|>
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2015 * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, [email protected] */ /*! \file SiconosGraphs.hpp * \brief Definitions of the graphs used in Siconos */ #ifndef SimulationGraphs_H #define SimulationGraphs_H #include "SiconosGraph.hpp" #include "SiconosProperties.hpp" #include "SiconosPointers.hpp" #include "SimulationTypeDef.hpp" /** the graph structure : * * InteractionsGraph = L(DynamicalSystemsGraph) * * where L is the line graph * transformation * * * Properties on graph : * -------------------- * * The properties on the graph enable to store the data that are specicic to a simulation * strategy. It avoids to burden the modeling classes that should be as independent as possible from * the simulation choices. * * There are mainly two types of properties * <ul> * <li> Mandatory properties DynamicalSystemProperties and InteractionProperties . * These properties are always instanciated for any kind of simulation. * The accesors to the property are illustrated in the followinf example : * For a given SP::DynamicalSystem ds and a given graph SP::DynamicalSystemsGrap DSG * * DynamicalSystemsGraph::VDescriptor dsv = DSG->descriptor(ds); * SP::OneStepintegrator osi = DSG->properties(dsv).osi; * </li> * <li> Optional Properties * They are installed thanks to the macro INSTALL_GRAPH_PROPERTIES. * * The accesors to the property are illustrated in the following example : * For a given SP::DynamicalSystem ds and a given graph SP::DynamicalSystemsGrap DSG * * DynamicalSystemsGraph::VDescriptor dsv = DSG->descriptor(ds); * DSG->name.insert(dsv, name); // insert the name in the property * const std::string& name = DSG[*dsv]->name; * * * </li> * </ul> */ /** \struct InteractionProperties mandatory properties for an Interaction */ struct InteractionProperties { SP::SiconosMatrix block; /**< diagonal block */ SP::DynamicalSystem source; unsigned int source_pos; SP::DynamicalSystem target; unsigned int target_pos; SP::OneStepIntegrator osi; bool forControl; /**< true if the relation is used to add a control input to a DS */ SP::VectorOfBlockVectors DSlink; /**< pointer links to DS variables needed for computation, mostly x (or q), z, r (or p) */ SP::VectorOfVectors workVectors; /**< set of SiconosVector, mostly to have continuous memory vectors (not the case with BlockVector in DSlink) */ SP::VectorOfSMatrices workMatrices; /**< To store jacobians */ ACCEPT_SERIALIZATION(InteractionProperties); }; /** \struct DynamicalSystemProperties mandatory properties for a DynamicalSystems */ struct DynamicalSystemProperties { SP::SiconosMatrix upper_block; /**< i,j block i<j */ SP::SiconosMatrix lower_block; /**< i,j block i>j */ SP::VectorOfVectors workVectors; /**< Used for instance in Newton iteration */ SP::VectorOfMatrices workMatrices; /**< Mostly for Lagrangian system */ SP::OneStepIntegrator osi; /**< Integrator used for the given DynamicalSystem */ SP::SimpleMatrix W; /**< Matrix for integration */ SP::SimpleMatrix WBoundaryConditions; /**< Matrix for integration of boundary conditions*/ // SP::SiconosMemory _xMemory /**< old value of x, TBD */ ACCEPT_SERIALIZATION(DynamicalSystemProperties); }; struct GraphProperties { bool symmetric; ACCEPT_SERIALIZATION(GraphProperties); }; typedef SiconosGraph < std11::shared_ptr<DynamicalSystem>, std11::shared_ptr<Interaction>, DynamicalSystemProperties, InteractionProperties, GraphProperties > _DynamicalSystemsGraph; typedef SiconosGraph < std11::shared_ptr<Interaction>, std11::shared_ptr<DynamicalSystem>, InteractionProperties, DynamicalSystemProperties, GraphProperties > _InteractionsGraph; struct DynamicalSystemsGraph : public _DynamicalSystemsGraph { /** optional properties : memory is allocated only on first access */ INSTALL_GRAPH_PROPERTIES(DynamicalSystems, ((VertexSP, MatrixIntegrator, Ad)) // for ZOH Integration ((VertexSP, MatrixIntegrator, AdInt)) // for ZOH Integration ((VertexSP, MatrixIntegrator, Ld)) // For Observer (ZOH Integration) ((VertexSP, MatrixIntegrator, Bd)) // For Controlled System (ZOH Integration) ((VertexSP, SiconosMatrix, B)) // For Controlled System ((VertexSP, SiconosMatrix, L)) // For Observer ((VertexSP, PluggedObject, pluginB)) // For Controlled System ((VertexSP, PluggedObject, pluginL)) // For Observer ((VertexSP, SiconosVector, e)) // For Observer ((VertexSP, SiconosVector, u)) // For Controlled System ((VertexSP, PluggedObject, pluginU)) // For Controlled System (nonlinear w.r.t u) ((VertexSP, PluggedObject, pluginJacgx)) // For Controlled System (nonlinear w.r.t u); compute nabla_x g(x, u) ((VertexSP, SiconosVector, tmpXdot)) // For Controlled System (nonlinear w.r.t u); tmpXdot = g(x, u) ((VertexSP, SimpleMatrix, jacgx)) // For Controlled System (nonlinear w.r.t u); jacgx = nabla_x g(x, u) ((Vertex, std::string, name)) // a name for a dynamical system ((Vertex, unsigned int, groupId))); // For group manipulations (example assign // a material id for contact law // determination // always needed -> DynamicalSystemProperties /** serialization hooks */ ACCEPT_SERIALIZATION(DynamicalSystemsGraph); // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_DynamicalSystemsGraph::VDescriptor vd) { Ad._store->erase(vd); AdInt._store->erase(vd); Ld._store->erase(vd); Bd._store->erase(vd); B._store->erase(vd); L._store->erase(vd); pluginB._store->erase(vd); pluginL._store->erase(vd); e._store->erase(vd); u._store->erase(vd); pluginU._store->erase(vd); pluginJacgx._store->erase(vd); tmpXdot._store->erase(vd); jacgx._store->erase(vd); name._store->erase(vd); groupId._store->erase(vd); } }; struct InteractionsGraph : public _InteractionsGraph { /** optional properties : memory is allocated only on first access */ INSTALL_GRAPH_PROPERTIES(Interactions, ((Vertex, SP::SimpleMatrix, blockProj)) // ProjectOnConstraint ((Edge, SP::SimpleMatrix, upper_blockProj)) // idem ((Edge, SP::SimpleMatrix, lower_blockProj)) // idem ((Vertex, std::string, name))); // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_InteractionsGraph::VDescriptor vd) { blockProj._store->erase(vd); name._store->erase(vd); } // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_InteractionsGraph::EDescriptor ed) { upper_blockProj._store->erase(ed); lower_blockProj._store->erase(ed); } /** serialization hooks */ ACCEPT_SERIALIZATION(InteractionsGraph); }; #endif <commit_msg>[kernel] typos in simulationgraph doc<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2015 * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos 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 Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, [email protected] */ /*! \file SiconosGraphs.hpp * \brief Definitions of the graphs used in Siconos */ #ifndef SimulationGraphs_H #define SimulationGraphs_H #include "SiconosGraph.hpp" #include "SiconosProperties.hpp" #include "SiconosPointers.hpp" #include "SimulationTypeDef.hpp" /** the graph structure : * * InteractionsGraph = L(DynamicalSystemsGraph) * * where L is the line graph * transformation * * * Properties on graph : * -------------------- * * The properties on the graph enable to store the data that are specific to a simulation * strategy. It avoids to burden the modeling classes that should be as independent as possible from * the simulation choices. * * There are mainly two types of properties * <ul> * <li> Mandatory properties DynamicalSystemProperties and InteractionProperties . * These properties are always instanciated for any kind of simulation. * The accessors to the property are illustrated in the following example : * For a given SP::DynamicalSystem ds and a given graph SP::DynamicalSystemsGraph DSG * * DynamicalSystemsGraph::VDescriptor dsv = DSG->descriptor(ds); * SP::OneStepintegrator osi = DSG->properties(dsv).osi; * </li> * <li> Optional Properties * They are installed thanks to the macro INSTALL_GRAPH_PROPERTIES. * * The accessors to the property are illustrated in the following example : * For a given SP::DynamicalSystem ds and a given graph SP::DynamicalSystemsGraph DSG * * DynamicalSystemsGraph::VDescriptor dsv = DSG->descriptor(ds); * DSG->name.insert(dsv, name); // insert the name in the property * const std::string& name = DSG[*dsv]->name; * * * </li> * </ul> */ /** \struct InteractionProperties mandatory properties for an Interaction */ struct InteractionProperties { SP::SiconosMatrix block; /**< diagonal block */ SP::DynamicalSystem source; unsigned int source_pos; SP::DynamicalSystem target; unsigned int target_pos; SP::OneStepIntegrator osi; bool forControl; /**< true if the relation is used to add a control input to a DS */ SP::VectorOfBlockVectors DSlink; /**< pointer links to DS variables needed for computation, mostly x (or q), z, r (or p) */ SP::VectorOfVectors workVectors; /**< set of SiconosVector, mostly to have continuous memory vectors (not the case with BlockVector in DSlink) */ SP::VectorOfSMatrices workMatrices; /**< To store jacobians */ ACCEPT_SERIALIZATION(InteractionProperties); }; /** \struct DynamicalSystemProperties mandatory properties for a DynamicalSystems */ struct DynamicalSystemProperties { SP::SiconosMatrix upper_block; /**< i,j block i<j */ SP::SiconosMatrix lower_block; /**< i,j block i>j */ SP::VectorOfVectors workVectors; /**< Used for instance in Newton iteration */ SP::VectorOfMatrices workMatrices; /**< Mostly for Lagrangian system */ SP::OneStepIntegrator osi; /**< Integrator used for the given DynamicalSystem */ SP::SimpleMatrix W; /**< Matrix for integration */ SP::SimpleMatrix WBoundaryConditions; /**< Matrix for integration of boundary conditions*/ // SP::SiconosMemory _xMemory /**< old value of x, TBD */ ACCEPT_SERIALIZATION(DynamicalSystemProperties); }; struct GraphProperties { bool symmetric; ACCEPT_SERIALIZATION(GraphProperties); }; typedef SiconosGraph < std11::shared_ptr<DynamicalSystem>, std11::shared_ptr<Interaction>, DynamicalSystemProperties, InteractionProperties, GraphProperties > _DynamicalSystemsGraph; typedef SiconosGraph < std11::shared_ptr<Interaction>, std11::shared_ptr<DynamicalSystem>, InteractionProperties, DynamicalSystemProperties, GraphProperties > _InteractionsGraph; struct DynamicalSystemsGraph : public _DynamicalSystemsGraph { /** optional properties : memory is allocated only on first access */ INSTALL_GRAPH_PROPERTIES(DynamicalSystems, ((VertexSP, MatrixIntegrator, Ad)) // for ZOH Integration ((VertexSP, MatrixIntegrator, AdInt)) // for ZOH Integration ((VertexSP, MatrixIntegrator, Ld)) // For Observer (ZOH Integration) ((VertexSP, MatrixIntegrator, Bd)) // For Controlled System (ZOH Integration) ((VertexSP, SiconosMatrix, B)) // For Controlled System ((VertexSP, SiconosMatrix, L)) // For Observer ((VertexSP, PluggedObject, pluginB)) // For Controlled System ((VertexSP, PluggedObject, pluginL)) // For Observer ((VertexSP, SiconosVector, e)) // For Observer ((VertexSP, SiconosVector, u)) // For Controlled System ((VertexSP, PluggedObject, pluginU)) // For Controlled System (nonlinear w.r.t u) ((VertexSP, PluggedObject, pluginJacgx)) // For Controlled System (nonlinear w.r.t u); compute nabla_x g(x, u) ((VertexSP, SiconosVector, tmpXdot)) // For Controlled System (nonlinear w.r.t u); tmpXdot = g(x, u) ((VertexSP, SimpleMatrix, jacgx)) // For Controlled System (nonlinear w.r.t u); jacgx = nabla_x g(x, u) ((Vertex, std::string, name)) // a name for a dynamical system ((Vertex, unsigned int, groupId))); // For group manipulations (example assign // a material id for contact law // determination // always needed -> DynamicalSystemProperties /** serialization hooks */ ACCEPT_SERIALIZATION(DynamicalSystemsGraph); // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_DynamicalSystemsGraph::VDescriptor vd) { Ad._store->erase(vd); AdInt._store->erase(vd); Ld._store->erase(vd); Bd._store->erase(vd); B._store->erase(vd); L._store->erase(vd); pluginB._store->erase(vd); pluginL._store->erase(vd); e._store->erase(vd); u._store->erase(vd); pluginU._store->erase(vd); pluginJacgx._store->erase(vd); tmpXdot._store->erase(vd); jacgx._store->erase(vd); name._store->erase(vd); groupId._store->erase(vd); } }; struct InteractionsGraph : public _InteractionsGraph { /** optional properties : memory is allocated only on first access */ INSTALL_GRAPH_PROPERTIES(Interactions, ((Vertex, SP::SimpleMatrix, blockProj)) // ProjectOnConstraint ((Edge, SP::SimpleMatrix, upper_blockProj)) // idem ((Edge, SP::SimpleMatrix, lower_blockProj)) // idem ((Vertex, std::string, name))); // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_InteractionsGraph::VDescriptor vd) { blockProj._store->erase(vd); name._store->erase(vd); } // to be installed with INSTALL_GRAPH_PROPERTIES void eraseProperties(_InteractionsGraph::EDescriptor ed) { upper_blockProj._store->erase(ed); lower_blockProj._store->erase(ed); } /** serialization hooks */ ACCEPT_SERIALIZATION(InteractionsGraph); }; #endif <|endoftext|>
<commit_before>#include <aleph/topology/io/LexicographicTriangulation.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/PhiPersistence.hh> #include <aleph/topology/BarycentricSubdivision.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/Skeleton.hh> #include <algorithm> #include <iostream> #include <string> #include <vector> using DataType = bool; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; /** Models a signature consisting of Betti numbers, i.e. a set of natural numbers. Signatures are comparable and are ordered lexicographically, i.e. in the manner one would expect. */ class Signature { public: template <class InputIterator> Signature( InputIterator begin, InputIterator end ) : _betti( begin, end ) { } bool operator<( const Signature& other ) const noexcept { return std::lexicographical_compare( _betti.begin(), _betti.end(), other._betti.begin(), other._betti.end() ); } long eulerCharacteristic() const noexcept { long chi = 0; bool s = true; for( auto&& betti : _betti ) { chi = s ? chi + betti : chi - betti; s = !s; } return chi; } using const_iterator = typename std::vector<std::size_t>::const_iterator; const_iterator begin() const noexcept { return _betti.begin(); } const_iterator end() const noexcept { return _betti.end() ; } private: std::vector<std::size_t> _betti; }; std::ostream& operator<<( std::ostream& o, const Signature& s ) { o << "["; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) o << ","; o << *it; } o << "]"; return o; } /** Converts a vector of persistence diagrams into a Betti signature. The maximum dimension needs to be specified in order to ensure that empty or missing persistence diagrams can still be handled correctly. */ template <class PersistenceDiagram> Signature makeSignature( const std::vector<PersistenceDiagram>& diagrams, std::size_t D ) { std::vector<std::size_t> bettiNumbers( D+1 ); for( auto&& diagram : diagrams ) { auto d = diagram.dimension(); auto b = diagram.betti(); bettiNumbers.at(d) = b; } return Signature( bettiNumbers.begin(), bettiNumbers.end() ); } /** Enumerates all possible perversities for a given dimension. One could say that this function is as wicked as possible. */ std::vector<aleph::Perversity> getPerversities( unsigned dimension ) { std::vector<aleph::Perversity> perversities; std::map< unsigned, std::vector<int> > possibleValues; for( unsigned d = 0; d < dimension; d++ ) { // Note that no shift in dimensions is required: as the dimension is // zero-based, the maximum value of the perversity in dimension zero // is zero. This is identical to demanding // // -1 \leq p_k \leq k-1 // // for k = [1,...,d]. for( int k = -1; k <= static_cast<int>( d ); k++ ) possibleValues[d].push_back( k ); } std::size_t numCombinations = 1; for( auto&& pair : possibleValues ) numCombinations *= pair.second.size(); // Stores the current index that was reached while traversing all // possible values of the perversity. The idea is that to add one // to the last index upon adding a new value. If the index is too // large, it goes back to zero and the previous index is modified // by one. std::vector<std::size_t> indices( possibleValues.size() ); for( std::size_t i = 0; i < numCombinations; i++ ) { std::vector<int> values; for( unsigned d = 0; d < dimension; d++ ) { auto index = indices.at(d); values.emplace_back( possibleValues.at(d).at(index) ); } // Always increase the last used index by one. If an overflow // occurs, the previous indices are updated as well. { auto last = dimension - 1; indices.at(last) = indices.at(last) + 1; // Check & propagate potential overflows to the previous indices // in the range. The index vector is reset to zero only when all // combinations have been visited. if( indices.at(last) >= possibleValues.at(last).size() ) { indices.at(last) = 0; for( unsigned d = 1; d < dimension; d++ ) { auto D = dimension - 1 - d; indices.at(D) = indices.at(D) + 1; if( indices.at(D) < possibleValues.at(D).size() ) break; else indices.at(D) = 0; } } } perversities.emplace_back( aleph::Perversity( values.begin(), values.end() ) ); } return perversities; } int main(int argc, char* argv[]) { if( argc <= 1 ) return -1; std::string filename = argv[1]; std::vector<SimplicialComplex> simplicialComplexes; aleph::topology::io::LexicographicTriangulationReader reader; reader( filename, simplicialComplexes ); // Create missing faces ---------------------------------------------- // // The triangulations are only specified by their top-level simplices, // so they need to be converted before being valid inputs for homology // calculations. for( auto&& K : simplicialComplexes ) { K.createMissingFaces(); K.sort(); } // Calculate homology ------------------------------------------------ // // We are only interested in the Betti numbers of the diagrams here as // the triangulations are not endowed with any weights or values. std::size_t index = 0; std::string level = " "; // separator to make JSON more readable std::cout << "{\n" << level << "\"homology\":" << level << "{\n"; for( auto&& K : simplicialComplexes ) { std::cout << level << level << "\"" << index << "\":" << level << "{\n"; bool dualize = true; bool includeAllUnpairedCreators = true; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << level << level << level << "\"betti\":" << level << signature << ",\n" << level << level << level << "\"euler\":" << level << signature.eulerCharacteristic() << "\n"; std::cout << level << level << "}"; if( index + 1 < simplicialComplexes.size() ) std::cout << ","; std::cout << "\n"; ++index; } std::cout << level << "},\n" << level << "\"intersection_homology\":" << level << "{\n"; // Calculate intersection homology ----------------------------------- // // The basic idea is to first decompose the given simplicial complex // into its skeletons. These skeletons then serve as a filtration of // the complex. In addition to this, we also calculate a barycentric // subdivision of the simplicial complex. The triangulation is hence // always "flag-like" following the paper: // // Elementary construction of perverse sheaves // Robert MacPherson and Kari Vilonen // Inventiones Mathematicae, Volume 84, pp. 403--435, 1986 // // As a last step, we iterate over all possible perversities for the // given triangulation and calculate their intersection homology. std::vector< std::vector<Signature> > allIntersectionHomologySignatures; allIntersectionHomologySignatures.reserve( simplicialComplexes.size() ); index = 0; for( auto&& K : simplicialComplexes ) { std::vector<SimplicialComplex> skeletons; skeletons.reserve( K.dimension() + 1 ); aleph::topology::Skeleton skeleton; for( std::size_t d = 0; d <= K.dimension(); d++ ) skeletons.emplace_back( skeleton( d, K ) ); aleph::topology::BarycentricSubdivision subdivision; auto L = subdivision( K ); // TODO: this is not optimal because the simplicial complexes may // share the same dimensionality. auto perversities = getPerversities( static_cast<unsigned>( K.dimension() ) ); std::vector<Signature> signatures; signatures.reserve( perversities.size() ); std::cout << level << level << "\"" << index << "\":" << level << "{\n"; std::size_t perversityIndex = 0; for( auto&& perversity : perversities ) { std::cout << level << level << level << "\"" << perversityIndex << "\"" << ":" << level << "{\n"; auto diagrams = aleph::calculateIntersectionHomology( L, skeletons, perversity ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << level << level << level << level << "\"perversity\":" << " " << perversity << ",\n" << level << level << level << level << "\"betti\":" << " " << signature << "\n"; std::cout << level << level << level << "}"; if( perversityIndex + 1 < perversities.size() ) std::cout<< ","; std::cout << "\n"; signatures.push_back( signature ); ++perversityIndex; } std::sort( signatures.begin(), signatures.end() ); allIntersectionHomologySignatures.emplace_back( signatures ); std::cout << level << level << "}"; if( index + 1 < simplicialComplexes.size() ) std::cout << ","; std::cout << "\n"; ++index; } std::cout << level << "}\n" << "}\n"; } <commit_msg>Fixed spurious conversion warnings for wicked triangulations executable<commit_after>#include <aleph/topology/io/LexicographicTriangulation.hh> #include <aleph/persistentHomology/Calculation.hh> #include <aleph/persistentHomology/PhiPersistence.hh> #include <aleph/topology/BarycentricSubdivision.hh> #include <aleph/topology/Simplex.hh> #include <aleph/topology/SimplicialComplex.hh> #include <aleph/topology/Skeleton.hh> #include <algorithm> #include <iostream> #include <string> #include <vector> using DataType = bool; using VertexType = unsigned short; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; /** Models a signature consisting of Betti numbers, i.e. a set of natural numbers. Signatures are comparable and are ordered lexicographically, i.e. in the manner one would expect. */ class Signature { public: template <class InputIterator> Signature( InputIterator begin, InputIterator end ) : _betti( begin, end ) { } bool operator<( const Signature& other ) const noexcept { return std::lexicographical_compare( _betti.begin(), _betti.end(), other._betti.begin(), other._betti.end() ); } long eulerCharacteristic() const noexcept { long chi = 0; bool s = true; for( auto&& betti : _betti ) { chi = s ? chi + long( betti ) : chi - long ( betti ); s = !s; } return chi; } using const_iterator = typename std::vector<std::size_t>::const_iterator; const_iterator begin() const noexcept { return _betti.begin(); } const_iterator end() const noexcept { return _betti.end() ; } private: std::vector<std::size_t> _betti; }; std::ostream& operator<<( std::ostream& o, const Signature& s ) { o << "["; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) o << ","; o << *it; } o << "]"; return o; } /** Converts a vector of persistence diagrams into a Betti signature. The maximum dimension needs to be specified in order to ensure that empty or missing persistence diagrams can still be handled correctly. */ template <class PersistenceDiagram> Signature makeSignature( const std::vector<PersistenceDiagram>& diagrams, std::size_t D ) { std::vector<std::size_t> bettiNumbers( D+1 ); for( auto&& diagram : diagrams ) { auto d = diagram.dimension(); auto b = diagram.betti(); bettiNumbers.at(d) = b; } return Signature( bettiNumbers.begin(), bettiNumbers.end() ); } /** Enumerates all possible perversities for a given dimension. One could say that this function is as wicked as possible. */ std::vector<aleph::Perversity> getPerversities( unsigned dimension ) { std::vector<aleph::Perversity> perversities; std::map< unsigned, std::vector<int> > possibleValues; for( unsigned d = 0; d < dimension; d++ ) { // Note that no shift in dimensions is required: as the dimension is // zero-based, the maximum value of the perversity in dimension zero // is zero. This is identical to demanding // // -1 \leq p_k \leq k-1 // // for k = [1,...,d]. for( int k = -1; k <= static_cast<int>( d ); k++ ) possibleValues[d].push_back( k ); } std::size_t numCombinations = 1; for( auto&& pair : possibleValues ) numCombinations *= pair.second.size(); // Stores the current index that was reached while traversing all // possible values of the perversity. The idea is that to add one // to the last index upon adding a new value. If the index is too // large, it goes back to zero and the previous index is modified // by one. std::vector<std::size_t> indices( possibleValues.size() ); for( std::size_t i = 0; i < numCombinations; i++ ) { std::vector<int> values; for( unsigned d = 0; d < dimension; d++ ) { auto index = indices.at(d); values.emplace_back( possibleValues.at(d).at(index) ); } // Always increase the last used index by one. If an overflow // occurs, the previous indices are updated as well. { auto last = dimension - 1; indices.at(last) = indices.at(last) + 1; // Check & propagate potential overflows to the previous indices // in the range. The index vector is reset to zero only when all // combinations have been visited. if( indices.at(last) >= possibleValues.at(last).size() ) { indices.at(last) = 0; for( unsigned d = 1; d < dimension; d++ ) { auto D = dimension - 1 - d; indices.at(D) = indices.at(D) + 1; if( indices.at(D) < possibleValues.at(D).size() ) break; else indices.at(D) = 0; } } } perversities.emplace_back( aleph::Perversity( values.begin(), values.end() ) ); } return perversities; } int main(int argc, char* argv[]) { if( argc <= 1 ) return -1; std::string filename = argv[1]; std::vector<SimplicialComplex> simplicialComplexes; aleph::topology::io::LexicographicTriangulationReader reader; reader( filename, simplicialComplexes ); // Create missing faces ---------------------------------------------- // // The triangulations are only specified by their top-level simplices, // so they need to be converted before being valid inputs for homology // calculations. for( auto&& K : simplicialComplexes ) { K.createMissingFaces(); K.sort(); } // Calculate homology ------------------------------------------------ // // We are only interested in the Betti numbers of the diagrams here as // the triangulations are not endowed with any weights or values. std::size_t index = 0; std::string level = " "; // separator to make JSON more readable std::cout << "{\n" << level << "\"homology\":" << level << "{\n"; for( auto&& K : simplicialComplexes ) { std::cout << level << level << "\"" << index << "\":" << level << "{\n"; bool dualize = true; bool includeAllUnpairedCreators = true; auto diagrams = aleph::calculatePersistenceDiagrams( K, dualize, includeAllUnpairedCreators ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << level << level << level << "\"betti\":" << level << signature << ",\n" << level << level << level << "\"euler\":" << level << signature.eulerCharacteristic() << "\n"; std::cout << level << level << "}"; if( index + 1 < simplicialComplexes.size() ) std::cout << ","; std::cout << "\n"; ++index; } std::cout << level << "},\n" << level << "\"intersection_homology\":" << level << "{\n"; // Calculate intersection homology ----------------------------------- // // The basic idea is to first decompose the given simplicial complex // into its skeletons. These skeletons then serve as a filtration of // the complex. In addition to this, we also calculate a barycentric // subdivision of the simplicial complex. The triangulation is hence // always "flag-like" following the paper: // // Elementary construction of perverse sheaves // Robert MacPherson and Kari Vilonen // Inventiones Mathematicae, Volume 84, pp. 403--435, 1986 // // As a last step, we iterate over all possible perversities for the // given triangulation and calculate their intersection homology. std::vector< std::vector<Signature> > allIntersectionHomologySignatures; allIntersectionHomologySignatures.reserve( simplicialComplexes.size() ); index = 0; for( auto&& K : simplicialComplexes ) { std::vector<SimplicialComplex> skeletons; skeletons.reserve( K.dimension() + 1 ); aleph::topology::Skeleton skeleton; for( std::size_t d = 0; d <= K.dimension(); d++ ) skeletons.emplace_back( skeleton( d, K ) ); aleph::topology::BarycentricSubdivision subdivision; auto L = subdivision( K ); // TODO: this is not optimal because the simplicial complexes may // share the same dimensionality. auto perversities = getPerversities( static_cast<unsigned>( K.dimension() ) ); std::vector<Signature> signatures; signatures.reserve( perversities.size() ); std::cout << level << level << "\"" << index << "\":" << level << "{\n"; std::size_t perversityIndex = 0; for( auto&& perversity : perversities ) { std::cout << level << level << level << "\"" << perversityIndex << "\"" << ":" << level << "{\n"; auto diagrams = aleph::calculateIntersectionHomology( L, skeletons, perversity ); auto signature = makeSignature( diagrams, K.dimension() ); std::cout << level << level << level << level << "\"perversity\":" << " " << perversity << ",\n" << level << level << level << level << "\"betti\":" << " " << signature << "\n"; std::cout << level << level << level << "}"; if( perversityIndex + 1 < perversities.size() ) std::cout<< ","; std::cout << "\n"; signatures.push_back( signature ); ++perversityIndex; } std::sort( signatures.begin(), signatures.end() ); allIntersectionHomologySignatures.emplace_back( signatures ); std::cout << level << level << "}"; if( index + 1 < simplicialComplexes.size() ) std::cout << ","; std::cout << "\n"; ++index; } std::cout << level << "}\n" << "}\n"; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_CreationWizard.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-05-22 17:58:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_CREATION_WIZARD_HXX #define _CHART2_CREATION_WIZARD_HXX #include "ServiceMacros.hxx" #include "TimerTriggeredControllerLock.hxx" #include "TabPageNotifiable.hxx" #include <com/sun/star/chart2/XChartDocument.hpp> #ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX #include <svtools/roadmapwizard.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif // for auto_ptr #include <memory> //............................................................................. namespace chart { //............................................................................. class RangeChooserTabPage; class DataSourceTabPage; class ChartTypeTemplateProvider; class DialogModel; class CreationWizard : public svt::RoadmapWizard , public TabPageNotifiable { public: CreationWizard( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xChartModel , const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext , sal_Int32 nOnePageOnlyIndex=-1 );//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap virtual ~CreationWizard(); bool isClosable(); // TabPageNotifiable virtual void setInvalidPage( TabPage * pTabPage ); virtual void setValidPage( TabPage * pTabPage ); protected: virtual sal_Bool leaveState( WizardState _nState ); virtual WizardState determineNextState(WizardState nCurrentState); virtual void enterState(WizardState nState); virtual String getStateDisplayName( WizardState nState ); private: //no default constructor CreationWizard(); virtual svt::OWizardPage* createPage(WizardState nState); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xChartModel; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext> m_xCC; bool m_bIsClosable; sal_Int32 m_nOnePageOnlyIndex;//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap ChartTypeTemplateProvider* m_pTemplateProvider; ::std::auto_ptr< DialogModel > m_apDialogModel; WizardState m_nFirstState; WizardState m_nLastState; TimerTriggeredControllerLock m_aTimerTriggeredControllerLock; // RangeChooserTabPage * m_pRangeChooserTabePage; // DataSourceTabPage * m_pDataSourceTabPage; bool m_bCanTravel; }; //............................................................................. } //namespace chart //............................................................................. #endif <commit_msg>INTEGRATION: CWS odbmacros2 (1.2.90); FILE MERGED 2008/01/15 09:55:46 fs 1.2.90.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_CreationWizard.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2008-03-06 19:18:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CHART2_CREATION_WIZARD_HXX #define _CHART2_CREATION_WIZARD_HXX #include "ServiceMacros.hxx" #include "TimerTriggeredControllerLock.hxx" #include "TabPageNotifiable.hxx" #include <com/sun/star/chart2/XChartDocument.hpp> #ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX #include <svtools/roadmapwizard.hxx> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif // for auto_ptr #include <memory> //............................................................................. namespace chart { //............................................................................. class RangeChooserTabPage; class DataSourceTabPage; class ChartTypeTemplateProvider; class DialogModel; class CreationWizard : public svt::RoadmapWizard , public TabPageNotifiable { public: CreationWizard( Window* pParent, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >& xChartModel , const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext , sal_Int32 nOnePageOnlyIndex=-1 );//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap virtual ~CreationWizard(); bool isClosable(); // TabPageNotifiable virtual void setInvalidPage( TabPage * pTabPage ); virtual void setValidPage( TabPage * pTabPage ); protected: virtual sal_Bool leaveState( WizardState _nState ); virtual WizardState determineNextState(WizardState nCurrentState) const; virtual void enterState(WizardState nState); virtual String getStateDisplayName( WizardState nState ) const; private: //no default constructor CreationWizard(); virtual svt::OWizardPage* createPage(WizardState nState); ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartDocument > m_xChartModel; ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext> m_xCC; bool m_bIsClosable; sal_Int32 m_nOnePageOnlyIndex;//if nOnePageOnlyIndex is an index of an exsisting page starting with 0, then only this page is displayed without next/previous and roadmap ChartTypeTemplateProvider* m_pTemplateProvider; ::std::auto_ptr< DialogModel > m_apDialogModel; WizardState m_nFirstState; WizardState m_nLastState; TimerTriggeredControllerLock m_aTimerTriggeredControllerLock; // RangeChooserTabPage * m_pRangeChooserTabePage; // DataSourceTabPage * m_pDataSourceTabPage; bool m_bCanTravel; }; //............................................................................. } //namespace chart //............................................................................. #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_manager_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/browser_notification_observers.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/authentication_notification_details.h" #include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/message_bubble.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/widget/widget.h" #include "views/window/non_client_view.h" #include "views/window/window.h" #include "views/window/window_gtk.h" using views::Background; using views::Label; using views::Textfield; using views::View; using views::Widget; namespace { const int kTitleY = 100; const int kPanelSpacing = 36; const int kTextfieldWidth = 286; const int kRowPad = 10; const int kLabelPad = 2; const int kLanguageMenuOffsetTop = 25; const int kLanguageMenuOffsetRight = 25; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kLabelColor = 0xFF808080; const SkColor kErrorColor = 0xFF8F384F; const char *kDefaultDomain = "@gmail.com"; } // namespace namespace chromeos { LoginManagerView::LoginManagerView(ScreenObserver* observer) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), languages_menubutton_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), bubble_(NULL), observer_(observer), error_id_(-1), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false) { // Create login observer to record time of login when successful. LogLoginSuccessObserver::Get(); authenticator_ = LoginUtils::Get()->CreateAuthenticator(this); } LoginManagerView::~LoginManagerView() { if (bubble_) bubble_->Close(); } void LoginManagerView::Init() { // Use rounded rect background. views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); create_account_link_ = new views::Link(std::wstring()); create_account_link_->SetController(this); AddChildView(create_account_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); // Restore previously logged in user. std::vector<UserManager::User> users = UserManager::Get()->GetUsers(); if (users.size() > 0) { username_field_->SetText(UTF8ToUTF16(users[0].email())); } RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { username_field_->SetReadOnly(true); password_field_->SetReadOnly(true); sign_in_button_->SetEnabled(false); } } bool LoginManagerView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void LoginManagerView::UpdateLocalizedStrings() { title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); ShowError(error_id_); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void LoginManagerView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void LoginManagerView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } void LoginManagerView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void LoginManagerView::Layout() { // Center the text fields, and align the rest of the views with them. int x = (width() - kTextfieldWidth) / 2; int y = kTitleY; int max_width = width() - (2 * x); y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(password_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(sign_in_button_, x, y, kTextfieldWidth, false) + kRowPad); y += setViewBounds(create_account_link_, x, y, kTextfieldWidth, false); y += kRowPad; x = width() - kLanguagesMenuWidth - kLanguageMenuOffsetRight; y = kLanguageMenuOffsetTop; languages_menubutton_->SetBounds(x, y, kLanguagesMenuWidth, kLanguagesMenuHeight); SchedulePaint(); } gfx::Size LoginManagerView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* LoginManagerView::GetContentsView() { return this; } void LoginManagerView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void LoginManagerView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void LoginManagerView::Login() { if (login_in_process_) { return; } login_in_process_ = true; sign_in_button_->SetEnabled(false); create_account_link_->SetEnabled(false); // Disallow 0 size username. if (username_field_->text().empty()) { // Return true so that processing ends return; } std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } Profile* profile = g_browser_process->profile_manager()->GetWizardProfile(); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(authenticator_.get(), &Authenticator::AuthenticateToLogin, profile, username, password)); } // Sign in button causes a login attempt. void LoginManagerView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void LoginManagerView::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == create_account_link_); observer_->OnExit(ScreenObserver::LOGIN_CREATE_ACCOUNT); } void LoginManagerView::OnLoginFailure(const std::string& error) { LOG(INFO) << "LoginManagerView: OnLoginFailure() " << error; NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary(); // Send notification of failure AuthenticationNotificationDetails details(false); NotificationService::current()->Notify( NotificationType::LOGIN_AUTHENTICATION, Source<LoginManagerView>(this), Details<AuthenticationNotificationDetails>(&details)); // Check networking after trying to login in case user is // cached locally or the local admin account. if (!network || !CrosLibrary::Get()->EnsureLoaded()) { ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY); } else if (!network->Connected()) { ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED); } else { ShowError(IDS_LOGIN_ERROR_AUTHENTICATING); // TODO(someone): get |error| onto the UI somehow? } login_in_process_ = false; sign_in_button_->SetEnabled(true); create_account_link_->SetEnabled(true); SetPassword(std::string()); password_field_->RequestFocus(); } void LoginManagerView::OnLoginSuccess(const std::string& username, const std::string& credentials) { // TODO(cmasone): something sensible if errors occur. if (observer_) { observer_->OnExit(ScreenObserver::LOGIN_SIGN_IN_SELECTED); } LoginUtils::Get()->CompleteLogin(username, credentials); } void LoginManagerView::ShowError(int error_id) { error_id_ = error_id; // Close bubble before showing anything new. // bubble_ will be set to NULL in callback. if (bubble_) bubble_->Close(); if (error_id_ != -1) { std::wstring error_text = l10n_util::GetString(error_id_); gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(this, &origin); screen_bounds.set_origin(origin); bubble_ = MessageBubble::Show( GetWidget(), screen_bounds, BubbleBorder::LEFT_TOP, ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING), error_text, this); } } bool LoginManagerView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; if (login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else if (error_id_ != -1) { // Clear all previous error messages. ShowError(-1); return false; } // Return false so that processing does not end return false; } } // namespace chromeos <commit_msg>Don't prefill username on "Other user" screen.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_manager_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/browser_notification_observers.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/authentication_notification_details.h" #include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/message_bubble.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/widget/widget.h" #include "views/window/non_client_view.h" #include "views/window/window.h" #include "views/window/window_gtk.h" using views::Background; using views::Label; using views::Textfield; using views::View; using views::Widget; namespace { const int kTitleY = 100; const int kPanelSpacing = 36; const int kTextfieldWidth = 286; const int kRowPad = 10; const int kLabelPad = 2; const int kLanguageMenuOffsetTop = 25; const int kLanguageMenuOffsetRight = 25; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kLabelColor = 0xFF808080; const SkColor kErrorColor = 0xFF8F384F; const char *kDefaultDomain = "@gmail.com"; } // namespace namespace chromeos { LoginManagerView::LoginManagerView(ScreenObserver* observer) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), languages_menubutton_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), bubble_(NULL), observer_(observer), error_id_(-1), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false) { // Create login observer to record time of login when successful. LogLoginSuccessObserver::Get(); authenticator_ = LoginUtils::Get()->CreateAuthenticator(this); } LoginManagerView::~LoginManagerView() { if (bubble_) bubble_->Close(); } void LoginManagerView::Init() { // Use rounded rect background. views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); create_account_link_ = new views::Link(std::wstring()); create_account_link_->SetController(this); AddChildView(create_account_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { username_field_->SetReadOnly(true); password_field_->SetReadOnly(true); sign_in_button_->SetEnabled(false); } } bool LoginManagerView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void LoginManagerView::UpdateLocalizedStrings() { title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); ShowError(error_id_); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void LoginManagerView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void LoginManagerView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } void LoginManagerView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void LoginManagerView::Layout() { // Center the text fields, and align the rest of the views with them. int x = (width() - kTextfieldWidth) / 2; int y = kTitleY; int max_width = width() - (2 * x); y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(password_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(sign_in_button_, x, y, kTextfieldWidth, false) + kRowPad); y += setViewBounds(create_account_link_, x, y, kTextfieldWidth, false); y += kRowPad; x = width() - kLanguagesMenuWidth - kLanguageMenuOffsetRight; y = kLanguageMenuOffsetTop; languages_menubutton_->SetBounds(x, y, kLanguagesMenuWidth, kLanguagesMenuHeight); SchedulePaint(); } gfx::Size LoginManagerView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* LoginManagerView::GetContentsView() { return this; } void LoginManagerView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void LoginManagerView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void LoginManagerView::Login() { if (login_in_process_) { return; } login_in_process_ = true; sign_in_button_->SetEnabled(false); create_account_link_->SetEnabled(false); // Disallow 0 size username. if (username_field_->text().empty()) { // Return true so that processing ends return; } std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } Profile* profile = g_browser_process->profile_manager()->GetWizardProfile(); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(authenticator_.get(), &Authenticator::AuthenticateToLogin, profile, username, password)); } // Sign in button causes a login attempt. void LoginManagerView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void LoginManagerView::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == create_account_link_); observer_->OnExit(ScreenObserver::LOGIN_CREATE_ACCOUNT); } void LoginManagerView::OnLoginFailure(const std::string& error) { LOG(INFO) << "LoginManagerView: OnLoginFailure() " << error; NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary(); // Send notification of failure AuthenticationNotificationDetails details(false); NotificationService::current()->Notify( NotificationType::LOGIN_AUTHENTICATION, Source<LoginManagerView>(this), Details<AuthenticationNotificationDetails>(&details)); // Check networking after trying to login in case user is // cached locally or the local admin account. if (!network || !CrosLibrary::Get()->EnsureLoaded()) { ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY); } else if (!network->Connected()) { ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED); } else { ShowError(IDS_LOGIN_ERROR_AUTHENTICATING); // TODO(someone): get |error| onto the UI somehow? } login_in_process_ = false; sign_in_button_->SetEnabled(true); create_account_link_->SetEnabled(true); SetPassword(std::string()); password_field_->RequestFocus(); } void LoginManagerView::OnLoginSuccess(const std::string& username, const std::string& credentials) { // TODO(cmasone): something sensible if errors occur. if (observer_) { observer_->OnExit(ScreenObserver::LOGIN_SIGN_IN_SELECTED); } LoginUtils::Get()->CompleteLogin(username, credentials); } void LoginManagerView::ShowError(int error_id) { error_id_ = error_id; // Close bubble before showing anything new. // bubble_ will be set to NULL in callback. if (bubble_) bubble_->Close(); if (error_id_ != -1) { std::wstring error_text = l10n_util::GetString(error_id_); gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(this, &origin); screen_bounds.set_origin(origin); bubble_ = MessageBubble::Show( GetWidget(), screen_bounds, BubbleBorder::LEFT_TOP, ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING), error_text, this); } } bool LoginManagerView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; if (login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else if (error_id_ != -1) { // Clear all previous error messages. ShowError(-1); return false; } // Return false so that processing does not end return false; } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_manager_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/browser_notification_observers.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/authentication_notification_details.h" #include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/message_bubble.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/widget/widget.h" #include "views/window/non_client_view.h" #include "views/window/window.h" #include "views/window/window_gtk.h" using views::Background; using views::Label; using views::Textfield; using views::View; using views::Widget; namespace { const int kTitleY = 100; const int kPanelSpacing = 36; const int kTextfieldWidth = 286; const int kRowPad = 10; const int kLabelPad = 2; const int kLanguageMenuOffsetTop = 25; const int kLanguageMenuOffsetRight = 25; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kLabelColor = 0xFF808080; const SkColor kErrorColor = 0xFF8F384F; const char *kDefaultDomain = "@gmail.com"; } // namespace namespace chromeos { LoginManagerView::LoginManagerView(ScreenObserver* observer) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), languages_menubutton_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), bubble_(NULL), observer_(observer), error_id_(-1), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false) { // Create login observer to record time of login when successful. LogLoginSuccessObserver::Get(); authenticator_ = LoginUtils::Get()->CreateAuthenticator(this); } LoginManagerView::~LoginManagerView() { if (bubble_) bubble_->Close(); } void LoginManagerView::Init() { // Use rounded rect background. views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); create_account_link_ = new views::Link(std::wstring()); create_account_link_->SetController(this); AddChildView(create_account_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { username_field_->SetReadOnly(true); password_field_->SetReadOnly(true); sign_in_button_->SetEnabled(false); } } bool LoginManagerView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void LoginManagerView::UpdateLocalizedStrings() { title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); ShowError(error_id_); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void LoginManagerView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void LoginManagerView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } void LoginManagerView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void LoginManagerView::Layout() { // Center the text fields, and align the rest of the views with them. int x = (width() - kTextfieldWidth) / 2; int y = kTitleY; int max_width = width() - (2 * x); y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(password_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(sign_in_button_, x, y, kTextfieldWidth, false) + kRowPad); y += setViewBounds(create_account_link_, x, y, kTextfieldWidth, false); y += kRowPad; x = width() - kLanguagesMenuWidth - kLanguageMenuOffsetRight; y = kLanguageMenuOffsetTop; languages_menubutton_->SetBounds(x, y, kLanguagesMenuWidth, kLanguagesMenuHeight); SchedulePaint(); } gfx::Size LoginManagerView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* LoginManagerView::GetContentsView() { return this; } void LoginManagerView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void LoginManagerView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void LoginManagerView::Login() { if (login_in_process_) { return; } login_in_process_ = true; sign_in_button_->SetEnabled(false); create_account_link_->SetEnabled(false); // Disallow 0 size username. if (username_field_->text().empty()) { // Return true so that processing ends return; } std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } Profile* profile = g_browser_process->profile_manager()->GetWizardProfile(); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(authenticator_.get(), &Authenticator::AuthenticateToLogin, profile, username, password)); } // Sign in button causes a login attempt. void LoginManagerView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void LoginManagerView::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == create_account_link_); observer_->OnExit(ScreenObserver::LOGIN_CREATE_ACCOUNT); } void LoginManagerView::OnLoginFailure(const std::string& error) { LOG(INFO) << "LoginManagerView: OnLoginFailure() " << error; NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary(); // Send notification of failure AuthenticationNotificationDetails details(false); NotificationService::current()->Notify( NotificationType::LOGIN_AUTHENTICATION, Source<LoginManagerView>(this), Details<AuthenticationNotificationDetails>(&details)); // Check networking after trying to login in case user is // cached locally or the local admin account. if (!network || !CrosLibrary::Get()->EnsureLoaded()) { ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY); } else if (!network->Connected()) { ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED); } else { ShowError(IDS_LOGIN_ERROR_AUTHENTICATING); // TODO(someone): get |error| onto the UI somehow? } login_in_process_ = false; sign_in_button_->SetEnabled(true); create_account_link_->SetEnabled(true); SetPassword(std::string()); password_field_->RequestFocus(); } void LoginManagerView::OnLoginSuccess(const std::string& username, const std::string& credentials) { // TODO(cmasone): something sensible if errors occur. if (observer_) { observer_->OnExit(ScreenObserver::LOGIN_SIGN_IN_SELECTED); } LoginUtils::Get()->CompleteLogin(username, credentials); } void LoginManagerView::ShowError(int error_id) { error_id_ = error_id; // Close bubble before showing anything new. // bubble_ will be set to NULL in callback. if (bubble_) bubble_->Close(); if (error_id_ != -1) { std::wstring error_text = l10n_util::GetString(error_id_); gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(this, &origin); screen_bounds.set_origin(origin); bubble_ = MessageBubble::Show( GetWidget(), screen_bounds, BubbleBorder::LEFT_TOP, ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING), error_text, this); } } bool LoginManagerView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; if (login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else if (error_id_ != -1) { // Clear all previous error messages. ShowError(-1); return false; } // Return false so that processing does not end return false; } } // namespace chromeos <commit_msg>Make missing/wrong croslib nonfatal error.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/login/login_manager_view.h" #include <signal.h> #include <sys/types.h> #include <algorithm> #include <vector> #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/callback.h" #include "base/command_line.h" #include "base/keyboard_codes.h" #include "base/logging.h" #include "base/process_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/chromeos/browser_notification_observers.h" #include "chrome/browser/chromeos/cros/cros_library.h" #include "chrome/browser/chromeos/cros/network_library.h" #include "chrome/browser/chromeos/login/authentication_notification_details.h" #include "chrome/browser/chromeos/login/login_utils.h" #include "chrome/browser/chromeos/login/message_bubble.h" #include "chrome/browser/chromeos/login/rounded_rect_painter.h" #include "chrome/browser/chromeos/login/screen_observer.h" #include "chrome/browser/profile.h" #include "chrome/browser/profile_manager.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/label.h" #include "views/widget/widget.h" #include "views/window/non_client_view.h" #include "views/window/window.h" #include "views/window/window_gtk.h" using views::Background; using views::Label; using views::Textfield; using views::View; using views::Widget; namespace { const int kTitleY = 100; const int kPanelSpacing = 36; const int kTextfieldWidth = 286; const int kRowPad = 10; const int kLabelPad = 2; const int kLanguageMenuOffsetTop = 25; const int kLanguageMenuOffsetRight = 25; const int kLanguagesMenuWidth = 200; const int kLanguagesMenuHeight = 30; const SkColor kLabelColor = 0xFF808080; const SkColor kErrorColor = 0xFF8F384F; const char *kDefaultDomain = "@gmail.com"; } // namespace namespace chromeos { LoginManagerView::LoginManagerView(ScreenObserver* observer) : username_field_(NULL), password_field_(NULL), title_label_(NULL), sign_in_button_(NULL), create_account_link_(NULL), languages_menubutton_(NULL), accel_focus_user_(views::Accelerator(base::VKEY_U, false, false, true)), accel_focus_pass_(views::Accelerator(base::VKEY_P, false, false, true)), bubble_(NULL), observer_(observer), error_id_(-1), ALLOW_THIS_IN_INITIALIZER_LIST(focus_grabber_factory_(this)), focus_delayed_(false), login_in_process_(false), authenticator_(NULL) { // Create login observer to record time of login when successful. LogLoginSuccessObserver::Get(); if (CrosLibrary::Get()->EnsureLoaded()) { authenticator_ = LoginUtils::Get()->CreateAuthenticator(this); } } LoginManagerView::~LoginManagerView() { if (bubble_) bubble_->Close(); } void LoginManagerView::Init() { // Use rounded rect background. views::Painter* painter = CreateWizardPainter( &BorderDefinition::kScreenBorder); set_background( views::Background::CreateBackgroundPainter(true, painter)); // Set up fonts. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); gfx::Font title_font = rb.GetFont(ResourceBundle::MediumBoldFont); title_label_ = new views::Label(); title_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); title_label_->SetFont(title_font); AddChildView(title_label_); username_field_ = new views::Textfield; AddChildView(username_field_); password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD); AddChildView(password_field_); sign_in_button_ = new views::NativeButton(this, std::wstring()); AddChildView(sign_in_button_); create_account_link_ = new views::Link(std::wstring()); create_account_link_->SetController(this); AddChildView(create_account_link_); language_switch_model_.InitLanguageMenu(); languages_menubutton_ = new views::MenuButton( NULL, std::wstring(), &language_switch_model_, true); AddChildView(languages_menubutton_); AddAccelerator(accel_focus_user_); AddAccelerator(accel_focus_pass_); UpdateLocalizedStrings(); RequestFocus(); // Controller to handle events from textfields username_field_->SetController(this); password_field_->SetController(this); if (!CrosLibrary::Get()->EnsureLoaded()) { username_field_->SetReadOnly(true); password_field_->SetReadOnly(true); sign_in_button_->SetEnabled(false); } } bool LoginManagerView::AcceleratorPressed( const views::Accelerator& accelerator) { if (accelerator == accel_focus_user_) { username_field_->RequestFocus(); return true; } if (accelerator == accel_focus_pass_) { password_field_->RequestFocus(); return true; } return false; } void LoginManagerView::UpdateLocalizedStrings() { title_label_->SetText(l10n_util::GetString(IDS_LOGIN_TITLE)); username_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_USERNAME)); password_field_->set_text_to_display_when_empty( l10n_util::GetStringUTF16(IDS_LOGIN_PASSWORD)); sign_in_button_->SetLabel(l10n_util::GetString(IDS_LOGIN_BUTTON)); create_account_link_->SetText( l10n_util::GetString(IDS_CREATE_ACCOUNT_BUTTON)); ShowError(error_id_); languages_menubutton_->SetText(language_switch_model_.GetCurrentLocaleName()); } void LoginManagerView::LocaleChanged() { UpdateLocalizedStrings(); Layout(); SchedulePaint(); } void LoginManagerView::RequestFocus() { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } void LoginManagerView::ViewHierarchyChanged(bool is_add, View *parent, View *child) { if (is_add && child == this) { MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::NativeViewHierarchyChanged(bool attached, gfx::NativeView native_view, views::RootView* root_view) { if (focus_delayed_ && attached) { focus_delayed_ = false; MessageLoop::current()->PostTask(FROM_HERE, focus_grabber_factory_.NewRunnableMethod( &LoginManagerView::FocusFirstField)); } } void LoginManagerView::FocusFirstField() { if (GetFocusManager()) { if (username_field_->text().empty()) username_field_->RequestFocus(); else password_field_->RequestFocus(); } else { // We are invisible - delay until it is no longer the case. focus_delayed_ = true; } } // Sets the bounds of the view, using x and y as the origin. // The width is determined by the min of width and the preferred size // of the view, unless force_width is true in which case it is always used. // The height is gotten from the preferred size and returned. static int setViewBounds( views::View* view, int x, int y, int width, bool force_width) { gfx::Size pref_size = view->GetPreferredSize(); if (!force_width) { if (pref_size.width() < width) { width = pref_size.width(); } } int height = pref_size.height(); view->SetBounds(x, y, width, height); return height; } void LoginManagerView::Layout() { // Center the text fields, and align the rest of the views with them. int x = (width() - kTextfieldWidth) / 2; int y = kTitleY; int max_width = width() - (2 * x); y += (setViewBounds(title_label_, x, y, max_width, false) + kRowPad); y += (setViewBounds(username_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(password_field_, x, y, kTextfieldWidth, true) + kRowPad); y += (setViewBounds(sign_in_button_, x, y, kTextfieldWidth, false) + kRowPad); y += setViewBounds(create_account_link_, x, y, kTextfieldWidth, false); y += kRowPad; x = width() - kLanguagesMenuWidth - kLanguageMenuOffsetRight; y = kLanguageMenuOffsetTop; languages_menubutton_->SetBounds(x, y, kLanguagesMenuWidth, kLanguagesMenuHeight); SchedulePaint(); } gfx::Size LoginManagerView::GetPreferredSize() { return gfx::Size(width(), height()); } views::View* LoginManagerView::GetContentsView() { return this; } void LoginManagerView::SetUsername(const std::string& username) { username_field_->SetText(UTF8ToUTF16(username)); } void LoginManagerView::SetPassword(const std::string& password) { password_field_->SetText(UTF8ToUTF16(password)); } void LoginManagerView::Login() { if (login_in_process_) { return; } login_in_process_ = true; sign_in_button_->SetEnabled(false); create_account_link_->SetEnabled(false); // Disallow 0 size username. if (username_field_->text().empty() || !authenticator_) { // Return true so that processing ends return; } std::string username = UTF16ToUTF8(username_field_->text()); // todo(cmasone) Need to sanitize memory used to store password. std::string password = UTF16ToUTF8(password_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } Profile* profile = g_browser_process->profile_manager()->GetWizardProfile(); ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableMethod(authenticator_.get(), &Authenticator::AuthenticateToLogin, profile, username, password)); } // Sign in button causes a login attempt. void LoginManagerView::ButtonPressed( views::Button* sender, const views::Event& event) { DCHECK(sender == sign_in_button_); Login(); } void LoginManagerView::LinkActivated(views::Link* source, int event_flags) { DCHECK(source == create_account_link_); observer_->OnExit(ScreenObserver::LOGIN_CREATE_ACCOUNT); } void LoginManagerView::OnLoginFailure(const std::string& error) { LOG(INFO) << "LoginManagerView: OnLoginFailure() " << error; NetworkLibrary* network = CrosLibrary::Get()->GetNetworkLibrary(); // Send notification of failure AuthenticationNotificationDetails details(false); NotificationService::current()->Notify( NotificationType::LOGIN_AUTHENTICATION, Source<LoginManagerView>(this), Details<AuthenticationNotificationDetails>(&details)); // Check networking after trying to login in case user is // cached locally or the local admin account. if (!network || !CrosLibrary::Get()->EnsureLoaded()) { ShowError(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY); } else if (!network->Connected()) { ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED); } else { ShowError(IDS_LOGIN_ERROR_AUTHENTICATING); // TODO(someone): get |error| onto the UI somehow? } login_in_process_ = false; sign_in_button_->SetEnabled(true); create_account_link_->SetEnabled(true); SetPassword(std::string()); password_field_->RequestFocus(); } void LoginManagerView::OnLoginSuccess(const std::string& username, const std::string& credentials) { // TODO(cmasone): something sensible if errors occur. if (observer_) { observer_->OnExit(ScreenObserver::LOGIN_SIGN_IN_SELECTED); } LoginUtils::Get()->CompleteLogin(username, credentials); } void LoginManagerView::ShowError(int error_id) { error_id_ = error_id; // Close bubble before showing anything new. // bubble_ will be set to NULL in callback. if (bubble_) bubble_->Close(); if (error_id_ != -1) { std::wstring error_text = l10n_util::GetString(error_id_); gfx::Rect screen_bounds(password_field_->bounds()); gfx::Point origin(screen_bounds.origin()); views::View::ConvertPointToScreen(this, &origin); screen_bounds.set_origin(origin); bubble_ = MessageBubble::Show( GetWidget(), screen_bounds, BubbleBorder::LEFT_TOP, ResourceBundle::GetSharedInstance().GetBitmapNamed(IDR_WARNING), error_text, this); } } bool LoginManagerView::HandleKeystroke(views::Textfield* s, const views::Textfield::Keystroke& keystroke) { if (!CrosLibrary::Get()->EnsureLoaded()) return false; if (login_in_process_) return false; if (keystroke.GetKeyboardCode() == base::VKEY_TAB) { if (username_field_->text().length() != 0) { std::string username = UTF16ToUTF8(username_field_->text()); if (username.find('@') == std::string::npos) { username += kDefaultDomain; username_field_->SetText(UTF8ToUTF16(username)); } return false; } } else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) { Login(); // Return true so that processing ends return true; } else if (error_id_ != -1) { // Clear all previous error messages. ShowError(-1); return false; } // Return false so that processing does not end return false; } } // namespace chromeos <|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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_, L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(window_->browser()); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripta panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, DISABLED_TestEnableScriptsTab) { RunTest("testEnableScriptsTab", kDebuggerTestPage); } } // namespace <commit_msg>DevTools: fix debugger test, reenable debugger and resources tests.<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 "base/command_line.h" #include "chrome/browser/browser.h" #include "chrome/browser/debugger/devtools_client_host.h" #include "chrome/browser/debugger/devtools_manager.h" #include "chrome/browser/debugger/devtools_window.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" namespace { // Used to block until a dev tools client window's browser is closed. class BrowserClosedObserver : public NotificationObserver { public: BrowserClosedObserver(Browser* browser) { registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(browser)); ui_test_utils::RunMessageLoop(); } virtual void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { MessageLoopForUI::current()->Quit(); } private: NotificationRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(BrowserClosedObserver); }; // The delay waited in some cases where we don't have a notifications for an // action we take. const int kActionDelayMs = 500; const wchar_t kSimplePage[] = L"files/devtools/simple_page.html"; const wchar_t kJsPage[] = L"files/devtools/js_page.html"; const wchar_t kDebuggerTestPage[] = L"files/devtools/debugger_test_page.html"; class DevToolsSanityTest : public InProcessBrowserTest { public: DevToolsSanityTest() { set_show_window(true); EnableDOMAutomation(); } protected: void RunTest(const std::string& test_name, const std::wstring& test_page) { OpenDevToolsWindow(test_page); std::string result; ASSERT_TRUE( ui_test_utils::ExecuteJavaScriptAndExtractString( client_contents_, L"", UTF8ToWide(StringPrintf("uiTests.runTest('%s')", test_name.c_str())), &result)); EXPECT_EQ("[OK]", result); CloseDevToolsWindow(); } void OpenDevToolsWindow(const std::wstring& test_page) { HTTPTestServer* server = StartHTTPServer(); GURL url = server->TestServerPageW(test_page); ui_test_utils::NavigateToURL(browser(), url); TabContents* tab = browser()->GetTabContentsAt(0); inspected_rvh_ = tab->render_view_host(); DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->OpenDevToolsWindow(inspected_rvh_); DevToolsClientHost* client_host = devtools_manager->GetDevToolsClientHostFor(inspected_rvh_); window_ = client_host->AsDevToolsWindow(); RenderViewHost* client_rvh = window_->GetRenderViewHost(); client_contents_ = client_rvh->delegate()->GetAsTabContents(); ui_test_utils::WaitForNavigation(&client_contents_->controller()); } void CloseDevToolsWindow() { DevToolsManager* devtools_manager = DevToolsManager::GetInstance(); devtools_manager->UnregisterDevToolsClientHostFor(inspected_rvh_); BrowserClosedObserver close_observer(window_->browser()); } TabContents* client_contents_; DevToolsWindow* window_; RenderViewHost* inspected_rvh_; }; // WebInspector opens. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestHostIsPresent) { RunTest("testHostIsPresent", kSimplePage); } // Tests elements panel basics. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestElementsTreeRoot) { RunTest("testElementsTreeRoot", kSimplePage); } // Tests main resource load. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestMainResource) { RunTest("testMainResource", kSimplePage); } // Tests resources panel enabling. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestEnableResourcesTab) { RunTest("testEnableResourcesTab", kSimplePage); } // Tests profiler panel. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestProfilerTab) { RunTest("testProfilerTab", kJsPage); } // Tests scripts panel showing. IN_PROC_BROWSER_TEST_F(DevToolsSanityTest, TestShowScriptsTab) { RunTest("testShowScriptsTab", kDebuggerTestPage); } } // namespace <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs FLAKY_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #if defined(OS_MAC) #define MAYBE_Tabs FAILS_Tabs #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <commit_msg>Whoops. Try again to disable a failing test.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/browser.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/pref_names.h" // Tabs is flaky on chromeos and linux views build. // http://crbug.com/48920 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_Tabs FLAKY_Tabs #elif defined(OS_MACOSX) // Tabs appears to timeout, or maybe crash on mac. // http://crbug.com/53779 #define MAYBE_Tabs FAILS_Tabs #else #define MAYBE_Tabs Tabs #endif // TabOnRemoved is flaky on chromeos and linux views debug build. // http://crbug.com/49258 #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) && !defined(NDEBUG) #define MAYBE_TabOnRemoved FLAKY_TabOnRemoved #else #define MAYBE_TabOnRemoved TabOnRemoved #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Tabs) { ASSERT_TRUE(test_server()->Start()); // The test creates a tab and checks that the URL of the new tab // is that of the new tab page. Make sure the pref that controls // this is set. browser()->profile()->GetPrefs()->SetBoolean( prefs::kHomePageIsNewTabPage, true); ASSERT_TRUE(RunExtensionTest("tabs/basics")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabGetCurrent) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/get_current")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabConnect) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/connect")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_TabOnRemoved) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_removed")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, CaptureVisibleTabJpeg) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_jpeg.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_CaptureVisibleTabPng) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionSubtest("tabs/capture_visible_tab", "test_png.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsOnUpdated) { ASSERT_TRUE(test_server()->Start()); ASSERT_TRUE(RunExtensionTest("tabs/on_updated")) << message_; } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (C) 2013 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "categorizedaccountmodel.h" #include "accountlistmodel.h" CategorizedAccountModel* CategorizedAccountModel::m_spInstance = nullptr; CategorizedAccountModel* CategorizedAccountModel::instance() { if (!m_spInstance) m_spInstance = new CategorizedAccountModel(); return m_spInstance; } CategorizedAccountModel::CategorizedAccountModel(QObject* parent) : QAbstractItemModel(parent) { connect(AccountListModel::instance(),SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(slotDataChanged(QModelIndex,QModelIndex))); connect(AccountListModel::instance(),SIGNAL(layoutChanged()),this,SLOT(slotLayoutchanged())); } CategorizedAccountModel::~CategorizedAccountModel() { } QModelIndex CategorizedAccountModel::mapToSource(const QModelIndex& idx) const { if (!idx.isValid() || !idx.parent().isValid()) return QModelIndex(); switch (idx.parent().row()) { case Categories::IP2IP: return AccountListModel::instance()->index(0,0); break; case Categories::SERVER: return AccountListModel::instance()->index(idx.row()+1,0); break; }; return QModelIndex(); } QVariant CategorizedAccountModel::data(const QModelIndex& index, int role ) const { if (!index.isValid()) return QVariant(); else if (index.parent().isValid()) { return mapToSource(index).data(role); } else { switch (role) { case Qt::DisplayRole: if (index.row() == Categories::IP2IP) return tr("Peer to peer"); else return tr("Server"); }; } return QVariant(); } int CategorizedAccountModel::rowCount(const QModelIndex& parent ) const { if (parent.parent().isValid()) return 0; else if (parent.isValid()) { if (parent.row() == 1) return 1; return AccountListModel::instance()->size()-1; } return 2; } int CategorizedAccountModel::columnCount(const QModelIndex& parent ) const { Q_UNUSED(parent) return 1; } QModelIndex CategorizedAccountModel::parent(const QModelIndex& idx) const { switch (idx.internalId()) { case 0: return QModelIndex(); case 1: return createIndex((int)Categories::SERVER,0,static_cast<quint32>(0)); case 2: return createIndex((int)Categories::IP2IP,0,static_cast<quint32>(0)); }; return QModelIndex(); } QModelIndex CategorizedAccountModel::index( int row, int column, const QModelIndex& parent ) const { if (parent.isValid() && parent.internalId() == 0) { if (row >= rowCount(parent)) return QModelIndex(); switch (parent.row()) { case Categories::SERVER: return createIndex(row,column,static_cast<quint32>(1)); break; case Categories::IP2IP: return createIndex(row,column,static_cast<quint32>(2)); break; }; } else if (parent.isValid()) return QModelIndex(); return createIndex(row,column,static_cast<quint32>(0)); } Qt::ItemFlags CategorizedAccountModel::flags(const QModelIndex& index ) const { if (index.parent().isValid()) return QAbstractItemModel::flags(index) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled; } bool CategorizedAccountModel::setData(const QModelIndex& index, const QVariant &value, int role ) { if (!index.isValid()) return false; else if (index.parent().isValid()) { return AccountListModel::instance()->setData(mapToSource(index),value,role); } return false; } QVariant CategorizedAccountModel::headerData(int section, Qt::Orientation orientation, int role ) const { Q_UNUSED(section) Q_UNUSED(orientation) if (role == Qt::DisplayRole) return tr("Accounts"); return QVariant(); } void CategorizedAccountModel::slotDataChanged(const QModelIndex& tl,const QModelIndex& br) { Q_UNUSED(tl) Q_UNUSED(br) emit layoutChanged(); } void CategorizedAccountModel::slotLayoutchanged() { emit layoutChanged(); } <commit_msg>[ #31822 ] Use internal pointer instead of internal ID, bypass Qt5 bug on 64 bit GCC<commit_after>/**************************************************************************** * Copyright (C) 2013 by Savoir-Faire Linux * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "categorizedaccountmodel.h" #include "accountlistmodel.h" CategorizedAccountModel* CategorizedAccountModel::m_spInstance = nullptr; namespace { const int TYPE_TOP_LEVEL = 0; const int TYPE_IP2IP = 2; const int TYPE_SERVER = 1; } CategorizedAccountModel* CategorizedAccountModel::instance() { if (!m_spInstance) m_spInstance = new CategorizedAccountModel(); return m_spInstance; } CategorizedAccountModel::CategorizedAccountModel(QObject* parent) : QAbstractItemModel(parent) { connect(AccountListModel::instance(),SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(slotDataChanged(QModelIndex,QModelIndex))); connect(AccountListModel::instance(),SIGNAL(layoutChanged()),this,SLOT(slotLayoutchanged())); } CategorizedAccountModel::~CategorizedAccountModel() { } QModelIndex CategorizedAccountModel::mapToSource(const QModelIndex& idx) const { if (!idx.isValid() || !idx.parent().isValid()) return QModelIndex(); switch (idx.parent().row()) { case Categories::IP2IP: return AccountListModel::instance()->index(0,0); break; case Categories::SERVER: return AccountListModel::instance()->index(idx.row()+1,0); break; }; return QModelIndex(); } QVariant CategorizedAccountModel::data(const QModelIndex& index, int role ) const { if (!index.isValid()) return QVariant(); else if (index.parent().isValid()) { return mapToSource(index).data(role); } else { switch (role) { case Qt::DisplayRole: if (index.row() == Categories::IP2IP) return tr("Peer to peer"); else return tr("Server"); }; } return QVariant(); } int CategorizedAccountModel::rowCount(const QModelIndex& parent ) const { if (parent.parent().isValid()) return 0; else if (parent.isValid()) { if (parent.row() == 1) return 1; return AccountListModel::instance()->size()-1; } return 2; } int CategorizedAccountModel::columnCount(const QModelIndex& parent ) const { Q_UNUSED(parent) return 1; } QModelIndex CategorizedAccountModel::parent(const QModelIndex& idx) const { switch (*static_cast<int*>(idx.internalPointer())) { case TYPE_TOP_LEVEL: return QModelIndex(); case TYPE_SERVER: return createIndex((int)Categories::SERVER,0,(void*)&TYPE_TOP_LEVEL); case TYPE_IP2IP: return createIndex((int)Categories::IP2IP,0,(void*)&TYPE_TOP_LEVEL); }; return QModelIndex(); } QModelIndex CategorizedAccountModel::index( int row, int column, const QModelIndex& parent ) const { if (parent.isValid() && *static_cast<int*>(parent.internalPointer()) == 0) { if (row >= rowCount(parent)) return QModelIndex(); switch (parent.row()) { case Categories::SERVER: return createIndex(row,column,(void*)&TYPE_SERVER); break; case Categories::IP2IP: return createIndex(row,column,(void*)&TYPE_IP2IP); break; }; } else if (parent.isValid()) return QModelIndex(); return createIndex(row,column,(void*)&TYPE_TOP_LEVEL); } Qt::ItemFlags CategorizedAccountModel::flags(const QModelIndex& index ) const { if (index.parent().isValid()) return QAbstractItemModel::flags(index) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled; } bool CategorizedAccountModel::setData(const QModelIndex& index, const QVariant &value, int role ) { if (!index.isValid()) return false; else if (index.parent().isValid()) { return AccountListModel::instance()->setData(mapToSource(index),value,role); } return false; } QVariant CategorizedAccountModel::headerData(int section, Qt::Orientation orientation, int role ) const { Q_UNUSED(section) Q_UNUSED(orientation) if (role == Qt::DisplayRole) return tr("Accounts"); return QVariant(); } void CategorizedAccountModel::slotDataChanged(const QModelIndex& tl,const QModelIndex& br) { Q_UNUSED(tl) Q_UNUSED(br) emit layoutChanged(); } void CategorizedAccountModel::slotLayoutchanged() { emit layoutChanged(); } <|endoftext|>
<commit_before>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s #include "Inputs/system-header-simulator-cxx.h" #if !LEAKS // expected-no-diagnostics #endif void *allocator(std::size_t size); void *operator new[](std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); } void *operator new(std::size_t, double d); class C { public: void *operator new(std::size_t); }; void testNewMethod() { void *p1 = C::operator new(0); // no warn C *p2 = new C; // no warn C *c3 = ::new C; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'c3'}} #endif void testOpNewArray() { void *p = operator new[](0); // call is inlined, no warn } void testNewExprArray() { int *p = new int[0]; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom non-placement operators void testOpNew() { void *p = operator new(0); // call is inlined, no warn } void testNewExpr() { int *p = new int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom NoThrow placement operators void testOpNewNoThrow() { void *p = operator new(0, std::nothrow); // call is inlined, no warn } #if LEAKS // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif void testNewExprNoThrow() { int *p = new(std::nothrow) int; } #if LEAKS // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom placement operators void testOpNewPlacement() { void *p = operator new(0, 0.1); // no warn } void testNewExprPlacement() { int *p = new(0.1) int; // no warn } <commit_msg>[analyzer] NFC: operator new: Fix new(nothrow) definition in tests.<commit_after>// RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -DLEAKS=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DALLOCATOR_INLINING=1 -fblocks -verify %s // RUN: %clang_analyze_cc1 -analyzer-checker=core,cplusplus.NewDelete,cplusplus.NewDeleteLeaks,unix.Malloc -std=c++11 -analyzer-config c++-allocator-inlining=true -DLEAKS=1 -DALLOCATOR_INLINING=1 -fblocks -verify %s #include "Inputs/system-header-simulator-cxx.h" #if !(LEAKS && !ALLOCATOR_INLINING) // expected-no-diagnostics #endif void *allocator(std::size_t size); void *operator new[](std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size) throw() { return allocator(size); } void *operator new(std::size_t size, const std::nothrow_t &nothrow) throw() { return allocator(size); } void *operator new(std::size_t, double d); class C { public: void *operator new(std::size_t); }; void testNewMethod() { void *p1 = C::operator new(0); // no warn C *p2 = new C; // no warn C *c3 = ::new C; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'c3'}} #endif void testOpNewArray() { void *p = operator new[](0); // call is inlined, no warn } void testNewExprArray() { int *p = new int[0]; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom non-placement operators void testOpNew() { void *p = operator new(0); // call is inlined, no warn } void testNewExpr() { int *p = new int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom NoThrow placement operators void testOpNewNoThrow() { void *p = operator new(0, std::nothrow); // call is inlined, no warn } void testNewExprNoThrow() { int *p = new(std::nothrow) int; } #if LEAKS && !ALLOCATOR_INLINING // expected-warning@-2{{Potential leak of memory pointed to by 'p'}} #endif //----- Custom placement operators void testOpNewPlacement() { void *p = operator new(0, 0.1); // no warn } void testNewExprPlacement() { int *p = new(0.1) int; // no warn } <|endoftext|>
<commit_before>// Test header and library paths when Clang is used with Android standalone // toolchain. // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target arm-linux-androideabi \ // RUN: -B%S/Inputs/basic_android_tree \ // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \ // RUN: | FileCheck %s // CHECK: {{.*}}clang{{(.exe)?}}" "-cc1" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3/arm-linux-androideabi" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/include" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/usr/include" // CHECK: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3/../../../../arm-linux-androideabi/lib" // CHECK: "-L{{.*}}/sysroot/usr/lib" <commit_msg>test/Driver/android-standalone.cpp: Fix test failure on Windowns, again.<commit_after>// Test header and library paths when Clang is used with Android standalone // toolchain. // // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \ // RUN: -target arm-linux-androideabi \ // RUN: -B%S/Inputs/basic_android_tree \ // RUN: --sysroot=%S/Inputs/basic_android_tree/sysroot \ // RUN: | FileCheck %s // CHECK: {{.*}}clang{{.*}}" "-cc1" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3" // CHECK: "-internal-isystem" "{{.*}}/arm-linux-androideabi/include/c++/4.4.3/arm-linux-androideabi" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/include" // CHECK: "-internal-externc-isystem" "{{.*}}/sysroot/usr/include" // CHECK: "{{.*}}ld{{(.exe)?}}" "--sysroot=[[SYSROOT:[^"]+]]" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3" // CHECK: "-L{{.*}}/lib/gcc/arm-linux-androideabi/4.4.3/../../../../arm-linux-androideabi/lib" // CHECK: "-L{{.*}}/sysroot/usr/lib" <|endoftext|>
<commit_before>// // App.cpp - Main application class for VTBuilder // // Copyright (c) 2001-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "Frame.h" #include "BuilderView.h" #include "vtdata/vtLog.h" #include "vtui/Helper.h" #include "gdal_priv.h" #include "App.h" #define HEAPBUSTER 0 #if HEAPBUSTER #include "../HeapBuster/HeapBuster.h" #endif IMPLEMENT_APP(BuilderApp) void BuilderApp::Args(int argc, wxChar **argv) { for (int i = 0; i < argc; i++) { wxString2 str = argv[i]; const char *cstr = str.mb_str(); if (!strncmp(cstr, "-locale=", 8)) m_locale_name = cstr+8; } } class LogCatcher : public wxLog { void DoLogString(const wxChar *szString, time_t t) { VTLOG(" wxLog: "); VTLOG(szString); VTLOG("\n"); } }; bool BuilderApp::OnInit() { #if WIN32 && defined(_MSC_VER) && DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif g_Log._StartLog("debug.txt"); VTLOG(APPNAME "\nBuild:"); #if DEBUG VTLOG(" Debug"); #else VTLOG(" Release"); #endif #if UNICODE VTLOG(" Unicode"); #endif VTLOG("\n"); #if WIN32 VTLOG(" Running on: "); LogWindowsVersion(); #endif // Redirect the wxWindows log messages to our own logging stream wxLog *logger = new LogCatcher(); wxLog::SetActiveTarget(logger); Args(argc, argv); SetupLocale(); VTLOG(" Initializing GDAL."); g_GDALWrapper.GuessDataPaths(); g_GDALWrapper.RequestGDALFormats(); // Fill list of layer type names if (vtLayer::LayerTypeNames.IsEmpty()) { // These must correspond to the order of the LayerType enum! vtLayer::LayerTypeNames.Add(_("Raw")); vtLayer::LayerTypeNames.Add(_("Elevation")); vtLayer::LayerTypeNames.Add(_("Image")); vtLayer::LayerTypeNames.Add(_("Road")); vtLayer::LayerTypeNames.Add(_("Structure")); vtLayer::LayerTypeNames.Add(_("Water")); vtLayer::LayerTypeNames.Add(_("Vegetation")); vtLayer::LayerTypeNames.Add(_("Transit")); vtLayer::LayerTypeNames.Add(_("Utility")); } VTLOG("Testing ability to allocate a frame object.\n"); wxFrame *frametest = new wxFrame(NULL, -1, _T("Title")); delete frametest; VTLOG(" Creating Main Frame Window,"); wxString2 title = _T(APPNAME); VTLOG(" title '%s'\n", title.mb_str()); MainFrame* frame = new MainFrame((wxFrame *) NULL, title, wxPoint(50, 50), wxSize(900, 500)); VTLOG(" Setting up the UI.\n"); frame->SetupUI(); VTLOG(" Showing the frame.\n"); frame->Show(TRUE); SetTopWindow(frame); VTLOG(" GDAL-supported formats:"); GDALDriverManager *poDM = GetGDALDriverManager(); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { if ((iDriver % 13) == 0) VTLOG("\n "); GDALDriver *poDriver = poDM->GetDriver( iDriver ); const char *name = poDriver->GetDescription(); VTLOG("%s ", name); } VTLOG("\n"); // Stuff for testing // wxString str("E:/Earth Imagery/NASA BlueMarble/MOD09A1.E.interpol.cyl.retouched.topo.3x00054x00027-N.bmp"); // wxString str("E:/Data-USA/Elevation/crater_0513.bt"); /* vtLayer *pLayer = frame->ImportImage(str); bool success = frame->AddLayerWithCheck(pLayer, true); frame->LoadLayer(str); */ // frame->LoadProject("E:/Locations/Romania/giurgiu.vtb"); // frame->ImportDataFromFile(LT_ELEVATION, "E:/Earth/NOAA Globe/g10g.hdr", false); // wxString2 str("E:/Data-USA/Terrains/Hawai`i.xml"); // frame->LoadLayer(str); // wxString fname("E:/VTP User's Data/Hangzhou/Data/BuildingData/a-bldgs-18dec-subset1.vtst"); // frame->LoadLayer(fname); // vtStructureLayer *pSL = frame->GetActiveStructureLayer(); // vtStructure *str = pSL->GetAt(0); // str->Select(true); // pSL->EditBuildingProperties(); // wxString fname("E:/Locations-USA/Hawai`i Island Data/DRG/O19154F8.TIF"); // frame->ImportDataFromFile(LT_IMAGE, fname, true); // frame->LoadProject("E:/Locations-USA/Hawai`i Island Content/Honoka`a/latest_temp.vtb"); // vtString fname = "E:/Locations-Hawai'i/Hawai`i Island Data/SDTS-DLG/waipahu_HI/transportation/852867.RR.sdts.tar.gz"; // frame->ImportDataFromArchive(LT_ROAD, fname, true); frame->ZoomAll(); #if HEAPBUSTER // Pull in the heap buster g_HeapBusterDummy = -1; #endif return TRUE; } int BuilderApp::OnExit() { VTLOG("App Exit\n"); return wxApp::OnExit(); } void BuilderApp::SetupLocale() { wxLog::SetVerbose(true); // Locale stuff int lang = wxLANGUAGE_DEFAULT; int default_lang = m_locale.GetSystemLanguage(); const wxLanguageInfo *info = wxLocale::GetLanguageInfo(default_lang); VTLOG("Default language: %d (%s)\n", default_lang, info->Description.mb_str()); // After wx2.4.2, wxWidgets looks in the application's directory for // locale catalogs, not the current directory. Here we force it to // look in the current directory as well. wxString cwd = wxGetCwd(); m_locale.AddCatalogLookupPathPrefix(cwd); bool bSuccess=false; if (m_locale_name != "") { VTLOG("Looking up language: %s\n", (const char *) m_locale_name); lang = GetLangFromName(wxString2(m_locale_name)); if (lang == wxLANGUAGE_UNKNOWN) { VTLOG(" Unknown, falling back on default language.\n"); lang = wxLANGUAGE_DEFAULT; } else { info = m_locale.GetLanguageInfo(lang); VTLOG("Initializing locale to language %d, Canonical name '%s', Description: '%s':\n", lang, info->CanonicalName.mb_str(), info->Description.mb_str()); bSuccess = m_locale.Init(lang, wxLOCALE_CONV_ENCODING); } } if (lang == wxLANGUAGE_DEFAULT) { VTLOG("Initializing locale to default language:\n"); bSuccess = m_locale.Init(wxLANGUAGE_DEFAULT, wxLOCALE_CONV_ENCODING); if (bSuccess) lang = default_lang; } if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" failed.\n"); if (lang != wxLANGUAGE_ENGLISH_US) { VTLOG("Attempting to load the 'VTBuilder.mo' catalog for the current locale.\n"); bSuccess = m_locale.AddCatalog(wxT("VTBuilder")); if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" not found.\n"); VTLOG("\n"); } // Test it // wxString test = _("&File"); wxLog::SetVerbose(false); } <commit_msg>moved initial zoomall until after first idle<commit_after>// // App.cpp - Main application class for VTBuilder // // Copyright (c) 2001-2005 Virtual Terrain Project // Free for all uses, see license.txt for details. // // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "Frame.h" #include "BuilderView.h" #include "vtdata/vtLog.h" #include "vtui/Helper.h" #include "gdal_priv.h" #include "App.h" #define HEAPBUSTER 0 #if HEAPBUSTER #include "../HeapBuster/HeapBuster.h" #endif IMPLEMENT_APP(BuilderApp) void BuilderApp::Args(int argc, wxChar **argv) { for (int i = 0; i < argc; i++) { wxString2 str = argv[i]; const char *cstr = str.mb_str(); if (!strncmp(cstr, "-locale=", 8)) m_locale_name = cstr+8; } } class LogCatcher : public wxLog { void DoLogString(const wxChar *szString, time_t t) { VTLOG(" wxLog: "); VTLOG(szString); VTLOG("\n"); } }; bool BuilderApp::OnInit() { #if WIN32 && defined(_MSC_VER) && DEBUG _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif g_Log._StartLog("debug.txt"); VTLOG(APPNAME "\nBuild:"); #if DEBUG VTLOG(" Debug"); #else VTLOG(" Release"); #endif #if UNICODE VTLOG(" Unicode"); #endif VTLOG("\n"); #if WIN32 VTLOG(" Running on: "); LogWindowsVersion(); #endif // Redirect the wxWindows log messages to our own logging stream wxLog *logger = new LogCatcher(); wxLog::SetActiveTarget(logger); Args(argc, argv); SetupLocale(); VTLOG(" Initializing GDAL."); g_GDALWrapper.GuessDataPaths(); g_GDALWrapper.RequestGDALFormats(); // Fill list of layer type names if (vtLayer::LayerTypeNames.IsEmpty()) { // These must correspond to the order of the LayerType enum! vtLayer::LayerTypeNames.Add(_("Raw")); vtLayer::LayerTypeNames.Add(_("Elevation")); vtLayer::LayerTypeNames.Add(_("Image")); vtLayer::LayerTypeNames.Add(_("Road")); vtLayer::LayerTypeNames.Add(_("Structure")); vtLayer::LayerTypeNames.Add(_("Water")); vtLayer::LayerTypeNames.Add(_("Vegetation")); vtLayer::LayerTypeNames.Add(_("Transit")); vtLayer::LayerTypeNames.Add(_("Utility")); } VTLOG("Testing ability to allocate a frame object.\n"); wxFrame *frametest = new wxFrame(NULL, -1, _T("Title")); delete frametest; VTLOG(" Creating Main Frame Window,"); wxString2 title = _T(APPNAME); VTLOG(" title '%s'\n", title.mb_str()); MainFrame* frame = new MainFrame((wxFrame *) NULL, title, wxPoint(50, 50), wxSize(900, 500)); VTLOG(" Setting up the UI.\n"); frame->SetupUI(); VTLOG(" Showing the frame.\n"); frame->Show(TRUE); SetTopWindow(frame); VTLOG(" GDAL-supported formats:"); GDALDriverManager *poDM = GetGDALDriverManager(); for( int iDriver = 0; iDriver < poDM->GetDriverCount(); iDriver++ ) { if ((iDriver % 13) == 0) VTLOG("\n "); GDALDriver *poDriver = poDM->GetDriver( iDriver ); const char *name = poDriver->GetDescription(); VTLOG("%s ", name); } VTLOG("\n"); // Stuff for testing // wxString str("E:/Earth Imagery/NASA BlueMarble/MOD09A1.E.interpol.cyl.retouched.topo.3x00054x00027-N.bmp"); // wxString str("E:/Data-USA/Elevation/crater_0513.bt"); /* vtLayer *pLayer = frame->ImportImage(str); bool success = frame->AddLayerWithCheck(pLayer, true); frame->LoadLayer(str); */ // frame->LoadProject("E:/Locations/Romania/giurgiu.vtb"); // frame->ImportDataFromFile(LT_ELEVATION, "E:/Earth/NOAA Globe/g10g.hdr", false); // wxString2 str("E:/Data-USA/Terrains/Hawai`i.xml"); // frame->LoadLayer(str); // wxString fname("E:/VTP User's Data/Hangzhou/Data/BuildingData/a-bldgs-18dec-subset1.vtst"); // frame->LoadLayer(fname); // vtStructureLayer *pSL = frame->GetActiveStructureLayer(); // vtStructure *str = pSL->GetAt(0); // str->Select(true); // pSL->EditBuildingProperties(); // wxString fname("E:/Locations-USA/Hawai`i Island Data/DRG/O19154F8.TIF"); // frame->ImportDataFromFile(LT_IMAGE, fname, true); // frame->LoadProject("E:/Locations-USA/Hawai`i Island Content/Honoka`a/latest_temp.vtb"); // vtString fname = "E:/Locations-Hawai'i/Hawai`i Island Data/SDTS-DLG/waipahu_HI/transportation/852867.RR.sdts.tar.gz"; // frame->ImportDataFromArchive(LT_ROAD, fname, true); #if HEAPBUSTER // Pull in the heap buster g_HeapBusterDummy = -1; #endif return TRUE; } int BuilderApp::OnExit() { VTLOG("App Exit\n"); return wxApp::OnExit(); } void BuilderApp::SetupLocale() { wxLog::SetVerbose(true); // Locale stuff int lang = wxLANGUAGE_DEFAULT; int default_lang = m_locale.GetSystemLanguage(); const wxLanguageInfo *info = wxLocale::GetLanguageInfo(default_lang); VTLOG("Default language: %d (%s)\n", default_lang, info->Description.mb_str()); // After wx2.4.2, wxWidgets looks in the application's directory for // locale catalogs, not the current directory. Here we force it to // look in the current directory as well. wxString cwd = wxGetCwd(); m_locale.AddCatalogLookupPathPrefix(cwd); bool bSuccess=false; if (m_locale_name != "") { VTLOG("Looking up language: %s\n", (const char *) m_locale_name); lang = GetLangFromName(wxString2(m_locale_name)); if (lang == wxLANGUAGE_UNKNOWN) { VTLOG(" Unknown, falling back on default language.\n"); lang = wxLANGUAGE_DEFAULT; } else { info = m_locale.GetLanguageInfo(lang); VTLOG("Initializing locale to language %d, Canonical name '%s', Description: '%s':\n", lang, info->CanonicalName.mb_str(), info->Description.mb_str()); bSuccess = m_locale.Init(lang, wxLOCALE_CONV_ENCODING); } } if (lang == wxLANGUAGE_DEFAULT) { VTLOG("Initializing locale to default language:\n"); bSuccess = m_locale.Init(wxLANGUAGE_DEFAULT, wxLOCALE_CONV_ENCODING); if (bSuccess) lang = default_lang; } if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" failed.\n"); if (lang != wxLANGUAGE_ENGLISH_US) { VTLOG("Attempting to load the 'VTBuilder.mo' catalog for the current locale.\n"); bSuccess = m_locale.AddCatalog(wxT("VTBuilder")); if (bSuccess) VTLOG(" succeeded.\n"); else VTLOG(" not found.\n"); VTLOG("\n"); } // Test it // wxString test = _("&File"); wxLog::SetVerbose(false); } <|endoftext|>
<commit_before>#include "regionmatrix.h" #include <string.h> #include "regiondataraw.h" #include "regiondatasplit.h" #include "regionmatrixproxy.h" using namespace petabricks; std::map<uint16_t, RegionDataIPtr> RegionMatrix::movingBuffer; pthread_mutex_t RegionMatrix::movingBuffer_mux; RegionMatrix::RegionMatrix(int dimensions, IndexT* size) { RegionDataIPtr regionData = new RegionDataRaw(dimensions, size); _regionHandler = new RegionHandler(regionData); _D = dimensions; _size = new IndexT[_D]; memcpy(_size, size, sizeof(IndexT) * _D); _splitOffset = new IndexT[_D]; memset(_splitOffset, 0, sizeof(IndexT) * _D); _numSliceDimensions = 0; _sliceDimensions = 0; _slicePositions = 0; pthread_mutex_init(&RegionMatrix::movingBuffer_mux, NULL); } /* RegionMatrix::RegionMatrix(RegionDataIPtr regionData) { _regionHandler = new RegionHandler(regionData); _D = _regionHandler->dimensions(); _size = new IndexT[_D]; memcpy(_size, regionData->size(), sizeof(IndexT) * _D); _splitOffset = new IndexT[_D]; memset(_splitOffset, 0, sizeof(IndexT) * _D); _numSliceDimensions = 0; _sliceDimensions = 0; _slicePositions = 0; } */ // // Called by split & slice // RegionMatrix::RegionMatrix(RegionHandlerPtr handler, int dimensions, IndexT* size, IndexT* splitOffset, int numSliceDimensions, int* sliceDimensions, IndexT* slicePositions) { _regionHandler = handler; _D = dimensions; _size = size; _splitOffset = splitOffset; _numSliceDimensions = numSliceDimensions; if (_numSliceDimensions > 0) { _sliceDimensions = sliceDimensions; _slicePositions = slicePositions; } } RegionMatrix::~RegionMatrix() { delete [] _size; delete [] _splitOffset; delete [] _sliceDimensions; delete [] _slicePositions; } void RegionMatrix::splitData(IndexT* splitSize) { acquireRegionData(); RegionDataIPtr newRegionData = new RegionDataSplit((RegionDataRaw*)_regionData.asPtr(), splitSize); releaseRegionData(); _regionHandler->updateRegionData(newRegionData); } void RegionMatrix::allocData() { acquireRegionData(); _regionData->allocData(); releaseRegionData(); } void RegionMatrix::importDataFromFile(char* filename) { // TODO: perf: move the import to regionDataRaw this->acquireRegionData(); _regionData->allocData(); MatrixIO* matrixio = new MatrixIO(filename, "r"); MatrixReaderScratch o = matrixio->readToMatrixReaderScratch(); ElementT* data = o.storage->data(); IndexT* coord = new IndexT[_D]; memset(coord, 0, sizeof(IndexT) * _D); int i = 0; while (true) { this->writeCell(coord, data[i]); i++; int z = this->incCoord(coord); if (z == -1) { break; } } this->releaseRegionData(); delete [] coord; delete matrixio; } ElementT RegionMatrix::readCell(const IndexT* coord) { IndexT* rd_coord = this->getRegionDataCoord(coord); ElementT elmt = _regionData->readCell(rd_coord); delete [] rd_coord; return elmt; } void RegionMatrix::writeCell(const IndexT* coord, ElementT value) { IndexT* rd_coord = this->getRegionDataCoord(coord); _regionData->writeCell(rd_coord, value); delete [] rd_coord; } int RegionMatrix::dimensions() { return _D; } IndexT* RegionMatrix::size() { return _size; } RegionMatrixPtr RegionMatrix::splitRegion(IndexT* offset, IndexT* size) { IndexT* offset_new = this->getRegionDataCoord(offset); IndexT* size_copy = new IndexT[_D]; memcpy(size_copy, size, sizeof(IndexT) * _D); int* sliceDimensions = new int[_numSliceDimensions]; memcpy(sliceDimensions, _sliceDimensions, sizeof(int) * _numSliceDimensions); IndexT* slicePositions = new IndexT[_numSliceDimensions]; memcpy(slicePositions, _slicePositions, sizeof(IndexT) * _numSliceDimensions); return new RegionMatrix(_regionHandler, _D, size_copy, offset_new, _numSliceDimensions, sliceDimensions, slicePositions); } RegionMatrixPtr RegionMatrix::sliceRegion(int d, IndexT pos){ int dimensions = _D - 1; IndexT* size = new IndexT[dimensions]; memcpy(size, _size, sizeof(IndexT) * d); memcpy(size + d, _size + d + 1, sizeof(IndexT) * (dimensions - d)); IndexT* offset = new IndexT[dimensions]; memcpy(offset, _splitOffset, sizeof(IndexT) * d); memcpy(offset + d, _splitOffset + d + 1, sizeof(IndexT) * (dimensions - d)); // maintain ordered array of _sliceDimensions + update d as necessary int numSliceDimensions = _numSliceDimensions + 1; int* sliceDimensions = new int[numSliceDimensions]; IndexT* slicePositions = new IndexT[numSliceDimensions]; if (_numSliceDimensions == 0) { sliceDimensions[0] = d; slicePositions[0] = pos + _splitOffset[d]; } else { bool isAddedNewD = false; for (int i = 0; i < numSliceDimensions; i++) { if (isAddedNewD) { sliceDimensions[i] = _sliceDimensions[i-1]; slicePositions[i] = _slicePositions[i-1]; } else if (d >= _sliceDimensions[i]) { sliceDimensions[i] = _sliceDimensions[i]; slicePositions[i] = _slicePositions[i]; d++; } else { sliceDimensions[i] = d; slicePositions[i] = pos + _splitOffset[d]; isAddedNewD = true; } } } return new RegionMatrix(_regionHandler, dimensions, size, offset, numSliceDimensions, sliceDimensions, slicePositions); } void RegionMatrix::moveToRemoteHost(RemoteHostPtr host, uint16_t movingBufferIndex) { RegionMatrixProxyPtr proxy = new RegionMatrixProxy(this->getRegionHandler()); RemoteObjectPtr local = proxy->genLocal(); // InitialMsg RegionDataRemoteMessage::InitialMessage* msg = new RegionDataRemoteMessage::InitialMessage(); msg->dimensions = _D; msg->movingBufferIndex = movingBufferIndex; memcpy(msg->size, _size, sizeof(msg->size)); int len = (sizeof msg) + sizeof(msg->size); host->createRemoteObject(local, &RegionDataRemote::genRemote, msg, len); local->waitUntilCreated(); } void RegionMatrix::updateHandler(uint16_t movingBufferIndex) { while (!RegionMatrix::movingBuffer[movingBufferIndex]) { jalib::memFence(); sched_yield(); } // TODO: lock region handler this->releaseRegionData(); _regionHandler->updateRegionData(RegionMatrix::movingBuffer[movingBufferIndex]); } void RegionMatrix::addMovingBuffer(RegionDataIPtr remoteData, uint16_t index) { pthread_mutex_lock(&RegionMatrix::movingBuffer_mux); RegionMatrix::movingBuffer[index] = remoteData; pthread_mutex_unlock(&RegionMatrix::movingBuffer_mux); } void RegionMatrix::removeMovingBuffer(uint16_t index) { pthread_mutex_lock(&RegionMatrix::movingBuffer_mux); RegionMatrix::movingBuffer.erase(index); pthread_mutex_unlock(&RegionMatrix::movingBuffer_mux); } // // Convert a coord to the one in _regionData // IndexT* RegionMatrix::getRegionDataCoord(const IndexT* coord_orig) { IndexT slice_index = 0; IndexT split_index = 0; IndexT* coord_new = new IndexT[_regionHandler->dimensions()]; for (int d = 0; d < _regionHandler->dimensions(); d++) { if (slice_index < _numSliceDimensions && d == _sliceDimensions[slice_index]) { // slice coord_new[d] = _slicePositions[slice_index]; slice_index++; } else { // split coord_new[d] = coord_orig[split_index] + _splitOffset[split_index]; split_index++; } } return coord_new; } /////////////////////////// int RegionMatrix::incCoord(IndexT* coord) { if (_D == 0) { return -1; } coord[0]++; for (int i = 0; i < _D - 1; ++i){ if (coord[i] >= _size[i]){ coord[i]=0; coord[i+1]++; } else{ return i; } } if (coord[_D - 1] >= _size[_D - 1]){ return -1; }else{ return _D - 1; } } void RegionMatrix::print() { printf("RegionMatrix: SIZE"); for (int d = 0; d < _D; d++) { printf(" %d", _size[d]); } printf("\n"); IndexT* coord = new IndexT[_D]; memset(coord, 0, (sizeof coord) * _D); this->acquireRegionData(); while (true) { printf("%4.8g ", this->readCell(coord)); int z = this->incCoord(coord); if (z == -1) { break; } while (z > 0) { printf("\n"); z--; } } this->releaseRegionData(); printf("\n\n"); delete [] coord; } <commit_msg>fix init moving buffer muxtex<commit_after>#include "regionmatrix.h" #include <string.h> #include "regiondataraw.h" #include "regiondatasplit.h" #include "regionmatrixproxy.h" using namespace petabricks; std::map<uint16_t, RegionDataIPtr> RegionMatrix::movingBuffer; pthread_mutex_t RegionMatrix::movingBuffer_mux = PTHREAD_MUTEX_INITIALIZER; RegionMatrix::RegionMatrix(int dimensions, IndexT* size) { RegionDataIPtr regionData = new RegionDataRaw(dimensions, size); _regionHandler = new RegionHandler(regionData); _D = dimensions; _size = new IndexT[_D]; memcpy(_size, size, sizeof(IndexT) * _D); _splitOffset = new IndexT[_D]; memset(_splitOffset, 0, sizeof(IndexT) * _D); _numSliceDimensions = 0; _sliceDimensions = 0; _slicePositions = 0; } /* RegionMatrix::RegionMatrix(RegionDataIPtr regionData) { _regionHandler = new RegionHandler(regionData); _D = _regionHandler->dimensions(); _size = new IndexT[_D]; memcpy(_size, regionData->size(), sizeof(IndexT) * _D); _splitOffset = new IndexT[_D]; memset(_splitOffset, 0, sizeof(IndexT) * _D); _numSliceDimensions = 0; _sliceDimensions = 0; _slicePositions = 0; } */ // // Called by split & slice // RegionMatrix::RegionMatrix(RegionHandlerPtr handler, int dimensions, IndexT* size, IndexT* splitOffset, int numSliceDimensions, int* sliceDimensions, IndexT* slicePositions) { _regionHandler = handler; _D = dimensions; _size = size; _splitOffset = splitOffset; _numSliceDimensions = numSliceDimensions; if (_numSliceDimensions > 0) { _sliceDimensions = sliceDimensions; _slicePositions = slicePositions; } } RegionMatrix::~RegionMatrix() { delete [] _size; delete [] _splitOffset; delete [] _sliceDimensions; delete [] _slicePositions; } void RegionMatrix::splitData(IndexT* splitSize) { acquireRegionData(); RegionDataIPtr newRegionData = new RegionDataSplit((RegionDataRaw*)_regionData.asPtr(), splitSize); releaseRegionData(); _regionHandler->updateRegionData(newRegionData); } void RegionMatrix::allocData() { acquireRegionData(); _regionData->allocData(); releaseRegionData(); } void RegionMatrix::importDataFromFile(char* filename) { // TODO: perf: move the import to regionDataRaw this->acquireRegionData(); _regionData->allocData(); MatrixIO* matrixio = new MatrixIO(filename, "r"); MatrixReaderScratch o = matrixio->readToMatrixReaderScratch(); ElementT* data = o.storage->data(); IndexT* coord = new IndexT[_D]; memset(coord, 0, sizeof(IndexT) * _D); int i = 0; while (true) { this->writeCell(coord, data[i]); i++; int z = this->incCoord(coord); if (z == -1) { break; } } this->releaseRegionData(); delete [] coord; delete matrixio; } ElementT RegionMatrix::readCell(const IndexT* coord) { IndexT* rd_coord = this->getRegionDataCoord(coord); ElementT elmt = _regionData->readCell(rd_coord); delete [] rd_coord; return elmt; } void RegionMatrix::writeCell(const IndexT* coord, ElementT value) { IndexT* rd_coord = this->getRegionDataCoord(coord); _regionData->writeCell(rd_coord, value); delete [] rd_coord; } int RegionMatrix::dimensions() { return _D; } IndexT* RegionMatrix::size() { return _size; } RegionMatrixPtr RegionMatrix::splitRegion(IndexT* offset, IndexT* size) { IndexT* offset_new = this->getRegionDataCoord(offset); IndexT* size_copy = new IndexT[_D]; memcpy(size_copy, size, sizeof(IndexT) * _D); int* sliceDimensions = new int[_numSliceDimensions]; memcpy(sliceDimensions, _sliceDimensions, sizeof(int) * _numSliceDimensions); IndexT* slicePositions = new IndexT[_numSliceDimensions]; memcpy(slicePositions, _slicePositions, sizeof(IndexT) * _numSliceDimensions); return new RegionMatrix(_regionHandler, _D, size_copy, offset_new, _numSliceDimensions, sliceDimensions, slicePositions); } RegionMatrixPtr RegionMatrix::sliceRegion(int d, IndexT pos){ int dimensions = _D - 1; IndexT* size = new IndexT[dimensions]; memcpy(size, _size, sizeof(IndexT) * d); memcpy(size + d, _size + d + 1, sizeof(IndexT) * (dimensions - d)); IndexT* offset = new IndexT[dimensions]; memcpy(offset, _splitOffset, sizeof(IndexT) * d); memcpy(offset + d, _splitOffset + d + 1, sizeof(IndexT) * (dimensions - d)); // maintain ordered array of _sliceDimensions + update d as necessary int numSliceDimensions = _numSliceDimensions + 1; int* sliceDimensions = new int[numSliceDimensions]; IndexT* slicePositions = new IndexT[numSliceDimensions]; if (_numSliceDimensions == 0) { sliceDimensions[0] = d; slicePositions[0] = pos + _splitOffset[d]; } else { bool isAddedNewD = false; for (int i = 0; i < numSliceDimensions; i++) { if (isAddedNewD) { sliceDimensions[i] = _sliceDimensions[i-1]; slicePositions[i] = _slicePositions[i-1]; } else if (d >= _sliceDimensions[i]) { sliceDimensions[i] = _sliceDimensions[i]; slicePositions[i] = _slicePositions[i]; d++; } else { sliceDimensions[i] = d; slicePositions[i] = pos + _splitOffset[d]; isAddedNewD = true; } } } return new RegionMatrix(_regionHandler, dimensions, size, offset, numSliceDimensions, sliceDimensions, slicePositions); } void RegionMatrix::moveToRemoteHost(RemoteHostPtr host, uint16_t movingBufferIndex) { RegionMatrixProxyPtr proxy = new RegionMatrixProxy(this->getRegionHandler()); RemoteObjectPtr local = proxy->genLocal(); // InitialMsg RegionDataRemoteMessage::InitialMessage* msg = new RegionDataRemoteMessage::InitialMessage(); msg->dimensions = _D; msg->movingBufferIndex = movingBufferIndex; memcpy(msg->size, _size, sizeof(msg->size)); int len = (sizeof msg) + sizeof(msg->size); host->createRemoteObject(local, &RegionDataRemote::genRemote, msg, len); local->waitUntilCreated(); } void RegionMatrix::updateHandler(uint16_t movingBufferIndex) { while (!RegionMatrix::movingBuffer[movingBufferIndex]) { jalib::memFence(); sched_yield(); } // TODO: lock region handler this->releaseRegionData(); _regionHandler->updateRegionData(RegionMatrix::movingBuffer[movingBufferIndex]); } void RegionMatrix::addMovingBuffer(RegionDataIPtr remoteData, uint16_t index) { pthread_mutex_lock(&RegionMatrix::movingBuffer_mux); RegionMatrix::movingBuffer[index] = remoteData; pthread_mutex_unlock(&RegionMatrix::movingBuffer_mux); } void RegionMatrix::removeMovingBuffer(uint16_t index) { pthread_mutex_lock(&RegionMatrix::movingBuffer_mux); RegionMatrix::movingBuffer.erase(index); pthread_mutex_unlock(&RegionMatrix::movingBuffer_mux); } // // Convert a coord to the one in _regionData // IndexT* RegionMatrix::getRegionDataCoord(const IndexT* coord_orig) { IndexT slice_index = 0; IndexT split_index = 0; IndexT* coord_new = new IndexT[_regionHandler->dimensions()]; for (int d = 0; d < _regionHandler->dimensions(); d++) { if (slice_index < _numSliceDimensions && d == _sliceDimensions[slice_index]) { // slice coord_new[d] = _slicePositions[slice_index]; slice_index++; } else { // split coord_new[d] = coord_orig[split_index] + _splitOffset[split_index]; split_index++; } } return coord_new; } /////////////////////////// int RegionMatrix::incCoord(IndexT* coord) { if (_D == 0) { return -1; } coord[0]++; for (int i = 0; i < _D - 1; ++i){ if (coord[i] >= _size[i]){ coord[i]=0; coord[i+1]++; } else{ return i; } } if (coord[_D - 1] >= _size[_D - 1]){ return -1; }else{ return _D - 1; } } void RegionMatrix::print() { printf("RegionMatrix: SIZE"); for (int d = 0; d < _D; d++) { printf(" %d", _size[d]); } printf("\n"); IndexT* coord = new IndexT[_D]; memset(coord, 0, (sizeof coord) * _D); this->acquireRegionData(); while (true) { printf("%4.8g ", this->readCell(coord)); int z = this->incCoord(coord); if (z == -1) { break; } while (z > 0) { printf("\n"); z--; } } this->releaseRegionData(); printf("\n\n"); delete [] coord; } <|endoftext|>
<commit_before>#include <UtH/Engine/Physics/Rigidbody.hpp> #include <UtH/Engine/GameObject.hpp> #include <UtH/Platform/Debug.hpp> // Helper functions //////////////////////////////////// b2Vec2 umathToBox2D(const pmath::Vec2& vec); pmath::Vec2 box2DToUmath(const b2Vec2& vec); //////////////////////////////////// using namespace uth; Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const std::string& name) : Component(name), m_world(world.GetBox2dWorldObject()), m_collider(collider) { defaults(); } Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const pmath::Vec2& size, const std::string& name) : Component(name), m_world(world.GetBox2dWorldObject()), m_collider(collider), m_size(size) { defaults(); } Rigidbody::~Rigidbody() { if (m_body != nullptr && !m_world.expired()) m_world.lock()->DestroyBody(m_body); } // Public void Rigidbody::Init() { init(); } void Rigidbody::Update(float) { const float angDegrees = GetAngle(); parent->transform.SetRotation(angDegrees); b2Vec2 pos = m_body->GetPosition(); pmath::Vec2 tpos(pos.x, pos.y); tpos *= PIXELS_PER_METER; parent->transform.SetPosition(tpos); } // Apply forces void Rigidbody::ApplyForce(const pmath::Vec2& force) { m_body->ApplyForceToCenter(umathToBox2D(force), true); } void Rigidbody::ApplyForce(const pmath::Vec2& force, const pmath::Vec2& point) { b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition(); m_body->ApplyForce(umathToBox2D(force), p, true); } void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse) { m_body->ApplyLinearImpulse(umathToBox2D(impulse), m_body->GetPosition(), true); } void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse, const pmath::Vec2& point) { b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition(); m_body->ApplyLinearImpulse(umathToBox2D(impulse), p, true); } void Rigidbody::ApplyTorque(const float torque) { m_body->ApplyTorque(-torque, true); } // Setters/Getters void Rigidbody::SetVelocity(const pmath::Vec2& velocity) { m_body->SetLinearVelocity(umathToBox2D(velocity)); } const pmath::Vec2 Rigidbody::GetVelocity() const { return box2DToUmath(m_body->GetLinearVelocity()); } void Rigidbody::SetAngularVelocity(float velocity) { m_body->SetAngularVelocity(velocity); } float Rigidbody::GetAngularVelocity() const { return m_body->GetAngularVelocity(); } void Rigidbody::SetSize(const pmath::Vec2& size) { SetUnitSize(size / PIXELS_PER_METER); } void Rigidbody::SetUnitSize(const pmath::Vec2& size) { // This function is kinda ugly but what can you do if(m_body->GetFixtureList()->GetType() != b2Shape::e_polygon) { WriteWarning("Calling SetSize(vec2 size) on a ball. Size not updated"); return; } // Remove original fixture m_body->DestroyFixture(m_body->GetFixtureList()); //WriteLog("x: %f,y: %f\n", size.x, size.y); b2PolygonShape box; box.SetAsBox(size.x, size.y); m_fixtureDef.shape = &box; m_body->CreateFixture(&m_fixtureDef); m_size = size; } void Rigidbody::SetSize(const float radius) { SetUnitSize(radius / PIXELS_PER_METER); } void Rigidbody::SetUnitSize(const float radius) { // This might be even more ugly if(m_fixtureDef.shape->GetType() != b2Shape::e_circle) { WriteWarning("Calling SetSize(float radius) on a box. Size not updated"); return; } // Remove original fixture m_body->DestroyFixture(m_body->GetFixtureList()); b2CircleShape circle; circle.m_radius = radius; m_fixtureDef.shape = &circle; m_body->CreateFixture(&m_fixtureDef); m_size.x = radius*2; m_size.y = radius*2; } const pmath::Vec2 Rigidbody::GetSize() { return m_size * PIXELS_PER_METER; } const pmath::Vec2 Rigidbody::GetUnitSize() { return m_size; } void Rigidbody::SetPosition(const pmath::Vec2& position) { b2Vec2 p = umathToBox2D(position / PIXELS_PER_METER); m_body->SetTransform(p, m_body->GetAngle()); } const pmath::Vec2 Rigidbody::GetPosition() { b2Vec2 pos = m_body->GetPosition(); pos *= PIXELS_PER_METER; return box2DToUmath(pos); } void Rigidbody::SetAngle(const float angle) { float ang = -angle * static_cast<float>(pmath::pi) / 180.f; m_body->SetTransform(m_body->GetPosition(), ang); } float Rigidbody::GetAngle() const { return -m_body->GetAngle() * 180.f / static_cast<float>(pmath::pi); } void Rigidbody::SetFixedRotation(bool value) { m_body->SetFixedRotation(value); } void Rigidbody::SetDensity(float density) { m_body->GetFixtureList()->SetDensity(density); m_body->ResetMassData(); } float Rigidbody::GetDensity() const { return m_body->GetFixtureList()->GetDensity(); } void Rigidbody::SetFriction(float friction) { m_body->GetFixtureList()->SetFriction(friction); } float Rigidbody::GetFriction() const { return m_body->GetFixtureList()->GetFriction(); } void Rigidbody::SetActive(bool value) { m_body->SetActive(value); m_active = value; } const bool Rigidbody::IsAwake() const { return m_body->IsAwake(); } void Rigidbody::SetBullet(bool value) { m_body->SetBullet(value); } const bool Rigidbody::IsBullet() const { return m_body->IsBullet(); } void Rigidbody::SetKinematic(bool value) { value ? m_body->SetType(b2_kinematicBody) : m_body->SetType(b2_dynamicBody); } // Private void Rigidbody::defaults() { m_body = nullptr; } void Rigidbody::init() { b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; pmath::Vec2 pos = parent->transform.GetPosition(); pos /= PIXELS_PER_METER; bodyDef.position.Set(pos.x, pos.y); m_body = m_world.lock()->CreateBody(&bodyDef); m_body->SetUserData(parent); if(!(m_size.lengthSquared() > 0)) m_size = parent->transform.GetSize(); m_size /= PIXELS_PER_METER; switch(m_collider) { case COLLIDER_BOX: { b2PolygonShape dynamicBox; dynamicBox.SetAsBox(m_size.x/2, m_size.y/2); m_fixtureDef.shape = &dynamicBox; m_fixtureDef.density = 1.0f; m_fixtureDef.friction = 0.3f; m_body->CreateFixture(&m_fixtureDef); } break; case COLLIDER_BALL: { b2CircleShape circleShape; circleShape.m_radius = m_size.x/2; m_fixtureDef.shape = &circleShape; m_fixtureDef.density = 1.0f; m_fixtureDef.friction = 0.3f; m_body->CreateFixture(&m_fixtureDef); } break; default: WriteError("Collider type undefined\nThis is probably bad"); break; } } void Rigidbody::SetRestitution(float restitution) { m_body->GetFixtureList()->SetRestitution(restitution); } float uth::Rigidbody::GetRestitution() const { return m_body->GetFixtureList()->GetRestitution(); } b2Vec2 umathToBox2D(const pmath::Vec2& vec) { return b2Vec2(vec.x, vec.y); } pmath::Vec2 box2DToUmath(const b2Vec2& vec) { return pmath::Vec2(vec.x, vec.y); }<commit_msg>Rigidbody takes scale into account during init<commit_after>#include <UtH/Engine/Physics/Rigidbody.hpp> #include <UtH/Engine/GameObject.hpp> #include <UtH/Platform/Debug.hpp> // Helper functions //////////////////////////////////// b2Vec2 umathToBox2D(const pmath::Vec2& vec); pmath::Vec2 box2DToUmath(const b2Vec2& vec); //////////////////////////////////// using namespace uth; Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const std::string& name) : Component(name), m_world(world.GetBox2dWorldObject()), m_collider(collider) { defaults(); } Rigidbody::Rigidbody(PhysicsWorld& world, const COLLIDER_TYPE collider, const pmath::Vec2& size, const std::string& name) : Component(name), m_world(world.GetBox2dWorldObject()), m_collider(collider), m_size(size) { defaults(); } Rigidbody::~Rigidbody() { if (m_body != nullptr && !m_world.expired()) m_world.lock()->DestroyBody(m_body); } // Public void Rigidbody::Init() { init(); } void Rigidbody::Update(float) { const float angDegrees = GetAngle(); parent->transform.SetRotation(angDegrees); b2Vec2 pos = m_body->GetPosition(); pmath::Vec2 tpos(pos.x, pos.y); tpos *= PIXELS_PER_METER; parent->transform.SetPosition(tpos); } // Apply forces void Rigidbody::ApplyForce(const pmath::Vec2& force) { m_body->ApplyForceToCenter(umathToBox2D(force), true); } void Rigidbody::ApplyForce(const pmath::Vec2& force, const pmath::Vec2& point) { b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition(); m_body->ApplyForce(umathToBox2D(force), p, true); } void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse) { m_body->ApplyLinearImpulse(umathToBox2D(impulse), m_body->GetPosition(), true); } void Rigidbody::ApplyImpulse(const pmath::Vec2& impulse, const pmath::Vec2& point) { b2Vec2 p = umathToBox2D(point / PIXELS_PER_METER) + m_body->GetPosition(); m_body->ApplyLinearImpulse(umathToBox2D(impulse), p, true); } void Rigidbody::ApplyTorque(const float torque) { m_body->ApplyTorque(-torque, true); } // Setters/Getters void Rigidbody::SetVelocity(const pmath::Vec2& velocity) { m_body->SetLinearVelocity(umathToBox2D(velocity)); } const pmath::Vec2 Rigidbody::GetVelocity() const { return box2DToUmath(m_body->GetLinearVelocity()); } void Rigidbody::SetAngularVelocity(float velocity) { m_body->SetAngularVelocity(velocity); } float Rigidbody::GetAngularVelocity() const { return m_body->GetAngularVelocity(); } void Rigidbody::SetSize(const pmath::Vec2& size) { SetUnitSize(size / PIXELS_PER_METER); } void Rigidbody::SetUnitSize(const pmath::Vec2& size) { // This function is kinda ugly but what can you do if(m_body->GetFixtureList()->GetType() != b2Shape::e_polygon) { WriteWarning("Calling SetSize(vec2 size) on a ball. Size not updated"); return; } // Remove original fixture m_body->DestroyFixture(m_body->GetFixtureList()); //WriteLog("x: %f,y: %f\n", size.x, size.y); b2PolygonShape box; box.SetAsBox(size.x, size.y); m_fixtureDef.shape = &box; m_body->CreateFixture(&m_fixtureDef); m_size = size; } void Rigidbody::SetSize(const float radius) { SetUnitSize(radius / PIXELS_PER_METER); } void Rigidbody::SetUnitSize(const float radius) { // This might be even more ugly if(m_fixtureDef.shape->GetType() != b2Shape::e_circle) { WriteWarning("Calling SetSize(float radius) on a box. Size not updated"); return; } // Remove original fixture m_body->DestroyFixture(m_body->GetFixtureList()); b2CircleShape circle; circle.m_radius = radius; m_fixtureDef.shape = &circle; m_body->CreateFixture(&m_fixtureDef); m_size.x = radius*2; m_size.y = radius*2; } const pmath::Vec2 Rigidbody::GetSize() { return m_size * PIXELS_PER_METER; } const pmath::Vec2 Rigidbody::GetUnitSize() { return m_size; } void Rigidbody::SetPosition(const pmath::Vec2& position) { b2Vec2 p = umathToBox2D(position / PIXELS_PER_METER); m_body->SetTransform(p, m_body->GetAngle()); } const pmath::Vec2 Rigidbody::GetPosition() { b2Vec2 pos = m_body->GetPosition(); pos *= PIXELS_PER_METER; return box2DToUmath(pos); } void Rigidbody::SetAngle(const float angle) { float ang = -angle * static_cast<float>(pmath::pi) / 180.f; m_body->SetTransform(m_body->GetPosition(), ang); } float Rigidbody::GetAngle() const { return -m_body->GetAngle() * 180.f / static_cast<float>(pmath::pi); } void Rigidbody::SetFixedRotation(bool value) { m_body->SetFixedRotation(value); } void Rigidbody::SetDensity(float density) { m_body->GetFixtureList()->SetDensity(density); m_body->ResetMassData(); } float Rigidbody::GetDensity() const { return m_body->GetFixtureList()->GetDensity(); } void Rigidbody::SetFriction(float friction) { m_body->GetFixtureList()->SetFriction(friction); } float Rigidbody::GetFriction() const { return m_body->GetFixtureList()->GetFriction(); } void Rigidbody::SetActive(bool value) { m_body->SetActive(value); m_active = value; } const bool Rigidbody::IsAwake() const { return m_body->IsAwake(); } void Rigidbody::SetBullet(bool value) { m_body->SetBullet(value); } const bool Rigidbody::IsBullet() const { return m_body->IsBullet(); } void Rigidbody::SetKinematic(bool value) { value ? m_body->SetType(b2_kinematicBody) : m_body->SetType(b2_dynamicBody); } // Private void Rigidbody::defaults() { m_body = nullptr; } void Rigidbody::init() { b2BodyDef bodyDef; bodyDef.type = b2_dynamicBody; pmath::Vec2 pos = parent->transform.GetPosition(); pos /= PIXELS_PER_METER; bodyDef.position.Set(pos.x, pos.y); m_body = m_world.lock()->CreateBody(&bodyDef); m_body->SetUserData(parent); if (!(m_size.lengthSquared() > 0)) { m_size = parent->transform.GetSize(); m_size.scale(parent->transform.GetScale()); } m_size /= PIXELS_PER_METER; switch(m_collider) { case COLLIDER_BOX: { b2PolygonShape dynamicBox; dynamicBox.SetAsBox(m_size.x/2, m_size.y/2); m_fixtureDef.shape = &dynamicBox; m_fixtureDef.density = 1.0f; m_fixtureDef.friction = 0.3f; m_body->CreateFixture(&m_fixtureDef); } break; case COLLIDER_BALL: { b2CircleShape circleShape; circleShape.m_radius = m_size.x/2; m_fixtureDef.shape = &circleShape; m_fixtureDef.density = 1.0f; m_fixtureDef.friction = 0.3f; m_body->CreateFixture(&m_fixtureDef); } break; default: WriteError("Collider type undefined\nThis is probably bad"); break; } } void Rigidbody::SetRestitution(float restitution) { m_body->GetFixtureList()->SetRestitution(restitution); } float uth::Rigidbody::GetRestitution() const { return m_body->GetFixtureList()->GetRestitution(); } b2Vec2 umathToBox2D(const pmath::Vec2& vec) { return b2Vec2(vec.x, vec.y); } pmath::Vec2 box2DToUmath(const b2Vec2& vec) { return pmath::Vec2(vec.x, vec.y); }<|endoftext|>
<commit_before>#include "sample/view/mrt_view.h" #include "basic/obj/basic_camera.h" #include "basic/obj/basic_light.h" #include "basic/obj/simple_object.h" #include "basic/mgr/basic_light_mgr.h" #include "basic/mgr/basic_texture_mgr.h" #include "basic/mgr/basic_shader_mgr.h" using namespace std; #define MRT_WIDTH 480 #define MRT_HEIGHT 688 #define SH_MRT "sh_mrt" #define SH_DRAW "sh_draw" class MrtRenderer : public BasicRenderer { private: GLuint mMrtFbo; GLuint mRenderBuffer; public: MrtRenderer() : mMrtFbo(0), mRenderBuffer(0) {} virtual ~MrtRenderer() {} void InitFbo(GLuint* texIds) { GLenum none = GL_NONE; glGenRenderbuffers(1, &mRenderBuffer); check_gl_error("glGenRenderbuffers"); glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer); check_gl_error("glBindRenderbuffer"); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, MRT_WIDTH, MRT_HEIGHT); check_gl_error("glRenderbufferStorage"); glGenFramebuffers(1, &mMrtFbo); check_gl_error("glGenFramebuffers"); glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo); check_gl_error("glBindFramebuffer"); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mRenderBuffer); for(unsigned int i=0; i<4 ;i++) { glBindTexture(GL_TEXTURE_2D, texIds[i]); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texIds[i], 0); glBindTexture(GL_TEXTURE_2D, 0); check_gl_error("glFramebufferTexture2D"); } LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]); GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(4, DrawBuffers); // Check FBO is ready to draw if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LOGE("FrameBufferObject is not complete!"); } glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } virtual void RenderFrame() { ComputeTick(); glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); Shader_Mgr.DrawObjects(SH_MRT); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glDisable(GL_CULL_FACE); Shader_Mgr.DrawObjects(SH_DRAW); glEnable(GL_CULL_FACE); } }; MrtView::MrtView(void *data) : SampleView(data, false) { mViewRenderer = new MrtRenderer(); } void MrtView::OnInit() { string mrt_vs = File_Loader.ReadFileToString("shader/view_mrt/mrt.vs"); string mrt_fs = File_Loader.ReadFileToString("shader/view_mrt/mrt.fs"); string draw_vs = File_Loader.ReadFileToString("shader/view_mrt/draw.vs"); string draw_fs = File_Loader.ReadFileToString("shader/view_mrt/draw.fs"); BasicMap<MaterialObj_U_Elem> mo_uniforms; mo_uniforms.mList[MTL_U_MAT_WORLD] = "worldMat"; mo_uniforms.mList[MTL_U_CAMERA_VIEW] = "viewMat"; mo_uniforms.mList[MTL_U_CAMERA_PROJ] = "projMat"; mo_uniforms.mList[MTL_U_CAMERA_POS] = "eyePos"; mo_uniforms.mList[MTL_U_MAT_SHINESS] = "materialSh"; BasicMap<PointLt_U_Elem> lt_uniforms; lt_uniforms.mList[U_PL_DIFFUSE] = "sourceDiff"; lt_uniforms.mList[U_PL_AMBIENT] = "sourceAmbi"; lt_uniforms.mList[U_PL_SPECULAR] = "sourceSpec"; lt_uniforms.mList[U_PL_POS] = "lightPos"; mViewRenderer->GetNewObject(MATERIAL_OBJ, "chess", mo_uniforms) ->ImportObj("obj3d/chess_tri", 2.0f) ->AttachShader(mrt_vs, mrt_fs, SH_MRT) ->AttachLight(POINT_LT, "point_light_1", lt_uniforms); Light_Mgr.GetLight("point_light_1")->mPosition = glm::vec3(0, 5.0f, 0); mViewRenderer->OffAutoRotate(); mViewRenderer->GetCamera()->SetEye(glm::vec3(-15, 15, 15)); TexProp texDiff(TEX_2D_PTR); texDiff.SetData("tex_diff", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texDiff.SetPointer(nullptr); texDiff.SetFilter(); TexProp texDraw(TEX_2D_PTR); texDraw.SetData("tex_draw", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texDraw.SetPointer(nullptr); texDraw.SetFilter(); TexProp texAmbi(TEX_2D_PTR); texAmbi.SetData("tex_ambi", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texAmbi.SetPointer(nullptr); texAmbi.SetFilter(); TexProp texAttn(TEX_2D_PTR); texAttn.SetData("tex_attn", MRT_WIDTH, MRT_HEIGHT, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texAttn.SetPointer(nullptr); texAttn.SetFilter(); BasicObject *obj; obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "diff", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texDiff, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "spec", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texDraw, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, 0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "ambi", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texAmbi, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0, -1.0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "attn", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texAttn, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, -1.0)); GLuint texIds[4]; texIds[0] = Texture_Mgr.GetTextureId("tex_diff"); texIds[1] = Texture_Mgr.GetTextureId("tex_draw"); texIds[2] = Texture_Mgr.GetTextureId("tex_ambi"); texIds[3] = Texture_Mgr.GetTextureId("tex_attn"); LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]); mViewRenderer->SetCurrShader(SH_DRAW); dynamic_cast<MrtRenderer *>(mViewRenderer)->InitFbo(texIds); } <commit_msg>resolve resolution issue<commit_after>#include "sample/view/mrt_view.h" #include "basic/mgr/basic_light_mgr.h" #include "basic/mgr/basic_texture_mgr.h" #include "basic/mgr/basic_shader_mgr.h" #include "basic/obj/basic_camera.h" #include "basic/obj/basic_light.h" #include "basic/obj/simple_object.h" using namespace std; #define SH_MRT "sh_mrt" #define SH_DRAW "sh_draw" class MrtRenderer : public BasicRenderer { private: GLuint mMrtFbo; GLuint mRenderBuffer; public: MrtRenderer() : mMrtFbo(0), mRenderBuffer(0), BasicRenderer() {} virtual ~MrtRenderer() {} void InitFbo(GLuint* texIds) { GLenum none = GL_NONE; glGenRenderbuffers(1, &mRenderBuffer); check_gl_error("glGenRenderbuffers"); glBindRenderbuffer(GL_RENDERBUFFER, mRenderBuffer); check_gl_error("glBindRenderbuffer"); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mWidth, mHeight); check_gl_error("glRenderbufferStorage"); glGenFramebuffers(1, &mMrtFbo); check_gl_error("glGenFramebuffers"); glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo); check_gl_error("glBindFramebuffer"); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mRenderBuffer); for(unsigned int i=0; i<4 ;i++) { glBindTexture(GL_TEXTURE_2D, texIds[i]); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, texIds[i], 0); glBindTexture(GL_TEXTURE_2D, 0); check_gl_error("glFramebufferTexture2D"); } LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]); GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 }; glDrawBuffers(4, DrawBuffers); // Check FBO is ready to draw if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { LOGE("FrameBufferObject is not complete!"); } glBindRenderbuffer(GL_RENDERBUFFER, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } virtual void RenderFrame() { ComputeTick(); glBindFramebuffer(GL_FRAMEBUFFER, mMrtFbo); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); Shader_Mgr.DrawObjects(SH_MRT); glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glDisable(GL_CULL_FACE); Shader_Mgr.DrawObjects(SH_DRAW); glEnable(GL_CULL_FACE); } }; MrtView::MrtView(void *data) : SampleView(data, false) { mViewRenderer = new MrtRenderer(); } void MrtView::OnInit() { string mrt_vs = File_Loader.ReadFileToString("shader/view_mrt/mrt.vs"); string mrt_fs = File_Loader.ReadFileToString("shader/view_mrt/mrt.fs"); string draw_vs = File_Loader.ReadFileToString("shader/view_mrt/draw.vs"); string draw_fs = File_Loader.ReadFileToString("shader/view_mrt/draw.fs"); BasicMap<MaterialObj_U_Elem> mo_uniforms; mo_uniforms.mList[MTL_U_MAT_WORLD] = "worldMat"; mo_uniforms.mList[MTL_U_CAMERA_VIEW] = "viewMat"; mo_uniforms.mList[MTL_U_CAMERA_PROJ] = "projMat"; mo_uniforms.mList[MTL_U_CAMERA_POS] = "eyePos"; mo_uniforms.mList[MTL_U_MAT_SHINESS] = "materialSh"; BasicMap<PointLt_U_Elem> lt_uniforms; lt_uniforms.mList[U_PL_DIFFUSE] = "sourceDiff"; lt_uniforms.mList[U_PL_AMBIENT] = "sourceAmbi"; lt_uniforms.mList[U_PL_SPECULAR] = "sourceSpec"; lt_uniforms.mList[U_PL_POS] = "lightPos"; mViewRenderer->GetNewObject(MATERIAL_OBJ, "chess", mo_uniforms) ->ImportObj("obj3d/chess_tri", 2.0f) ->AttachShader(mrt_vs, mrt_fs, SH_MRT) ->AttachLight(POINT_LT, "point_light_1", lt_uniforms); Light_Mgr.GetLight("point_light_1")->mPosition = glm::vec3(0, 5.0f, 0); mViewRenderer->OffAutoRotate(); mViewRenderer->GetCamera()->SetEye(glm::vec3(-15, 15, 15)); int w = mViewRenderer->GetWidth(); int h = mViewRenderer->GetHeight(); TexProp texDiff(TEX_2D_PTR); texDiff.SetData("tex_diff", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texDiff.SetPointer(nullptr); texDiff.SetFilter(); TexProp texDraw(TEX_2D_PTR); texDraw.SetData("tex_draw", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texDraw.SetPointer(nullptr); texDraw.SetFilter(); TexProp texAmbi(TEX_2D_PTR); texAmbi.SetData("tex_ambi", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texAmbi.SetPointer(nullptr); texAmbi.SetFilter(); TexProp texAttn(TEX_2D_PTR); texAttn.SetData("tex_attn", w, h, GL_RGB, GL_RGB8, GL_UNSIGNED_BYTE); texAttn.SetPointer(nullptr); texAttn.SetFilter(); BasicObject *obj; obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "diff", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texDiff, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "spec", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texDraw, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, 0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "ambi", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texAmbi, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(0, -1.0)); obj = mViewRenderer->GetNewObject(SIMPLE_OBJ, "attn", mo_uniforms) ->AttachShader(draw_vs, draw_fs, SH_DRAW) ->AttachTexture(texAttn, "s_tex"); dynamic_cast<SimpleObject *>(obj)->Init(glm::vec2(-1.0, -1.0)); GLuint texIds[4]; texIds[0] = Texture_Mgr.GetTextureId("tex_diff"); texIds[1] = Texture_Mgr.GetTextureId("tex_draw"); texIds[2] = Texture_Mgr.GetTextureId("tex_ambi"); texIds[3] = Texture_Mgr.GetTextureId("tex_attn"); LOGI("texid [%d, %d, %d, %d]", texIds[0],texIds[1],texIds[2],texIds[3]); mViewRenderer->SetCurrShader(SH_DRAW); dynamic_cast<MrtRenderer *>(mViewRenderer)->InitFbo(texIds); } <|endoftext|>
<commit_before>#include <fstream> #include "Simbody.h" #include "Exception.h" #include "FileAdapter.h" #include "TimeSeriesTable.h" #include "XsensDataReader.h" namespace OpenSim { XsensDataReader* XsensDataReader::clone() const { return new XsensDataReader{*this}; } DataAdapter::OutputTables XsensDataReader::extendRead(const std::string& folderName) const { std::vector<std::ifstream*> imuStreams; std::vector<std::string> labels; // files specified by prefix + file name exist double dataRate = SimTK::NaN; int packetCounterIndex = -1; int accIndex = -1; int gyroIndex = -1; int magIndex = -1; int rotationsIndex = -1; int n_imus = _settings.getProperty_ExperimentalSensors().size(); int last_size = 1024; // Will read data into pre-allocated Matrices in-memory rather than appendRow // on the fly to avoid the overhead of SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus }; std::vector<double> times; times.resize(last_size); std::string prefix = _settings.get_trial_prefix(); for (int index = 0; index < n_imus; ++index) { std::string prefix = _settings.get_trial_prefix(); const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index); auto fileName = folderName + prefix + nextItem.getName() +".txt"; auto* nextStream = new std::ifstream{ fileName }; OPENSIM_THROW_IF(!nextStream->good(), FileDoesNotExist, fileName); // Add imu name to labels labels.push_back(nextItem.get_name_in_model()); // Add corresponding stream to imuStreams imuStreams.push_back(nextStream); // Skip lines to get to data std::string line; int labels_line_number = 5; // Undocumented, just found empirically in Xsens output files for (int j = 0; j <= labels_line_number; j++) { std::getline(*nextStream, line); if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1 std::vector<std::string> tokens = FileAdapter::tokenize(line, ", "); // find Update Rate: and parse into dataRate if (tokens.size() < 4) continue; if (tokens[1] == "Update" && tokens[2] == "Rate:") { dataRate = std::stod(tokens[3]); } } if (j == labels_line_number) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5 std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t"); if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter"); if (accIndex == -1) accIndex = find_index(tokens, "Acc_X"); if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X"); if (magIndex == -1) magIndex = find_index(tokens, "Mag_X"); if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]"); } } } // internally keep track of what data was found in input files bool foundLinearAccelerationData = (accIndex != -1); bool foundMagneticHeadingData = (magIndex != -1); bool foundAngularVelocityData = (gyroIndex != -1); // If no Orientation data is available or dataRate can't be deduced we'll abort completely OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)), TableMissingHeader); // For all tables, will create row, stitch values from different files then append,time and timestep // are based on the first file bool done = false; double time = 0.0; double timeIncrement = 1 / dataRate; int rowNumber = 0; while (!done){ // Make vectors one per table TimeSeriesTableQuaternion::RowVector orientation_row_vector{ n_imus, SimTK::Quaternion() }; TimeSeriesTableVec3::RowVector accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; // Cycle through the filles collating values int imu_index = 0; for (std::vector<std::ifstream*>::iterator it = imuStreams.begin(); it != imuStreams.end(); ++it, ++imu_index) { std::ifstream* nextStream = *it; // parse gyro info from imuStream std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r"); if (nextRow.empty()) { done = true; break; } if (foundLinearAccelerationData) accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]), std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2])); if (foundMagneticHeadingData) magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]), std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2])); if (foundAngularVelocityData) gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]), std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2])); // Create Mat33 then convert into Quaternion SimTK::Mat33 imu_matrix{ SimTK::NaN }; int matrix_entry_index = 0; for (int mcol = 0; mcol < 3; mcol++) { for (int mrow = 0; mrow < 3; mrow++) { imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]); matrix_entry_index++; } } // Convert imu_matrix to Quaternion SimTK::Rotation imu_rotation{ imu_matrix }; orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion(); } if (done) break; // append to the tables times[rowNumber] = time; if (foundLinearAccelerationData) linearAccelerationData[rowNumber] = accel_row_vector; if (foundMagneticHeadingData) magneticHeadingData[rowNumber] = magneto_row_vector; if (foundAngularVelocityData) angularVelocityData[rowNumber] = gyro_row_vector; rotationsData[rowNumber] = orientation_row_vector; time += timeIncrement; rowNumber++; if (std::remainder(rowNumber, last_size) == 0) { // resize all Data/Matrices, double the size while keeping data int newSize = last_size*2; times.resize(newSize); // Repeat for Data matrices in use if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus); if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus); if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus); rotationsData.resizeKeep(newSize, n_imus); last_size = newSize; } } // Trim Matrices in use to actual data and move into tables times.resize(rowNumber); // Repeat for Data matrices in use and create Tables from them or size 0 for empty linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0, n_imus); magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0, n_imus); angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0, n_imus); rotationsData.resizeKeep(rowNumber, n_imus); // Now create the tables from matrices // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading // Tables could be empty if data is not present in file(s) DataAdapter::OutputTables tables = createTablesFromMatrices(dataRate, labels, times, rotationsData, linearAccelerationData, magneticHeadingData, angularVelocityData); return tables; } int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) { int returnIndex = -1; std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch); if (it != tokens.end()) returnIndex = static_cast<int>(std::distance(tokens.begin(), it)); return returnIndex; } } <commit_msg>Replace line couting to find labels by looking for PacketCounter to indicate line of 'labels' in xsens exported .txt files<commit_after>#include <fstream> #include "Simbody.h" #include "Exception.h" #include "FileAdapter.h" #include "TimeSeriesTable.h" #include "XsensDataReader.h" namespace OpenSim { XsensDataReader* XsensDataReader::clone() const { return new XsensDataReader{*this}; } DataAdapter::OutputTables XsensDataReader::extendRead(const std::string& folderName) const { std::vector<std::ifstream*> imuStreams; std::vector<std::string> labels; // files specified by prefix + file name exist double dataRate = SimTK::NaN; int packetCounterIndex = -1; int accIndex = -1; int gyroIndex = -1; int magIndex = -1; int rotationsIndex = -1; int n_imus = _settings.getProperty_ExperimentalSensors().size(); int last_size = 1024; // Will read data into pre-allocated Matrices in-memory rather than appendRow // on the fly to avoid the overhead of SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus }; std::vector<double> times; times.resize(last_size); std::string prefix = _settings.get_trial_prefix(); for (int index = 0; index < n_imus; ++index) { std::string prefix = _settings.get_trial_prefix(); const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index); auto fileName = folderName + prefix + nextItem.getName() +".txt"; auto* nextStream = new std::ifstream{ fileName }; OPENSIM_THROW_IF(!nextStream->good(), FileDoesNotExist, fileName); // Add imu name to labels labels.push_back(nextItem.get_name_in_model()); // Add corresponding stream to imuStreams imuStreams.push_back(nextStream); // Skip lines to get to data std::string line; bool labelsFound = false; packetCounterIndex = -1; // Force moving file pointer to beginning of data for each stream for (int j = 0; !labelsFound; j++) { std::getline(*nextStream, line); if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1 std::vector<std::string> tokens = FileAdapter::tokenize(line, ", "); // find Update Rate: and parse into dataRate if (tokens.size() < 4) continue; if (tokens[1] == "Update" && tokens[2] == "Rate:") { dataRate = std::stod(tokens[3]); } } if (!labelsFound) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5 std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t"); if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter"); if (packetCounterIndex == -1) { // Could be comment, skip over continue; } else { labelsFound = true; if (accIndex == -1) accIndex = find_index(tokens, "Acc_X"); if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X"); if (magIndex == -1) magIndex = find_index(tokens, "Mag_X"); if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]"); } } } } // internally keep track of what data was found in input files bool foundLinearAccelerationData = (accIndex != -1); bool foundMagneticHeadingData = (magIndex != -1); bool foundAngularVelocityData = (gyroIndex != -1); // If no Orientation data is available or dataRate can't be deduced we'll abort completely OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)), TableMissingHeader); // For all tables, will create row, stitch values from different files then append,time and timestep // are based on the first file bool done = false; double time = 0.0; double timeIncrement = 1 / dataRate; int rowNumber = 0; while (!done){ // Make vectors one per table TimeSeriesTableQuaternion::RowVector orientation_row_vector{ n_imus, SimTK::Quaternion() }; TimeSeriesTableVec3::RowVector accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; // Cycle through the filles collating values int imu_index = 0; for (std::vector<std::ifstream*>::iterator it = imuStreams.begin(); it != imuStreams.end(); ++it, ++imu_index) { std::ifstream* nextStream = *it; // parse gyro info from imuStream std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r"); if (nextRow.empty()) { done = true; break; } if (foundLinearAccelerationData) accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]), std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2])); if (foundMagneticHeadingData) magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]), std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2])); if (foundAngularVelocityData) gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]), std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2])); // Create Mat33 then convert into Quaternion SimTK::Mat33 imu_matrix{ SimTK::NaN }; int matrix_entry_index = 0; for (int mcol = 0; mcol < 3; mcol++) { for (int mrow = 0; mrow < 3; mrow++) { imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]); matrix_entry_index++; } } // Convert imu_matrix to Quaternion SimTK::Rotation imu_rotation{ imu_matrix }; orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion(); } if (done) break; // append to the tables times[rowNumber] = time; if (foundLinearAccelerationData) linearAccelerationData[rowNumber] = accel_row_vector; if (foundMagneticHeadingData) magneticHeadingData[rowNumber] = magneto_row_vector; if (foundAngularVelocityData) angularVelocityData[rowNumber] = gyro_row_vector; rotationsData[rowNumber] = orientation_row_vector; time += timeIncrement; rowNumber++; if (std::remainder(rowNumber, last_size) == 0) { // resize all Data/Matrices, double the size while keeping data int newSize = last_size*2; times.resize(newSize); // Repeat for Data matrices in use if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus); if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus); if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus); rotationsData.resizeKeep(newSize, n_imus); last_size = newSize; } } // Trim Matrices in use to actual data and move into tables times.resize(rowNumber); // Repeat for Data matrices in use and create Tables from them or size 0 for empty linearAccelerationData.resizeKeep(foundLinearAccelerationData? rowNumber : 0, n_imus); magneticHeadingData.resizeKeep(foundMagneticHeadingData? rowNumber : 0, n_imus); angularVelocityData.resizeKeep(foundAngularVelocityData? rowNumber :0, n_imus); rotationsData.resizeKeep(rowNumber, n_imus); // Now create the tables from matrices // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading // Tables could be empty if data is not present in file(s) DataAdapter::OutputTables tables = createTablesFromMatrices(dataRate, labels, times, rotationsData, linearAccelerationData, magneticHeadingData, angularVelocityData); return tables; } int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) { int returnIndex = -1; std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch); if (it != tokens.end()) returnIndex = static_cast<int>(std::distance(tokens.begin(), it)); return returnIndex; } } <|endoftext|>
<commit_before>#include <fstream> #include "Simbody.h" #include "Exception.h" #include "FileAdapter.h" #include "TimeSeriesTable.h" #include "XsensDataReader.h" namespace OpenSim { const std::string XsensDataReader::Orientations{ "orientations" }; const std::string XsensDataReader::LinearAccelerations{ "linear_accelerations" }; const std::string XsensDataReader::MagneticHeading{ "magnetic_heading" }; const std::string XsensDataReader::AngularVelocity{ "angular_velocity" }; XsensDataReader* XsensDataReader::clone() const { return new XsensDataReader{*this}; } DataAdapter::OutputTables XsensDataReader::extendRead(const std::string& folderName) const { std::vector<std::ifstream*> imuStreams; std::vector<std::string> labels; // files specified by prefix + file name exist double dataRate = SimTK::NaN; int packetCounterIndex = -1; int accIndex = -1; int gyroIndex = -1; int magIndex = -1; int rotationsIndex = -1; int n_imus = _settings.getProperty_ExperimentalSensors().size(); int last_size = 1024; // Will read data into pre-allocated Matrices in-memory rather than appendRow // on the fly to avoid the overhead of SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus }; std::vector<double> times; times.resize(last_size); std::string prefix = _settings.get_trial_prefix(); for (int index = 0; index < n_imus; ++index) { std::string prefix = _settings.get_trial_prefix(); const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index); auto fileName = folderName + prefix + nextItem.getName() +".txt"; auto* nextStream = new std::ifstream{ fileName }; OPENSIM_THROW_IF(!nextStream->good(), FileDoesNotExist, fileName); // Add imu name to labels labels.push_back(nextItem.get_name_in_model()); // Add corresponding stream to imuStreams imuStreams.push_back(nextStream); // Skip lines to get to data std::string line; for (int j = 0; j < 6; j++) { std::getline(*nextStream, line); if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1 std::vector<std::string> tokens = FileAdapter::tokenize(line, ", "); // find Update Rate: and parse into dataRate if (tokens.size() < 4) continue; if (tokens[1] == "Update" && tokens[2] == "Rate:") { dataRate = std::stod(tokens[3]); } } if (j == 5) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5 std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t"); if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter"); if (accIndex == -1) accIndex = find_index(tokens, "Acc_X"); if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X"); if (magIndex == -1) magIndex = find_index(tokens, "Mag_X"); if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]"); } } } // internally keep track of what data was found in input files bool foundLinearAccelerationData = (accIndex != -1); bool foundMagneticHeadingData = (magIndex != -1); bool foundAngularVelocityData = (gyroIndex != -1); // If no Orientation data is available or dataRate can't be deduced we'll abort completely OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)), TableMissingHeader); // For all tables, will create row, stitch values from different files then append,time and timestep // are based on the first file bool done = false; double time = 0.0; double timeIncrement = 1 / dataRate; int rowNumber = 0; while (!done){ // Make vectors one per table TimeSeriesTableQuaternion::RowVector orientation_row_vector{ n_imus, SimTK::Quaternion() }; TimeSeriesTableVec3::RowVector accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; // Cycle through the filles collating values int imu_index = 0; for (std::vector<std::ifstream*>::iterator it = imuStreams.begin(); it != imuStreams.end(); ++it, ++imu_index) { std::ifstream* nextStream = *it; // parse gyro info from imuStream std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r"); if (nextRow.empty()) { done = true; break; } if (foundLinearAccelerationData) accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]), std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2])); if (foundMagneticHeadingData) magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]), std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2])); if (foundAngularVelocityData) gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]), std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2])); // Create Mat33 then convert into Quaternion SimTK::Mat33 imu_matrix{ SimTK::NaN }; int matrix_entry_index = 0; for (int mcol = 0; mcol < 3; mcol++) { for (int mrow = 0; mrow < 3; mrow++) { imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]); matrix_entry_index++; } } // Convert imu_matrix to Quaternion SimTK::Rotation imu_rotation{ imu_matrix }; orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion(); } if (done) break; // append to the tables times[rowNumber] = time; if (foundLinearAccelerationData) linearAccelerationData[rowNumber] = accel_row_vector; if (foundMagneticHeadingData) magneticHeadingData[rowNumber] = magneto_row_vector; if (foundAngularVelocityData) angularVelocityData[rowNumber] = gyro_row_vector; rotationsData[rowNumber] = orientation_row_vector; time += timeIncrement; rowNumber++; if (std::remainder(rowNumber, last_size) == 0) { // resize all Data/Matrices, double the size while keeping data int newSize = last_size*2; times.resize(newSize); // Repeat for Data matrices in use if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus); if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus); if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus); rotationsData.resizeKeep(newSize, n_imus); last_size = newSize; } } // Trim Matrices in use to actual data and move into tables int actualSize = rowNumber; times.resize(actualSize); // Repeat for Data matrices in use and create Tables from them or size 0 for empty linearAccelerationData.resizeKeep(foundLinearAccelerationData? actualSize: 0, n_imus); magneticHeadingData.resizeKeep(foundMagneticHeadingData?actualSize: 0, n_imus); angularVelocityData.resizeKeep(foundAngularVelocityData?actualSize:0, n_imus); rotationsData.resizeKeep(actualSize, n_imus); // Now create the tables from matrices // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading // Tables could be empty if data is not present in file(s) DataAdapter::OutputTables tables{}; auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels); orientationTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(Orientations, orientationTable); std::vector<double> emptyTimes; auto accelerationTable = (foundLinearAccelerationData ? std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels)); accelerationTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(LinearAccelerations, accelerationTable); auto magneticHeadingTable = (foundMagneticHeadingData ? std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels)); magneticHeadingTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(MagneticHeading, magneticHeadingTable); auto angularVelocityTable = (foundAngularVelocityData ? std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels)); angularVelocityTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(AngularVelocity, angularVelocityTable); return tables; } int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) { int returnIndex = -1; std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch); if (it != tokens.end()) returnIndex = static_cast<int>(std::distance(tokens.begin(), it)); return returnIndex; } } <commit_msg>One place to specify number of lines to sktp to locate headers in txt files<commit_after>#include <fstream> #include "Simbody.h" #include "Exception.h" #include "FileAdapter.h" #include "TimeSeriesTable.h" #include "XsensDataReader.h" namespace OpenSim { const std::string XsensDataReader::Orientations{ "orientations" }; const std::string XsensDataReader::LinearAccelerations{ "linear_accelerations" }; const std::string XsensDataReader::MagneticHeading{ "magnetic_heading" }; const std::string XsensDataReader::AngularVelocity{ "angular_velocity" }; XsensDataReader* XsensDataReader::clone() const { return new XsensDataReader{*this}; } DataAdapter::OutputTables XsensDataReader::extendRead(const std::string& folderName) const { std::vector<std::ifstream*> imuStreams; std::vector<std::string> labels; // files specified by prefix + file name exist double dataRate = SimTK::NaN; int packetCounterIndex = -1; int accIndex = -1; int gyroIndex = -1; int magIndex = -1; int rotationsIndex = -1; int n_imus = _settings.getProperty_ExperimentalSensors().size(); int last_size = 1024; // Will read data into pre-allocated Matrices in-memory rather than appendRow // on the fly to avoid the overhead of SimTK::Matrix_<SimTK::Quaternion> rotationsData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> linearAccelerationData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> magneticHeadingData{ last_size, n_imus }; SimTK::Matrix_<SimTK::Vec3> angularVelocityData{ last_size, n_imus }; std::vector<double> times; times.resize(last_size); std::string prefix = _settings.get_trial_prefix(); for (int index = 0; index < n_imus; ++index) { std::string prefix = _settings.get_trial_prefix(); const ExperimentalSensor& nextItem = _settings.get_ExperimentalSensors(index); auto fileName = folderName + prefix + nextItem.getName() +".txt"; auto* nextStream = new std::ifstream{ fileName }; OPENSIM_THROW_IF(!nextStream->good(), FileDoesNotExist, fileName); // Add imu name to labels labels.push_back(nextItem.get_name_in_model()); // Add corresponding stream to imuStreams imuStreams.push_back(nextStream); // Skip lines to get to data std::string line; int labels_line_number = 5; // Undocumented, just found empirically in Xsens output files for (int j = 0; j <= labels_line_number; j++) { std::getline(*nextStream, line); if (j == 1 && SimTK::isNaN(dataRate)) { // Extract Data rate from line 1 std::vector<std::string> tokens = FileAdapter::tokenize(line, ", "); // find Update Rate: and parse into dataRate if (tokens.size() < 4) continue; if (tokens[1] == "Update" && tokens[2] == "Rate:") { dataRate = std::stod(tokens[3]); } } if (j == labels_line_number) { // Find indices for PacketCounter, Acc_{X,Y,Z}, Gyr_{X,Y,Z}, Mag_{X,Y,Z} on line 5 std::vector<std::string> tokens = FileAdapter::tokenize(line, "\t"); if (packetCounterIndex == -1) packetCounterIndex = find_index(tokens, "PacketCounter"); if (accIndex == -1) accIndex = find_index(tokens, "Acc_X"); if (gyroIndex == -1) gyroIndex = find_index(tokens, "Gyr_X"); if (magIndex == -1) magIndex = find_index(tokens, "Mag_X"); if (rotationsIndex == -1) rotationsIndex = find_index(tokens, "Mat[1][1]"); } } } // internally keep track of what data was found in input files bool foundLinearAccelerationData = (accIndex != -1); bool foundMagneticHeadingData = (magIndex != -1); bool foundAngularVelocityData = (gyroIndex != -1); // If no Orientation data is available or dataRate can't be deduced we'll abort completely OPENSIM_THROW_IF((rotationsIndex == -1 || SimTK::isNaN(dataRate)), TableMissingHeader); // For all tables, will create row, stitch values from different files then append,time and timestep // are based on the first file bool done = false; double time = 0.0; double timeIncrement = 1 / dataRate; int rowNumber = 0; while (!done){ // Make vectors one per table TimeSeriesTableQuaternion::RowVector orientation_row_vector{ n_imus, SimTK::Quaternion() }; TimeSeriesTableVec3::RowVector accel_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector magneto_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; TimeSeriesTableVec3::RowVector gyro_row_vector{ n_imus, SimTK::Vec3(SimTK::NaN) }; // Cycle through the filles collating values int imu_index = 0; for (std::vector<std::ifstream*>::iterator it = imuStreams.begin(); it != imuStreams.end(); ++it, ++imu_index) { std::ifstream* nextStream = *it; // parse gyro info from imuStream std::vector<std::string> nextRow = FileAdapter::getNextLine(*nextStream, "\t\r"); if (nextRow.empty()) { done = true; break; } if (foundLinearAccelerationData) accel_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[accIndex]), std::stod(nextRow[accIndex + 1]), std::stod(nextRow[accIndex + 2])); if (foundMagneticHeadingData) magneto_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[magIndex]), std::stod(nextRow[magIndex + 1]), std::stod(nextRow[magIndex + 2])); if (foundAngularVelocityData) gyro_row_vector[imu_index] = SimTK::Vec3(std::stod(nextRow[gyroIndex]), std::stod(nextRow[gyroIndex + 1]), std::stod(nextRow[gyroIndex + 2])); // Create Mat33 then convert into Quaternion SimTK::Mat33 imu_matrix{ SimTK::NaN }; int matrix_entry_index = 0; for (int mcol = 0; mcol < 3; mcol++) { for (int mrow = 0; mrow < 3; mrow++) { imu_matrix[mrow][mcol] = std::stod(nextRow[rotationsIndex + matrix_entry_index]); matrix_entry_index++; } } // Convert imu_matrix to Quaternion SimTK::Rotation imu_rotation{ imu_matrix }; orientation_row_vector[imu_index] = imu_rotation.convertRotationToQuaternion(); } if (done) break; // append to the tables times[rowNumber] = time; if (foundLinearAccelerationData) linearAccelerationData[rowNumber] = accel_row_vector; if (foundMagneticHeadingData) magneticHeadingData[rowNumber] = magneto_row_vector; if (foundAngularVelocityData) angularVelocityData[rowNumber] = gyro_row_vector; rotationsData[rowNumber] = orientation_row_vector; time += timeIncrement; rowNumber++; if (std::remainder(rowNumber, last_size) == 0) { // resize all Data/Matrices, double the size while keeping data int newSize = last_size*2; times.resize(newSize); // Repeat for Data matrices in use if (foundLinearAccelerationData) linearAccelerationData.resizeKeep(newSize, n_imus); if (foundMagneticHeadingData) magneticHeadingData.resizeKeep(newSize, n_imus); if (foundAngularVelocityData) angularVelocityData.resizeKeep(newSize, n_imus); rotationsData.resizeKeep(newSize, n_imus); last_size = newSize; } } // Trim Matrices in use to actual data and move into tables int actualSize = rowNumber; times.resize(actualSize); // Repeat for Data matrices in use and create Tables from them or size 0 for empty linearAccelerationData.resizeKeep(foundLinearAccelerationData? actualSize: 0, n_imus); magneticHeadingData.resizeKeep(foundMagneticHeadingData?actualSize: 0, n_imus); angularVelocityData.resizeKeep(foundAngularVelocityData?actualSize:0, n_imus); rotationsData.resizeKeep(actualSize, n_imus); // Now create the tables from matrices // Create 4 tables for Rotations, LinearAccelerations, AngularVelocity, MagneticHeading // Tables could be empty if data is not present in file(s) DataAdapter::OutputTables tables{}; auto orientationTable = std::make_shared<TimeSeriesTableQuaternion>(times, rotationsData, labels); orientationTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(Orientations, orientationTable); std::vector<double> emptyTimes; auto accelerationTable = (foundLinearAccelerationData ? std::make_shared<TimeSeriesTableVec3>(times, linearAccelerationData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, linearAccelerationData, labels)); accelerationTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(LinearAccelerations, accelerationTable); auto magneticHeadingTable = (foundMagneticHeadingData ? std::make_shared<TimeSeriesTableVec3>(times, magneticHeadingData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, magneticHeadingData, labels)); magneticHeadingTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(MagneticHeading, magneticHeadingTable); auto angularVelocityTable = (foundAngularVelocityData ? std::make_shared<TimeSeriesTableVec3>(times, angularVelocityData, labels) : std::make_shared<TimeSeriesTableVec3>(emptyTimes, angularVelocityData, labels)); angularVelocityTable->updTableMetaData() .setValueForKey("DataRate", std::to_string(dataRate)); tables.emplace(AngularVelocity, angularVelocityTable); return tables; } int XsensDataReader::find_index(std::vector<std::string>& tokens, const std::string& keyToMatch) { int returnIndex = -1; std::vector<std::string>::iterator it = std::find(tokens.begin(), tokens.end(), keyToMatch); if (it != tokens.end()) returnIndex = static_cast<int>(std::distance(tokens.begin(), it)); return returnIndex; } } <|endoftext|>
<commit_before>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the top-level functionality for the LLVM interpreter. // This interpreter is designed to be a very simple, portable, inefficient // interpreter. // //===----------------------------------------------------------------------===// #include "Interpreter.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/ModuleProvider.h" using namespace llvm; static struct RegisterInterp { RegisterInterp() { Interpreter::Register(); } } InterpRegistrator; namespace llvm { void LinkInInterpreter() { } } /// create - Create a new interpreter object. This can never fail. /// ExecutionEngine *Interpreter::create(ModuleProvider *MP) { Module *M; try { M = MP->materializeModule(); } catch (...) { return 0; // error materializing the module. } // FIXME: This should probably compute the entire data layout std::string DataLayout; int Test = 0; *(char*)&Test = 1; // Return true if the host is little endian bool isLittleEndian = (Test == 1); DataLayout.append(isLittleEndian ? "e" : "E"); bool Ptr64 = sizeof(void*) == 8; DataLayout.append(Ptr64 ? "-p:64:64" : "-p:32:32"); M->setDataLayout(DataLayout); return new Interpreter(M); } //===----------------------------------------------------------------------===// // Interpreter ctor - Initialize stuff // Interpreter::Interpreter(Module *M) : ExecutionEngine(M), TD(M) { memset(&ExitValue, 0, sizeof(ExitValue)); setTargetData(&TD); // Initialize the "backend" initializeExecutionEngine(); initializeExternalFunctions(); emitGlobals(); IL = new IntrinsicLowering(TD); } Interpreter::~Interpreter() { delete IL; } void Interpreter::runAtExitHandlers () { while (!AtExitHandlers.empty()) { callFunction(AtExitHandlers.back(), std::vector<GenericValue>()); AtExitHandlers.pop_back(); run(); } } /// run - Start execution with the specified function and arguments. /// GenericValue Interpreter::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert (F && "Function *F was null at entry to run()"); // Try extra hard not to pass extra args to a function that isn't // expecting them. C programmers frequently bend the rules and // declare main() with fewer parameters than it actually gets // passed, and the interpreter barfs if you pass a function more // parameters than it is declared to take. This does not attempt to // take into account gratuitous differences in declared types, // though. std::vector<GenericValue> ActualArgs; const unsigned ArgCount = F->getFunctionType()->getNumParams(); for (unsigned i = 0; i < ArgCount; ++i) ActualArgs.push_back(ArgValues[i]); // Set up the function call. callFunction(F, ActualArgs); // Start executing the function. run(); return ExitValue; } <commit_msg>Remove tabs.<commit_after>//===- Interpreter.cpp - Top-Level LLVM Interpreter Implementation --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the top-level functionality for the LLVM interpreter. // This interpreter is designed to be a very simple, portable, inefficient // interpreter. // //===----------------------------------------------------------------------===// #include "Interpreter.h" #include "llvm/CodeGen/IntrinsicLowering.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/ModuleProvider.h" using namespace llvm; static struct RegisterInterp { RegisterInterp() { Interpreter::Register(); } } InterpRegistrator; namespace llvm { void LinkInInterpreter() { } } /// create - Create a new interpreter object. This can never fail. /// ExecutionEngine *Interpreter::create(ModuleProvider *MP) { Module *M; try { M = MP->materializeModule(); } catch (...) { return 0; // error materializing the module. } // FIXME: This should probably compute the entire data layout std::string DataLayout; int Test = 0; *(char*)&Test = 1; // Return true if the host is little endian bool isLittleEndian = (Test == 1); DataLayout.append(isLittleEndian ? "e" : "E"); bool Ptr64 = sizeof(void*) == 8; DataLayout.append(Ptr64 ? "-p:64:64" : "-p:32:32"); M->setDataLayout(DataLayout); return new Interpreter(M); } //===----------------------------------------------------------------------===// // Interpreter ctor - Initialize stuff // Interpreter::Interpreter(Module *M) : ExecutionEngine(M), TD(M) { memset(&ExitValue, 0, sizeof(ExitValue)); setTargetData(&TD); // Initialize the "backend" initializeExecutionEngine(); initializeExternalFunctions(); emitGlobals(); IL = new IntrinsicLowering(TD); } Interpreter::~Interpreter() { delete IL; } void Interpreter::runAtExitHandlers () { while (!AtExitHandlers.empty()) { callFunction(AtExitHandlers.back(), std::vector<GenericValue>()); AtExitHandlers.pop_back(); run(); } } /// run - Start execution with the specified function and arguments. /// GenericValue Interpreter::runFunction(Function *F, const std::vector<GenericValue> &ArgValues) { assert (F && "Function *F was null at entry to run()"); // Try extra hard not to pass extra args to a function that isn't // expecting them. C programmers frequently bend the rules and // declare main() with fewer parameters than it actually gets // passed, and the interpreter barfs if you pass a function more // parameters than it is declared to take. This does not attempt to // take into account gratuitous differences in declared types, // though. std::vector<GenericValue> ActualArgs; const unsigned ArgCount = F->getFunctionType()->getNumParams(); for (unsigned i = 0; i < ArgCount; ++i) ActualArgs.push_back(ArgValues[i]); // Set up the function call. callFunction(F, ActualArgs); // Start executing the function. run(); return ExitValue; } <|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/ui/webui/bidi_checker_web_ui_test.h" #include "base/base_paths.h" #include "base/i18n/rtl.h" #include "base/path_service.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/autofill/autofill_common_test.h" #include "chrome/browser/autofill/autofill_profile.h" #include "chrome/browser/autofill/personal_data_manager.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/history/history.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "ui/base/resource/resource_bundle.h" #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) #include <gtk/gtk.h> #endif // These tests are failing on linux views build. crbug.com/96891 #if defined(TOOLKIT_VIEWS) && defined(OS_LINUX) && !defined(OS_CHROMEOS) #define MAYBE_TestCrashesPageRTL DISABLED_TestCrashesPageRTL #define MAYBE_TestDownloadsPageRTL DISABLED_TestDownloadsPageRTL #define MAYBE_TestMainHistoryPageRTL DISABLED_TestMainHistoryPageRTL #define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL #define MAYBE_TestPluginsPageRTL DISABLED_TestPluginsPageRTL #define MAYBE_TestSettingsAutofillPageRTL DISABLED_TestSettingsAutofillPageRTL #define MAYBE_TestSettingsPageRTL DISABLED_TestSettingsPageRTL #else #define MAYBE_TestCrashesPageRTL TestCrashesPageRTL #define MAYBE_TestDownloadsPageRTL TestDownloadsPageRTL #define MAYBE_TestMainHistoryPageRTL TestMainHistoryPageRTL // Disabled, http://crbug.com/97453 #define MAYBE_TestNewTabPageRTL DISABLED_TestNewTabPageRTL #define MAYBE_TestPluginsPageRTL TestPluginsPageRTL #define MAYBE_TestSettingsAutofillPageRTL TestSettingsAutofillPageRTL #define MAYBE_TestSettingsPageRTL TestSettingsPageRTL #endif static const FilePath::CharType* kWebUIBidiCheckerLibraryJS = FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js"); namespace { FilePath WebUIBidiCheckerLibraryJSPath() { FilePath src_root; if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root)) LOG(ERROR) << "Couldn't find source root"; return src_root.Append(kWebUIBidiCheckerLibraryJS); } } static const FilePath::CharType* kBidiCheckerTestsJS = FILE_PATH_LITERAL("bidichecker_tests.js"); WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {} WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {} void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() { WebUIBrowserTest::SetUpInProcessBrowserTestFixture(); WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath()); WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS)); } void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[], bool isRTL) { ui_test_utils::NavigateToURL(browser(), GURL(pageURL)); ASSERT_TRUE(RunJavascriptTest("runBidiChecker", Value::CreateStringValue(pageURL), Value::CreateBooleanValue(isRTL))); } // WebUIBidiCheckerBrowserTestFakeBidi WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {} WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {} void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() { WebUIBidiCheckerBrowserTest::SetUpOnMainThread(); FilePath pak_path; app_locale_ = base::i18n::GetConfiguredLocale(); ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path)); pak_path = pak_path.DirName(); pak_path = pak_path.AppendASCII("pseudo_locales"); pak_path = pak_path.AppendASCII("fake-bidi"); pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak")); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path); ResourceBundle::ReloadSharedInstance("he"); #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL); #endif } void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() { WebUIBidiCheckerBrowserTest::CleanUpOnMainThread(); #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR); #endif ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath()); ResourceBundle::ReloadSharedInstance(app_locale_); } // Tests IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) { HistoryService* history_service = browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS); GURL history_url = GURL("http://www.ynet.co.il"); history_service->AddPage(history_url, history::SOURCE_BROWSED); string16 title; ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21", 12, &title)); history_service->SetPageTitle(history_url, title); RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestMainHistoryPageRTL) { HistoryService* history_service = browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS); GURL history_url = GURL("http://www.google.com"); history_service->AddPage(history_url, history::SOURCE_BROWSED); string16 title = UTF8ToUTF16("Google"); history_service->SetPageTitle(history_url, title); WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestCrashesPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestDownloadsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage( chrome::kChromeUIDownloadsURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestNewTabPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestPluginsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestSettingsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage( chrome::kChromeUISettingsURL, true); } #if defined(OS_MACOSX) // http://crbug.com/94642 #define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR #elif defined(OS_WIN) // http://crbug.com/95425 #define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR #else #define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR #endif // defined(OS_MACOSX) IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, MAYBE_TestSettingsAutofillPageLTR) { std::string url(chrome::kChromeUISettingsURL); url += std::string(chrome::kAutofillSubPage); autofill_test::DisableSystemServices(browser()->profile()); AutofillProfile profile; autofill_test::SetProfileInfo( &profile, "\xD7\x9E\xD7\xA9\xD7\x94", "\xD7\x91", "\xD7\x9B\xD7\x94\xD7\x9F", "[email protected]", "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E", "\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33", "\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36", "\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91", "", "66183", "\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C", "0000"); PersonalDataManager* personal_data_manager = PersonalDataManagerFactory::GetForProfile(browser()->profile()); ASSERT_TRUE(personal_data_manager); personal_data_manager->AddProfile(profile); RunBidiCheckerOnPage(url.c_str(), false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, MAYBE_TestSettingsAutofillPageRTL) { std::string url(chrome::kChromeUISettingsURL); url += std::string(chrome::kAutofillSubPage); autofill_test::DisableSystemServices(browser()->profile()); AutofillProfile profile; autofill_test::SetProfileInfo( &profile, "Milton", "C.", "Waddams", "[email protected]", "Initech", "4120 Freidrich Lane", "Basement", "Austin", "Texas", "78744", "United States", "5125551234"); PersonalDataManager* personal_data_manager = PersonalDataManagerFactory::GetForProfile(browser()->profile()); ASSERT_TRUE(personal_data_manager); personal_data_manager->AddProfile(profile); WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true); } <commit_msg>Fixing bidi checker issues 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/ui/webui/bidi_checker_web_ui_test.h" #include "base/base_paths.h" #include "base/i18n/rtl.h" #include "base/path_service.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/autofill/autofill_common_test.h" #include "chrome/browser/autofill/autofill_profile.h" #include "chrome/browser/autofill/personal_data_manager.h" #include "chrome/browser/autofill/personal_data_manager_factory.h" #include "chrome/browser/history/history.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "ui/base/resource/resource_bundle.h" #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) #include <gtk/gtk.h> #endif static const FilePath::CharType* kWebUIBidiCheckerLibraryJS = FILE_PATH_LITERAL("third_party/bidichecker/bidichecker_packaged.js"); namespace { FilePath WebUIBidiCheckerLibraryJSPath() { FilePath src_root; if (!PathService::Get(base::DIR_SOURCE_ROOT, &src_root)) LOG(ERROR) << "Couldn't find source root"; return src_root.Append(kWebUIBidiCheckerLibraryJS); } } static const FilePath::CharType* kBidiCheckerTestsJS = FILE_PATH_LITERAL("bidichecker_tests.js"); WebUIBidiCheckerBrowserTest::~WebUIBidiCheckerBrowserTest() {} WebUIBidiCheckerBrowserTest::WebUIBidiCheckerBrowserTest() {} void WebUIBidiCheckerBrowserTest::SetUpInProcessBrowserTestFixture() { WebUIBrowserTest::SetUpInProcessBrowserTestFixture(); WebUIBrowserTest::AddLibrary(WebUIBidiCheckerLibraryJSPath()); WebUIBrowserTest::AddLibrary(FilePath(kBidiCheckerTestsJS)); } void WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(const char pageURL[], bool isRTL) { ui_test_utils::NavigateToURL(browser(), GURL(pageURL)); ASSERT_TRUE(RunJavascriptTest("runBidiChecker", Value::CreateStringValue(pageURL), Value::CreateBooleanValue(isRTL))); } // WebUIBidiCheckerBrowserTestFakeBidi WebUIBidiCheckerBrowserTestFakeBidi::~WebUIBidiCheckerBrowserTestFakeBidi() {} WebUIBidiCheckerBrowserTestFakeBidi::WebUIBidiCheckerBrowserTestFakeBidi() {} void WebUIBidiCheckerBrowserTestFakeBidi::SetUpOnMainThread() { WebUIBidiCheckerBrowserTest::SetUpOnMainThread(); FilePath pak_path; app_locale_ = base::i18n::GetConfiguredLocale(); ASSERT_TRUE(PathService::Get(base::FILE_MODULE, &pak_path)); pak_path = pak_path.DirName(); pak_path = pak_path.AppendASCII("pseudo_locales"); pak_path = pak_path.AppendASCII("fake-bidi"); pak_path = pak_path.ReplaceExtension(FILE_PATH_LITERAL("pak")); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(pak_path); ResourceBundle::ReloadSharedInstance("he"); base::i18n::SetICUDefaultLocale("he"); #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_RTL); #endif } void WebUIBidiCheckerBrowserTestFakeBidi::CleanUpOnMainThread() { WebUIBidiCheckerBrowserTest::CleanUpOnMainThread(); #if defined(OS_POSIX) && defined(TOOLKIT_USES_GTK) gtk_widget_set_default_direction(GTK_TEXT_DIR_LTR); #endif base::i18n::SetICUDefaultLocale(app_locale_); ResourceBundle::GetSharedInstance().OverrideLocalePakForTest(FilePath()); ResourceBundle::ReloadSharedInstance(app_locale_); } // Tests IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestMainHistoryPageLTR) { HistoryService* history_service = browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS); GURL history_url = GURL("http://www.ynet.co.il"); history_service->AddPage(history_url, history::SOURCE_BROWSED); string16 title; ASSERT_TRUE(UTF8ToUTF16("\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x21", 12, &title)); history_service->SetPageTitle(history_url, title); RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestMainHistoryPageRTL) { HistoryService* history_service = browser()->profile()->GetHistoryService(Profile::IMPLICIT_ACCESS); GURL history_url = GURL("http://www.google.com"); history_service->AddPage(history_url, history::SOURCE_BROWSED); string16 title = UTF8ToUTF16("Google"); history_service->SetPageTitle(history_url, title); WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIHistoryURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestAboutPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIAboutURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestBugReportPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIBugReportURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestCrashesPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestCrashesPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUICrashesURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestDownloadsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIDownloadsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestDownloadsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage( chrome::kChromeUIDownloadsURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestNewTabPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, false); } // http://crbug.com/97453 IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, DISABLED_TestNewTabPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUINewTabURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestPluginsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestPluginsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(chrome::kChromeUIPluginsURL, true); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, TestSettingsPageLTR) { RunBidiCheckerOnPage(chrome::kChromeUISettingsURL, false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestSettingsPageRTL) { WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage( chrome::kChromeUISettingsURL, true); } #if defined(OS_MACOSX) // http://crbug.com/94642 #define MAYBE_TestSettingsAutofillPageLTR FLAKY_TestSettingsAutofillPageLTR #elif defined(OS_WIN) // http://crbug.com/95425 #define MAYBE_TestSettingsAutofillPageLTR FAILS_TestSettingsAutofillPageLTR #else #define MAYBE_TestSettingsAutofillPageLTR TestSettingsAutofillPageLTR #endif // defined(OS_MACOSX) IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTest, MAYBE_TestSettingsAutofillPageLTR) { std::string url(chrome::kChromeUISettingsURL); url += std::string(chrome::kAutofillSubPage); autofill_test::DisableSystemServices(browser()->profile()); AutofillProfile profile; autofill_test::SetProfileInfo( &profile, "\xD7\x9E\xD7\xA9\xD7\x94", "\xD7\x91", "\xD7\x9B\xD7\x94\xD7\x9F", "[email protected]", "\xD7\x91\xD7\x93\xD7\x99\xD7\xA7\xD7\x94\x20\xD7\x91\xD7\xA2\xD7\x9E", "\xD7\x93\xD7\xA8\xD7\x9A\x20\xD7\x9E\xD7\xA0\xD7\x97\xD7\x9D\x20\xD7\x91\xD7\x92\xD7\x99\xD7\x9F\x20\x32\x33", "\xD7\xA7\xD7\x95\xD7\x9E\xD7\x94\x20\x32\x36", "\xD7\xAA\xD7\x9C\x20\xD7\x90\xD7\x91\xD7\x99\xD7\x91", "", "66183", "\xD7\x99\xD7\xA9\xD7\xA8\xD7\x90\xD7\x9C", "0000"); PersonalDataManager* personal_data_manager = PersonalDataManagerFactory::GetForProfile(browser()->profile()); ASSERT_TRUE(personal_data_manager); personal_data_manager->AddProfile(profile); RunBidiCheckerOnPage(url.c_str(), false); } IN_PROC_BROWSER_TEST_F(WebUIBidiCheckerBrowserTestFakeBidi, TestSettingsAutofillPageRTL) { std::string url(chrome::kChromeUISettingsURL); url += std::string(chrome::kAutofillSubPage); autofill_test::DisableSystemServices(browser()->profile()); AutofillProfile profile; autofill_test::SetProfileInfo( &profile, "Milton", "C.", "Waddams", "[email protected]", "Initech", "4120 Freidrich Lane", "Basement", "Austin", "Texas", "78744", "United States", "5125551234"); PersonalDataManager* personal_data_manager = PersonalDataManagerFactory::GetForProfile(browser()->profile()); ASSERT_TRUE(personal_data_manager); personal_data_manager->AddProfile(profile); WebUIBidiCheckerBrowserTest::RunBidiCheckerOnPage(url.c_str(), true); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/prefs/pref_service.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_util.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "google_apis/gaia/gaia_urls.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/escape.h" #include "net/base/network_change_notifier.h" #include "net/base/url_util.h" #include "ui/base/l10n/l10n_util.h" using content::WebContents; namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyAutoClose[] = "auto_close"; const char kSyncPromoQueryKeyContinue[] = "continue"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; const char kSyncPromoQueryKeySource[] = "source"; // Gaia cannot support about:blank as a continue URL, so using a hosted blank // page instead. const char kContinueUrl[] = "https://www.google.com/intl/%s/chrome/blank.html?%s=%d"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Forces the web based signin flow when set. bool g_force_web_based_signin_flow = false; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; // Enable for both organic and distribution. return true; } content::WebUIDataSource* CreateSyncUIHTMLSource(content::WebUI* web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUISyncPromoHost); DictionaryValue localized_strings; options::CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); html_source->AddLocalizedStrings(localized_strings); html_source->SetJsonPath(kStringsJsFile); html_source->AddResourcePath(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->SetDefaultResource(IDR_SYNC_PROMO_HTML); html_source->SetUseJsonJSFormatV2(); return html_source; } } // namespace SyncPromoUI::SyncPromoUI(content::WebUI* web_ui) : WebUIController(web_ui) { SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); web_ui->AddMessageHandler(handler); // Set up the chrome://theme/ source. Profile* profile = Profile::FromWebUI(web_ui); ThemeSource* theme = new ThemeSource(profile); content::URLDataSource::Add(profile, theme); // Set up the sync promo source. content::WebUIDataSource::Add(profile, CreateSyncUIHTMLSource(web_ui)); sync_promo_trial::RecordUserShownPromo(web_ui); } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #else // Don't bother if we don't have any kind of network connection. if (net::NetworkChangeNotifier::IsOffline()) return false; // Display the signin promo if the user is not signed in. SigninManager* signin = SigninManagerFactory::GetForProfile( profile->GetOriginalProfile()); return !signin->AuthInProgress() && signin->IsSigninAllowed() && signin->GetAuthenticatedUsername().empty(); #endif } // static void SyncPromoUI::RegisterUserPrefs(PrefRegistrySyncable* registry) { registry->RegisterIntegerPref(prefs::kSyncPromoStartupCount, 0, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kSyncPromoUserSkipped, false, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefRegistrySyncable::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(registry); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService* prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo for Google Chrome builds. #if defined(GOOGLE_CHROME_BUILD) return true; #else return false; #endif } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, Source source, bool auto_close) { DCHECK_NE(SOURCE_UNKNOWN, source); std::string url_string; if (UseWebBasedSigninFlow()) { // Build a Gaia-based URL that can be used to sign the user into chrome. // There are required request parameters: // // - tell Gaia which service the user is signing into. In this case, // a chrome sign in uses the service "chromiumsync" // - provide a continue URL. This is the URL that Gaia will redirect to // once the sign is complete. // // The continue URL includes a source parameter that can be extracted using // the function GetSourceForSyncPromoURL() below. This is used to know // which of the chrome sign in access points was used to sign the userr in. // See OneClickSigninHelper for details. url_string = GaiaUrls::GetInstance()->service_login_url(); url_string.append("?service=chromiumsync&sarp=1&rm=hide"); const std::string& locale = g_browser_process->GetApplicationLocale(); std::string continue_url = base::StringPrintf(kContinueUrl, locale.c_str(), kSyncPromoQueryKeySource, static_cast<int>(source)); base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyContinue, net::EscapeQueryParamValue( continue_url, false).c_str()); } else { url_string = base::StringPrintf("%s?%s=%d", chrome::kChromeUISyncPromoURL, kSyncPromoQueryKeySource, static_cast<int>(source)); if (auto_close) base::StringAppendF(&url_string, "&%s=1", kSyncPromoQueryKeyAutoClose); if (!next_page.spec().empty()) { base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyNextPage, net::EscapeQueryParamValue(next_page.spec(), false).c_str()); } } return GURL(url_string); } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { const char* key_name = UseWebBasedSigninFlow() ? kSyncPromoQueryKeyContinue : kSyncPromoQueryKeyNextPage; std::string value; if (net::GetValueForKeyInQuery(url, key_name, &value)) { return GURL(value); } return GURL(); } // static SyncPromoUI::Source SyncPromoUI::GetSourceForSyncPromoURL(const GURL& url) { std::string value; if (net::GetValueForKeyInQuery(url, kSyncPromoQueryKeySource, &value)) { int source = 0; if (base::StringToInt(value, &source) && source >= SOURCE_START_PAGE && source < SOURCE_UNKNOWN) { return static_cast<Source>(source); } } return SOURCE_UNKNOWN; } // static bool SyncPromoUI::GetAutoCloseForSyncPromoURL(const GURL& url) { std::string value; if (net::GetValueForKeyInQuery(url, kSyncPromoQueryKeyAutoClose, &value)) { int source = 0; base::StringToInt(value, &source); return (source == 1); } return false; } // static bool SyncPromoUI::UseWebBasedSigninFlow() { #if defined(ENABLE_ONE_CLICK_SIGNIN) return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseClientLoginSigninFlow) || g_force_web_based_signin_flow; #else return false; #endif } // static void SyncPromoUI::ForceWebBasedSigninFlowForTesting(bool force) { g_force_web_based_signin_flow = force; } <commit_msg>Adding a check to not show sync promo for incognito profiles. <commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/sync_promo/sync_promo_ui.h" #include "base/command_line.h" #include "base/prefs/pref_service.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/strings/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/first_run/first_run.h" #include "chrome/browser/google/google_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/ui/webui/options/core_options_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_handler.h" #include "chrome/browser/ui/webui/sync_promo/sync_promo_trial.h" #include "chrome/browser/ui/webui/theme_source.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/net/url_util.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/browser/url_data_source.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "google_apis/gaia/gaia_urls.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "net/base/escape.h" #include "net/base/network_change_notifier.h" #include "net/base/url_util.h" #include "ui/base/l10n/l10n_util.h" using content::WebContents; namespace { const char kStringsJsFile[] = "strings.js"; const char kSyncPromoJsFile[] = "sync_promo.js"; const char kSyncPromoQueryKeyAutoClose[] = "auto_close"; const char kSyncPromoQueryKeyContinue[] = "continue"; const char kSyncPromoQueryKeyNextPage[] = "next_page"; const char kSyncPromoQueryKeySource[] = "source"; // Gaia cannot support about:blank as a continue URL, so using a hosted blank // page instead. const char kContinueUrl[] = "https://www.google.com/intl/%s/chrome/blank.html?%s=%d"; // The maximum number of times we want to show the sync promo at startup. const int kSyncPromoShowAtStartupMaximum = 10; // Forces the web based signin flow when set. bool g_force_web_based_signin_flow = false; // Checks we want to show the sync promo for the given brand. bool AllowPromoAtStartupForCurrentBrand() { std::string brand; google_util::GetBrand(&brand); if (brand.empty()) return true; if (google_util::IsInternetCafeBrandCode(brand)) return false; // Enable for both organic and distribution. return true; } content::WebUIDataSource* CreateSyncUIHTMLSource(content::WebUI* web_ui) { content::WebUIDataSource* html_source = content::WebUIDataSource::Create(chrome::kChromeUISyncPromoHost); DictionaryValue localized_strings; options::CoreOptionsHandler::GetStaticLocalizedValues(&localized_strings); SyncSetupHandler::GetStaticLocalizedValues(&localized_strings, web_ui); html_source->AddLocalizedStrings(localized_strings); html_source->SetJsonPath(kStringsJsFile); html_source->AddResourcePath(kSyncPromoJsFile, IDR_SYNC_PROMO_JS); html_source->SetDefaultResource(IDR_SYNC_PROMO_HTML); html_source->SetUseJsonJSFormatV2(); return html_source; } } // namespace SyncPromoUI::SyncPromoUI(content::WebUI* web_ui) : WebUIController(web_ui) { SyncPromoHandler* handler = new SyncPromoHandler( g_browser_process->profile_manager()); web_ui->AddMessageHandler(handler); // Set up the chrome://theme/ source. Profile* profile = Profile::FromWebUI(web_ui); ThemeSource* theme = new ThemeSource(profile); content::URLDataSource::Add(profile, theme); // Set up the sync promo source. content::WebUIDataSource::Add(profile, CreateSyncUIHTMLSource(web_ui)); sync_promo_trial::RecordUserShownPromo(web_ui); } // static bool SyncPromoUI::HasShownPromoAtStartup(Profile* profile) { return profile->GetPrefs()->HasPrefPath(prefs::kSyncPromoStartupCount); } // static bool SyncPromoUI::ShouldShowSyncPromo(Profile* profile) { #if defined(OS_CHROMEOS) // There's no need to show the sync promo on cros since cros users are logged // into sync already. return false; #else // Don't bother if we don't have any kind of network connection. if (net::NetworkChangeNotifier::IsOffline()) return false; // Don't show if the profile is an incognito. if (profile->IsOffTheRecord()) return false; // Display the signin promo if the user is not signed in. SigninManager* signin = SigninManagerFactory::GetForProfile( profile->GetOriginalProfile()); return !signin->AuthInProgress() && signin->IsSigninAllowed() && signin->GetAuthenticatedUsername().empty(); #endif } // static void SyncPromoUI::RegisterUserPrefs(PrefRegistrySyncable* registry) { registry->RegisterIntegerPref(prefs::kSyncPromoStartupCount, 0, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kSyncPromoUserSkipped, false, PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterBooleanPref(prefs::kSyncPromoShowOnFirstRunAllowed, true, PrefRegistrySyncable::UNSYNCABLE_PREF); SyncPromoHandler::RegisterUserPrefs(registry); } // static bool SyncPromoUI::ShouldShowSyncPromoAtStartup(Profile* profile, bool is_new_profile) { DCHECK(profile); if (!ShouldShowSyncPromo(profile)) return false; const CommandLine& command_line = *CommandLine::ForCurrentProcess(); if (command_line.HasSwitch(switches::kNoFirstRun)) is_new_profile = false; if (!is_new_profile) { if (!HasShownPromoAtStartup(profile)) return false; } if (HasUserSkippedSyncPromo(profile)) return false; // For Chinese users skip the sync promo. if (g_browser_process->GetApplicationLocale() == "zh-CN") return false; PrefService* prefs = profile->GetPrefs(); int show_count = prefs->GetInteger(prefs::kSyncPromoStartupCount); if (show_count >= kSyncPromoShowAtStartupMaximum) return false; // This pref can be set in the master preferences file to allow or disallow // showing the sync promo at startup. if (prefs->HasPrefPath(prefs::kSyncPromoShowOnFirstRunAllowed)) return prefs->GetBoolean(prefs::kSyncPromoShowOnFirstRunAllowed); // For now don't show the promo for some brands. if (!AllowPromoAtStartupForCurrentBrand()) return false; // Default to show the promo for Google Chrome builds. #if defined(GOOGLE_CHROME_BUILD) return true; #else return false; #endif } void SyncPromoUI::DidShowSyncPromoAtStartup(Profile* profile) { int show_count = profile->GetPrefs()->GetInteger( prefs::kSyncPromoStartupCount); show_count++; profile->GetPrefs()->SetInteger(prefs::kSyncPromoStartupCount, show_count); } bool SyncPromoUI::HasUserSkippedSyncPromo(Profile* profile) { return profile->GetPrefs()->GetBoolean(prefs::kSyncPromoUserSkipped); } void SyncPromoUI::SetUserSkippedSyncPromo(Profile* profile) { profile->GetPrefs()->SetBoolean(prefs::kSyncPromoUserSkipped, true); } // static GURL SyncPromoUI::GetSyncPromoURL(const GURL& next_page, Source source, bool auto_close) { DCHECK_NE(SOURCE_UNKNOWN, source); std::string url_string; if (UseWebBasedSigninFlow()) { // Build a Gaia-based URL that can be used to sign the user into chrome. // There are required request parameters: // // - tell Gaia which service the user is signing into. In this case, // a chrome sign in uses the service "chromiumsync" // - provide a continue URL. This is the URL that Gaia will redirect to // once the sign is complete. // // The continue URL includes a source parameter that can be extracted using // the function GetSourceForSyncPromoURL() below. This is used to know // which of the chrome sign in access points was used to sign the userr in. // See OneClickSigninHelper for details. url_string = GaiaUrls::GetInstance()->service_login_url(); url_string.append("?service=chromiumsync&sarp=1&rm=hide"); const std::string& locale = g_browser_process->GetApplicationLocale(); std::string continue_url = base::StringPrintf(kContinueUrl, locale.c_str(), kSyncPromoQueryKeySource, static_cast<int>(source)); base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyContinue, net::EscapeQueryParamValue( continue_url, false).c_str()); } else { url_string = base::StringPrintf("%s?%s=%d", chrome::kChromeUISyncPromoURL, kSyncPromoQueryKeySource, static_cast<int>(source)); if (auto_close) base::StringAppendF(&url_string, "&%s=1", kSyncPromoQueryKeyAutoClose); if (!next_page.spec().empty()) { base::StringAppendF(&url_string, "&%s=%s", kSyncPromoQueryKeyNextPage, net::EscapeQueryParamValue(next_page.spec(), false).c_str()); } } return GURL(url_string); } // static GURL SyncPromoUI::GetNextPageURLForSyncPromoURL(const GURL& url) { const char* key_name = UseWebBasedSigninFlow() ? kSyncPromoQueryKeyContinue : kSyncPromoQueryKeyNextPage; std::string value; if (net::GetValueForKeyInQuery(url, key_name, &value)) { return GURL(value); } return GURL(); } // static SyncPromoUI::Source SyncPromoUI::GetSourceForSyncPromoURL(const GURL& url) { std::string value; if (net::GetValueForKeyInQuery(url, kSyncPromoQueryKeySource, &value)) { int source = 0; if (base::StringToInt(value, &source) && source >= SOURCE_START_PAGE && source < SOURCE_UNKNOWN) { return static_cast<Source>(source); } } return SOURCE_UNKNOWN; } // static bool SyncPromoUI::GetAutoCloseForSyncPromoURL(const GURL& url) { std::string value; if (net::GetValueForKeyInQuery(url, kSyncPromoQueryKeyAutoClose, &value)) { int source = 0; base::StringToInt(value, &source); return (source == 1); } return false; } // static bool SyncPromoUI::UseWebBasedSigninFlow() { #if defined(ENABLE_ONE_CLICK_SIGNIN) return !CommandLine::ForCurrentProcess()->HasSwitch( switches::kUseClientLoginSigninFlow) || g_force_web_based_signin_flow; #else return false; #endif } // static void SyncPromoUI::ForceWebBasedSigninFlowForTesting(bool force) { g_force_web_based_signin_flow = force; } <|endoftext|>