{"text":"\/\/===------------------------ memory_resource.cpp -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"experimental\/memory_resource\"\n\n#ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER\n#include \"atomic\"\n#else\n#include \"mutex\"\n#endif\n\n_LIBCPP_BEGIN_NAMESPACE_LFTS_PMR\n\n\/\/ memory_resource\n\n\/\/memory_resource::~memory_resource() {}\n\n\/\/ new_delete_resource()\n\nclass _LIBCPP_TYPE_VIS_ONLY __new_delete_memory_resource_imp\n : public memory_resource\n{\npublic:\n ~__new_delete_memory_resource_imp() = default;\n\nprotected:\n virtual void* do_allocate(size_t __size, size_t __align)\n { return __allocate(__size); }\n\n virtual void do_deallocate(void * __p, size_t, size_t)\n { __deallocate(__p); }\n\n virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT\n { return &__other == this; }\n};\n\n\/\/ null_memory_resource()\n\nclass _LIBCPP_TYPE_VIS_ONLY __null_memory_resource_imp\n : public memory_resource\n{\npublic:\n ~__null_memory_resource_imp() = default;\n\nprotected:\n virtual void* do_allocate(size_t, size_t) {\n#ifndef _LIBCPP_HAS_NO_EXCEPTIONS\n throw std::bad_alloc();\n#else\n abort();\n#endif\n }\n virtual void do_deallocate(void *, size_t, size_t) {}\n virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT\n { return &__other == this; }\n};\n\nunion ResourceInitHelper {\n struct {\n __new_delete_memory_resource_imp new_delete_res;\n __null_memory_resource_imp null_res;\n } resources;\n char dummy;\n _LIBCPP_CONSTEXPR_AFTER_CXX11 ResourceInitHelper() : resources() {}\n ~ResourceInitHelper() {}\n};\n\/\/ When compiled in C++14 this initialization should be a constant expression.\n\/\/ Only in C++11 is \"init_priority\" needed to ensure initialization order.\nResourceInitHelper res_init __attribute__((init_priority (101)));\n\nmemory_resource * new_delete_resource() _NOEXCEPT {\n return &res_init.resources.new_delete_res;\n}\n\nmemory_resource * null_memory_resource() _NOEXCEPT {\n return &res_init.resources.null_res;\n}\n\n\/\/ default_memory_resource()\n\nstatic memory_resource *\n__default_memory_resource(bool set = false, memory_resource * new_res = nullptr) _NOEXCEPT\n{\n#ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER\n static atomic __res =\n ATOMIC_VAR_INIT(&res_init.resources.new_delete_res);\n if (set) {\n new_res = new_res ? new_res : new_delete_resource();\n \/\/ TODO: Can a weaker ordering be used?\n return _VSTD::atomic_exchange_explicit(\n &__res, new_res, memory_order::memory_order_acq_rel);\n }\n else {\n return _VSTD::atomic_load_explicit(\n &__res, memory_order::memory_order_acquire);\n }\n#else\n static memory_resource * res = &res_init.resources.new_delete_res;\n static mutex res_lock;\n if (set) {\n new_res = new_res ? new_res : new_delete_resource();\n lock_guard guard(res_lock);\n memory_resource * old_res = res;\n res = new_res;\n return old_res;\n } else {\n lock_guard guard(res_lock);\n return res;\n }\n#endif\n}\n\nmemory_resource * get_default_resource() _NOEXCEPT\n{\n return __default_memory_resource();\n}\n\nmemory_resource * set_default_resource(memory_resource * __new_res) _NOEXCEPT\n{\n return __default_memory_resource(true, __new_res);\n}\n\n_LIBCPP_END_NAMESPACE_LFTS_PMRFix one more usage of _LIBCPP_HAS_NO_EXCEPTIONS\/\/===------------------------ memory_resource.cpp -------------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is dual licensed under the MIT and the University of Illinois Open\n\/\/ Source Licenses. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"experimental\/memory_resource\"\n\n#ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER\n#include \"atomic\"\n#else\n#include \"mutex\"\n#endif\n\n_LIBCPP_BEGIN_NAMESPACE_LFTS_PMR\n\n\/\/ memory_resource\n\n\/\/memory_resource::~memory_resource() {}\n\n\/\/ new_delete_resource()\n\nclass _LIBCPP_TYPE_VIS_ONLY __new_delete_memory_resource_imp\n : public memory_resource\n{\npublic:\n ~__new_delete_memory_resource_imp() = default;\n\nprotected:\n virtual void* do_allocate(size_t __size, size_t __align)\n { return __allocate(__size); }\n\n virtual void do_deallocate(void * __p, size_t, size_t)\n { __deallocate(__p); }\n\n virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT\n { return &__other == this; }\n};\n\n\/\/ null_memory_resource()\n\nclass _LIBCPP_TYPE_VIS_ONLY __null_memory_resource_imp\n : public memory_resource\n{\npublic:\n ~__null_memory_resource_imp() = default;\n\nprotected:\n virtual void* do_allocate(size_t, size_t) {\n#ifndef _LIBCPP_NO_EXCEPTIONS\n throw std::bad_alloc();\n#else\n abort();\n#endif\n }\n virtual void do_deallocate(void *, size_t, size_t) {}\n virtual bool do_is_equal(memory_resource const & __other) const _NOEXCEPT\n { return &__other == this; }\n};\n\nunion ResourceInitHelper {\n struct {\n __new_delete_memory_resource_imp new_delete_res;\n __null_memory_resource_imp null_res;\n } resources;\n char dummy;\n _LIBCPP_CONSTEXPR_AFTER_CXX11 ResourceInitHelper() : resources() {}\n ~ResourceInitHelper() {}\n};\n\/\/ When compiled in C++14 this initialization should be a constant expression.\n\/\/ Only in C++11 is \"init_priority\" needed to ensure initialization order.\nResourceInitHelper res_init __attribute__((init_priority (101)));\n\nmemory_resource * new_delete_resource() _NOEXCEPT {\n return &res_init.resources.new_delete_res;\n}\n\nmemory_resource * null_memory_resource() _NOEXCEPT {\n return &res_init.resources.null_res;\n}\n\n\/\/ default_memory_resource()\n\nstatic memory_resource *\n__default_memory_resource(bool set = false, memory_resource * new_res = nullptr) _NOEXCEPT\n{\n#ifndef _LIBCPP_HAS_NO_ATOMIC_HEADER\n static atomic __res =\n ATOMIC_VAR_INIT(&res_init.resources.new_delete_res);\n if (set) {\n new_res = new_res ? new_res : new_delete_resource();\n \/\/ TODO: Can a weaker ordering be used?\n return _VSTD::atomic_exchange_explicit(\n &__res, new_res, memory_order::memory_order_acq_rel);\n }\n else {\n return _VSTD::atomic_load_explicit(\n &__res, memory_order::memory_order_acquire);\n }\n#else\n static memory_resource * res = &res_init.resources.new_delete_res;\n static mutex res_lock;\n if (set) {\n new_res = new_res ? new_res : new_delete_resource();\n lock_guard guard(res_lock);\n memory_resource * old_res = res;\n res = new_res;\n return old_res;\n } else {\n lock_guard guard(res_lock);\n return res;\n }\n#endif\n}\n\nmemory_resource * get_default_resource() _NOEXCEPT\n{\n return __default_memory_resource();\n}\n\nmemory_resource * set_default_resource(memory_resource * __new_res) _NOEXCEPT\n{\n return __default_memory_resource(true, __new_res);\n}\n\n_LIBCPP_END_NAMESPACE_LFTS_PMR<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015, LAAS-CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core.\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core. If not, see .\n\n#include \n#include \n#include \n\nnamespace hpp {\n namespace core {\n void complement (size_type size, const SizeIntervals_t& intervals,\n\t\t SizeIntervals_t& result)\n {\n std::vector unionOfIntervals (size+1, false);\n for (SizeIntervals_t::const_iterator it = intervals.begin ();\n\t it != intervals.end (); ++it) {\n\tfor (size_type i=it->first; i < it->first + it->second; ++i) {\n\t unionOfIntervals [i] = true;\n\t}\n }\n unionOfIntervals [size] = true;\n unsigned int state = 0;\n SizeInterval_t interval;\n for (size_type i=0; i <= (size_type) unionOfIntervals.size (); ++i) {\n\tif ((state == 0) && (unionOfIntervals [i] == false)) {\n\t \/\/ start a new interval\n\t state = 1;\n\t interval.first = i;\n\t} else if ((state == 1) && unionOfIntervals [i] == true) {\n\t \/\/ finish current interval\n\t state = 0;\n\t interval.second = i - interval.first;\n\t result.push_back (interval);\n\t}\n }\n }\n\n HPP_PREDEF_CLASS (ImplicitFunction);\n typedef boost::shared_ptr ImplicitFunctionPtr_t;\n class ImplicitFunction : public DifferentiableFunction\n {\n public:\n static ImplicitFunctionPtr_t create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf, const SizeIntervals_t& outputVelocity)\n {\n\tImplicitFunction* ptr = new ImplicitFunction\n\t (robot, function, outputConf, outputVelocity);\n\treturn ImplicitFunctionPtr_t (ptr);\n }\n void solve (ConfigurationOut_t configuration, vectorIn_t rhs)\n {\n\tassert (rhs.size () == output_.size ());\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t configuration.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\t(*inputToOutput_) (output_, input_);\n\tindex = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputConfIntervals_.begin ();\n\t it != outputConfIntervals_.end (); ++it) {\n\t configuration.segment (it->first, it->second) =\n\t output_.segment (index, it->second) +\n\t rhs.segment (index, it->second);\n\t index += it->second;\n\t}\n }\n\n protected:\n ImplicitFunction (const DevicePtr_t& robot,\n\t\t\tconst DifferentiableFunctionPtr_t& function,\n\t\t\tconst SizeIntervals_t& outputConf,\n\t\t\tconst SizeIntervals_t& outputVelocity)\n\t: DifferentiableFunction (robot->configSize (), robot->numberDof (),\n\t\t\t\t function->outputSize (),\n\t\t\t\t function->outputDerivativeSize ()),\n\t robot_ (robot), inputToOutput_ (function), inputConfIntervals_ (),\n\t inputDerivIntervals_ (), outputConfIntervals_ (outputConf),\n\t outputDerivIntervals_ (outputVelocity)\n {\n\t\/\/ Check input consistency\n\t\/\/ Each configuration variable is either input or output\n\tassert (function->inputSize () + function->outputSize () ==\n\t\trobot->configSize ());\n\t\/\/ Each velocity variable is either input or output\n\tassert (function->inputDerivativeSize () +\n\t\tfunction->outputDerivativeSize () == robot->numberDof ());\n\tinput_.resize (function->inputSize ());\n\toutput_.resize (function->outputSize ());\n\tJ_.resize (function->outputDerivativeSize (),\n\t\t function->inputDerivativeSize ());\n\tsize_type size = 0;\n\t\/\/ Sum of configuration output interval sizes equal function output size\n\tfor (SizeIntervals_t::const_iterator it = outputConf.begin ();\n\t it != outputConf.end (); ++it) {\n\t size += it->second;\n\t}\n\tassert (size == function->outputSize ());\n\t\/\/ Sum of velocity output interval sizes equal function output\n\t\/\/ derivative size\n\tsize = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputVelocity.begin ();\n\t it != outputVelocity.end (); ++it) {\n\t size += it->second;\n\t}\n\tassert (size == function->outputDerivativeSize ());\n\t\/\/ Conpute input intervals\n\tcomplement (robot->configSize (), outputConfIntervals_,\n\t\t inputConfIntervals_);\n\tcomplement (robot->numberDof (), outputDerivIntervals_,\n\t\t inputDerivIntervals_);\n }\n\n void impl_compute (vectorOut_t result, vectorIn_t argument) const\n {\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputConfIntervals_.begin ();\n\t it != outputConfIntervals_.end (); ++it) {\n\t result.segment (index, it->second) =\n\t argument.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\tindex = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t argument.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\t(*inputToOutput_) (output_, input_);\n\tresult -= output_;\n }\n\n void impl_jacobian (matrixOut_t jacobian, vectorIn_t arg) const\n {\n\tjacobian.setZero ();\n\tsize_type row = 0;\n\tfor (SizeIntervals_t::const_iterator it=outputDerivIntervals_.begin ();\n\t it != outputDerivIntervals_.end (); ++it) {\n\t for (size_type col=it->first; col < it->first + it->second; ++col) {\n\t jacobian (row, col) = 1;\n\t ++row;\n\t }\n\t}\n\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t arg.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\tinputToOutput_->jacobian (J_, input_);\n\tsize_type col=0;\n\tsize_type nbRows = inputToOutput_->outputDerivativeSize ();\n\tfor (SizeIntervals_t::const_iterator it = inputDerivIntervals_.begin ();\n\t it != inputDerivIntervals_.end (); ++it) {\n\t jacobian.block (0, it->first, nbRows, it->second) =\n\t - J_.block (0, col, nbRows, it->second);\n\t col += it->second;\n\t}\n }\n\n private:\n DevicePtr_t robot_;\n DifferentiableFunctionPtr_t inputToOutput_;\n SizeIntervals_t inputConfIntervals_;\n SizeIntervals_t inputDerivIntervals_;\n SizeIntervals_t outputConfIntervals_;\n SizeIntervals_t outputDerivIntervals_;\n mutable vector_t input_;\n mutable vector_t output_;\n \/\/ Jacobian of explicit function\n mutable matrix_t J_;\n }; \/\/ class ImplicitFunction\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(robot, function, outputConf, outputVelocity);\n return ExplicitNumericalConstraintPtr_t (ptr);\n }\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity, vectorIn_t rhs)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(robot, function, outputConf, outputVelocity, rhs);\n return ExplicitNumericalConstraintPtr_t (ptr);\n }\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::createCopy\n (const ExplicitNumericalConstraintPtr_t& other)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(*other);\n ExplicitNumericalConstraintPtr_t shPtr (ptr);\n ExplicitNumericalConstraintWkPtr_t wkPtr (shPtr);\n ptr->init (wkPtr);\n return shPtr;\n }\n\n EquationPtr_t ExplicitNumericalConstraint::copy () const\n {\n return createCopy (weak_.lock ());\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity) :\n NumericalConstraint (ImplicitFunction::create\n\t\t\t (robot, function, outputConf, outputVelocity),\n\t\t\t Equality::create ())\n {\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity, vectorIn_t rhs) :\n NumericalConstraint (ImplicitFunction::create\n\t\t\t (robot, function, outputConf, outputVelocity),\n\t\t\t Equality::create (), rhs)\n {\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const ExplicitNumericalConstraint& other) :\n NumericalConstraint (other), inputToOutput_ (other.inputToOutput_)\n {\n }\n\n void ExplicitNumericalConstraint::solve (ConfigurationOut_t configuration)\n {\n HPP_STATIC_CAST_REF_CHECK (ImplicitFunction, *(functionPtr ()));\n HPP_STATIC_PTR_CAST (ImplicitFunction, functionPtr ())->solve\n\t(configuration, rightHandSide ());\n }\n\n\n } \/\/ namespace core\n} \/\/ namespace hpp\nCall init method in ExplicitNumericalConstraint::create.\/\/ Copyright (c) 2015, LAAS-CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core.\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core. If not, see .\n\n#include \n#include \n#include \n\nnamespace hpp {\n namespace core {\n void complement (size_type size, const SizeIntervals_t& intervals,\n\t\t SizeIntervals_t& result)\n {\n std::vector unionOfIntervals (size+1, false);\n for (SizeIntervals_t::const_iterator it = intervals.begin ();\n\t it != intervals.end (); ++it) {\n\tfor (size_type i=it->first; i < it->first + it->second; ++i) {\n\t unionOfIntervals [i] = true;\n\t}\n }\n unionOfIntervals [size] = true;\n unsigned int state = 0;\n SizeInterval_t interval;\n for (size_type i=0; i <= (size_type) unionOfIntervals.size (); ++i) {\n\tif ((state == 0) && (unionOfIntervals [i] == false)) {\n\t \/\/ start a new interval\n\t state = 1;\n\t interval.first = i;\n\t} else if ((state == 1) && unionOfIntervals [i] == true) {\n\t \/\/ finish current interval\n\t state = 0;\n\t interval.second = i - interval.first;\n\t result.push_back (interval);\n\t}\n }\n }\n\n HPP_PREDEF_CLASS (ImplicitFunction);\n typedef boost::shared_ptr ImplicitFunctionPtr_t;\n class ImplicitFunction : public DifferentiableFunction\n {\n public:\n static ImplicitFunctionPtr_t create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf, const SizeIntervals_t& outputVelocity)\n {\n\tImplicitFunction* ptr = new ImplicitFunction\n\t (robot, function, outputConf, outputVelocity);\n\treturn ImplicitFunctionPtr_t (ptr);\n }\n void solve (ConfigurationOut_t configuration, vectorIn_t rhs)\n {\n\tassert (rhs.size () == output_.size ());\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t configuration.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\t(*inputToOutput_) (output_, input_);\n\tindex = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputConfIntervals_.begin ();\n\t it != outputConfIntervals_.end (); ++it) {\n\t configuration.segment (it->first, it->second) =\n\t output_.segment (index, it->second) +\n\t rhs.segment (index, it->second);\n\t index += it->second;\n\t}\n }\n\n protected:\n ImplicitFunction (const DevicePtr_t& robot,\n\t\t\tconst DifferentiableFunctionPtr_t& function,\n\t\t\tconst SizeIntervals_t& outputConf,\n\t\t\tconst SizeIntervals_t& outputVelocity)\n\t: DifferentiableFunction (robot->configSize (), robot->numberDof (),\n\t\t\t\t function->outputSize (),\n\t\t\t\t function->outputDerivativeSize ()),\n\t robot_ (robot), inputToOutput_ (function), inputConfIntervals_ (),\n\t inputDerivIntervals_ (), outputConfIntervals_ (outputConf),\n\t outputDerivIntervals_ (outputVelocity)\n {\n\t\/\/ Check input consistency\n\t\/\/ Each configuration variable is either input or output\n\tassert (function->inputSize () + function->outputSize () ==\n\t\trobot->configSize ());\n\t\/\/ Each velocity variable is either input or output\n\tassert (function->inputDerivativeSize () +\n\t\tfunction->outputDerivativeSize () == robot->numberDof ());\n\tinput_.resize (function->inputSize ());\n\toutput_.resize (function->outputSize ());\n\tJ_.resize (function->outputDerivativeSize (),\n\t\t function->inputDerivativeSize ());\n\tsize_type size = 0;\n\t\/\/ Sum of configuration output interval sizes equal function output size\n\tfor (SizeIntervals_t::const_iterator it = outputConf.begin ();\n\t it != outputConf.end (); ++it) {\n\t size += it->second;\n\t}\n\tassert (size == function->outputSize ());\n\t\/\/ Sum of velocity output interval sizes equal function output\n\t\/\/ derivative size\n\tsize = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputVelocity.begin ();\n\t it != outputVelocity.end (); ++it) {\n\t size += it->second;\n\t}\n\tassert (size == function->outputDerivativeSize ());\n\t\/\/ Conpute input intervals\n\tcomplement (robot->configSize (), outputConfIntervals_,\n\t\t inputConfIntervals_);\n\tcomplement (robot->numberDof (), outputDerivIntervals_,\n\t\t inputDerivIntervals_);\n }\n\n void impl_compute (vectorOut_t result, vectorIn_t argument) const\n {\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = outputConfIntervals_.begin ();\n\t it != outputConfIntervals_.end (); ++it) {\n\t result.segment (index, it->second) =\n\t argument.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\tindex = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t argument.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\t(*inputToOutput_) (output_, input_);\n\tresult -= output_;\n }\n\n void impl_jacobian (matrixOut_t jacobian, vectorIn_t arg) const\n {\n\tjacobian.setZero ();\n\tsize_type row = 0;\n\tfor (SizeIntervals_t::const_iterator it=outputDerivIntervals_.begin ();\n\t it != outputDerivIntervals_.end (); ++it) {\n\t for (size_type col=it->first; col < it->first + it->second; ++col) {\n\t jacobian (row, col) = 1;\n\t ++row;\n\t }\n\t}\n\n\tsize_type index = 0;\n\tfor (SizeIntervals_t::const_iterator it = inputConfIntervals_.begin ();\n\t it != inputConfIntervals_.end (); ++it) {\n\t input_.segment (index, it->second) =\n\t arg.segment (it->first, it->second);\n\t index += it->second;\n\t}\n\tinputToOutput_->jacobian (J_, input_);\n\tsize_type col=0;\n\tsize_type nbRows = inputToOutput_->outputDerivativeSize ();\n\tfor (SizeIntervals_t::const_iterator it = inputDerivIntervals_.begin ();\n\t it != inputDerivIntervals_.end (); ++it) {\n\t jacobian.block (0, it->first, nbRows, it->second) =\n\t - J_.block (0, col, nbRows, it->second);\n\t col += it->second;\n\t}\n }\n\n private:\n DevicePtr_t robot_;\n DifferentiableFunctionPtr_t inputToOutput_;\n SizeIntervals_t inputConfIntervals_;\n SizeIntervals_t inputDerivIntervals_;\n SizeIntervals_t outputConfIntervals_;\n SizeIntervals_t outputDerivIntervals_;\n mutable vector_t input_;\n mutable vector_t output_;\n \/\/ Jacobian of explicit function\n mutable matrix_t J_;\n }; \/\/ class ImplicitFunction\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(robot, function, outputConf, outputVelocity);\n ExplicitNumericalConstraintPtr_t shPtr (ptr);\n ExplicitNumericalConstraintWkPtr_t wkPtr (shPtr);\n ptr->init (wkPtr);\n return shPtr;\n }\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::create\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity, vectorIn_t rhs)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(robot, function, outputConf, outputVelocity, rhs);\n ExplicitNumericalConstraintPtr_t shPtr (ptr);\n ExplicitNumericalConstraintWkPtr_t wkPtr (shPtr);\n ptr->init (wkPtr);\n return shPtr;\n }\n\n ExplicitNumericalConstraintPtr_t ExplicitNumericalConstraint::createCopy\n (const ExplicitNumericalConstraintPtr_t& other)\n {\n ExplicitNumericalConstraint* ptr = new ExplicitNumericalConstraint\n\t(*other);\n ExplicitNumericalConstraintPtr_t shPtr (ptr);\n ExplicitNumericalConstraintWkPtr_t wkPtr (shPtr);\n ptr->init (wkPtr);\n return shPtr;\n }\n\n EquationPtr_t ExplicitNumericalConstraint::copy () const\n {\n return createCopy (weak_.lock ());\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity) :\n NumericalConstraint (ImplicitFunction::create\n\t\t\t (robot, function, outputConf, outputVelocity),\n\t\t\t Equality::create ())\n {\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const DevicePtr_t& robot, const DifferentiableFunctionPtr_t& function,\n const SizeIntervals_t& outputConf,\n const SizeIntervals_t& outputVelocity, vectorIn_t rhs) :\n NumericalConstraint (ImplicitFunction::create\n\t\t\t (robot, function, outputConf, outputVelocity),\n\t\t\t Equality::create (), rhs)\n {\n }\n\n ExplicitNumericalConstraint::ExplicitNumericalConstraint\n (const ExplicitNumericalConstraint& other) :\n NumericalConstraint (other), inputToOutput_ (other.inputToOutput_)\n {\n }\n\n void ExplicitNumericalConstraint::solve (ConfigurationOut_t configuration)\n {\n HPP_STATIC_CAST_REF_CHECK (ImplicitFunction, *(functionPtr ()));\n HPP_STATIC_PTR_CAST (ImplicitFunction, functionPtr ())->solve\n\t(configuration, rightHandSide ());\n }\n\n\n } \/\/ namespace core\n} \/\/ namespace hpp\n<|endoftext|>"} {"text":"#include \"BluPrivatePCH.h\"\n\nRenderHandler::RenderHandler(int32 width, int32 height, UBluEye* ui)\n{\n\tthis->Width = width;\n\tthis->Height = height;\n\tthis->parentUI = ui;\n}\n\nbool RenderHandler::GetViewRect(CefRefPtr browser, CefRect &rect)\n{\n\trect = CefRect(0, 0, Width, Height);\n\treturn true;\n}\n\nvoid RenderHandler::OnPaint(CefRefPtr browser, PaintElementType type, const RectList &dirtyRects, const void *buffer, int width, int height)\n{\n\tFUpdateTextureRegion2D *updateRegions = static_cast(FMemory::Malloc(sizeof(FUpdateTextureRegion2D) * dirtyRects.size()));\n\n\tint current = 0;\n\tfor (auto dirtyRect : dirtyRects)\n\t{\n\t\tupdateRegions[current].DestX = updateRegions[current].SrcX = dirtyRect.x;\n\t\tupdateRegions[current].DestY = updateRegions[current].SrcY = dirtyRect.y;\n\t\tupdateRegions[current].Height = dirtyRect.height;\n\t\tupdateRegions[current].Width = dirtyRect.width;\n\n\t\tcurrent++;\n\t}\n\n\t\/\/ Trigger our parent UIs Texture to update\n\tparentUI->TextureUpdate(buffer, updateRegions, dirtyRects.size());\n}\n\nbool BrowserClient::OnProcessMessageReceived(CefRefPtr browser, CefProcessId source_process, CefRefPtr message)\n{\n\t\n\tFString data;\n\tFString name = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(0).ToString().c_str()));\n\tFString type = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(2).ToString().c_str()));\n\tFString data_type = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(3).ToString().c_str()));\n\t\n\tif (type == \"js_event\")\n\t{\n\t\t\n\t\t\/\/ Check the datatype\n\t\t\n\t\tif (data_type == \"bool\")\n\t\t\tdata = message->GetArgumentList()->GetBool(1) ? TEXT(\"true\") : TEXT(\"false\");\n\t\telse if (data_type == \"int\")\n\t\t\tdata = FString::FromInt(message->GetArgumentList()->GetInt(1));\n\t\telse if (data_type == \"string\")\n\t\t\tdata = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(1).ToString().c_str()));\n\t\telse if (data_type == \"double\")\n\t\t\tdata = FString::SanitizeFloat(message->GetArgumentList()->GetDouble(1));\n\t\t\n\t\tevent_emitter->Broadcast(name, data);\n\t}\n\t\n\treturn true;\n\t\n}\n\n\n\/\/The path slashes have to be reversed to work with CEF\nFString ReversePathSlashes(FString forwardPath)\n{\n\treturn forwardPath.Replace(TEXT(\"\/\"), TEXT(\"\\\\\"));\n}\nFString UtilityBLUIDownloadsFolder()\n{\n\treturn ReversePathSlashes(FPaths::ConvertRelativePathToFull(FPaths::GameDir() + \"Plugins\/BLUI\/Downloads\/\"));\n}\n\n\nvoid BrowserClient::SetEventEmitter(FScriptEvent* emitter)\n{\n\tthis->event_emitter = emitter;\n}\n\nvoid BrowserClient::OnBeforeDownload(\n\tCefRefPtr browser,\n\tCefRefPtr download_item,\n\tconst CefString & suggested_name,\n\tCefRefPtr callback)\n{\n\tUNREFERENCED_PARAMETER(browser);\n\tUNREFERENCED_PARAMETER(download_item);\n\n\t\/\/We use this concatenation method to mix c_str with regular FString and then convert the result back to c_str\n\tFString downloadPath = UtilityBLUIDownloadsFolder() + FString(suggested_name.c_str());\n\n\tcallback->Continue(*downloadPath, false);\t\/\/don't show the download dialog, just go for it\n\n\tUE_LOG(LogClass, Log, TEXT(\"Downloading file for path %s\"), *downloadPath);\n}\n\nvoid BrowserClient::OnDownloadUpdated(\n\tCefRefPtr browser,\n\tCefRefPtr download_item,\n\tCefRefPtr callback)\n{\n\tint percentage = download_item->GetPercentComplete();\n\tFString url = FString(download_item->GetFullPath().c_str());\n\t\n\tUE_LOG(LogClass, Log, TEXT(\"Download %s Updated: %d\"), *url , percentage);\n\n\tblu->DownloadUpdated.Broadcast(url, percentage);\n\n\tif (percentage == 100 && download_item->IsComplete()) {\n\t\tUE_LOG(LogClass, Log, TEXT(\"Download %s Complete\"), *url);\n\t\tblu->DownloadComplete.Broadcast(url);\n\t}\n\n\t\/\/Example download cancel\/pause etc, we just have to hijack this\n\t\/\/callback->Cancel();\n}\n\nAdded changes from Shammah Branch#include \"BluPrivatePCH.h\"\n\nRenderHandler::RenderHandler(int32 width, int32 height, UBluEye* ui)\n{\n\tthis->Width = width;\n\tthis->Height = height;\n\tthis->parentUI = ui;\n}\n\nbool RenderHandler::GetViewRect(CefRefPtr browser, CefRect &rect)\n{\n\tif (IsRunningDedicatedServer())\n\t{\n \trect = CefRect(0, 0, 0, 0);\n\t}\n\telse\n\t{\n\t \trect = CefRect(0, 0, width, height);\n\t}\n\treturn true;\n}\n\nvoid RenderHandler::OnPaint(CefRefPtr browser, PaintElementType type, const RectList &dirtyRects, const void *buffer, int width, int height)\n{\n\tFUpdateTextureRegion2D *updateRegions = static_cast(FMemory::Malloc(sizeof(FUpdateTextureRegion2D) * dirtyRects.size()));\n\n\tint current = 0;\n\tfor (auto dirtyRect : dirtyRects)\n\t{\n\t\tupdateRegions[current].DestX = updateRegions[current].SrcX = dirtyRect.x;\n\t\tupdateRegions[current].DestY = updateRegions[current].SrcY = dirtyRect.y;\n\t\tupdateRegions[current].Height = dirtyRect.height;\n\t\tupdateRegions[current].Width = dirtyRect.width;\n\n\t\tcurrent++;\n\t}\n\n\t\/\/ Trigger our parent UIs Texture to update\n\tparentUI->TextureUpdate(buffer, updateRegions, dirtyRects.size());\n}\n\nbool BrowserClient::OnProcessMessageReceived(CefRefPtr browser, CefProcessId source_process, CefRefPtr message)\n{\n\t\n\tFString data;\n\tFString name = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(0).ToString().c_str()));\n\tFString type = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(2).ToString().c_str()));\n\tFString data_type = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(3).ToString().c_str()));\n\t\n\tif (type == \"js_event\")\n\t{\n\t\t\n\t\t\/\/ Check the datatype\n\t\t\n\t\tif (data_type == \"bool\")\n\t\t\tdata = message->GetArgumentList()->GetBool(1) ? TEXT(\"true\") : TEXT(\"false\");\n\t\telse if (data_type == \"int\")\n\t\t\tdata = FString::FromInt(message->GetArgumentList()->GetInt(1));\n\t\telse if (data_type == \"string\")\n\t\t\tdata = FString(UTF8_TO_TCHAR(message->GetArgumentList()->GetString(1).ToString().c_str()));\n\t\telse if (data_type == \"double\")\n\t\t\tdata = FString::SanitizeFloat(message->GetArgumentList()->GetDouble(1));\n\t\t\n\t\tevent_emitter->Broadcast(name, data);\n\t}\n\t\n\treturn true;\n\t\n}\n\n\n\/\/The path slashes have to be reversed to work with CEF\nFString ReversePathSlashes(FString forwardPath)\n{\n\treturn forwardPath.Replace(TEXT(\"\/\"), TEXT(\"\\\\\"));\n}\nFString UtilityBLUIDownloadsFolder()\n{\n\treturn ReversePathSlashes(FPaths::ConvertRelativePathToFull(FPaths::GameDir() + \"Plugins\/BLUI\/Downloads\/\"));\n}\n\n\nvoid BrowserClient::SetEventEmitter(FScriptEvent* emitter)\n{\n\tthis->event_emitter = emitter;\n}\n\nvoid BrowserClient::OnBeforeDownload(\n\tCefRefPtr browser,\n\tCefRefPtr download_item,\n\tconst CefString & suggested_name,\n\tCefRefPtr callback)\n{\n\tUNREFERENCED_PARAMETER(browser);\n\tUNREFERENCED_PARAMETER(download_item);\n\n\t\/\/We use this concatenation method to mix c_str with regular FString and then convert the result back to c_str\n\tFString downloadPath = UtilityBLUIDownloadsFolder() + FString(suggested_name.c_str());\n\n\tcallback->Continue(*downloadPath, false);\t\/\/don't show the download dialog, just go for it\n\n\tUE_LOG(LogClass, Log, TEXT(\"Downloading file for path %s\"), *downloadPath);\n}\n\nvoid BrowserClient::OnDownloadUpdated(\n\tCefRefPtr browser,\n\tCefRefPtr download_item,\n\tCefRefPtr callback)\n{\n\tint percentage = download_item->GetPercentComplete();\n\tFString url = FString(download_item->GetFullPath().c_str());\n\t\n\tUE_LOG(LogClass, Log, TEXT(\"Download %s Updated: %d\"), *url , percentage);\n\n\tblu->DownloadUpdated.Broadcast(url, percentage);\n\n\tif (percentage == 100 && download_item->IsComplete()) {\n\t\tUE_LOG(LogClass, Log, TEXT(\"Download %s Complete\"), *url);\n\t\tblu->DownloadComplete.Broadcast(url);\n\t}\n\n\t\/\/Example download cancel\/pause etc, we just have to hijack this\n\t\/\/callback->Cancel();\n}\n\n<|endoftext|>"} {"text":"\n#include \"quadCoderDriver_signed.hpp\"\n\n\/* ROBOT PHYSICAL DEFINITIONS *\/ \/*TODO: determine these values *\/\n#define MOTOR_RATIO\t\t((double)20)\n\/\/#define WHEEL_RADIUS\t\t((double)5 \/ (double)MOTOR_RATIO)\n\n\/\/in meters\n#define WHEEL_RADIUS\t\t(double(.146) \/ double(2))\n\/\/unknown units\n#define WHEEL_BASE\t\t((double)28)\n\n\/\/there are 4 ticks per mark on the disk\n#define NUMBERTICKS\t\tdouble(800)\n\/\/#define NUMBERTICKS\t\tdouble(400)\n\n\/\/this is det by delay within arduino code\n#define SMAPLEDELAY\t\tdouble(5e-3)\nquadCoderDriver_signed::quadCoderDriver_signed()\n{\n\tm_connected = false;\n\tifname = ENCODER_IF_BOARD;\n\tai.initLink(ENCODER_IF_BOARD);\n\tm_connected = true;\n}\n\nquadCoderDriver_signed::quadCoderDriver_signed(byte coder_name)\n{\n\tm_connected = false;\n\tthis->ifname = coder_name;\n\tai.initLink(ifname);\n\tm_connected = true;\n}\n\nbool quadCoderDriver_signed::getEncoderState(new_encoder_pk_t& out)\n{\n\n\tif(ai.sendCommand(ENCODER_GET_READING, NULL, 0))\n\t{\n\t\treturn true;\n\t}\n\n\tbyte retcmd = ENCODER_GET_READING;\n\tbyte* data = NULL;\n\t\n\tif(ai.recvCommand(retcmd, data))\n\t{\n\t\treturn true;\n\t}\n\n\tmemcpy(&out, data, sizeof(new_encoder_pk_t));\n\tdelete[] data;\n\treturn false;\n}\n\n\/\/in meters per second\nbool quadCoderDriver_signed::getEncoderVel(double& vel_l, double& vel_r)\n{\n\tnew_encoder_pk_t out;\n\t\n\tif(getEncoderState(out))\n\t{\n\t\treturn true;\n\t}\n\n\tdouble dtheta_l = ((out.dl \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) \/ SMAPLEDELAY;\n\tvel_l = dtheta_l * WHEEL_RADIUS;\n\n\tdouble dtheta_r = ((out.dr \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) \/ SMAPLEDELAY;\n\tvel_r = dtheta_r * WHEEL_RADIUS;\n\n\treturn false;\n}\n\n\/* Returns distance each wheel has traveled in meters since last reset *\/\nbool quadCoderDriver_signed::getEncoderDist(double& dist_l, double& dist_r)\n{\n\tnew_encoder_pk_t out;\n\t\n\tif(getEncoderState(out))\n\t{\n\t\treturn true;\n\t}\n\n\tdist_l = ((out.pl \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) * WHEEL_RADIUS;\n\tdist_r = ((out.pr \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) * WHEEL_RADIUS;\n\n\treturn false;\n}\n\nbool quadCoderDriver_signed::resetCount()\n{\n\tif(ai.sendCommand(ENCODER_RESET_COUNT, NULL, 0))\n\t{\n\t\treturn true;\n\t}\n\n\tbyte retcmd = ENCODER_GET_READING;\n\tbyte* data = NULL;\n\n\treturn ai.recvCommand(retcmd, data);\n}\nwrong spelling\n#include \"quadCoderDriver_signed.hpp\"\n\n\/* ROBOT PHYSICAL DEFINITIONS *\/ \/*TODO: determine these values *\/\n#define MOTOR_RATIO\t\t((double)20)\n\/\/#define WHEEL_RADIUS\t\t((double)5 \/ (double)MOTOR_RATIO)\n\n\/\/in meters\n#define WHEEL_RADIUS\t\t(double(.146) \/ double(2))\n\/\/unknown units\n#define WHEEL_BASE\t\t((double)28)\n\n\/\/there are 4 ticks per mark on the disk\n#define NUMBERTICKS\t\tdouble(800)\n\/\/#define NUMBERTICKS\t\tdouble(400)\n\n\/\/this is det by delay within arduino code\n#define SAMPLEDELAY\t\tdouble(5e-3)\nquadCoderDriver_signed::quadCoderDriver_signed()\n{\n\tm_connected = false;\n\tifname = ENCODER_IF_BOARD;\n\tai.initLink(ENCODER_IF_BOARD);\n\tm_connected = true;\n}\n\nquadCoderDriver_signed::quadCoderDriver_signed(byte coder_name)\n{\n\tm_connected = false;\n\tthis->ifname = coder_name;\n\tai.initLink(ifname);\n\tm_connected = true;\n}\n\nbool quadCoderDriver_signed::getEncoderState(new_encoder_pk_t& out)\n{\n\n\tif(ai.sendCommand(ENCODER_GET_READING, NULL, 0))\n\t{\n\t\treturn true;\n\t}\n\n\tbyte retcmd = ENCODER_GET_READING;\n\tbyte* data = NULL;\n\t\n\tif(ai.recvCommand(retcmd, data))\n\t{\n\t\treturn true;\n\t}\n\n\tmemcpy(&out, data, sizeof(new_encoder_pk_t));\n\tdelete[] data;\n\treturn false;\n}\n\n\/\/in meters per second\nbool quadCoderDriver_signed::getEncoderVel(double& vel_l, double& vel_r)\n{\n\tnew_encoder_pk_t out;\n\t\n\tif(getEncoderState(out))\n\t{\n\t\treturn true;\n\t}\n\n\tdouble dtheta_l = ((out.dl \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) \/ SMAPLEDELAY;\n\tvel_l = dtheta_l * WHEEL_RADIUS;\n\n\tdouble dtheta_r = ((out.dr \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) \/ SMAPLEDELAY;\n\tvel_r = dtheta_r * WHEEL_RADIUS;\n\n\treturn false;\n}\n\n\/* Returns distance each wheel has traveled in meters since last reset *\/\nbool quadCoderDriver_signed::getEncoderDist(double& dist_l, double& dist_r)\n{\n\tnew_encoder_pk_t out;\n\t\n\tif(getEncoderState(out))\n\t{\n\t\treturn true;\n\t}\n\n\tdist_l = ((out.pl \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) * WHEEL_RADIUS;\n\tdist_r = ((out.pr \/ NUMBERTICKS * double(2)*M_PI) \/ MOTOR_RATIO) * WHEEL_RADIUS;\n\n\treturn false;\n}\n\nbool quadCoderDriver_signed::resetCount()\n{\n\tif(ai.sendCommand(ENCODER_RESET_COUNT, NULL, 0))\n\t{\n\t\treturn true;\n\t}\n\n\tbyte retcmd = ENCODER_GET_READING;\n\tbyte* data = NULL;\n\n\treturn ai.recvCommand(retcmd, data);\n}\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Camera.h\"\r\n#include \"CollisionShape.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"DebugRenderer.h\"\r\n#include \"Engine.h\"\r\n#include \"File.h\"\r\n#include \"FileSystem.h\"\r\n#include \"Font.h\"\r\n#include \"Graphics.h\"\r\n#include \"Input.h\"\r\n#include \"Light.h\"\r\n#include \"Material.h\"\r\n#include \"Model.h\"\r\n#include \"Octree.h\"\r\n#include \"PhysicsWorld.h\"\r\n#include \"Renderer.h\"\r\n#include \"ResourceCache.h\"\r\n#include \"RigidBody.h\"\r\n#include \"StaticModel.h\"\r\n#include \"Text.h\"\r\n#include \"UI.h\"\r\n#include \"Zone.h\"\r\n\r\n#include \"Physics.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\n\/\/ Expands to this example's entry-point\r\nDEFINE_APPLICATION_MAIN(Physics)\r\n\r\nPhysics::Physics(Context* context) :\r\n Sample(context),\r\n yaw_(0.0f),\r\n pitch_(0.0f),\r\n drawDebug_(false)\r\n{\r\n}\r\n\r\nvoid Physics::Start()\r\n{\r\n \/\/ Execute base class startup\r\n Sample::Start();\r\n\r\n \/\/ Create the scene content\r\n CreateScene();\r\n \r\n \/\/ Create the UI content\r\n CreateInstructions();\r\n \r\n \/\/ Setup the viewport for displaying the scene\r\n SetupViewport();\r\n\r\n \/\/ Hook up to the frame update and render post-update events\r\n SubscribeToEvents();\r\n}\r\n\r\nvoid Physics::CreateScene()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n \r\n scene_ = new Scene(context_);\r\n \r\n \/\/ Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)\r\n \/\/ Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must\r\n \/\/ exist before creating drawable components, the PhysicsWorld must exist before creating physics components.\r\n \/\/ Finally, create a DebugRenderer component so that we can draw physics debug geometry\r\n scene_->CreateComponent();\r\n scene_->CreateComponent();\r\n scene_->CreateComponent();\r\n \r\n \/\/ Create a Zone component for ambient lighting & fog control\r\n Node* zoneNode = scene_->CreateChild(\"Zone\");\r\n Zone* zone = zoneNode->CreateComponent();\r\n zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));\r\n zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));\r\n zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));\r\n zone->SetFogStart(100.0f);\r\n zone->SetFogEnd(300.0f);\r\n \r\n \/\/ Create a directional light to the world. Enable cascaded shadows on it\r\n Node* lightNode = scene_->CreateChild(\"DirectionalLight\");\r\n lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));\r\n Light* light = lightNode->CreateComponent();\r\n light->SetLightType(LIGHT_DIRECTIONAL);\r\n light->SetCastShadows(true);\r\n light->SetShadowBias(BiasParameters(0.0001f, 0.5f));\r\n \/\/ Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance\r\n light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));\r\n \r\n {\r\n \/\/ Create a floor object, 100 x 100 world units. Adjust position so that the ground is at zero Y\r\n Node* floorNode = scene_->CreateChild(\"Floor\");\r\n floorNode->SetPosition(Vector3(0.0f, -0.25f, 0.0f));\r\n floorNode->SetScale(Vector3(100.0f, 0.5f, 100.0f));\r\n StaticModel* floorObject = floorNode->CreateComponent();\r\n floorObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n floorObject->SetMaterial(cache->GetResource(\"Materials\/StoneTiled.xml\"));\r\n \r\n \/\/ Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default\r\n \/\/ parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate\r\n \/\/ in the physics simulation\r\n RigidBody* body = floorNode->CreateComponent();\r\n CollisionShape* shape = floorNode->CreateComponent();\r\n \/\/ Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the\r\n \/\/ rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)\r\n shape->SetBox(Vector3::ONE);\r\n }\r\n \r\n {\r\n \/\/ Create a pyramid of movable physics objects\r\n for (int y = 0; y < 8; ++y)\r\n {\r\n for (int x = -y; x <= y; ++x)\r\n {\r\n Node* boxNode = scene_->CreateChild(\"Box\");\r\n boxNode->SetPosition(Vector3((float)x, -(float)y + 8.0f, 0.0f));\r\n StaticModel* boxObject = boxNode->CreateComponent();\r\n boxObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n boxObject->SetMaterial(cache->GetResource(\"Materials\/StoneEnvMapSmall.xml\"));\r\n boxObject->SetCastShadows(true);\r\n \r\n \/\/ Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable\r\n \/\/ and also adjust friction. The actual mass is not important; only the mass ratios between colliding \r\n \/\/ objects are significant\r\n RigidBody* body = boxNode->CreateComponent();\r\n body->SetMass(1.0f);\r\n body->SetFriction(0.75f);\r\n CollisionShape* shape = boxNode->CreateComponent();\r\n shape->SetBox(Vector3::ONE);\r\n }\r\n }\r\n }\r\n \r\n \/\/ Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside\r\n \/\/ the scene, because we want it to be unaffected by scene load\/save\r\n cameraNode_ = new Node(context_);\r\n Camera* camera = cameraNode_->CreateComponent();\r\n camera->SetFarClip(300.0f);\r\n \r\n \/\/ Set an initial position for the camera scene node above the floor\r\n cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -20.0f));\r\n}\r\n\r\nvoid Physics::CreateInstructions()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n UI* ui = GetSubsystem();\r\n \r\n \/\/ Construct new Text object, set string to display and font to use\r\n Text* instructionText = ui->GetRoot()->CreateChild();\r\n instructionText->SetText(\r\n \"Use WASD keys and mouse to move\\n\"\r\n \"LMB to spawn physics objects\\n\"\r\n \"F5 to save scene, F7 to load\\n\"\r\n \"Space to toggle physics debug geometry\"\r\n );\r\n instructionText->SetFont(cache->GetResource(\"Fonts\/Anonymous Pro.ttf\"), 15);\r\n \r\n \/\/ Position the text relative to the screen center\r\n instructionText->SetHorizontalAlignment(HA_CENTER);\r\n instructionText->SetVerticalAlignment(VA_CENTER);\r\n instructionText->SetPosition(0, ui->GetRoot()->GetHeight() \/ 4);\r\n}\r\n\r\nvoid Physics::SetupViewport()\r\n{\r\n Renderer* renderer = GetSubsystem();\r\n \r\n \/\/ Set up a viewport to the Renderer subsystem so that the 3D scene can be seen\r\n SharedPtr viewport(new Viewport(context_, scene_, cameraNode_->GetComponent()));\r\n renderer->SetViewport(0, viewport);\r\n}\r\n\r\nvoid Physics::MoveCamera(float timeStep)\r\n{\r\n \/\/ Do not move if the UI has a focused element (the console)\r\n if (GetSubsystem()->GetFocusElement())\r\n return;\r\n \r\n Input* input = GetSubsystem();\r\n \r\n \/\/ Movement speed as world units per second\r\n const float MOVE_SPEED = 20.0f;\r\n \/\/ Mouse sensitivity as degrees per pixel\r\n const float MOUSE_SENSITIVITY = 0.1f;\r\n \r\n \/\/ Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees\r\n IntVector2 mouseMove = input->GetMouseMove();\r\n yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;\r\n pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;\r\n pitch_ = Clamp(pitch_, -90.0f, 90.0f);\r\n \r\n \/\/ Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero\r\n cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));\r\n \r\n \/\/ Read WASD keys and move the camera scene node to the corresponding direction if they are pressed\r\n if (input->GetKeyDown('W'))\r\n cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('S'))\r\n cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('A'))\r\n cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('D'))\r\n cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);\r\n \r\n \/\/ \"Shoot\" a physics object with left mousebutton\r\n if (input->GetMouseButtonPress(MOUSEB_LEFT))\r\n SpawnObject();\r\n \r\n \/\/ Toggle physics debug geometry with space\r\n if (input->GetKeyPress(KEY_SPACE))\r\n drawDebug_ = !drawDebug_;\r\n}\r\n\r\nvoid Physics::SpawnObject()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n \r\n \/\/ Create a smaller box at camera position\r\n Node* boxNode = scene_->CreateChild(\"SmallBox\");\r\n boxNode->SetPosition(cameraNode_->GetPosition());\r\n boxNode->SetRotation(cameraNode_->GetRotation());\r\n boxNode->SetScale(0.25f);\r\n StaticModel* boxObject = boxNode->CreateComponent();\r\n boxObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n boxObject->SetMaterial(cache->GetResource(\"Materials\/StoneEnvMapSmall.xml\"));\r\n boxObject->SetCastShadows(true);\r\n \r\n \/\/ Create physics components, use a smaller mass also\r\n RigidBody* body = boxNode->CreateComponent();\r\n body->SetMass(0.25f);\r\n body->SetFriction(0.75f);\r\n CollisionShape* shape = boxNode->CreateComponent();\r\n shape->SetBox(Vector3::ONE);\r\n \r\n const float OBJECT_VELOCITY = 10.0f;\r\n \r\n \/\/ Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component\r\n \/\/ to overcome gravity better\r\n body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);\r\n}\r\n\r\nvoid Physics::SubscribeToEvents()\r\n{\r\n \/\/ Subscribes HandleUpdate() method for processing update events\r\n SubscribeToEvent(E_UPDATE, HANDLER(Physics, HandleUpdate));\r\n \r\n \/\/ Subscribes HandlePostRenderUpdate() method for processing the post-render update event, during which we request\r\n \/\/ debug geometry\r\n SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Physics, HandlePostRenderUpdate));\r\n}\r\n\r\nvoid Physics::HandleUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ Event parameters are always defined inside a namespace corresponding to the event's name\r\n using namespace Update;\r\n\r\n \/\/ Take the frame time step, which is stored as a float\r\n float timeStep = eventData[P_TIMESTEP].GetFloat();\r\n \r\n \/\/ Move the camera, scale movement with time step\r\n MoveCamera(timeStep);\r\n \r\n \/\/ Check for loading\/saving the scene. Save the scene to the file Data\/Scenes\/Physics.xml relative to the executable\r\n \/\/ directory\r\n Input* input = GetSubsystem();\r\n if (input->GetKeyPress(KEY_F5))\r\n {\r\n File saveFile(context_, GetSubsystem()->GetProgramDir() + \"Data\/Scenes\/Physics.xml\", FILE_WRITE);\r\n scene_->SaveXML(saveFile);\r\n }\r\n if (input->GetKeyPress(KEY_F7))\r\n {\r\n File loadFile(context_, GetSubsystem()->GetProgramDir() + \"Data\/Scenes\/Physics.xml\", FILE_READ);\r\n scene_->LoadXML(loadFile);\r\n }\r\n}\r\n\r\nvoid Physics::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret\r\n if (drawDebug_)\r\n scene_->GetComponent()->DrawDebugGeometry(true);\r\n}\r\nLarger plane in the Physics sample.\/\/\r\n\/\/ Copyright (c) 2008-2013 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"Camera.h\"\r\n#include \"CollisionShape.h\"\r\n#include \"CoreEvents.h\"\r\n#include \"DebugRenderer.h\"\r\n#include \"Engine.h\"\r\n#include \"File.h\"\r\n#include \"FileSystem.h\"\r\n#include \"Font.h\"\r\n#include \"Graphics.h\"\r\n#include \"Input.h\"\r\n#include \"Light.h\"\r\n#include \"Material.h\"\r\n#include \"Model.h\"\r\n#include \"Octree.h\"\r\n#include \"PhysicsWorld.h\"\r\n#include \"Renderer.h\"\r\n#include \"ResourceCache.h\"\r\n#include \"RigidBody.h\"\r\n#include \"StaticModel.h\"\r\n#include \"Text.h\"\r\n#include \"UI.h\"\r\n#include \"Zone.h\"\r\n\r\n#include \"Physics.h\"\r\n\r\n#include \"DebugNew.h\"\r\n\r\n\/\/ Expands to this example's entry-point\r\nDEFINE_APPLICATION_MAIN(Physics)\r\n\r\nPhysics::Physics(Context* context) :\r\n Sample(context),\r\n yaw_(0.0f),\r\n pitch_(0.0f),\r\n drawDebug_(false)\r\n{\r\n}\r\n\r\nvoid Physics::Start()\r\n{\r\n \/\/ Execute base class startup\r\n Sample::Start();\r\n\r\n \/\/ Create the scene content\r\n CreateScene();\r\n \r\n \/\/ Create the UI content\r\n CreateInstructions();\r\n \r\n \/\/ Setup the viewport for displaying the scene\r\n SetupViewport();\r\n\r\n \/\/ Hook up to the frame update and render post-update events\r\n SubscribeToEvents();\r\n}\r\n\r\nvoid Physics::CreateScene()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n \r\n scene_ = new Scene(context_);\r\n \r\n \/\/ Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000)\r\n \/\/ Create a physics simulation world with default parameters, which will update at 60fps. Like the Octree must\r\n \/\/ exist before creating drawable components, the PhysicsWorld must exist before creating physics components.\r\n \/\/ Finally, create a DebugRenderer component so that we can draw physics debug geometry\r\n scene_->CreateComponent();\r\n scene_->CreateComponent();\r\n scene_->CreateComponent();\r\n \r\n \/\/ Create a Zone component for ambient lighting & fog control\r\n Node* zoneNode = scene_->CreateChild(\"Zone\");\r\n Zone* zone = zoneNode->CreateComponent();\r\n zone->SetBoundingBox(BoundingBox(-1000.0f, 1000.0f));\r\n zone->SetAmbientColor(Color(0.15f, 0.15f, 0.15f));\r\n zone->SetFogColor(Color(0.5f, 0.5f, 0.7f));\r\n zone->SetFogStart(100.0f);\r\n zone->SetFogEnd(300.0f);\r\n \r\n \/\/ Create a directional light to the world. Enable cascaded shadows on it\r\n Node* lightNode = scene_->CreateChild(\"DirectionalLight\");\r\n lightNode->SetDirection(Vector3(0.6f, -1.0f, 0.8f));\r\n Light* light = lightNode->CreateComponent();\r\n light->SetLightType(LIGHT_DIRECTIONAL);\r\n light->SetCastShadows(true);\r\n light->SetShadowBias(BiasParameters(0.0001f, 0.5f));\r\n \/\/ Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance\r\n light->SetShadowCascade(CascadeParameters(10.0f, 50.0f, 200.0f, 0.0f, 0.8f));\r\n \r\n {\r\n \/\/ Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y\r\n Node* floorNode = scene_->CreateChild(\"Floor\");\r\n floorNode->SetPosition(Vector3(0.0f, -0.5f, 0.0f));\r\n floorNode->SetScale(Vector3(500.0f, 1.0f, 500.0f));\r\n StaticModel* floorObject = floorNode->CreateComponent();\r\n floorObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n floorObject->SetMaterial(cache->GetResource(\"Materials\/StoneTiled.xml\"));\r\n \r\n \/\/ Make the floor physical by adding RigidBody and CollisionShape components. The RigidBody's default\r\n \/\/ parameters make the object static (zero mass.) Note that a CollisionShape by itself will not participate\r\n \/\/ in the physics simulation\r\n RigidBody* body = floorNode->CreateComponent();\r\n CollisionShape* shape = floorNode->CreateComponent();\r\n \/\/ Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the\r\n \/\/ rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.)\r\n shape->SetBox(Vector3::ONE);\r\n }\r\n \r\n {\r\n \/\/ Create a pyramid of movable physics objects\r\n for (int y = 0; y < 8; ++y)\r\n {\r\n for (int x = -y; x <= y; ++x)\r\n {\r\n Node* boxNode = scene_->CreateChild(\"Box\");\r\n boxNode->SetPosition(Vector3((float)x, -(float)y + 8.0f, 0.0f));\r\n StaticModel* boxObject = boxNode->CreateComponent();\r\n boxObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n boxObject->SetMaterial(cache->GetResource(\"Materials\/StoneEnvMapSmall.xml\"));\r\n boxObject->SetCastShadows(true);\r\n \r\n \/\/ Create RigidBody and CollisionShape components like above. Give the RigidBody mass to make it movable\r\n \/\/ and also adjust friction. The actual mass is not important; only the mass ratios between colliding \r\n \/\/ objects are significant\r\n RigidBody* body = boxNode->CreateComponent();\r\n body->SetMass(1.0f);\r\n body->SetFriction(0.75f);\r\n CollisionShape* shape = boxNode->CreateComponent();\r\n shape->SetBox(Vector3::ONE);\r\n }\r\n }\r\n }\r\n \r\n \/\/ Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside\r\n \/\/ the scene, because we want it to be unaffected by scene load\/save\r\n cameraNode_ = new Node(context_);\r\n Camera* camera = cameraNode_->CreateComponent();\r\n camera->SetFarClip(300.0f);\r\n \r\n \/\/ Set an initial position for the camera scene node above the floor\r\n cameraNode_->SetPosition(Vector3(0.0f, 5.0f, -20.0f));\r\n}\r\n\r\nvoid Physics::CreateInstructions()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n UI* ui = GetSubsystem();\r\n \r\n \/\/ Construct new Text object, set string to display and font to use\r\n Text* instructionText = ui->GetRoot()->CreateChild();\r\n instructionText->SetText(\r\n \"Use WASD keys and mouse to move\\n\"\r\n \"LMB to spawn physics objects\\n\"\r\n \"F5 to save scene, F7 to load\\n\"\r\n \"Space to toggle physics debug geometry\"\r\n );\r\n instructionText->SetFont(cache->GetResource(\"Fonts\/Anonymous Pro.ttf\"), 15);\r\n \r\n \/\/ Position the text relative to the screen center\r\n instructionText->SetHorizontalAlignment(HA_CENTER);\r\n instructionText->SetVerticalAlignment(VA_CENTER);\r\n instructionText->SetPosition(0, ui->GetRoot()->GetHeight() \/ 4);\r\n}\r\n\r\nvoid Physics::SetupViewport()\r\n{\r\n Renderer* renderer = GetSubsystem();\r\n \r\n \/\/ Set up a viewport to the Renderer subsystem so that the 3D scene can be seen\r\n SharedPtr viewport(new Viewport(context_, scene_, cameraNode_->GetComponent()));\r\n renderer->SetViewport(0, viewport);\r\n}\r\n\r\nvoid Physics::MoveCamera(float timeStep)\r\n{\r\n \/\/ Do not move if the UI has a focused element (the console)\r\n if (GetSubsystem()->GetFocusElement())\r\n return;\r\n \r\n Input* input = GetSubsystem();\r\n \r\n \/\/ Movement speed as world units per second\r\n const float MOVE_SPEED = 20.0f;\r\n \/\/ Mouse sensitivity as degrees per pixel\r\n const float MOUSE_SENSITIVITY = 0.1f;\r\n \r\n \/\/ Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees\r\n IntVector2 mouseMove = input->GetMouseMove();\r\n yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;\r\n pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;\r\n pitch_ = Clamp(pitch_, -90.0f, 90.0f);\r\n \r\n \/\/ Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero\r\n cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0f));\r\n \r\n \/\/ Read WASD keys and move the camera scene node to the corresponding direction if they are pressed\r\n if (input->GetKeyDown('W'))\r\n cameraNode_->TranslateRelative(Vector3::FORWARD * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('S'))\r\n cameraNode_->TranslateRelative(Vector3::BACK * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('A'))\r\n cameraNode_->TranslateRelative(Vector3::LEFT * MOVE_SPEED * timeStep);\r\n if (input->GetKeyDown('D'))\r\n cameraNode_->TranslateRelative(Vector3::RIGHT * MOVE_SPEED * timeStep);\r\n \r\n \/\/ \"Shoot\" a physics object with left mousebutton\r\n if (input->GetMouseButtonPress(MOUSEB_LEFT))\r\n SpawnObject();\r\n \r\n \/\/ Toggle physics debug geometry with space\r\n if (input->GetKeyPress(KEY_SPACE))\r\n drawDebug_ = !drawDebug_;\r\n}\r\n\r\nvoid Physics::SpawnObject()\r\n{\r\n ResourceCache* cache = GetSubsystem();\r\n \r\n \/\/ Create a smaller box at camera position\r\n Node* boxNode = scene_->CreateChild(\"SmallBox\");\r\n boxNode->SetPosition(cameraNode_->GetPosition());\r\n boxNode->SetRotation(cameraNode_->GetRotation());\r\n boxNode->SetScale(0.25f);\r\n StaticModel* boxObject = boxNode->CreateComponent();\r\n boxObject->SetModel(cache->GetResource(\"Models\/Box.mdl\"));\r\n boxObject->SetMaterial(cache->GetResource(\"Materials\/StoneEnvMapSmall.xml\"));\r\n boxObject->SetCastShadows(true);\r\n \r\n \/\/ Create physics components, use a smaller mass also\r\n RigidBody* body = boxNode->CreateComponent();\r\n body->SetMass(0.25f);\r\n body->SetFriction(0.75f);\r\n CollisionShape* shape = boxNode->CreateComponent();\r\n shape->SetBox(Vector3::ONE);\r\n \r\n const float OBJECT_VELOCITY = 10.0f;\r\n \r\n \/\/ Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component\r\n \/\/ to overcome gravity better\r\n body->SetLinearVelocity(cameraNode_->GetRotation() * Vector3(0.0f, 0.25f, 1.0f) * OBJECT_VELOCITY);\r\n}\r\n\r\nvoid Physics::SubscribeToEvents()\r\n{\r\n \/\/ Subscribes HandleUpdate() method for processing update events\r\n SubscribeToEvent(E_UPDATE, HANDLER(Physics, HandleUpdate));\r\n \r\n \/\/ Subscribes HandlePostRenderUpdate() method for processing the post-render update event, during which we request\r\n \/\/ debug geometry\r\n SubscribeToEvent(E_POSTRENDERUPDATE, HANDLER(Physics, HandlePostRenderUpdate));\r\n}\r\n\r\nvoid Physics::HandleUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ Event parameters are always defined inside a namespace corresponding to the event's name\r\n using namespace Update;\r\n\r\n \/\/ Take the frame time step, which is stored as a float\r\n float timeStep = eventData[P_TIMESTEP].GetFloat();\r\n \r\n \/\/ Move the camera, scale movement with time step\r\n MoveCamera(timeStep);\r\n \r\n \/\/ Check for loading\/saving the scene. Save the scene to the file Data\/Scenes\/Physics.xml relative to the executable\r\n \/\/ directory\r\n Input* input = GetSubsystem();\r\n if (input->GetKeyPress(KEY_F5))\r\n {\r\n File saveFile(context_, GetSubsystem()->GetProgramDir() + \"Data\/Scenes\/Physics.xml\", FILE_WRITE);\r\n scene_->SaveXML(saveFile);\r\n }\r\n if (input->GetKeyPress(KEY_F7))\r\n {\r\n File loadFile(context_, GetSubsystem()->GetProgramDir() + \"Data\/Scenes\/Physics.xml\", FILE_READ);\r\n scene_->LoadXML(loadFile);\r\n }\r\n}\r\n\r\nvoid Physics::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)\r\n{\r\n \/\/ If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret\r\n if (drawDebug_)\r\n scene_->GetComponent()->DrawDebugGeometry(true);\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/animation\/TimingInput.h\"\n\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"core\/css\/parser\/BisonCSSParser.h\"\n#include \"core\/css\/resolver\/CSSToStyleMap.h\"\n\nnamespace WebCore {\n\nvoid TimingInput::setStartDelay(Timing& timing, double startDelay)\n{\n if (std::isfinite(startDelay))\n timing.startDelay = startDelay;\n else\n timing.startDelay = Timing::defaults().startDelay;\n}\n\nvoid TimingInput::setEndDelay(Timing& timing, double endDelay)\n{\n if (std::isfinite(endDelay))\n timing.endDelay = endDelay;\n else\n timing.endDelay = Timing::defaults().endDelay;\n}\n\nvoid TimingInput::setFillMode(Timing& timing, const String& fillMode)\n{\n if (fillMode == \"none\") {\n timing.fillMode = Timing::FillModeNone;\n } else if (fillMode == \"backwards\") {\n timing.fillMode = Timing::FillModeBackwards;\n } else if (fillMode == \"both\") {\n timing.fillMode = Timing::FillModeBoth;\n } else if (fillMode == \"forwards\") {\n timing.fillMode = Timing::FillModeForwards;\n } else {\n timing.fillMode = Timing::defaults().fillMode;\n }\n}\n\nvoid TimingInput::setIterationStart(Timing& timing, double iterationStart)\n{\n if (std::isfinite(iterationStart))\n timing.iterationStart = std::max(iterationStart, 0);\n else\n timing.iterationStart = Timing::defaults().iterationStart;\n}\n\nvoid TimingInput::setIterationCount(Timing& timing, double iterationCount)\n{\n if (!std::isnan(iterationCount))\n timing.iterationCount = std::max(iterationCount, 0);\n else\n timing.iterationCount = Timing::defaults().iterationCount;\n}\n\nvoid TimingInput::setIterationDuration(Timing& timing, double iterationDuration)\n{\n if (!std::isnan(iterationDuration) && iterationDuration >= 0)\n timing.iterationDuration = iterationDuration;\n else\n timing.iterationDuration = Timing::defaults().iterationDuration;\n}\n\nvoid TimingInput::setPlaybackRate(Timing& timing, double playbackRate)\n{\n if (std::isfinite(playbackRate))\n timing.playbackRate = playbackRate;\n else\n timing.playbackRate = Timing::defaults().playbackRate;\n}\n\nvoid TimingInput::setPlaybackDirection(Timing& timing, const String& direction)\n{\n if (direction == \"reverse\") {\n timing.direction = Timing::PlaybackDirectionReverse;\n } else if (direction == \"alternate\") {\n timing.direction = Timing::PlaybackDirectionAlternate;\n } else if (direction == \"alternate-reverse\") {\n timing.direction = Timing::PlaybackDirectionAlternateReverse;\n } else {\n timing.direction = Timing::defaults().direction;\n }\n}\n\nvoid TimingInput::setTimingFunction(Timing& timing, const String& timingFunctionString)\n{\n RefPtrWillBeRawPtr timingFunctionValue = BisonCSSParser::parseAnimationTimingFunctionValue(timingFunctionString);\n if (timingFunctionValue) {\n RefPtr timingFunction = CSSToStyleMap::animationTimingFunction(timingFunctionValue.get(), false);\n if (timingFunction) {\n timing.timingFunction = timingFunction;\n return;\n }\n }\n timing.timingFunction = Timing::defaults().timingFunction;\n}\n\nTiming TimingInput::convert(const Dictionary& timingInputDictionary)\n{\n Timing result;\n\n \/\/ FIXME: This method needs to be refactored to handle invalid\n \/\/ null, NaN, Infinity values better.\n \/\/ See: http:\/\/www.w3.org\/TR\/WebIDL\/#es-double\n double startDelay = 0;\n timingInputDictionary.get(\"delay\", startDelay);\n setStartDelay(result, startDelay);\n\n double endDelay = 0;\n timingInputDictionary.get(\"endDelay\", endDelay);\n setEndDelay(result, endDelay);\n\n String fillMode;\n timingInputDictionary.get(\"fill\", fillMode);\n setFillMode(result, fillMode);\n\n double iterationStart = 0;\n timingInputDictionary.get(\"iterationStart\", iterationStart);\n setIterationStart(result, iterationStart);\n\n double iterationCount = 1;\n timingInputDictionary.get(\"iterations\", iterationCount);\n setIterationCount(result, iterationCount);\n\n double iterationDuration\n if (timingInputDictionary.get(\"duration\", iterationDuration)) {\n setIterationDuration(result, iterationDuration);\n }\n\n double playbackRate = 1;\n timingInputDictionary.get(\"playbackRate\", playbackRate);\n setPlaybackRate(result, playbackRate);\n\n String direction;\n timingInputDictionary.get(\"direction\", direction);\n setPlaybackDirection(result, direction);\n\n String timingFunctionString;\n timingInputDictionary.get(\"easing\", timingFunctionString);\n setTimingFunction(result, timingFunctionString);\n\n result.assertValid();\n\n return result;\n}\n\nTiming TimingInput::convert(double duration)\n{\n Timing result;\n setIterationDuration(result, duration);\n return result;\n}\n\n} \/\/ namespace WebCore\nRevert r169876 \"Remove use of a V8 handle outside of bindings code in TimingInput.cpp.\"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n#include \"core\/animation\/TimingInput.h\"\n\n#include \"bindings\/v8\/Dictionary.h\"\n#include \"core\/css\/parser\/BisonCSSParser.h\"\n#include \"core\/css\/resolver\/CSSToStyleMap.h\"\n\nnamespace WebCore {\n\nvoid TimingInput::setStartDelay(Timing& timing, double startDelay)\n{\n if (std::isfinite(startDelay))\n timing.startDelay = startDelay;\n else\n timing.startDelay = Timing::defaults().startDelay;\n}\n\nvoid TimingInput::setEndDelay(Timing& timing, double endDelay)\n{\n if (std::isfinite(endDelay))\n timing.endDelay = endDelay;\n else\n timing.endDelay = Timing::defaults().endDelay;\n}\n\nvoid TimingInput::setFillMode(Timing& timing, const String& fillMode)\n{\n if (fillMode == \"none\") {\n timing.fillMode = Timing::FillModeNone;\n } else if (fillMode == \"backwards\") {\n timing.fillMode = Timing::FillModeBackwards;\n } else if (fillMode == \"both\") {\n timing.fillMode = Timing::FillModeBoth;\n } else if (fillMode == \"forwards\") {\n timing.fillMode = Timing::FillModeForwards;\n } else {\n timing.fillMode = Timing::defaults().fillMode;\n }\n}\n\nvoid TimingInput::setIterationStart(Timing& timing, double iterationStart)\n{\n if (std::isfinite(iterationStart))\n timing.iterationStart = std::max(iterationStart, 0);\n else\n timing.iterationStart = Timing::defaults().iterationStart;\n}\n\nvoid TimingInput::setIterationCount(Timing& timing, double iterationCount)\n{\n if (!std::isnan(iterationCount))\n timing.iterationCount = std::max(iterationCount, 0);\n else\n timing.iterationCount = Timing::defaults().iterationCount;\n}\n\nvoid TimingInput::setIterationDuration(Timing& timing, double iterationDuration)\n{\n if (!std::isnan(iterationDuration) && iterationDuration >= 0)\n timing.iterationDuration = iterationDuration;\n else\n timing.iterationDuration = Timing::defaults().iterationDuration;\n}\n\nvoid TimingInput::setPlaybackRate(Timing& timing, double playbackRate)\n{\n if (std::isfinite(playbackRate))\n timing.playbackRate = playbackRate;\n else\n timing.playbackRate = Timing::defaults().playbackRate;\n}\n\nvoid TimingInput::setPlaybackDirection(Timing& timing, const String& direction)\n{\n if (direction == \"reverse\") {\n timing.direction = Timing::PlaybackDirectionReverse;\n } else if (direction == \"alternate\") {\n timing.direction = Timing::PlaybackDirectionAlternate;\n } else if (direction == \"alternate-reverse\") {\n timing.direction = Timing::PlaybackDirectionAlternateReverse;\n } else {\n timing.direction = Timing::defaults().direction;\n }\n}\n\nvoid TimingInput::setTimingFunction(Timing& timing, const String& timingFunctionString)\n{\n RefPtrWillBeRawPtr timingFunctionValue = BisonCSSParser::parseAnimationTimingFunctionValue(timingFunctionString);\n if (timingFunctionValue) {\n RefPtr timingFunction = CSSToStyleMap::animationTimingFunction(timingFunctionValue.get(), false);\n if (timingFunction) {\n timing.timingFunction = timingFunction;\n return;\n }\n }\n timing.timingFunction = Timing::defaults().timingFunction;\n}\n\nTiming TimingInput::convert(const Dictionary& timingInputDictionary)\n{\n Timing result;\n\n \/\/ FIXME: This method needs to be refactored to handle invalid\n \/\/ null, NaN, Infinity values better.\n \/\/ See: http:\/\/www.w3.org\/TR\/WebIDL\/#es-double\n double startDelay = 0;\n timingInputDictionary.get(\"delay\", startDelay);\n setStartDelay(result, startDelay);\n\n double endDelay = 0;\n timingInputDictionary.get(\"endDelay\", endDelay);\n setEndDelay(result, endDelay);\n\n String fillMode;\n timingInputDictionary.get(\"fill\", fillMode);\n setFillMode(result, fillMode);\n\n double iterationStart = 0;\n timingInputDictionary.get(\"iterationStart\", iterationStart);\n setIterationStart(result, iterationStart);\n\n double iterationCount = 1;\n timingInputDictionary.get(\"iterations\", iterationCount);\n setIterationCount(result, iterationCount);\n\n v8::Local iterationDurationValue;\n if (timingInputDictionary.get(\"duration\", iterationDurationValue)) {\n double iterationDuration = iterationDurationValue->NumberValue();\n setIterationDuration(result, iterationDuration);\n }\n\n double playbackRate = 1;\n timingInputDictionary.get(\"playbackRate\", playbackRate);\n setPlaybackRate(result, playbackRate);\n\n String direction;\n timingInputDictionary.get(\"direction\", direction);\n setPlaybackDirection(result, direction);\n\n String timingFunctionString;\n timingInputDictionary.get(\"easing\", timingFunctionString);\n setTimingFunction(result, timingFunctionString);\n\n result.assertValid();\n\n return result;\n}\n\nTiming TimingInput::convert(double duration)\n{\n Timing result;\n setIterationDuration(result, duration);\n return result;\n}\n\n} \/\/ namespace WebCore\n<|endoftext|>"} {"text":"#pragma once\n#ifndef FORWARDER_HPP\n# define FORWARDER_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace generic\n{\n\ntemplate\nclass forwarder;\n\ntemplate\nclass forwarder\n{\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n template\n forwarder(T&& f) : stub_(handler::stub)\n {\n static_assert(sizeof(T) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_destructible::value,\n \"functor not trivially destructible\");\n new (&store_) handler(::std::forward(f));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same::type>{}\n >::type\n >\n forwarder& operator=(T&& f)\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible::value,\n \"functor not trivially destructible\");\n new (&store_) handler(::std::forward(f));\n\n stub_ = handler::stub;\n\n return *this;\n }\n\n R operator() (A... args) const\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward(args)...);\n }\n\nprivate:\n template\n struct handler\n {\n handler(T&& f) noexcept : f_(::std::forward(f))\n {\n }\n\n static R stub(void const* ptr, A&&... args)\n {\n return static_cast const*>(ptr)->\n f_(::std::forward(args)...);\n }\n\n T f_;\n };\n\n#if defined(__clang__)\n using max_align_type = long double;\n#elif defined(__GNUC__)\n using max_align_type = ::max_align_t;\n#else\n using max_align_type = ::std::max_align_t;\n#endif\n\n alignas(max_align_type) ::std::uintptr_t store_;\n\n R (*stub_)(void const*, A&&...){};\n};\n\n}\n\n#endif \/\/ FORWARDER_HPP\nsome fixes#pragma once\n#ifndef FORWARDER_HPP\n# define FORWARDER_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace generic\n{\n\ntemplate\nclass forwarder;\n\ntemplate\nclass forwarder\n{\npublic:\n forwarder() = default;\n\n forwarder(forwarder const&) = default;\n\n template\n forwarder(T&& f) : stub_(handler::stub)\n {\n static_assert(sizeof(T) <= sizeof(store_),\n \"functor too large\");\n static_assert(::std::is_trivially_destructible::value,\n \"functor not trivially destructible\");\n new (&store_) handler(::std::forward(f));\n }\n\n forwarder& operator=(forwarder const&) = default;\n\n template <\n typename T,\n typename = typename ::std::enable_if<\n !::std::is_same::type>{}\n >::type\n >\n forwarder& operator=(T&& f)\n {\n static_assert(sizeof(T) <= sizeof(store_), \"functor too large\");\n static_assert(::std::is_trivially_destructible::value,\n \"functor not trivially destructible\");\n new (&store_) handler(::std::forward(f));\n\n stub_ = handler::stub;\n\n return *this;\n }\n\n R operator() (A... args) const\n {\n \/\/assert(stub_);\n return stub_(&store_, ::std::forward(args)...);\n }\n\nprivate:\n template\n struct handler\n {\n handler(T&& f) noexcept : f_(::std::forward(f))\n {\n }\n\n static R stub(void const* ptr, A&&... args)\n {\n return static_cast const*>(ptr)->\n f_(::std::forward(args)...);\n }\n\n T f_;\n };\n\n R (*stub_)(void const*, A&&...){};\n\n#if defined(__clang__)\n using max_align_type = long double;\n#elif defined(__GNUC__)\n using max_align_type = ::max_align_t;\n#else\n using max_align_type = ::std::max_align_t;\n#endif\n\n alignas(max_align_type) ::std::uintptr_t store_;\n};\n\n}\n\n#endif \/\/ FORWARDER_HPP\n<|endoftext|>"} {"text":"#include \n#include \"SysUtil.h\"\n#include \"lib\/mace.h\"\n#include \"lib\/SysUtil.h\"\n\n#include \"services\/ReplayTree\/ReplayTree-init.h\"\n#include \"services\/RandTree\/RandTree-init.h\"\n#include \"services\/GenericTreeMulticast\/GenericTreeMulticast-init.h\"\n#include \"services\/GenericTreeMulticast\/DeferredGenericTreeMulticast-init.h\"\n#include \"services\/SignedMulticast\/SignedMulticast-init.h\"\n#include \"services\/SignedMulticast\/DeferredSignedMulticast-init.h\"\n#include \"services\/Pastry\/Pastry-init.h\"\n#include \"services\/Bamboo\/Bamboo-init.h\"\n#include \"services\/Bamboo\/DeferredBamboo-init.h\"\n#include \"services\/ScribeMS\/ScribeMS-init.h\"\n#include \"services\/ScribeMS\/Scribe-init.h\"\n#include \"services\/ScribeMS\/DeferredScribeMS-init.h\"\n#include \"services\/GenericOverlayRoute\/CacheRecursiveOverlayRoute-init.h\"\n#include \"services\/GenericOverlayRoute\/RecursiveOverlayRoute.h\"\n#include \"services\/GenericOverlayRoute\/RecursiveOverlayRoute-init.h\"\n#include \"TcpTransport.h\"\n#include \"TcpTransport-init.h\"\n#include \"UdpTransport.h\"\n#include \"UdpTransport-init.h\"\n#include \"services\/Transport\/DeferredRouteTransportWrapper.h\"\n#include \"services\/Transport\/DeferredRouteTransportWrapper-init.h\"\n#include \"services\/Transport\/RouteTransportWrapper.h\"\n#include \"services\/Transport\/RouteTransportWrapper-init.h\"\n\n\n\/* Variables *\/\nMaceKey myip; \/\/This is always the IP address\nMaceKey mygroup; \/\/ This is the local group_id.\n\n\/* Calculate moving average of latency *\/\nint gotten = 0; \/\/ number of pkts received\ndouble avg_lat = 0.0; \/\/ the average latency of received pkts\nstd::vector arr_lat;\nstd::map arr_crit;\ntypedef std::set ip_list;\nstd::map arr_crit_list;\n\npthread_mutex_t deliverMutex;\n\n\nclass MyHandler : public ReceiveDataHandler {\n public:\n MyHandler() : uid(NumberGen::Instance(NumberGen::HANDLER_UID)->GetVal())\n {}\n\n const int uid;\n\n \/* source, dest(=group_id), msg, uid *\/\n void deliver(const MaceKey& source, const MaceKey& dest, const std::string& msg, registration_uid_t serviceUid)\n {\n double delay = 0.0;\n int msg_id = 0;\n\n ScopedLock sl(deliverMutex);\n\n if (msg.size() > sizeof(double)) \n {\n\n std::vector strs;\n std::string s = msg;\n boost::split(strs, s, boost::is_any_of(\",\"));\n\n assert(strs.size() > 2 );\n\n \/\/std::cout << \"Message process..\" << std::endl;\n\n msg_id = (int) boost::lexical_cast(strs[0]);\n delay = ((double)TimeUtil::timeu() - boost::lexical_cast(strs[1]))\/1000000;\n\n if (delay > 1000.0) \n {\n \/\/printf(\"exception: weird time sent detected in app: %llu %llu\\n\", TimeUtil::timeu(), boost::lexical_cast(msg.data()));\n }\n else \n {\n \/\/ calculate critical delay\n assert(msg_id >= 0);\n }\n std::ostringstream os;\n os << \"* Message [ \"<< strs[0] << \" ] from : \"<< strs[2] << \" Channel : \" << serviceUid << \" Delay : \" << delay << \" Sent: \" << strs[1] << \" Now: \" << TimeUtil::timeu() << \" (source: \" << source << \" dest: \" << dest << \" )\" << std::endl;\n std::cout << os.str();\n }\n return;\n }\n};\n\n\nint main(int argc, char* argv[]) {\n\n pthread_mutex_init(&deliverMutex, 0);\n\n \/* Add required params *\/\n params::addRequired(\"MACE_PORT\", \"Port to use for connections. Allow a gap of 10 between processes\");\n params::addRequired(\"BOOTSTRAP_NODES\", \"Addresses of nodes to add. e.g. IPV4\/1.1.1.1:port IPV4\/2.2.2.2 ... (be aware of uppercases!)\");\n params::addRequired(\"ALL_NODES\", \"Addresses of nodes to add. e.g. IPV4\/1.1.1.1:port IPV4\/2.2.2.2 ... (be aware of uppercases!)\");\n params::addRequired(\"NUM_THREADS\", \"Number of transport threads.\");\n params::addRequired(\"IP_INTERVAL\", \"If multiple transport used, number of intervals between IP needs to be specified.\");\n params::addRequired(\"DELAY\", \"Delay for time.\");\n params::addRequired(\"PERIOD\", \"Wait time to send message periodically.\");\n params::loadparams(argc, argv);\n\n Log::configure();\n\n Log::autoAddAll();\n\n \/* Get parameters *\/\n myip = MaceKey(ipv4, Util::getMaceAddr());\n mygroup = MaceKey(sha160, myip.toString());\n int delay = params::get(\"DELAY\", 1000000);\n int period = params::get(\"PERIOD\", 6000000);\n int num_threads = params::get(\"NUM_THREADS\", 1);\n int ip_interval = params::get(\"IP_INTERVAL\", 1);\n int num_messages = params::get(\"NUM_MESSAGES\", 10);\n double current_time = params::get(\"CURRENT\", 0);\n\n printf(\"* myip: %s\\n\", myip.toString().c_str());\n printf(\"* mygroup: %s\\n\", mygroup.toString().c_str());\n printf(\"* delay: %d\\n\", delay);\n printf(\"* period: %d\\n\", period);\n printf(\"* num_threads: %d\\n\", num_threads);\n printf(\"* ip_interval: %d\\n\", ip_interval);\n printf(\"* current_time: %.4f\\n\", current_time);\n\n \/* Get nodeset and create subgroups *\/\n NodeSet bootGroups = params::get(\"BOOTSTRAP_NODES\"); \/\/ ipv4\n NodeSet allGroups = params::get(\"ALL_NODES\"); \/\/ ipv4\n\n std::list thingsToExit;\n\n\n \/* Create services *\/\n MyHandler* appHandler;\n\n TransportServiceClass *ntcp = &(TcpTransport_namespace::new_TcpTransport_TransportEx(num_threads));\n TransportServiceClass *udp = &(UdpTransport_namespace::new_UdpTransport_Transport()); \/\/ 1\n\n RouteServiceClass* rtw = &(DeferredRouteTransportWrapper_namespace::new_DeferredRouteTransportWrapper_Route(*ntcp)); \/\/ 1\n \/\/RouteServiceClass* rtw = &(RouteTransportWrapper_namespace::new_RouteTransportWrapper_Route(*ntcp)); \/\/ 1\n OverlayRouterServiceClass* bamboo = &(Bamboo_namespace::new_Bamboo_OverlayRouter(*rtw, *udp)); \/\/ 1\n OverlayRouterServiceClass* dbamboo = &(DeferredBamboo_namespace::new_DeferredBamboo_OverlayRouter(*bamboo)); \/\/ 1\n RouteServiceClass* ror = &(RecursiveOverlayRoute_namespace::new_RecursiveOverlayRoute_Route(*ntcp, *dbamboo)); \/\/ 1\n ScribeTreeServiceClass *scribe = &(ScribeMS_namespace::new_ScribeMS_ScribeTree(*bamboo, *ror)); \/\/ 1\n TreeServiceClass *dscribe = &(DeferredScribeMS_namespace::new_DeferredScribeMS_Tree(*scribe)); \/\/ 1\n RouteServiceClass* cror = &(CacheRecursiveOverlayRoute_namespace::new_CacheRecursiveOverlayRoute_Route(*bamboo, *ntcp, 30)); \n DeferredHierarchicalMulticastServiceClass* gtm = &(GenericTreeMulticast_namespace::new_GenericTreeMulticast_DeferredHierarchicalMulticast(*cror, *dscribe));\n HierarchicalMulticastServiceClass* dgtm = &(DeferredGenericTreeMulticast_namespace::new_DeferredGenericTreeMulticast_HierarchicalMulticast(*gtm));\n MulticastServiceClass* sm = &(SignedMulticast_namespace::new_SignedMulticast_Multicast(*dgtm, delay));\n MulticastServiceClass* dsm = &(DeferredSignedMulticast_namespace::new_DeferredSignedMulticast_Multicast(*sm));\n thingsToExit.push_back(dsm);\n\n\/\/ sm->maceInit();\n\/\/ sm->registerHandler(*appHandler, appHandler->uid);\n dsm->maceInit();\n dsm->registerHandler(*appHandler, appHandler->uid);\n\n \/* Now register services *\/\n\n \/* Now handle groups *\/\n ASSERT(!allGroups.empty());\n\n \/* Joining overlay *\/\n std::cout << \"* AllGroups listed are : \" << allGroups << std::endl;;\n\n uint64_t sleepJoinO = (uint64_t)current_time * 1000000 + 5000000 - TimeUtil::timeu();\n std::cout << \"* Waiting until 5 seconds into run to joinOverlay... ( \" << sleepJoinO << \" micros left)\" << std::endl;\n SysUtil::sleepu(sleepJoinO);\n\n bamboo->joinOverlay(bootGroups);\n\n uint64_t sleepJoinG = (uint64_t)current_time * 1000000 + 25000000 - TimeUtil::timeu();\n std::cout << \"* Waiting until 25 seconds into run to joinGroup... ( \" << sleepJoinG << \" micros left)\" << std::endl;\n SysUtil::sleepu(sleepJoinG);\n\n\n std::cout << \"* Creating\/joining self-group \" << mygroup << std::endl;\n dynamic_cast(scribe)->createGroup(mygroup, appHandler->uid); \/\/ create self group\n\n for (NodeSet::const_iterator j = allGroups.begin();j != allGroups.end(); j++) {\n std::cout << \"* Joining group \" << (*j) << std::endl;\n dynamic_cast(scribe)->joinGroup(MaceKey(sha160, (*j).toString()), appHandler->uid);\n }\n\n std::cout << \"* Done in joining\" << std::endl;\n\n uint64_t sleepMessage = (uint64_t)current_time * 1000000 + 45000000 - TimeUtil::timeu();\n\n std::cout << \"* Waiting until 45 seconds into run to start messaging... ( \" << sleepMessage << \" left)\" << std::endl;\n\n SysUtil::sleepu(sleepMessage);\n\n std::cout << \"* Messaging...\" << std::endl;\n\n \/* Basically, it will keep sending to their groups. *\/\n int msg_id = 0;\n while(num_messages-->0)\n {\n std::cout << \"* Sending message [ \"<multicast(mygroup, s.str(), appHandler->uid);\n dsm->multicast(mygroup, s.str(), appHandler->uid);\n msg_id++;\n SysUtil::sleepu(period);\n }\n\n SysUtil::sleepu(5000000);\n\n std::cout << \"* Halting.\" << std::endl;\n\n \/\/ All done.\n for(std::list::iterator ex = thingsToExit.begin(); ex != thingsToExit.end(); ex++) {\n (*ex)->maceExit();\n }\n Scheduler::haltScheduler();\n\n return 0;\n\n}\nappHandler uninitialized bug fixed#include \n#include \"SysUtil.h\"\n#include \"lib\/mace.h\"\n#include \"lib\/SysUtil.h\"\n\n#include \"services\/ReplayTree\/ReplayTree-init.h\"\n#include \"services\/RandTree\/RandTree-init.h\"\n#include \"services\/GenericTreeMulticast\/GenericTreeMulticast-init.h\"\n#include \"services\/GenericTreeMulticast\/DeferredGenericTreeMulticast-init.h\"\n#include \"services\/SignedMulticast\/SignedMulticast-init.h\"\n#include \"services\/SignedMulticast\/DeferredSignedMulticast-init.h\"\n#include \"services\/Pastry\/Pastry-init.h\"\n#include \"services\/Bamboo\/Bamboo-init.h\"\n#include \"services\/Bamboo\/DeferredBamboo-init.h\"\n#include \"services\/ScribeMS\/ScribeMS-init.h\"\n#include \"services\/ScribeMS\/Scribe-init.h\"\n#include \"services\/ScribeMS\/DeferredScribeMS-init.h\"\n#include \"services\/GenericOverlayRoute\/CacheRecursiveOverlayRoute-init.h\"\n#include \"services\/GenericOverlayRoute\/RecursiveOverlayRoute.h\"\n#include \"services\/GenericOverlayRoute\/RecursiveOverlayRoute-init.h\"\n#include \"TcpTransport.h\"\n#include \"TcpTransport-init.h\"\n#include \"UdpTransport.h\"\n#include \"UdpTransport-init.h\"\n#include \"services\/Transport\/DeferredRouteTransportWrapper.h\"\n#include \"services\/Transport\/DeferredRouteTransportWrapper-init.h\"\n#include \"services\/Transport\/RouteTransportWrapper.h\"\n#include \"services\/Transport\/RouteTransportWrapper-init.h\"\n\n\n\/* Variables *\/\nMaceKey myip; \/\/This is always the IP address\nMaceKey mygroup; \/\/ This is the local group_id.\n\n\/* Calculate moving average of latency *\/\nint gotten = 0; \/\/ number of pkts received\ndouble avg_lat = 0.0; \/\/ the average latency of received pkts\nstd::vector arr_lat;\nstd::map arr_crit;\ntypedef std::set ip_list;\nstd::map arr_crit_list;\n\npthread_mutex_t deliverMutex;\n\n\nclass MyHandler : public ReceiveDataHandler {\n public:\n MyHandler() : uid(NumberGen::Instance(NumberGen::HANDLER_UID)->GetVal())\n {}\n\n const int uid;\n\n \/* source, dest(=group_id), msg, uid *\/\n void deliver(const MaceKey& source, const MaceKey& dest, const std::string& msg, registration_uid_t serviceUid)\n {\n double delay = 0.0;\n int msg_id = 0;\n\n ScopedLock sl(deliverMutex);\n\n if (msg.size() > sizeof(double)) \n {\n\n std::vector strs;\n std::string s = msg;\n boost::split(strs, s, boost::is_any_of(\",\"));\n\n assert(strs.size() > 2 );\n\n \/\/std::cout << \"Message process..\" << std::endl;\n\n msg_id = (int) boost::lexical_cast(strs[0]);\n delay = ((double)TimeUtil::timeu() - boost::lexical_cast(strs[1]))\/1000000;\n\n if (delay > 1000.0) \n {\n \/\/printf(\"exception: weird time sent detected in app: %llu %llu\\n\", TimeUtil::timeu(), boost::lexical_cast(msg.data()));\n }\n else \n {\n \/\/ calculate critical delay\n assert(msg_id >= 0);\n }\n std::ostringstream os;\n os << \"* Message [ \"<< strs[0] << \" ] from : \"<< strs[2] << \" Channel : \" << serviceUid << \" Delay : \" << delay << \" Sent: \" << strs[1] << \" Now: \" << TimeUtil::timeu() << \" (source: \" << source << \" dest: \" << dest << \" )\" << std::endl;\n std::cout << os.str();\n }\n return;\n }\n};\n\n\nint main(int argc, char* argv[]) {\n\n pthread_mutex_init(&deliverMutex, 0);\n\n \/* Add required params *\/\n params::addRequired(\"MACE_PORT\", \"Port to use for connections. Allow a gap of 10 between processes\");\n params::addRequired(\"BOOTSTRAP_NODES\", \"Addresses of nodes to add. e.g. IPV4\/1.1.1.1:port IPV4\/2.2.2.2 ... (be aware of uppercases!)\");\n params::addRequired(\"ALL_NODES\", \"Addresses of nodes to add. e.g. IPV4\/1.1.1.1:port IPV4\/2.2.2.2 ... (be aware of uppercases!)\");\n params::addRequired(\"NUM_THREADS\", \"Number of transport threads.\");\n params::addRequired(\"IP_INTERVAL\", \"If multiple transport used, number of intervals between IP needs to be specified.\");\n params::addRequired(\"DELAY\", \"Delay for time.\");\n params::addRequired(\"PERIOD\", \"Wait time to send message periodically.\");\n params::loadparams(argc, argv);\n\n Log::configure();\n\n Log::autoAddAll();\n\n \/* Get parameters *\/\n myip = MaceKey(ipv4, Util::getMaceAddr());\n mygroup = MaceKey(sha160, myip.toString());\n int delay = params::get(\"DELAY\", 1000000);\n int period = params::get(\"PERIOD\", 6000000);\n int num_threads = params::get(\"NUM_THREADS\", 1);\n int ip_interval = params::get(\"IP_INTERVAL\", 1);\n int num_messages = params::get(\"NUM_MESSAGES\", 10);\n double current_time = params::get(\"CURRENT\", 0);\n\n printf(\"* myip: %s\\n\", myip.toString().c_str());\n printf(\"* mygroup: %s\\n\", mygroup.toString().c_str());\n printf(\"* delay: %d\\n\", delay);\n printf(\"* period: %d\\n\", period);\n printf(\"* num_threads: %d\\n\", num_threads);\n printf(\"* ip_interval: %d\\n\", ip_interval);\n printf(\"* current_time: %.4f\\n\", current_time);\n\n \/* Get nodeset and create subgroups *\/\n NodeSet bootGroups = params::get(\"BOOTSTRAP_NODES\"); \/\/ ipv4\n NodeSet allGroups = params::get(\"ALL_NODES\"); \/\/ ipv4\n\n std::list thingsToExit;\n\n\n \/* Create services *\/\n MyHandler* appHandler;\n\n appHandler = new MyHandler();\n\n TransportServiceClass *ntcp = &(TcpTransport_namespace::new_TcpTransport_TransportEx(num_threads));\n TransportServiceClass *udp = &(UdpTransport_namespace::new_UdpTransport_Transport()); \/\/ 1\n\n RouteServiceClass* rtw = &(DeferredRouteTransportWrapper_namespace::new_DeferredRouteTransportWrapper_Route(*ntcp)); \/\/ 1\n \/\/RouteServiceClass* rtw = &(RouteTransportWrapper_namespace::new_RouteTransportWrapper_Route(*ntcp)); \/\/ 1\n OverlayRouterServiceClass* bamboo = &(Bamboo_namespace::new_Bamboo_OverlayRouter(*rtw, *udp)); \/\/ 1\n OverlayRouterServiceClass* dbamboo = &(DeferredBamboo_namespace::new_DeferredBamboo_OverlayRouter(*bamboo)); \/\/ 1\n RouteServiceClass* ror = &(RecursiveOverlayRoute_namespace::new_RecursiveOverlayRoute_Route(*ntcp, *dbamboo)); \/\/ 1\n ScribeTreeServiceClass *scribe = &(ScribeMS_namespace::new_ScribeMS_ScribeTree(*bamboo, *ror)); \/\/ 1\n TreeServiceClass *dscribe = &(DeferredScribeMS_namespace::new_DeferredScribeMS_Tree(*scribe)); \/\/ 1\n RouteServiceClass* cror = &(CacheRecursiveOverlayRoute_namespace::new_CacheRecursiveOverlayRoute_Route(*bamboo, *ntcp, 30)); \n DeferredHierarchicalMulticastServiceClass* gtm = &(GenericTreeMulticast_namespace::new_GenericTreeMulticast_DeferredHierarchicalMulticast(*cror, *dscribe));\n HierarchicalMulticastServiceClass* dgtm = &(DeferredGenericTreeMulticast_namespace::new_DeferredGenericTreeMulticast_HierarchicalMulticast(*gtm));\n MulticastServiceClass* sm = &(SignedMulticast_namespace::new_SignedMulticast_Multicast(*dgtm, delay));\n MulticastServiceClass* dsm = &(DeferredSignedMulticast_namespace::new_DeferredSignedMulticast_Multicast(*sm));\n thingsToExit.push_back(dsm);\n\n\/\/ sm->maceInit();\n\/\/ sm->registerHandler(*appHandler, appHandler->uid);\n dsm->maceInit();\n dsm->registerHandler(*appHandler, appHandler->uid);\n\n \/* Now register services *\/\n\n \/* Now handle groups *\/\n ASSERT(!allGroups.empty());\n\n \/* Joining overlay *\/\n std::cout << \"* AllGroups listed are : \" << allGroups << std::endl;;\n\n uint64_t sleepJoinO = (uint64_t)current_time * 1000000 + 5000000 - TimeUtil::timeu();\n std::cout << \"* Waiting until 5 seconds into run to joinOverlay... ( \" << sleepJoinO << \" micros left)\" << std::endl;\n SysUtil::sleepu(sleepJoinO);\n\n bamboo->joinOverlay(bootGroups);\n\n uint64_t sleepJoinG = (uint64_t)current_time * 1000000 + 25000000 - TimeUtil::timeu();\n std::cout << \"* Waiting until 25 seconds into run to joinGroup... ( \" << sleepJoinG << \" micros left)\" << std::endl;\n SysUtil::sleepu(sleepJoinG);\n\n\n std::cout << \"* Creating\/joining self-group \" << mygroup << std::endl;\n dynamic_cast(scribe)->createGroup(mygroup, appHandler->uid); \/\/ create self group\n\n for (NodeSet::const_iterator j = allGroups.begin();j != allGroups.end(); j++) {\n std::cout << \"* Joining group \" << (*j) << std::endl;\n dynamic_cast(scribe)->joinGroup(MaceKey(sha160, (*j).toString()), appHandler->uid);\n }\n\n std::cout << \"* Done in joining\" << std::endl;\n\n uint64_t sleepMessage = (uint64_t)current_time * 1000000 + 45000000 - TimeUtil::timeu();\n\n std::cout << \"* Waiting until 45 seconds into run to start messaging... ( \" << sleepMessage << \" left)\" << std::endl;\n\n SysUtil::sleepu(sleepMessage);\n\n std::cout << \"* Messaging...\" << std::endl;\n\n \/* Basically, it will keep sending to their groups. *\/\n int msg_id = 0;\n while(num_messages-->0)\n {\n std::cout << \"* Sending message [ \"<multicast(mygroup, s.str(), appHandler->uid);\n dsm->multicast(mygroup, s.str(), appHandler->uid);\n msg_id++;\n SysUtil::sleepu(period);\n }\n\n SysUtil::sleepu(5000000);\n\n std::cout << \"* Halting.\" << std::endl;\n\n \/\/ All done.\n for(std::list::iterator ex = thingsToExit.begin(); ex != thingsToExit.end(); ex++) {\n (*ex)->maceExit();\n }\n Scheduler::haltScheduler();\n\n return 0;\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/jxl\/render_pipeline\/stage_noise.h\"\n\n#undef HWY_TARGET_INCLUDE\n#define HWY_TARGET_INCLUDE \"lib\/jxl\/render_pipeline\/stage_noise.cc\"\n#include \n#include \n\n#include \"lib\/jxl\/sanitizers.h\"\n#include \"lib\/jxl\/transfer_functions-inl.h\"\n\nHWY_BEFORE_NAMESPACE();\nnamespace jxl {\nnamespace HWY_NAMESPACE {\n\n\/\/ These templates are not found via ADL.\nusing hwy::HWY_NAMESPACE::Max;\nusing hwy::HWY_NAMESPACE::ShiftRight;\nusing hwy::HWY_NAMESPACE::Vec;\nusing hwy::HWY_NAMESPACE::ZeroIfNegative;\n\nusing D = HWY_CAPPED(float, kBlockDim);\nusing DI = hwy::HWY_NAMESPACE::Rebind;\nusing DI8 = hwy::HWY_NAMESPACE::Repartition;\n\n\/\/ [0, max_value]\ntemplate \nstatic HWY_INLINE V Clamp0ToMax(D d, const V x, const V max_value) {\n const auto clamped = Min(x, max_value);\n return ZeroIfNegative(clamped);\n}\n\n\/\/ x is in [0+delta, 1+delta], delta ~= 0.06\ntemplate \ntypename StrengthEval::V NoiseStrength(const StrengthEval& eval,\n const typename StrengthEval::V x) {\n return Clamp0ToMax(D(), eval(x), Set(D(), 1.0f));\n}\n\n\/\/ TODO(veluca): SIMD-fy.\nclass StrengthEvalLut {\n public:\n using V = Vec;\n\n explicit StrengthEvalLut(const NoiseParams& noise_params)\n#if HWY_TARGET == HWY_SCALAR\n : noise_params_(noise_params)\n#endif\n {\n#if HWY_TARGET != HWY_SCALAR\n uint32_t lut[8];\n memcpy(lut, noise_params.lut, sizeof(lut));\n for (size_t i = 0; i < 8; i++) {\n low16_lut[2 * i] = (lut[i] >> 0) & 0xFF;\n low16_lut[2 * i + 1] = (lut[i] >> 8) & 0xFF;\n high16_lut[2 * i] = (lut[i] >> 16) & 0xFF;\n high16_lut[2 * i + 1] = (lut[i] >> 24) & 0xFF;\n }\n#endif\n }\n\n V operator()(const V vx) const {\n constexpr size_t kScale = NoiseParams::kNumNoisePoints - 2;\n auto scaled_vx = Max(Zero(D()), Mul(vx, Set(D(), kScale)));\n auto floor_x = Floor(scaled_vx);\n auto frac_x = Sub(scaled_vx, floor_x);\n floor_x = IfThenElse(Ge(scaled_vx, Set(D(), kScale)), Set(D(), kScale - 1),\n floor_x);\n frac_x = IfThenElse(Ge(scaled_vx, Set(D(), kScale)), Set(D(), 1), frac_x);\n auto floor_x_int = ConvertTo(DI(), floor_x);\n#if HWY_TARGET == HWY_SCALAR\n auto low = Set(D(), noise_params_.lut[floor_x_int.raw]);\n auto hi = Set(D(), noise_params_.lut[floor_x_int.raw + 1]);\n#else\n \/\/ Set each lane's bytes to {0, 0, 2x+1, 2x}.\n auto floorx_indices_low =\n Add(Mul(floor_x_int, Set(DI(), 0x0202)), Set(DI(), 0x0100));\n \/\/ Set each lane's bytes to {2x+1, 2x, 0, 0}.\n auto floorx_indices_hi =\n Add(Mul(floor_x_int, Set(DI(), 0x02020000)), Set(DI(), 0x01000000));\n \/\/ load LUT\n auto low16 = BitCast(DI(), LoadDup128(DI8(), low16_lut));\n auto lowm = Set(DI(), 0xFFFF);\n auto hi16 = BitCast(DI(), LoadDup128(DI8(), high16_lut));\n auto him = Set(DI(), 0xFFFF0000);\n \/\/ low = noise_params.lut[floor_x]\n auto low =\n BitCast(D(), Or(And(TableLookupBytes(low16, floorx_indices_low), lowm),\n And(TableLookupBytes(hi16, floorx_indices_hi), him)));\n \/\/ hi = noise_params.lut[floor_x+1]\n floorx_indices_low = Add(floorx_indices_low, Set(DI(), 0x0202));\n floorx_indices_hi = Add(floorx_indices_hi, Set(DI(), 0x02020000));\n auto hi =\n BitCast(D(), Or(And(TableLookupBytes(low16, floorx_indices_low), lowm),\n And(TableLookupBytes(hi16, floorx_indices_hi), him)));\n#endif\n return MulAdd(Sub(hi, low), frac_x, low);\n }\n\n private:\n#if HWY_TARGET != HWY_SCALAR\n \/\/ noise_params.lut transformed into two 16-bit lookup tables.\n HWY_ALIGN uint8_t high16_lut[16];\n HWY_ALIGN uint8_t low16_lut[16];\n#else\n const NoiseParams& noise_params_;\n#endif\n};\n\ntemplate \nvoid AddNoiseToRGB(const D d, const Vec rnd_noise_r,\n const Vec rnd_noise_g, const Vec rnd_noise_cor,\n const Vec noise_strength_g, const Vec noise_strength_r,\n float ytox, float ytob, float* JXL_RESTRICT out_x,\n float* JXL_RESTRICT out_y, float* JXL_RESTRICT out_b) {\n const auto kRGCorr = Set(d, 0.9921875f); \/\/ 127\/128\n const auto kRGNCorr = Set(d, 0.0078125f); \/\/ 1\/128\n\n const auto red_noise =\n Mul(noise_strength_r,\n MulAdd(kRGNCorr, rnd_noise_r, Mul(kRGCorr, rnd_noise_cor)));\n const auto green_noise =\n Mul(noise_strength_g,\n MulAdd(kRGNCorr, rnd_noise_g, Mul(kRGCorr, rnd_noise_cor)));\n\n auto vx = LoadU(d, out_x);\n auto vy = LoadU(d, out_y);\n auto vb = LoadU(d, out_b);\n\n const auto rg_noise = Add(red_noise, green_noise);\n vx = Add(MulAdd(Set(d, ytox), rg_noise, Sub(red_noise, green_noise)), vx);\n vy = Add(vy, rg_noise);\n vb = MulAdd(Set(d, ytob), rg_noise, vb);\n\n StoreU(vx, d, out_x);\n StoreU(vy, d, out_y);\n StoreU(vb, d, out_b);\n}\n\nclass AddNoiseStage : public RenderPipelineStage {\n public:\n AddNoiseStage(const NoiseParams& noise_params,\n const ColorCorrelationMap& cmap, size_t first_c)\n : RenderPipelineStage(RenderPipelineStage::Settings::Symmetric(\n \/*shift=*\/0, \/*border=*\/0)),\n noise_params_(noise_params),\n cmap_(cmap),\n first_c_(first_c) {}\n\n void ProcessRow(const RowInfo& input_rows, const RowInfo& output_rows,\n size_t xextra, size_t xsize, size_t xpos, size_t ypos,\n size_t thread_id) const final {\n PROFILER_ZONE(\"Noise apply\");\n\n if (!noise_params_.HasAny()) return;\n const StrengthEvalLut noise_model(noise_params_);\n D d;\n const auto half = Set(d, 0.5f);\n\n \/\/ With the prior subtract-random Laplacian approximation, rnd_* ranges were\n \/\/ about [-1.5, 1.6]; Laplacian3 about doubles this to [-3.6, 3.6], so the\n \/\/ normalizer is half of what it was before (0.5).\n const auto norm_const = Set(d, 0.22f);\n\n float ytox = cmap_.YtoXRatio(0);\n float ytob = cmap_.YtoBRatio(0);\n\n const size_t xsize_v = RoundUpTo(xsize, Lanes(d));\n\n float* JXL_RESTRICT row_x = GetInputRow(input_rows, 0, 0);\n float* JXL_RESTRICT row_y = GetInputRow(input_rows, 1, 0);\n float* JXL_RESTRICT row_b = GetInputRow(input_rows, 2, 0);\n const float* JXL_RESTRICT row_rnd_r =\n GetInputRow(input_rows, first_c_ + 0, 0);\n const float* JXL_RESTRICT row_rnd_g =\n GetInputRow(input_rows, first_c_ + 1, 0);\n const float* JXL_RESTRICT row_rnd_c =\n GetInputRow(input_rows, first_c_ + 2, 0);\n \/\/ Needed by the calls to Floor() in StrengthEvalLut. Only arithmetic and\n \/\/ shuffles are otherwise done on the data, so this is safe.\n msan::UnpoisonMemory(row_x + xsize, (xsize_v - xsize) * sizeof(float));\n msan::UnpoisonMemory(row_y + xsize, (xsize_v - xsize) * sizeof(float));\n for (size_t x = 0; x < xsize_v; x += Lanes(d)) {\n const auto vx = LoadU(d, row_x + x);\n const auto vy = LoadU(d, row_y + x);\n const auto in_g = Sub(vy, vx);\n const auto in_r = Add(vy, vx);\n const auto noise_strength_g = NoiseStrength(noise_model, Mul(in_g, half));\n const auto noise_strength_r = NoiseStrength(noise_model, Mul(in_r, half));\n const auto addit_rnd_noise_red = Mul(LoadU(d, row_rnd_r + x), norm_const);\n const auto addit_rnd_noise_green =\n Mul(LoadU(d, row_rnd_g + x), norm_const);\n const auto addit_rnd_noise_correlated =\n Mul(LoadU(d, row_rnd_c + x), norm_const);\n AddNoiseToRGB(D(), addit_rnd_noise_red, addit_rnd_noise_green,\n addit_rnd_noise_correlated, noise_strength_g,\n noise_strength_r, ytox, ytob, row_x + x, row_y + x,\n row_b + x);\n }\n msan::PoisonMemory(row_x + xsize, (xsize_v - xsize) * sizeof(float));\n msan::PoisonMemory(row_y + xsize, (xsize_v - xsize) * sizeof(float));\n msan::PoisonMemory(row_b + xsize, (xsize_v - xsize) * sizeof(float));\n }\n\n RenderPipelineChannelMode GetChannelMode(size_t c) const final {\n return c >= first_c_ ? RenderPipelineChannelMode::kInput\n : c < 3 ? RenderPipelineChannelMode::kInPlace\n : RenderPipelineChannelMode::kIgnored;\n }\n\n const char* GetName() const override { return \"AddNoise\"; }\n\n private:\n const NoiseParams& noise_params_;\n const ColorCorrelationMap& cmap_;\n size_t first_c_;\n};\n\nstd::unique_ptr GetAddNoiseStage(\n const NoiseParams& noise_params, const ColorCorrelationMap& cmap,\n size_t noise_c_start) {\n return jxl::make_unique(noise_params, cmap, noise_c_start);\n}\n\nclass ConvolveNoiseStage : public RenderPipelineStage {\n public:\n explicit ConvolveNoiseStage(size_t first_c)\n : RenderPipelineStage(RenderPipelineStage::Settings::Symmetric(\n \/*shift=*\/0, \/*border=*\/2)),\n first_c_(first_c) {}\n\n void ProcessRow(const RowInfo& input_rows, const RowInfo& output_rows,\n size_t xextra, size_t xsize, size_t xpos, size_t ypos,\n size_t thread_id) const final {\n PROFILER_ZONE(\"Noise convolve\");\n\n const HWY_FULL(float) d;\n for (size_t c = first_c_; c < first_c_ + 3; c++) {\n float* JXL_RESTRICT rows[5];\n for (size_t i = 0; i < 5; i++) {\n rows[i] = GetInputRow(input_rows, c, i - 2);\n }\n float* JXL_RESTRICT row_out = GetOutputRow(output_rows, c, 0);\n for (ssize_t x = -RoundUpTo(xextra, Lanes(d));\n x < (ssize_t)(xsize + xextra); x += Lanes(d)) {\n const auto p00 = LoadU(d, rows[2] + x);\n auto others = Zero(d);\n \/\/ TODO(eustas): sum loaded values to reduce the calculation chain\n for (ssize_t i = -2; i <= 2; i++) {\n others = Add(others, LoadU(d, rows[0] + x + i));\n others = Add(others, LoadU(d, rows[1] + x + i));\n others = Add(others, LoadU(d, rows[3] + x + i));\n others = Add(others, LoadU(d, rows[4] + x + i));\n }\n others = Add(others, LoadU(d, rows[2] + x - 2));\n others = Add(others, LoadU(d, rows[2] + x - 1));\n others = Add(others, LoadU(d, rows[2] + x + 1));\n others = Add(others, LoadU(d, rows[2] + x + 2));\n \/\/ 4 * (1 - box kernel)\n auto pixels = MulAdd(others, Set(d, 0.16), Mul(p00, Set(d, -3.84)));\n StoreU(pixels, d, row_out + x);\n }\n }\n }\n\n RenderPipelineChannelMode GetChannelMode(size_t c) const final {\n return c >= first_c_ ? RenderPipelineChannelMode::kInOut\n : RenderPipelineChannelMode::kIgnored;\n }\n\n const char* GetName() const override { return \"ConvNoise\"; }\n\n private:\n size_t first_c_;\n};\n\nstd::unique_ptr GetConvolveNoiseStage(\n size_t noise_c_start) {\n return jxl::make_unique(noise_c_start);\n}\n\n\/\/ NOLINTNEXTLINE(google-readability-namespace-comments)\n} \/\/ namespace HWY_NAMESPACE\n} \/\/ namespace jxl\nHWY_AFTER_NAMESPACE();\n\n#if HWY_ONCE\nnamespace jxl {\n\nHWY_EXPORT(GetAddNoiseStage);\nHWY_EXPORT(GetConvolveNoiseStage);\n\nstd::unique_ptr GetAddNoiseStage(\n const NoiseParams& noise_params, const ColorCorrelationMap& cmap,\n size_t noise_c_start) {\n return HWY_DYNAMIC_DISPATCH(GetAddNoiseStage)(noise_params, cmap,\n noise_c_start);\n}\n\nstd::unique_ptr GetConvolveNoiseStage(\n size_t noise_c_start) {\n return HWY_DYNAMIC_DISPATCH(GetConvolveNoiseStage)(noise_c_start);\n}\n\n} \/\/ namespace jxl\n#endif\nReapply the noise LUT fix from #1238 to the render pipeline (#1893)\/\/ Copyright (c) the JPEG XL Project Authors. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style\n\/\/ license that can be found in the LICENSE file.\n\n#include \"lib\/jxl\/render_pipeline\/stage_noise.h\"\n\n#undef HWY_TARGET_INCLUDE\n#define HWY_TARGET_INCLUDE \"lib\/jxl\/render_pipeline\/stage_noise.cc\"\n#include \n#include \n\n#include \"lib\/jxl\/sanitizers.h\"\n#include \"lib\/jxl\/transfer_functions-inl.h\"\n\nHWY_BEFORE_NAMESPACE();\nnamespace jxl {\nnamespace HWY_NAMESPACE {\n\n\/\/ These templates are not found via ADL.\nusing hwy::HWY_NAMESPACE::Max;\nusing hwy::HWY_NAMESPACE::ShiftRight;\nusing hwy::HWY_NAMESPACE::Vec;\nusing hwy::HWY_NAMESPACE::ZeroIfNegative;\n\nusing D = HWY_CAPPED(float, kBlockDim);\nusing DI = hwy::HWY_NAMESPACE::Rebind;\nusing DI8 = hwy::HWY_NAMESPACE::Repartition;\n\n\/\/ [0, max_value]\ntemplate \nstatic HWY_INLINE V Clamp0ToMax(D d, const V x, const V max_value) {\n const auto clamped = Min(x, max_value);\n return ZeroIfNegative(clamped);\n}\n\n\/\/ x is in [0+delta, 1+delta], delta ~= 0.06\ntemplate \ntypename StrengthEval::V NoiseStrength(const StrengthEval& eval,\n const typename StrengthEval::V x) {\n return Clamp0ToMax(D(), eval(x), Set(D(), 1.0f));\n}\n\n\/\/ TODO(veluca): SIMD-fy.\nclass StrengthEvalLut {\n public:\n using V = Vec;\n\n explicit StrengthEvalLut(const NoiseParams& noise_params)\n#if HWY_TARGET == HWY_SCALAR\n : noise_params_(noise_params)\n#endif\n {\n#if HWY_TARGET != HWY_SCALAR\n uint32_t lut[8];\n memcpy(lut, noise_params.lut, sizeof(lut));\n for (size_t i = 0; i < 8; i++) {\n low16_lut[2 * i] = (lut[i] >> 0) & 0xFF;\n low16_lut[2 * i + 1] = (lut[i] >> 8) & 0xFF;\n high16_lut[2 * i] = (lut[i] >> 16) & 0xFF;\n high16_lut[2 * i + 1] = (lut[i] >> 24) & 0xFF;\n }\n#endif\n }\n\n V operator()(const V vx) const {\n constexpr size_t kScale = NoiseParams::kNumNoisePoints - 2;\n auto scaled_vx = Max(Zero(D()), Mul(vx, Set(D(), kScale)));\n auto floor_x = Floor(scaled_vx);\n auto frac_x = Sub(scaled_vx, floor_x);\n floor_x = IfThenElse(Ge(scaled_vx, Set(D(), kScale + 1)), Set(D(), kScale),\n floor_x);\n frac_x =\n IfThenElse(Ge(scaled_vx, Set(D(), kScale + 1)), Set(D(), 1), frac_x);\n auto floor_x_int = ConvertTo(DI(), floor_x);\n#if HWY_TARGET == HWY_SCALAR\n auto low = Set(D(), noise_params_.lut[floor_x_int.raw]);\n auto hi = Set(D(), noise_params_.lut[floor_x_int.raw + 1]);\n#else\n \/\/ Set each lane's bytes to {0, 0, 2x+1, 2x}.\n auto floorx_indices_low =\n Add(Mul(floor_x_int, Set(DI(), 0x0202)), Set(DI(), 0x0100));\n \/\/ Set each lane's bytes to {2x+1, 2x, 0, 0}.\n auto floorx_indices_hi =\n Add(Mul(floor_x_int, Set(DI(), 0x02020000)), Set(DI(), 0x01000000));\n \/\/ load LUT\n auto low16 = BitCast(DI(), LoadDup128(DI8(), low16_lut));\n auto lowm = Set(DI(), 0xFFFF);\n auto hi16 = BitCast(DI(), LoadDup128(DI8(), high16_lut));\n auto him = Set(DI(), 0xFFFF0000);\n \/\/ low = noise_params.lut[floor_x]\n auto low =\n BitCast(D(), Or(And(TableLookupBytes(low16, floorx_indices_low), lowm),\n And(TableLookupBytes(hi16, floorx_indices_hi), him)));\n \/\/ hi = noise_params.lut[floor_x+1]\n floorx_indices_low = Add(floorx_indices_low, Set(DI(), 0x0202));\n floorx_indices_hi = Add(floorx_indices_hi, Set(DI(), 0x02020000));\n auto hi =\n BitCast(D(), Or(And(TableLookupBytes(low16, floorx_indices_low), lowm),\n And(TableLookupBytes(hi16, floorx_indices_hi), him)));\n#endif\n return MulAdd(Sub(hi, low), frac_x, low);\n }\n\n private:\n#if HWY_TARGET != HWY_SCALAR\n \/\/ noise_params.lut transformed into two 16-bit lookup tables.\n HWY_ALIGN uint8_t high16_lut[16];\n HWY_ALIGN uint8_t low16_lut[16];\n#else\n const NoiseParams& noise_params_;\n#endif\n};\n\ntemplate \nvoid AddNoiseToRGB(const D d, const Vec rnd_noise_r,\n const Vec rnd_noise_g, const Vec rnd_noise_cor,\n const Vec noise_strength_g, const Vec noise_strength_r,\n float ytox, float ytob, float* JXL_RESTRICT out_x,\n float* JXL_RESTRICT out_y, float* JXL_RESTRICT out_b) {\n const auto kRGCorr = Set(d, 0.9921875f); \/\/ 127\/128\n const auto kRGNCorr = Set(d, 0.0078125f); \/\/ 1\/128\n\n const auto red_noise =\n Mul(noise_strength_r,\n MulAdd(kRGNCorr, rnd_noise_r, Mul(kRGCorr, rnd_noise_cor)));\n const auto green_noise =\n Mul(noise_strength_g,\n MulAdd(kRGNCorr, rnd_noise_g, Mul(kRGCorr, rnd_noise_cor)));\n\n auto vx = LoadU(d, out_x);\n auto vy = LoadU(d, out_y);\n auto vb = LoadU(d, out_b);\n\n const auto rg_noise = Add(red_noise, green_noise);\n vx = Add(MulAdd(Set(d, ytox), rg_noise, Sub(red_noise, green_noise)), vx);\n vy = Add(vy, rg_noise);\n vb = MulAdd(Set(d, ytob), rg_noise, vb);\n\n StoreU(vx, d, out_x);\n StoreU(vy, d, out_y);\n StoreU(vb, d, out_b);\n}\n\nclass AddNoiseStage : public RenderPipelineStage {\n public:\n AddNoiseStage(const NoiseParams& noise_params,\n const ColorCorrelationMap& cmap, size_t first_c)\n : RenderPipelineStage(RenderPipelineStage::Settings::Symmetric(\n \/*shift=*\/0, \/*border=*\/0)),\n noise_params_(noise_params),\n cmap_(cmap),\n first_c_(first_c) {}\n\n void ProcessRow(const RowInfo& input_rows, const RowInfo& output_rows,\n size_t xextra, size_t xsize, size_t xpos, size_t ypos,\n size_t thread_id) const final {\n PROFILER_ZONE(\"Noise apply\");\n\n if (!noise_params_.HasAny()) return;\n const StrengthEvalLut noise_model(noise_params_);\n D d;\n const auto half = Set(d, 0.5f);\n\n \/\/ With the prior subtract-random Laplacian approximation, rnd_* ranges were\n \/\/ about [-1.5, 1.6]; Laplacian3 about doubles this to [-3.6, 3.6], so the\n \/\/ normalizer is half of what it was before (0.5).\n const auto norm_const = Set(d, 0.22f);\n\n float ytox = cmap_.YtoXRatio(0);\n float ytob = cmap_.YtoBRatio(0);\n\n const size_t xsize_v = RoundUpTo(xsize, Lanes(d));\n\n float* JXL_RESTRICT row_x = GetInputRow(input_rows, 0, 0);\n float* JXL_RESTRICT row_y = GetInputRow(input_rows, 1, 0);\n float* JXL_RESTRICT row_b = GetInputRow(input_rows, 2, 0);\n const float* JXL_RESTRICT row_rnd_r =\n GetInputRow(input_rows, first_c_ + 0, 0);\n const float* JXL_RESTRICT row_rnd_g =\n GetInputRow(input_rows, first_c_ + 1, 0);\n const float* JXL_RESTRICT row_rnd_c =\n GetInputRow(input_rows, first_c_ + 2, 0);\n \/\/ Needed by the calls to Floor() in StrengthEvalLut. Only arithmetic and\n \/\/ shuffles are otherwise done on the data, so this is safe.\n msan::UnpoisonMemory(row_x + xsize, (xsize_v - xsize) * sizeof(float));\n msan::UnpoisonMemory(row_y + xsize, (xsize_v - xsize) * sizeof(float));\n for (size_t x = 0; x < xsize_v; x += Lanes(d)) {\n const auto vx = LoadU(d, row_x + x);\n const auto vy = LoadU(d, row_y + x);\n const auto in_g = Sub(vy, vx);\n const auto in_r = Add(vy, vx);\n const auto noise_strength_g = NoiseStrength(noise_model, Mul(in_g, half));\n const auto noise_strength_r = NoiseStrength(noise_model, Mul(in_r, half));\n const auto addit_rnd_noise_red = Mul(LoadU(d, row_rnd_r + x), norm_const);\n const auto addit_rnd_noise_green =\n Mul(LoadU(d, row_rnd_g + x), norm_const);\n const auto addit_rnd_noise_correlated =\n Mul(LoadU(d, row_rnd_c + x), norm_const);\n AddNoiseToRGB(D(), addit_rnd_noise_red, addit_rnd_noise_green,\n addit_rnd_noise_correlated, noise_strength_g,\n noise_strength_r, ytox, ytob, row_x + x, row_y + x,\n row_b + x);\n }\n msan::PoisonMemory(row_x + xsize, (xsize_v - xsize) * sizeof(float));\n msan::PoisonMemory(row_y + xsize, (xsize_v - xsize) * sizeof(float));\n msan::PoisonMemory(row_b + xsize, (xsize_v - xsize) * sizeof(float));\n }\n\n RenderPipelineChannelMode GetChannelMode(size_t c) const final {\n return c >= first_c_ ? RenderPipelineChannelMode::kInput\n : c < 3 ? RenderPipelineChannelMode::kInPlace\n : RenderPipelineChannelMode::kIgnored;\n }\n\n const char* GetName() const override { return \"AddNoise\"; }\n\n private:\n const NoiseParams& noise_params_;\n const ColorCorrelationMap& cmap_;\n size_t first_c_;\n};\n\nstd::unique_ptr GetAddNoiseStage(\n const NoiseParams& noise_params, const ColorCorrelationMap& cmap,\n size_t noise_c_start) {\n return jxl::make_unique(noise_params, cmap, noise_c_start);\n}\n\nclass ConvolveNoiseStage : public RenderPipelineStage {\n public:\n explicit ConvolveNoiseStage(size_t first_c)\n : RenderPipelineStage(RenderPipelineStage::Settings::Symmetric(\n \/*shift=*\/0, \/*border=*\/2)),\n first_c_(first_c) {}\n\n void ProcessRow(const RowInfo& input_rows, const RowInfo& output_rows,\n size_t xextra, size_t xsize, size_t xpos, size_t ypos,\n size_t thread_id) const final {\n PROFILER_ZONE(\"Noise convolve\");\n\n const HWY_FULL(float) d;\n for (size_t c = first_c_; c < first_c_ + 3; c++) {\n float* JXL_RESTRICT rows[5];\n for (size_t i = 0; i < 5; i++) {\n rows[i] = GetInputRow(input_rows, c, i - 2);\n }\n float* JXL_RESTRICT row_out = GetOutputRow(output_rows, c, 0);\n for (ssize_t x = -RoundUpTo(xextra, Lanes(d));\n x < (ssize_t)(xsize + xextra); x += Lanes(d)) {\n const auto p00 = LoadU(d, rows[2] + x);\n auto others = Zero(d);\n \/\/ TODO(eustas): sum loaded values to reduce the calculation chain\n for (ssize_t i = -2; i <= 2; i++) {\n others = Add(others, LoadU(d, rows[0] + x + i));\n others = Add(others, LoadU(d, rows[1] + x + i));\n others = Add(others, LoadU(d, rows[3] + x + i));\n others = Add(others, LoadU(d, rows[4] + x + i));\n }\n others = Add(others, LoadU(d, rows[2] + x - 2));\n others = Add(others, LoadU(d, rows[2] + x - 1));\n others = Add(others, LoadU(d, rows[2] + x + 1));\n others = Add(others, LoadU(d, rows[2] + x + 2));\n \/\/ 4 * (1 - box kernel)\n auto pixels = MulAdd(others, Set(d, 0.16), Mul(p00, Set(d, -3.84)));\n StoreU(pixels, d, row_out + x);\n }\n }\n }\n\n RenderPipelineChannelMode GetChannelMode(size_t c) const final {\n return c >= first_c_ ? RenderPipelineChannelMode::kInOut\n : RenderPipelineChannelMode::kIgnored;\n }\n\n const char* GetName() const override { return \"ConvNoise\"; }\n\n private:\n size_t first_c_;\n};\n\nstd::unique_ptr GetConvolveNoiseStage(\n size_t noise_c_start) {\n return jxl::make_unique(noise_c_start);\n}\n\n\/\/ NOLINTNEXTLINE(google-readability-namespace-comments)\n} \/\/ namespace HWY_NAMESPACE\n} \/\/ namespace jxl\nHWY_AFTER_NAMESPACE();\n\n#if HWY_ONCE\nnamespace jxl {\n\nHWY_EXPORT(GetAddNoiseStage);\nHWY_EXPORT(GetConvolveNoiseStage);\n\nstd::unique_ptr GetAddNoiseStage(\n const NoiseParams& noise_params, const ColorCorrelationMap& cmap,\n size_t noise_c_start) {\n return HWY_DYNAMIC_DISPATCH(GetAddNoiseStage)(noise_params, cmap,\n noise_c_start);\n}\n\nstd::unique_ptr GetConvolveNoiseStage(\n size_t noise_c_start) {\n return HWY_DYNAMIC_DISPATCH(GetConvolveNoiseStage)(noise_c_start);\n}\n\n} \/\/ namespace jxl\n#endif\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/\n\/\/ License: LGPL\n\/\/ \n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/ \n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n\n#include \"ossimPluginProjectionFactory.h\"\n#include \n#include \n\/\/#include \"ossimRadarSatModel.h\"\n\/\/#include \"ossimEnvisatAsarModel.h\"\n#include \"ossimTerraSarModel.h\"\n\/\/#include \n\/\/#include \"ossimRadarSat2Model.h\"\n#include \"ossimErsSarModel.h\"\n\nossimPluginProjectionFactory* ossimPluginProjectionFactory::instance()\n{\n static ossimPluginProjectionFactory* factoryInstance = new ossimPluginProjectionFactory();\n \n return factoryInstance;\n}\n\n\/\/ FIXME: 2 methods with the same name\nossimProjection* ossimPluginProjectionFactory::createProjection(const ossimFilename& filename,\n ossim_uint32 entryIdx)const\n{\n ossimProjection* result = 0;\n \/*\n if ( !result )\n {\n ossimRadarSat2Model* model = new ossimRadarSat2Model();\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n *\/\n\n if ( !result )\n {\n ossimTerraSarModel* model = new ossimTerraSarModel();\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n \n if ( !result )\n {\n ossimErsSarModel* model = new ossimErsSarModel();\n std::cout << \"Here!\" << std::endl;\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n\n \n return result;\n}\n\nossimProjection* ossimPluginProjectionFactory::createProjection(\n const ossimString& name)const\n{\n\/\/ if (name == STATIC_TYPE_NAME(ossimRadarSatModel))\n\/\/ {\n\/\/ \t return new ossimRadarSatModel;\n\/\/ }\n\/\/ else if (name == STATIC_TYPE_NAME(ossimEnvisatAsarModel))\n\/\/ {\n\/\/ \t return new ossimEnvisatAsarModel;\n\/\/ }\n\/\/ \telse if (name == STATIC_TYPE_NAME(ossimTerraSarModel))\n\/\/ {\n\/\/ \t return new ossimTerraSarModel;\n\/\/ }\n \/\/ \telse if (name == STATIC_TYPE_NAME(ossimCosmoSkymedModel))\n \/\/ {\n \/\/ \t return new ossimCosmoSkymedModel;\n \/\/ }\n \/*\n if (name == STATIC_TYPE_NAME(ossimRadarSat2Model))\n {\n return new ossimRadarSat2Model();\n }\n else\n *\/\n \n if (name == STATIC_TYPE_NAME(ossimTerraSarModel))\n {\n return new ossimTerraSarModel();\n }\n else if (name == STATIC_TYPE_NAME(ossimErsSarModel))\n {\n \t return new ossimErsSarModel;\n }\n return 0;\n}\n\nossimProjection* ossimPluginProjectionFactory::createProjection(\n const ossimKeywordlist& kwl, const char* prefix)const\n{\n ossimProjection* result = 0;\n\n const char* lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW);\n if (lookup)\n {\n ossimString type = lookup;\n \n \/*\n if (type == \"ossimRadarSat2Model\")\n {\n result = new ossimRadarSat2Model();\n if ( !result->loadState(kwl, prefix) )\n {\n delete result;\n result = 0;\n }\n }\n else\n *\/\n \n if (type == \"ossimTerraSarModel\")\n {\n result = new ossimTerraSarModel();\n if ( !result->loadState(kwl, prefix) )\n {\n delete result;\n result = 0;\n }\n }\n }\n \n return result;\n}\n\nossimObject* ossimPluginProjectionFactory::createObject(\n const ossimString& typeName)const\n{\n return createProjection(typeName);\n}\n\nossimObject* ossimPluginProjectionFactory::createObject(\n const ossimKeywordlist& kwl, const char* prefix)const\n{\n return createProjection(kwl, prefix);\n}\n\n\nvoid ossimPluginProjectionFactory::getTypeNameList(std::vector& typeList)const\n{\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimRadarSatModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimRadarSat2Model));\n typeList.push_back(STATIC_TYPE_NAME(ossimTerraSarModel));\n \/\/ result.push_back(STATIC_TYPE_NAME(ossimCosmoSkymedModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimEnvisatAsarModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimErsSarModel));\n}\nMinor correction\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ \"Copyright Centre National d'Etudes Spatiales\"\n\/\/\n\/\/ License: LGPL\n\/\/ \n\/\/ See LICENSE.txt file in the top level directory for more details.\n\/\/ \n\/\/----------------------------------------------------------------------------\n\/\/ $Id$\n\n\n#include \"ossimPluginProjectionFactory.h\"\n#include \n#include \n\/\/#include \"ossimRadarSatModel.h\"\n\/\/#include \"ossimEnvisatAsarModel.h\"\n#include \"ossimTerraSarModel.h\"\n\/\/#include \n\/\/#include \"ossimRadarSat2Model.h\"\n#include \"ossimErsSarModel.h\"\n\nossimPluginProjectionFactory* ossimPluginProjectionFactory::instance()\n{\n static ossimPluginProjectionFactory* factoryInstance = new ossimPluginProjectionFactory();\n \n return factoryInstance;\n}\n\n\/\/ FIXME: 2 methods with the same name\nossimProjection* ossimPluginProjectionFactory::createProjection(const ossimFilename& filename,\n ossim_uint32 entryIdx)const\n{\n ossimProjection* result = 0;\n \/*\n if ( !result )\n {\n ossimRadarSat2Model* model = new ossimRadarSat2Model();\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n *\/\n\n if ( !result )\n {\n ossimTerraSarModel* model = new ossimTerraSarModel();\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n \n if ( !result )\n {\n ossimErsSarModel* model = new ossimErsSarModel();\n if ( model->open(filename) )\n {\n result = model;\n }\n else\n {\n delete model;\n model = 0;\n }\n }\n\n \n return result;\n}\n\nossimProjection* ossimPluginProjectionFactory::createProjection(\n const ossimString& name)const\n{\n\/\/ if (name == STATIC_TYPE_NAME(ossimRadarSatModel))\n\/\/ {\n\/\/ \t return new ossimRadarSatModel;\n\/\/ }\n\/\/ else if (name == STATIC_TYPE_NAME(ossimEnvisatAsarModel))\n\/\/ {\n\/\/ \t return new ossimEnvisatAsarModel;\n\/\/ }\n\/\/ \telse if (name == STATIC_TYPE_NAME(ossimTerraSarModel))\n\/\/ {\n\/\/ \t return new ossimTerraSarModel;\n\/\/ }\n \/\/ \telse if (name == STATIC_TYPE_NAME(ossimCosmoSkymedModel))\n \/\/ {\n \/\/ \t return new ossimCosmoSkymedModel;\n \/\/ }\n \/*\n if (name == STATIC_TYPE_NAME(ossimRadarSat2Model))\n {\n return new ossimRadarSat2Model();\n }\n else\n *\/\n \n if (name == STATIC_TYPE_NAME(ossimTerraSarModel))\n {\n return new ossimTerraSarModel();\n }\n else if (name == STATIC_TYPE_NAME(ossimErsSarModel))\n {\n \t return new ossimErsSarModel;\n }\n return 0;\n}\n\nossimProjection* ossimPluginProjectionFactory::createProjection(\n const ossimKeywordlist& kwl, const char* prefix)const\n{\n ossimProjection* result = 0;\n\n const char* lookup = kwl.find(prefix, ossimKeywordNames::TYPE_KW);\n if (lookup)\n {\n ossimString type = lookup;\n \n \/*\n if (type == \"ossimRadarSat2Model\")\n {\n result = new ossimRadarSat2Model();\n if ( !result->loadState(kwl, prefix) )\n {\n delete result;\n result = 0;\n }\n }\n else\n *\/\n \n if (type == \"ossimTerraSarModel\")\n {\n result = new ossimTerraSarModel();\n if ( !result->loadState(kwl, prefix) )\n {\n delete result;\n result = 0;\n }\n }\n }\n \n return result;\n}\n\nossimObject* ossimPluginProjectionFactory::createObject(\n const ossimString& typeName)const\n{\n return createProjection(typeName);\n}\n\nossimObject* ossimPluginProjectionFactory::createObject(\n const ossimKeywordlist& kwl, const char* prefix)const\n{\n return createProjection(kwl, prefix);\n}\n\n\nvoid ossimPluginProjectionFactory::getTypeNameList(std::vector& typeList)const\n{\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimRadarSatModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimRadarSat2Model));\n typeList.push_back(STATIC_TYPE_NAME(ossimTerraSarModel));\n \/\/ result.push_back(STATIC_TYPE_NAME(ossimCosmoSkymedModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimEnvisatAsarModel));\n \/\/typeList.push_back(STATIC_TYPE_NAME(ossimErsSarModel));\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/common_types.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/opus\/interface\/audio_encoder_opus.h\"\n\nnamespace webrtc {\n\nnamespace {\nconst CodecInst kOpusSettings = {105, \"opus\", 48000, 960, 1, 32000};\n} \/\/ namespace\n\nclass AudioEncoderOpusTest : public ::testing::Test {\n protected:\n void CreateCodec(int num_channels) {\n codec_inst_.channels = num_channels;\n encoder_.reset(new AudioEncoderOpus(codec_inst_));\n auto expected_app =\n num_channels == 1 ? AudioEncoderOpus::kVoip : AudioEncoderOpus::kAudio;\n EXPECT_EQ(expected_app, encoder_->application());\n }\n\n CodecInst codec_inst_ = kOpusSettings;\n rtc::scoped_ptr encoder_;\n};\n\nTEST_F(AudioEncoderOpusTest, DefaultApplicationModeMono) {\n CreateCodec(1);\n}\n\nTEST_F(AudioEncoderOpusTest, DefaultApplicationModeStereo) {\n CreateCodec(2);\n}\n\nTEST_F(AudioEncoderOpusTest, ChangeApplicationMode) {\n CreateCodec(2);\n EXPECT_TRUE(encoder_->SetApplication(AudioEncoder::Application::kSpeech));\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n}\n\nTEST_F(AudioEncoderOpusTest, ResetWontChangeApplicationMode) {\n CreateCodec(2);\n\n \/\/ Trigger a reset.\n encoder_->Reset();\n \/\/ Verify that the mode is still kAudio.\n EXPECT_EQ(AudioEncoderOpus::kAudio, encoder_->application());\n\n \/\/ Now change to kVoip.\n EXPECT_TRUE(encoder_->SetApplication(AudioEncoder::Application::kSpeech));\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n\n \/\/ Trigger a reset again.\n encoder_->Reset();\n \/\/ Verify that the mode is still kVoip.\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n}\n\nTEST_F(AudioEncoderOpusTest, ToggleDtx) {\n CreateCodec(2);\n \/\/ Enable DTX\n EXPECT_TRUE(encoder_->SetDtx(true));\n \/\/ Verify that the mode is still kAudio.\n EXPECT_EQ(AudioEncoderOpus::kAudio, encoder_->application());\n \/\/ Turn off DTX.\n EXPECT_TRUE(encoder_->SetDtx(false));\n}\n\nTEST_F(AudioEncoderOpusTest, SetBitrate) {\n CreateCodec(1);\n \/\/ Constants are replicated from audio_encoder_opus.cc.\n const int kMinBitrateBps = 500;\n const int kMaxBitrateBps = 512000;\n \/\/ Set a too low bitrate.\n encoder_->SetTargetBitrate(kMinBitrateBps - 1);\n EXPECT_EQ(kMinBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set a too high bitrate.\n encoder_->SetTargetBitrate(kMaxBitrateBps + 1);\n EXPECT_EQ(kMaxBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set the minimum rate.\n encoder_->SetTargetBitrate(kMinBitrateBps);\n EXPECT_EQ(kMinBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set the maximum rate.\n encoder_->SetTargetBitrate(kMaxBitrateBps);\n EXPECT_EQ(kMaxBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set rates from 1000 up to 32000 bps.\n for (int rate = 1000; rate <= 32000; rate += 1000) {\n encoder_->SetTargetBitrate(rate);\n EXPECT_EQ(rate, encoder_->GetTargetBitrate());\n }\n}\n\nnamespace {\n\n\/\/ These constants correspond to those used in\n\/\/ AudioEncoderOpus::SetProjectedPacketLossRate.\nconst double kPacketLossRate20 = 0.20;\nconst double kPacketLossRate10 = 0.10;\nconst double kPacketLossRate5 = 0.05;\nconst double kPacketLossRate1 = 0.01;\nconst double kLossRate20Margin = 0.02;\nconst double kLossRate10Margin = 0.01;\nconst double kLossRate5Margin = 0.01;\n\n\/\/ Repeatedly sets packet loss rates in the range [from, to], increasing by\n\/\/ 0.01 in each step. The function verifies that the actual loss rate is\n\/\/ |expected_return|.\nvoid TestSetPacketLossRate(AudioEncoderOpus* encoder,\n double from,\n double to,\n double expected_return) {\n for (double loss = from; loss <= to;\n (to >= from) ? loss += 0.01 : loss -= 0.01) {\n encoder->SetProjectedPacketLossRate(loss);\n EXPECT_DOUBLE_EQ(expected_return, encoder->packet_loss_rate());\n }\n}\n\n} \/\/ namespace\n\nTEST_F(AudioEncoderOpusTest, PacketLossRateOptimized) {\n CreateCodec(1);\n\n \/\/ Note that the order of the following calls is critical.\n TestSetPacketLossRate(encoder_.get(), 0.0, 0.0, 0.0);\n TestSetPacketLossRate(encoder_.get(), kPacketLossRate1,\n kPacketLossRate5 + kLossRate5Margin - 0.01,\n kPacketLossRate1);\n TestSetPacketLossRate(encoder_.get(), kPacketLossRate5 + kLossRate5Margin,\n kPacketLossRate10 + kLossRate10Margin - 0.01,\n kPacketLossRate5);\n TestSetPacketLossRate(encoder_.get(), kPacketLossRate10 + kLossRate10Margin,\n kPacketLossRate20 + kLossRate20Margin - 0.01,\n kPacketLossRate10);\n TestSetPacketLossRate(encoder_.get(), kPacketLossRate20 + kLossRate20Margin,\n 1.0, kPacketLossRate20);\n TestSetPacketLossRate(encoder_.get(), kPacketLossRate20 + kLossRate20Margin,\n kPacketLossRate20 - kLossRate20Margin,\n kPacketLossRate20);\n TestSetPacketLossRate(\n encoder_.get(), kPacketLossRate20 - kLossRate20Margin - 0.01,\n kPacketLossRate10 - kLossRate10Margin, kPacketLossRate10);\n TestSetPacketLossRate(encoder_.get(),\n kPacketLossRate10 - kLossRate10Margin - 0.01,\n kPacketLossRate5 - kLossRate5Margin, kPacketLossRate5);\n TestSetPacketLossRate(encoder_.get(),\n kPacketLossRate5 - kLossRate5Margin - 0.01,\n kPacketLossRate1, kPacketLossRate1);\n TestSetPacketLossRate(encoder_.get(), 0.0, 0.0, 0.0);\n}\n\n} \/\/ namespace webrtc\nAudioEncoderOpusTest.PacketLossRateOptimized: Fix bug and make prettier\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/base\/scoped_ptr.h\"\n#include \"webrtc\/common_types.h\"\n#include \"webrtc\/modules\/audio_coding\/codecs\/opus\/interface\/audio_encoder_opus.h\"\n\nnamespace webrtc {\n\nnamespace {\nconst CodecInst kOpusSettings = {105, \"opus\", 48000, 960, 1, 32000};\n} \/\/ namespace\n\nclass AudioEncoderOpusTest : public ::testing::Test {\n protected:\n void CreateCodec(int num_channels) {\n codec_inst_.channels = num_channels;\n encoder_.reset(new AudioEncoderOpus(codec_inst_));\n auto expected_app =\n num_channels == 1 ? AudioEncoderOpus::kVoip : AudioEncoderOpus::kAudio;\n EXPECT_EQ(expected_app, encoder_->application());\n }\n\n CodecInst codec_inst_ = kOpusSettings;\n rtc::scoped_ptr encoder_;\n};\n\nTEST_F(AudioEncoderOpusTest, DefaultApplicationModeMono) {\n CreateCodec(1);\n}\n\nTEST_F(AudioEncoderOpusTest, DefaultApplicationModeStereo) {\n CreateCodec(2);\n}\n\nTEST_F(AudioEncoderOpusTest, ChangeApplicationMode) {\n CreateCodec(2);\n EXPECT_TRUE(encoder_->SetApplication(AudioEncoder::Application::kSpeech));\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n}\n\nTEST_F(AudioEncoderOpusTest, ResetWontChangeApplicationMode) {\n CreateCodec(2);\n\n \/\/ Trigger a reset.\n encoder_->Reset();\n \/\/ Verify that the mode is still kAudio.\n EXPECT_EQ(AudioEncoderOpus::kAudio, encoder_->application());\n\n \/\/ Now change to kVoip.\n EXPECT_TRUE(encoder_->SetApplication(AudioEncoder::Application::kSpeech));\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n\n \/\/ Trigger a reset again.\n encoder_->Reset();\n \/\/ Verify that the mode is still kVoip.\n EXPECT_EQ(AudioEncoderOpus::kVoip, encoder_->application());\n}\n\nTEST_F(AudioEncoderOpusTest, ToggleDtx) {\n CreateCodec(2);\n \/\/ Enable DTX\n EXPECT_TRUE(encoder_->SetDtx(true));\n \/\/ Verify that the mode is still kAudio.\n EXPECT_EQ(AudioEncoderOpus::kAudio, encoder_->application());\n \/\/ Turn off DTX.\n EXPECT_TRUE(encoder_->SetDtx(false));\n}\n\nTEST_F(AudioEncoderOpusTest, SetBitrate) {\n CreateCodec(1);\n \/\/ Constants are replicated from audio_encoder_opus.cc.\n const int kMinBitrateBps = 500;\n const int kMaxBitrateBps = 512000;\n \/\/ Set a too low bitrate.\n encoder_->SetTargetBitrate(kMinBitrateBps - 1);\n EXPECT_EQ(kMinBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set a too high bitrate.\n encoder_->SetTargetBitrate(kMaxBitrateBps + 1);\n EXPECT_EQ(kMaxBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set the minimum rate.\n encoder_->SetTargetBitrate(kMinBitrateBps);\n EXPECT_EQ(kMinBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set the maximum rate.\n encoder_->SetTargetBitrate(kMaxBitrateBps);\n EXPECT_EQ(kMaxBitrateBps, encoder_->GetTargetBitrate());\n \/\/ Set rates from 1000 up to 32000 bps.\n for (int rate = 1000; rate <= 32000; rate += 1000) {\n encoder_->SetTargetBitrate(rate);\n EXPECT_EQ(rate, encoder_->GetTargetBitrate());\n }\n}\n\nnamespace {\n\n\/\/ Returns a vector with the n evenly-spaced numbers a, a + (b - a)\/(n - 1),\n\/\/ ..., b.\nstd::vector IntervalSteps(double a, double b, size_t n) {\n DCHECK_GT(n, 1u);\n const double step = (b - a) \/ (n - 1);\n std::vector points;\n for (size_t i = 0; i < n; ++i)\n points.push_back(a + i * step);\n return points;\n}\n\n\/\/ Sets the packet loss rate to each number in the vector in turn, and verifies\n\/\/ that the loss rate as reported by the encoder is |expected_return| for all\n\/\/ of them.\nvoid TestSetPacketLossRate(AudioEncoderOpus* encoder,\n const std::vector& losses,\n double expected_return) {\n for (double loss : losses) {\n encoder->SetProjectedPacketLossRate(loss);\n EXPECT_DOUBLE_EQ(expected_return, encoder->packet_loss_rate());\n }\n}\n\n} \/\/ namespace\n\nTEST_F(AudioEncoderOpusTest, PacketLossRateOptimized) {\n CreateCodec(1);\n auto I = [](double a, double b) { return IntervalSteps(a, b, 10); };\n const double eps = 1e-15;\n\n \/\/ Note that the order of the following calls is critical.\n\n \/\/ clang-format off\n TestSetPacketLossRate(encoder_.get(), I(0.00 , 0.01 - eps), 0.00);\n TestSetPacketLossRate(encoder_.get(), I(0.01 + eps, 0.06 - eps), 0.01);\n TestSetPacketLossRate(encoder_.get(), I(0.06 + eps, 0.11 - eps), 0.05);\n TestSetPacketLossRate(encoder_.get(), I(0.11 + eps, 0.22 - eps), 0.10);\n TestSetPacketLossRate(encoder_.get(), I(0.22 + eps, 1.00 ), 0.20);\n\n TestSetPacketLossRate(encoder_.get(), I(1.00 , 0.18 + eps), 0.20);\n TestSetPacketLossRate(encoder_.get(), I(0.18 - eps, 0.09 + eps), 0.10);\n TestSetPacketLossRate(encoder_.get(), I(0.09 - eps, 0.04 + eps), 0.05);\n TestSetPacketLossRate(encoder_.get(), I(0.04 - eps, 0.01 + eps), 0.01);\n TestSetPacketLossRate(encoder_.get(), I(0.01 - eps, 0.00 ), 0.00);\n \/\/ clang-format on\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_upgrade.hxx\"\n#include \"direct.hxx\"\n#include \"header_writer.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_dechunk.hxx\"\n#include \"istream\/istream_memory.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"http\/Date.hxx\"\n#include \"util\/DecimalFormat.h\"\n\n#include \n\nbool\nHttpServerConnection::MaybeSend100Continue()\n{\n assert(IsValid());\n assert(request.read_state == Request::BODY);\n\n if (!request.expect_100_continue)\n return true;\n\n assert(!response.istream.IsDefined());\n\n request.expect_100_continue = false;\n\n \/* this string is simple enough to expect that we don't need to\n check for partial writes, not before we have sent a single byte\n of response to the peer *\/\n static const char *const response_string = \"HTTP\/1.1 100 Continue\\r\\n\\r\\n\";\n const size_t length = strlen(response_string);\n ssize_t nbytes = socket.Write(response_string, length);\n if (gcc_likely(nbytes == (ssize_t)length))\n return true;\n\n if (nbytes == WRITE_ERRNO)\n SocketErrorErrno(\"write error\");\n else if (nbytes != WRITE_DESTROYED)\n SocketError(\"write error\");\n return false;\n}\n\nstatic size_t\nformat_status_line(char *p, http_status_t status)\n{\n assert(http_status_is_valid(status));\n\n const char *status_string = http_status_to_string(status);\n assert(status_string != nullptr);\n size_t length = strlen(status_string);\n\n memcpy(p, \"HTTP\/1.1 \", 9);\n memcpy(p + 9, status_string, length);\n length += 9;\n p[length++] = '\\r';\n p[length++] = '\\n';\n\n return length;\n}\n\ninline void\nHttpServerConnection::SubmitResponse(http_status_t status,\n HttpHeaders &&headers,\n UnusedIstreamPtr _body)\n{\n assert(http_status_is_valid(status));\n assert(score != HTTP_SERVER_NEW);\n assert(socket.IsConnected());\n assert(request.read_state == Request::END ||\n request.body_state == Request::BodyState::READING);\n\n if (http_status_is_success(status)) {\n if (score == HTTP_SERVER_FIRST)\n score = HTTP_SERVER_SUCCESS;\n } else {\n score = HTTP_SERVER_ERROR;\n }\n\n if (request.read_state == HttpServerConnection::Request::BODY &&\n \/* if we didn't send \"100 Continue\" yet, we should do it now;\n we don't know if the request body will be used, but at\n least it hasn't been closed yet *\/\n !MaybeSend100Continue())\n return;\n\n auto &request_pool = request.request->pool;\n\n response.status = status;\n Istream *status_stream\n = istream_memory_new(&request_pool,\n response.status_buffer,\n format_status_line(response.status_buffer,\n status));\n\n \/* how will we transfer the body? determine length and\n transfer-encoding *\/\n\n const off_t content_length = _body ? _body.GetAvailable(false) : 0;\n if (http_method_is_empty(request.request->method))\n _body.Clear();\n\n auto *body = _body.Steal();\n if (content_length == (off_t)-1) {\n \/* the response length is unknown yet *\/\n assert(!http_status_is_empty(status));\n\n if (body != nullptr && keep_alive) {\n \/* keep-alive is enabled, which means that we have to\n enable chunking *\/\n headers.Write(\"transfer-encoding\", \"chunked\");\n\n \/* optimized code path: if an istream_dechunked shall get\n chunked via istream_chunk, let's just skip both to\n reduce the amount of work and I\/O we have to do *\/\n if (!istream_dechunk_check_verbatim(*body))\n body = istream_chunked_new(request_pool, *body);\n }\n } else if (http_status_is_empty(status)) {\n assert(content_length == 0);\n } else if (body != nullptr) {\n \/* fixed body size *\/\n format_uint64(response.content_length_buffer, content_length);\n headers.Write(\"content-length\", response.content_length_buffer);\n }\n\n const bool upgrade = body != nullptr && http_is_upgrade(status, headers);\n if (upgrade) {\n headers.Write(\"connection\", \"upgrade\");\n headers.MoveToBuffer(\"upgrade\");\n } else if (!keep_alive && !request.http_1_0)\n headers.Write(\"connection\", \"close\");\n\n GrowingBuffer headers3 = headers.ToBuffer();\n headers3.Write(\"\\r\\n\", 2);\n Istream *header_stream = istream_gb_new(request_pool, std::move(headers3));\n\n response.length = - status_stream->GetAvailable(false)\n - header_stream->GetAvailable(false);\n\n \/* make sure the access logger gets a negative value if there\n is no response body *\/\n response.length -= body == nullptr;\n\n body = istream_cat_new(request_pool, status_stream,\n header_stream, body);\n\n SetResponseIstream(*body);\n TryWrite();\n}\n\nvoid\nhttp_server_response(const HttpServerRequest *request,\n http_status_t status,\n HttpHeaders &&headers,\n UnusedIstreamPtr body)\n{\n auto &connection = request->connection;\n assert(connection.request.request == request);\n\n connection.SubmitResponse(status, std::move(headers), std::move(body));\n}\n\nvoid\nhttp_server_simple_response(const HttpServerRequest &request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(unsigned(status) >= 200 && unsigned(status) < 600);\n\n if (http_status_is_empty(status))\n msg = nullptr;\n else if (msg == nullptr)\n msg = http_status_to_string(status);\n\n HttpHeaders headers(request.pool);\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n if (location != nullptr)\n headers.Write(\"location\", location);\n\n Istream *body = nullptr;\n if (msg != nullptr) {\n headers.Write(\"content-type\", \"text\/plain\");\n body = istream_string_new(&request.pool, msg);\n }\n\n http_server_response(&request, status, std::move(headers),\n UnusedIstreamPtr(body));\n}\n\nvoid\nhttp_server_send_message(const HttpServerRequest *request,\n http_status_t status, const char *msg)\n{\n HttpHeaders headers(request->pool);\n\n headers.Write(\"content-type\", \"text\/plain\");\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n http_server_response(request, status, std::move(headers),\n UnusedIstreamPtr(istream_string_new(&request->pool,\n msg)));\n}\n\nvoid\nhttp_server_send_redirect(const HttpServerRequest *request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(request != nullptr);\n assert(status >= 300 && status < 400);\n assert(location != nullptr);\n\n if (msg == nullptr)\n msg = \"redirection\";\n\n HttpHeaders headers(request->pool);\n\n headers.Write(\"content-type\", \"text\/plain\");\n headers.Write(\"location\", location);\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n http_server_response(request, status, std::move(headers),\n UnusedIstreamPtr(istream_string_new(&request->pool,\n msg)));\n}\nhttp_server: emit Content-Length in HEAD responses\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_upgrade.hxx\"\n#include \"direct.hxx\"\n#include \"header_writer.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_dechunk.hxx\"\n#include \"istream\/istream_memory.hxx\"\n#include \"istream\/istream_string.hxx\"\n#include \"http\/Date.hxx\"\n#include \"util\/DecimalFormat.h\"\n\n#include \n\nbool\nHttpServerConnection::MaybeSend100Continue()\n{\n assert(IsValid());\n assert(request.read_state == Request::BODY);\n\n if (!request.expect_100_continue)\n return true;\n\n assert(!response.istream.IsDefined());\n\n request.expect_100_continue = false;\n\n \/* this string is simple enough to expect that we don't need to\n check for partial writes, not before we have sent a single byte\n of response to the peer *\/\n static const char *const response_string = \"HTTP\/1.1 100 Continue\\r\\n\\r\\n\";\n const size_t length = strlen(response_string);\n ssize_t nbytes = socket.Write(response_string, length);\n if (gcc_likely(nbytes == (ssize_t)length))\n return true;\n\n if (nbytes == WRITE_ERRNO)\n SocketErrorErrno(\"write error\");\n else if (nbytes != WRITE_DESTROYED)\n SocketError(\"write error\");\n return false;\n}\n\nstatic size_t\nformat_status_line(char *p, http_status_t status)\n{\n assert(http_status_is_valid(status));\n\n const char *status_string = http_status_to_string(status);\n assert(status_string != nullptr);\n size_t length = strlen(status_string);\n\n memcpy(p, \"HTTP\/1.1 \", 9);\n memcpy(p + 9, status_string, length);\n length += 9;\n p[length++] = '\\r';\n p[length++] = '\\n';\n\n return length;\n}\n\ninline void\nHttpServerConnection::SubmitResponse(http_status_t status,\n HttpHeaders &&headers,\n UnusedIstreamPtr _body)\n{\n assert(http_status_is_valid(status));\n assert(score != HTTP_SERVER_NEW);\n assert(socket.IsConnected());\n assert(request.read_state == Request::END ||\n request.body_state == Request::BodyState::READING);\n\n if (http_status_is_success(status)) {\n if (score == HTTP_SERVER_FIRST)\n score = HTTP_SERVER_SUCCESS;\n } else {\n score = HTTP_SERVER_ERROR;\n }\n\n if (request.read_state == HttpServerConnection::Request::BODY &&\n \/* if we didn't send \"100 Continue\" yet, we should do it now;\n we don't know if the request body will be used, but at\n least it hasn't been closed yet *\/\n !MaybeSend100Continue())\n return;\n\n auto &request_pool = request.request->pool;\n\n response.status = status;\n Istream *status_stream\n = istream_memory_new(&request_pool,\n response.status_buffer,\n format_status_line(response.status_buffer,\n status));\n\n \/* how will we transfer the body? determine length and\n transfer-encoding *\/\n\n const bool got_body = _body;\n const off_t content_length = got_body ? _body.GetAvailable(false) : 0;\n if (http_method_is_empty(request.request->method))\n _body.Clear();\n\n auto *body = _body.Steal();\n if (content_length == (off_t)-1) {\n \/* the response length is unknown yet *\/\n assert(!http_status_is_empty(status));\n\n if (body != nullptr && keep_alive) {\n \/* keep-alive is enabled, which means that we have to\n enable chunking *\/\n headers.Write(\"transfer-encoding\", \"chunked\");\n\n \/* optimized code path: if an istream_dechunked shall get\n chunked via istream_chunk, let's just skip both to\n reduce the amount of work and I\/O we have to do *\/\n if (!istream_dechunk_check_verbatim(*body))\n body = istream_chunked_new(request_pool, *body);\n }\n } else if (http_status_is_empty(status)) {\n assert(content_length == 0);\n } else if (got_body) {\n \/* fixed body size *\/\n format_uint64(response.content_length_buffer, content_length);\n headers.Write(\"content-length\", response.content_length_buffer);\n }\n\n const bool upgrade = body != nullptr && http_is_upgrade(status, headers);\n if (upgrade) {\n headers.Write(\"connection\", \"upgrade\");\n headers.MoveToBuffer(\"upgrade\");\n } else if (!keep_alive && !request.http_1_0)\n headers.Write(\"connection\", \"close\");\n\n GrowingBuffer headers3 = headers.ToBuffer();\n headers3.Write(\"\\r\\n\", 2);\n Istream *header_stream = istream_gb_new(request_pool, std::move(headers3));\n\n response.length = - status_stream->GetAvailable(false)\n - header_stream->GetAvailable(false);\n\n \/* make sure the access logger gets a negative value if there\n is no response body *\/\n response.length -= body == nullptr;\n\n body = istream_cat_new(request_pool, status_stream,\n header_stream, body);\n\n SetResponseIstream(*body);\n TryWrite();\n}\n\nvoid\nhttp_server_response(const HttpServerRequest *request,\n http_status_t status,\n HttpHeaders &&headers,\n UnusedIstreamPtr body)\n{\n auto &connection = request->connection;\n assert(connection.request.request == request);\n\n connection.SubmitResponse(status, std::move(headers), std::move(body));\n}\n\nvoid\nhttp_server_simple_response(const HttpServerRequest &request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(unsigned(status) >= 200 && unsigned(status) < 600);\n\n if (http_status_is_empty(status))\n msg = nullptr;\n else if (msg == nullptr)\n msg = http_status_to_string(status);\n\n HttpHeaders headers(request.pool);\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n if (location != nullptr)\n headers.Write(\"location\", location);\n\n Istream *body = nullptr;\n if (msg != nullptr) {\n headers.Write(\"content-type\", \"text\/plain\");\n body = istream_string_new(&request.pool, msg);\n }\n\n http_server_response(&request, status, std::move(headers),\n UnusedIstreamPtr(body));\n}\n\nvoid\nhttp_server_send_message(const HttpServerRequest *request,\n http_status_t status, const char *msg)\n{\n HttpHeaders headers(request->pool);\n\n headers.Write(\"content-type\", \"text\/plain\");\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n http_server_response(request, status, std::move(headers),\n UnusedIstreamPtr(istream_string_new(&request->pool,\n msg)));\n}\n\nvoid\nhttp_server_send_redirect(const HttpServerRequest *request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(request != nullptr);\n assert(status >= 300 && status < 400);\n assert(location != nullptr);\n\n if (msg == nullptr)\n msg = \"redirection\";\n\n HttpHeaders headers(request->pool);\n\n headers.Write(\"content-type\", \"text\/plain\");\n headers.Write(\"location\", location);\n\n#ifndef NO_DATE_HEADER\n headers.Write(\"date\", http_date_format(std::chrono::system_clock::now()));\n#endif\n\n http_server_response(request, status, std::move(headers),\n UnusedIstreamPtr(istream_string_new(&request->pool,\n msg)));\n}\n<|endoftext|>"} {"text":"\/* libs\/graphics\/images\/SkImageDecoder_libgif.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkColor.h\"\n#include \"SkColorPriv.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n#include \"SkPackBits.h\"\n\n#include \"gif_lib.h\"\n\nclass SkGIFImageDecoder : public SkImageDecoder {\npublic:\n virtual Format getFormat() const {\n return kGIF_Format;\n }\n \nprotected:\n virtual bool onDecode(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode);\n};\n\nstatic const uint8_t gStartingIterlaceYValue[] = {\n 0, 4, 2, 1\n};\nstatic const uint8_t gDeltaIterlaceYValue[] = {\n 8, 8, 4, 2\n};\n\n\/* Implement the GIF interlace algorithm in an iterator.\n 1) grab every 8th line beginning at 0\n 2) grab every 8th line beginning at 4\n 3) grab every 4th line beginning at 2\n 4) grab every 2nd line beginning at 1\n*\/\nclass GifInterlaceIter {\npublic:\n GifInterlaceIter(int height) : fHeight(height) {\n fStartYPtr = gStartingIterlaceYValue;\n fDeltaYPtr = gDeltaIterlaceYValue;\n\n fCurrY = *fStartYPtr++;\n fDeltaY = *fDeltaYPtr++;\n }\n \n int currY() const {\n SkASSERT(fStartYPtr);\n SkASSERT(fDeltaYPtr);\n return fCurrY;\n }\n\n void next() {\n SkASSERT(fStartYPtr);\n SkASSERT(fDeltaYPtr);\n\n int y = fCurrY + fDeltaY;\n \/\/ We went from an if statement to a while loop so that we iterate\n \/\/ through fStartYPtr until a valid row is found. This is so that images\n \/\/ that are smaller than 5x5 will not trash memory.\n while (y >= fHeight) {\n if (gStartingIterlaceYValue +\n SK_ARRAY_COUNT(gStartingIterlaceYValue) == fStartYPtr) {\n \/\/ we done\n SkDEBUGCODE(fStartYPtr = NULL;)\n SkDEBUGCODE(fDeltaYPtr = NULL;)\n y = 0;\n } else {\n y = *fStartYPtr++;\n fDeltaY = *fDeltaYPtr++;\n }\n }\n fCurrY = y;\n }\n \nprivate:\n const int fHeight;\n int fCurrY;\n int fDeltaY;\n const uint8_t* fStartYPtr;\n const uint8_t* fDeltaYPtr;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/#define GIF_STAMP \"GIF\" \/* First chars in file - GIF stamp. *\/\n\/\/#define GIF_STAMP_LEN (sizeof(GIF_STAMP) - 1)\n\nstatic int DecodeCallBackProc(GifFileType* fileType, GifByteType* out,\n int size) {\n SkStream* stream = (SkStream*) fileType->UserData;\n return (int) stream->read(out, size);\n}\n\nvoid CheckFreeExtension(SavedImage* Image) {\n if (Image->ExtensionBlocks) {\n FreeExtension(Image);\n }\n}\n\n\/\/ return NULL on failure\nstatic const ColorMapObject* find_colormap(const GifFileType* gif) {\n const ColorMapObject* cmap = gif->Image.ColorMap;\n if (NULL == cmap) {\n cmap = gif->SColorMap;\n }\n \/\/ some sanity checks\n if ((unsigned)cmap->ColorCount > 256 ||\n cmap->ColorCount != (1 << cmap->BitsPerPixel)) {\n cmap = NULL;\n }\n return cmap;\n}\n\n\/\/ return -1 if not found (i.e. we're completely opaque)\nstatic int find_transpIndex(const SavedImage& image, int colorCount) {\n int transpIndex = -1;\n for (int i = 0; i < image.ExtensionBlockCount; ++i) {\n const ExtensionBlock* eb = image.ExtensionBlocks + i;\n if (eb->Function == 0xF9 && eb->ByteCount == 4) {\n if (eb->Bytes[0] & 1) {\n transpIndex = (unsigned char)eb->Bytes[3];\n \/\/ check for valid transpIndex\n if (transpIndex >= colorCount) {\n transpIndex = -1;\n }\n break;\n }\n }\n }\n return transpIndex;\n}\n\nstatic bool error_return(GifFileType* gif, const SkBitmap& bm,\n const char msg[]) {\n#if 0\n SkDebugf(\"libgif error <%s> bitmap [%d %d] pixels %p colortable %p\\n\",\n msg, bm.width(), bm.height(), bm.getPixels(), bm.getColorTable());\n#endif\n return false;\n}\n\nbool SkGIFImageDecoder::onDecode(SkStream* sk_stream, SkBitmap* bm,\n SkBitmap::Config prefConfig, Mode mode) { \n GifFileType* gif = DGifOpen(sk_stream, DecodeCallBackProc);\n if (NULL == gif) {\n return error_return(gif, *bm, \"DGifOpen\");\n }\n\n SkAutoTCallIProc acp(gif);\n\n SavedImage temp_save;\n temp_save.ExtensionBlocks=NULL;\n temp_save.ExtensionBlockCount=0;\n SkAutoTCallVProc acp2(&temp_save);\n\n int width, height;\n GifRecordType recType;\n GifByteType *extData;\n int transpIndex = -1; \/\/ -1 means we don't have it (yet)\n \n do {\n if (DGifGetRecordType(gif, &recType) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetRecordType\");\n }\n \n switch (recType) {\n case IMAGE_DESC_RECORD_TYPE: {\n if (DGifGetImageDesc(gif) == GIF_ERROR) {\n return error_return(gif, *bm, \"IMAGE_DESC_RECORD_TYPE\");\n }\n \n if (gif->ImageCount < 1) { \/\/ sanity check\n return error_return(gif, *bm, \"ImageCount < 1\");\n }\n \n width = gif->SWidth;\n height = gif->SHeight;\n if (width <= 0 || height <= 0 ||\n !this->chooseFromOneChoice(SkBitmap::kIndex8_Config,\n width, height)) {\n return error_return(gif, *bm, \"chooseFromOneChoice\");\n }\n \n bm->setConfig(SkBitmap::kIndex8_Config, width, height);\n if (SkImageDecoder::kDecodeBounds_Mode == mode)\n return true;\n\n SavedImage* image = &gif->SavedImages[gif->ImageCount-1];\n const GifImageDesc& desc = image->ImageDesc;\n \n \/\/ check for valid descriptor\n if ( (desc.Top | desc.Left) < 0 ||\n desc.Left + desc.Width > width ||\n desc.Top + desc.Height > height) {\n return error_return(gif, *bm, \"TopLeft\");\n }\n \n \/\/ now we decode the colortable\n int colorCount = 0;\n {\n const ColorMapObject* cmap = find_colormap(gif);\n if (NULL == cmap) {\n return error_return(gif, *bm, \"null cmap\");\n }\n\n colorCount = cmap->ColorCount;\n SkColorTable* ctable = SkNEW_ARGS(SkColorTable, (colorCount));\n SkPMColor* colorPtr = ctable->lockColors();\n for (int index = 0; index < colorCount; index++)\n colorPtr[index] = SkPackARGB32(0xFF,\n cmap->Colors[index].Red, \n cmap->Colors[index].Green,\n cmap->Colors[index].Blue);\n\n transpIndex = find_transpIndex(temp_save, colorCount);\n if (transpIndex < 0)\n ctable->setFlags(ctable->getFlags() | SkColorTable::kColorsAreOpaque_Flag);\n else\n colorPtr[transpIndex] = 0; \/\/ ram in a transparent SkPMColor\n ctable->unlockColors(true);\n\n SkAutoUnref aurts(ctable);\n if (!this->allocPixelRef(bm, ctable)) {\n return error_return(gif, *bm, \"allocPixelRef\");\n }\n }\n \n SkAutoLockPixels alp(*bm);\n\n \/\/ time to decode the scanlines\n \/\/\n uint8_t* scanline = bm->getAddr8(0, 0);\n const int rowBytes = bm->rowBytes();\n const int innerWidth = desc.Width;\n const int innerHeight = desc.Height;\n\n \/\/ abort if either inner dimension is <= 0\n if (innerWidth <= 0 || innerHeight <= 0) {\n return error_return(gif, *bm, \"non-pos inner width\/height\");\n }\n\n \/\/ are we only a subset of the total bounds?\n if ((desc.Top | desc.Left) > 0 ||\n innerWidth < width || innerHeight < height)\n {\n int fill;\n if (transpIndex >= 0) {\n fill = transpIndex;\n } else {\n fill = gif->SBackGroundColor;\n }\n \/\/ check for valid fill index\/color\n if (static_cast(fill) >=\n static_cast(colorCount)) {\n fill = 0;\n }\n memset(scanline, fill, bm->getSize());\n \/\/ bump our starting address\n scanline += desc.Top * rowBytes + desc.Left;\n }\n \n \/\/ now decode each scanline\n if (gif->Image.Interlace)\n {\n GifInterlaceIter iter(innerHeight);\n for (int y = 0; y < innerHeight; y++)\n {\n uint8_t* row = scanline + iter.currY() * rowBytes;\n if (DGifGetLine(gif, row, innerWidth) == GIF_ERROR) {\n return error_return(gif, *bm, \"interlace DGifGetLine\");\n }\n iter.next();\n }\n }\n else\n {\n \/\/ easy, non-interlace case\n for (int y = 0; y < innerHeight; y++) {\n if (DGifGetLine(gif, scanline, innerWidth) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetLine\");\n }\n scanline += rowBytes;\n }\n }\n goto DONE;\n } break;\n \n case EXTENSION_RECORD_TYPE:\n if (DGifGetExtension(gif, &temp_save.Function,\n &extData) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetExtension\");\n }\n\n while (extData != NULL) {\n \/* Create an extension block with our data *\/\n if (AddExtensionBlock(&temp_save, extData[0],\n &extData[1]) == GIF_ERROR) {\n return error_return(gif, *bm, \"AddExtensionBlock\");\n }\n if (DGifGetExtensionNext(gif, &extData) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetExtensionNext\");\n }\n temp_save.Function = 0;\n }\n break;\n \n case TERMINATE_RECORD_TYPE:\n break;\n \n default:\t\/* Should be trapped by DGifGetRecordType *\/\n break;\n }\n } while (recType != TERMINATE_RECORD_TYPE);\n\nDONE:\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkTRegistry.h\"\n\nstatic SkImageDecoder* Factory(SkStream* stream) {\n char buf[GIF_STAMP_LEN];\n if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {\n if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||\n memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||\n memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {\n return SkNEW(SkGIFImageDecoder);\n }\n }\n return NULL;\n}\n\nstatic SkTRegistry gReg(Factory);\ncheck for null cmap\/* libs\/graphics\/images\/SkImageDecoder_libgif.cpp\n**\n** Copyright 2006, The Android Open Source Project\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\"); \n** you may not use this file except in compliance with the License. \n** You may obtain a copy of the License at \n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0 \n**\n** Unless required by applicable law or agreed to in writing, software \n** distributed under the License is distributed on an \"AS IS\" BASIS, \n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. \n** See the License for the specific language governing permissions and \n** limitations under the License.\n*\/\n\n#include \"SkImageDecoder.h\"\n#include \"SkColor.h\"\n#include \"SkColorPriv.h\"\n#include \"SkStream.h\"\n#include \"SkTemplates.h\"\n#include \"SkPackBits.h\"\n\n#include \"gif_lib.h\"\n\nclass SkGIFImageDecoder : public SkImageDecoder {\npublic:\n virtual Format getFormat() const {\n return kGIF_Format;\n }\n \nprotected:\n virtual bool onDecode(SkStream* stream, SkBitmap* bm,\n SkBitmap::Config pref, Mode mode);\n};\n\nstatic const uint8_t gStartingIterlaceYValue[] = {\n 0, 4, 2, 1\n};\nstatic const uint8_t gDeltaIterlaceYValue[] = {\n 8, 8, 4, 2\n};\n\n\/* Implement the GIF interlace algorithm in an iterator.\n 1) grab every 8th line beginning at 0\n 2) grab every 8th line beginning at 4\n 3) grab every 4th line beginning at 2\n 4) grab every 2nd line beginning at 1\n*\/\nclass GifInterlaceIter {\npublic:\n GifInterlaceIter(int height) : fHeight(height) {\n fStartYPtr = gStartingIterlaceYValue;\n fDeltaYPtr = gDeltaIterlaceYValue;\n\n fCurrY = *fStartYPtr++;\n fDeltaY = *fDeltaYPtr++;\n }\n \n int currY() const {\n SkASSERT(fStartYPtr);\n SkASSERT(fDeltaYPtr);\n return fCurrY;\n }\n\n void next() {\n SkASSERT(fStartYPtr);\n SkASSERT(fDeltaYPtr);\n\n int y = fCurrY + fDeltaY;\n \/\/ We went from an if statement to a while loop so that we iterate\n \/\/ through fStartYPtr until a valid row is found. This is so that images\n \/\/ that are smaller than 5x5 will not trash memory.\n while (y >= fHeight) {\n if (gStartingIterlaceYValue +\n SK_ARRAY_COUNT(gStartingIterlaceYValue) == fStartYPtr) {\n \/\/ we done\n SkDEBUGCODE(fStartYPtr = NULL;)\n SkDEBUGCODE(fDeltaYPtr = NULL;)\n y = 0;\n } else {\n y = *fStartYPtr++;\n fDeltaY = *fDeltaYPtr++;\n }\n }\n fCurrY = y;\n }\n \nprivate:\n const int fHeight;\n int fCurrY;\n int fDeltaY;\n const uint8_t* fStartYPtr;\n const uint8_t* fDeltaYPtr;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/#define GIF_STAMP \"GIF\" \/* First chars in file - GIF stamp. *\/\n\/\/#define GIF_STAMP_LEN (sizeof(GIF_STAMP) - 1)\n\nstatic int DecodeCallBackProc(GifFileType* fileType, GifByteType* out,\n int size) {\n SkStream* stream = (SkStream*) fileType->UserData;\n return (int) stream->read(out, size);\n}\n\nvoid CheckFreeExtension(SavedImage* Image) {\n if (Image->ExtensionBlocks) {\n FreeExtension(Image);\n }\n}\n\n\/\/ return NULL on failure\nstatic const ColorMapObject* find_colormap(const GifFileType* gif) {\n const ColorMapObject* cmap = gif->Image.ColorMap;\n if (NULL == cmap) {\n cmap = gif->SColorMap;\n }\n \/\/ some sanity checks\n if (cmap && ((unsigned)cmap->ColorCount > 256 ||\n cmap->ColorCount != (1 << cmap->BitsPerPixel))) {\n cmap = NULL;\n }\n return cmap;\n}\n\n\/\/ return -1 if not found (i.e. we're completely opaque)\nstatic int find_transpIndex(const SavedImage& image, int colorCount) {\n int transpIndex = -1;\n for (int i = 0; i < image.ExtensionBlockCount; ++i) {\n const ExtensionBlock* eb = image.ExtensionBlocks + i;\n if (eb->Function == 0xF9 && eb->ByteCount == 4) {\n if (eb->Bytes[0] & 1) {\n transpIndex = (unsigned char)eb->Bytes[3];\n \/\/ check for valid transpIndex\n if (transpIndex >= colorCount) {\n transpIndex = -1;\n }\n break;\n }\n }\n }\n return transpIndex;\n}\n\nstatic bool error_return(GifFileType* gif, const SkBitmap& bm,\n const char msg[]) {\n#if 0\n SkDebugf(\"libgif error <%s> bitmap [%d %d] pixels %p colortable %p\\n\",\n msg, bm.width(), bm.height(), bm.getPixels(), bm.getColorTable());\n#endif\n return false;\n}\n\nbool SkGIFImageDecoder::onDecode(SkStream* sk_stream, SkBitmap* bm,\n SkBitmap::Config prefConfig, Mode mode) { \n GifFileType* gif = DGifOpen(sk_stream, DecodeCallBackProc);\n if (NULL == gif) {\n return error_return(gif, *bm, \"DGifOpen\");\n }\n\n SkAutoTCallIProc acp(gif);\n\n SavedImage temp_save;\n temp_save.ExtensionBlocks=NULL;\n temp_save.ExtensionBlockCount=0;\n SkAutoTCallVProc acp2(&temp_save);\n\n int width, height;\n GifRecordType recType;\n GifByteType *extData;\n int transpIndex = -1; \/\/ -1 means we don't have it (yet)\n \n do {\n if (DGifGetRecordType(gif, &recType) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetRecordType\");\n }\n \n switch (recType) {\n case IMAGE_DESC_RECORD_TYPE: {\n if (DGifGetImageDesc(gif) == GIF_ERROR) {\n return error_return(gif, *bm, \"IMAGE_DESC_RECORD_TYPE\");\n }\n \n if (gif->ImageCount < 1) { \/\/ sanity check\n return error_return(gif, *bm, \"ImageCount < 1\");\n }\n \n width = gif->SWidth;\n height = gif->SHeight;\n if (width <= 0 || height <= 0 ||\n !this->chooseFromOneChoice(SkBitmap::kIndex8_Config,\n width, height)) {\n return error_return(gif, *bm, \"chooseFromOneChoice\");\n }\n \n bm->setConfig(SkBitmap::kIndex8_Config, width, height);\n if (SkImageDecoder::kDecodeBounds_Mode == mode)\n return true;\n\n SavedImage* image = &gif->SavedImages[gif->ImageCount-1];\n const GifImageDesc& desc = image->ImageDesc;\n \n \/\/ check for valid descriptor\n if ( (desc.Top | desc.Left) < 0 ||\n desc.Left + desc.Width > width ||\n desc.Top + desc.Height > height) {\n return error_return(gif, *bm, \"TopLeft\");\n }\n \n \/\/ now we decode the colortable\n int colorCount = 0;\n {\n const ColorMapObject* cmap = find_colormap(gif);\n if (NULL == cmap) {\n return error_return(gif, *bm, \"null cmap\");\n }\n\n colorCount = cmap->ColorCount;\n SkColorTable* ctable = SkNEW_ARGS(SkColorTable, (colorCount));\n SkPMColor* colorPtr = ctable->lockColors();\n for (int index = 0; index < colorCount; index++)\n colorPtr[index] = SkPackARGB32(0xFF,\n cmap->Colors[index].Red, \n cmap->Colors[index].Green,\n cmap->Colors[index].Blue);\n\n transpIndex = find_transpIndex(temp_save, colorCount);\n if (transpIndex < 0)\n ctable->setFlags(ctable->getFlags() | SkColorTable::kColorsAreOpaque_Flag);\n else\n colorPtr[transpIndex] = 0; \/\/ ram in a transparent SkPMColor\n ctable->unlockColors(true);\n\n SkAutoUnref aurts(ctable);\n if (!this->allocPixelRef(bm, ctable)) {\n return error_return(gif, *bm, \"allocPixelRef\");\n }\n }\n \n SkAutoLockPixels alp(*bm);\n\n \/\/ time to decode the scanlines\n \/\/\n uint8_t* scanline = bm->getAddr8(0, 0);\n const int rowBytes = bm->rowBytes();\n const int innerWidth = desc.Width;\n const int innerHeight = desc.Height;\n\n \/\/ abort if either inner dimension is <= 0\n if (innerWidth <= 0 || innerHeight <= 0) {\n return error_return(gif, *bm, \"non-pos inner width\/height\");\n }\n\n \/\/ are we only a subset of the total bounds?\n if ((desc.Top | desc.Left) > 0 ||\n innerWidth < width || innerHeight < height)\n {\n int fill;\n if (transpIndex >= 0) {\n fill = transpIndex;\n } else {\n fill = gif->SBackGroundColor;\n }\n \/\/ check for valid fill index\/color\n if (static_cast(fill) >=\n static_cast(colorCount)) {\n fill = 0;\n }\n memset(scanline, fill, bm->getSize());\n \/\/ bump our starting address\n scanline += desc.Top * rowBytes + desc.Left;\n }\n \n \/\/ now decode each scanline\n if (gif->Image.Interlace)\n {\n GifInterlaceIter iter(innerHeight);\n for (int y = 0; y < innerHeight; y++)\n {\n uint8_t* row = scanline + iter.currY() * rowBytes;\n if (DGifGetLine(gif, row, innerWidth) == GIF_ERROR) {\n return error_return(gif, *bm, \"interlace DGifGetLine\");\n }\n iter.next();\n }\n }\n else\n {\n \/\/ easy, non-interlace case\n for (int y = 0; y < innerHeight; y++) {\n if (DGifGetLine(gif, scanline, innerWidth) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetLine\");\n }\n scanline += rowBytes;\n }\n }\n goto DONE;\n } break;\n \n case EXTENSION_RECORD_TYPE:\n if (DGifGetExtension(gif, &temp_save.Function,\n &extData) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetExtension\");\n }\n\n while (extData != NULL) {\n \/* Create an extension block with our data *\/\n if (AddExtensionBlock(&temp_save, extData[0],\n &extData[1]) == GIF_ERROR) {\n return error_return(gif, *bm, \"AddExtensionBlock\");\n }\n if (DGifGetExtensionNext(gif, &extData) == GIF_ERROR) {\n return error_return(gif, *bm, \"DGifGetExtensionNext\");\n }\n temp_save.Function = 0;\n }\n break;\n \n case TERMINATE_RECORD_TYPE:\n break;\n \n default:\t\/* Should be trapped by DGifGetRecordType *\/\n break;\n }\n } while (recType != TERMINATE_RECORD_TYPE);\n\nDONE:\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkTRegistry.h\"\n\nstatic SkImageDecoder* Factory(SkStream* stream) {\n char buf[GIF_STAMP_LEN];\n if (stream->read(buf, GIF_STAMP_LEN) == GIF_STAMP_LEN) {\n if (memcmp(GIF_STAMP, buf, GIF_STAMP_LEN) == 0 ||\n memcmp(GIF87_STAMP, buf, GIF_STAMP_LEN) == 0 ||\n memcmp(GIF89_STAMP, buf, GIF_STAMP_LEN) == 0) {\n return SkNEW(SkGIFImageDecoder);\n }\n }\n return NULL;\n}\n\nstatic SkTRegistry gReg(Factory);\n<|endoftext|>"} {"text":"\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass MixedDimensionMeshTest : public CppUnit::TestCase {\n \/**\n * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping\n * on the edge is consistent. That is, they share the same global node numbers and\n * the same dof numbers for a variable.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n CPPUNIT_TEST( testPointLocatorList );\n CPPUNIT_TEST( testPointLocatorTree );\n\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\n SerialMesh* _mesh;\n\n void build_mesh()\n {\n _mesh = new SerialMesh(*TestCommWorld);\n\n \/*\n (0,1) (1,1)\n x---------------x\n | |\n | |\n | |\n | |\n | |\n x---------------x\n (0,0) (1,0)\n | |\n | |\n | |\n | |\n x---------------x\n (0,-1) (1,-1)\n *\/\n\n _mesh->set_mesh_dimension(2);\n\n _mesh->add_point( Point(0.0,-1.0), 4 );\n _mesh->add_point( Point(1.0,-1.0), 5 );\n _mesh->add_point( Point(1.0, 0.0), 1 );\n _mesh->add_point( Point(1.0, 1.0), 2 );\n _mesh->add_point( Point(0.0, 1.0), 3 );\n _mesh->add_point( Point(0.0, 0.0), 0 );\n\n {\n Elem* elem_top = _mesh->add_elem( new Quad4 );\n elem_top->set_node(0) = _mesh->node_ptr(0);\n elem_top->set_node(1) = _mesh->node_ptr(1);\n elem_top->set_node(2) = _mesh->node_ptr(2);\n elem_top->set_node(3) = _mesh->node_ptr(3);\n\n Elem* elem_bottom = _mesh->add_elem( new Quad4 );\n elem_bottom->set_node(0) = _mesh->node_ptr(4);\n elem_bottom->set_node(1) = _mesh->node_ptr(5);\n elem_bottom->set_node(2) = _mesh->node_ptr(1);\n elem_bottom->set_node(3) = _mesh->node_ptr(0);\n\n Elem* edge = _mesh->add_elem( new Edge2 );\n edge->set_node(0) = _mesh->node_ptr(0);\n edge->set_node(1) = _mesh->node_ptr(1);\n }\n\n \/\/ libMesh will renumber, but we numbered according to its scheme\n \/\/ anyway. We do this because when we call uniformly_refine subsequently,\n \/\/ it's going use skip_renumber=false.\n _mesh->prepare_for_use(false \/*skip_renumber*\/);\n }\n\npublic:\n void setUp()\n {\n this->build_mesh();\n }\n\n void tearDown()\n {\n delete _mesh;\n }\n\n void testMesh()\n {\n \/\/ There'd better be 3 elements\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );\n\n \/\/ There'd better be only 6 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the bottom edge of the top QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );\n }\n\n void testDofOrdering()\n {\n EquationSystems es(*_mesh);\n es.add_system(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );\n\n \/* The dofs for the EDGE2 element should be the same\n as the bottom edge of the top QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );\n\n \/* The dofs for the EDGE2 element should be the same\n as the top edge of the bottom QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );\n }\n\n void testPointLocatorList()\n {\n AutoPtr locator = PointLocatorBase::build(LIST,*_mesh);\n\n Point top_point(0.4, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n }\n\n void testPointLocatorTree()\n {\n AutoPtr locator = _mesh->sub_point_locator();\n\n Point top_point(0.5, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n }\n\n};\n\nclass MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {\n \/**\n * The goal of this test is the same as the previous, but now we do a\n * uniform refinement and make sure the result mesh is consistent. i.e.\n * the new node shared between the 1D elements is the same as the node\n * shared on the underlying quads, and so on.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n\n CPPUNIT_TEST_SUITE_END();\n\n \/\/ Yes, this is necessary. Somewhere in those macros is a protected\/private\npublic:\n\n void setUp()\n {\n \/*\n\n 3-------10------2\n | | |\n | 5 | 6 |\n 8-------7-------9\n | | |\n | 3 | 4 |\n 0-------6-------1\n | | |\n | 9 | 10 |\n 13------12-------14\n | | |\n | 7 | 8 |\n 4-------11------5\n\n *\/\n this->build_mesh();\n#ifdef LIBMESH_ENABLE_AMR\n MeshRefinement(*_mesh).uniformly_refine(1);\n#endif\n }\n\n void testMesh()\n {\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ We should have 13 total and 10 active elements.\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );\n\n \/\/ We should have 15 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );\n\n \/\/ EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );\n\n \/\/ EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );\n\n \/\/ EDGE2,id=11 should have same nodes of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );\n\n \/\/ EDGE2,id=12 should have same nodes of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );\n\n \/\/ Shared node between the EDGE2 elements should have the same global id\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );\n#endif\n }\n\n void testDofOrdering()\n {\n#ifdef LIBMESH_ENABLE_AMR\n EquationSystems es(*_mesh);\n es.add_system(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector top_quad3_dof_indices, top_quad4_dof_indices;\n std::vector bottom_quad9_dof_indices, bottom_quad10_dof_indices;\n std::vector edge11_dof_indices, edge12_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );\n dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );\n dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );\n dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );\n dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );\n dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );\n\n \/\/ EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );\n\n \/\/ EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );\n\n \/\/ EDGE2,id=11 should have same dofs of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );\n\n \/\/ EDGE2,id=12 should have same dofs of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );\n\n \/\/EDGE2 elements should have same shared dof number\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );\n#endif\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );\nUpdate MixedDimension test to test out new PointLocator API\/\/ Ignore unused parameter warnings coming from cppuint headers\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"test_comm.h\"\n\nusing namespace libMesh;\n\nclass MixedDimensionMeshTest : public CppUnit::TestCase {\n \/**\n * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping\n * on the edge is consistent. That is, they share the same global node numbers and\n * the same dof numbers for a variable.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n CPPUNIT_TEST( testPointLocatorList );\n CPPUNIT_TEST( testPointLocatorTree );\n\n CPPUNIT_TEST_SUITE_END();\n\nprotected:\n\n SerialMesh* _mesh;\n\n void build_mesh()\n {\n _mesh = new SerialMesh(*TestCommWorld);\n\n \/*\n (0,1) (1,1)\n x---------------x\n | |\n | |\n | |\n | |\n | |\n x---------------x\n (0,0) (1,0)\n | |\n | |\n | |\n | |\n x---------------x\n (0,-1) (1,-1)\n *\/\n\n _mesh->set_mesh_dimension(2);\n\n _mesh->add_point( Point(0.0,-1.0), 4 );\n _mesh->add_point( Point(1.0,-1.0), 5 );\n _mesh->add_point( Point(1.0, 0.0), 1 );\n _mesh->add_point( Point(1.0, 1.0), 2 );\n _mesh->add_point( Point(0.0, 1.0), 3 );\n _mesh->add_point( Point(0.0, 0.0), 0 );\n\n {\n Elem* elem_top = _mesh->add_elem( new Quad4 );\n elem_top->set_node(0) = _mesh->node_ptr(0);\n elem_top->set_node(1) = _mesh->node_ptr(1);\n elem_top->set_node(2) = _mesh->node_ptr(2);\n elem_top->set_node(3) = _mesh->node_ptr(3);\n\n Elem* elem_bottom = _mesh->add_elem( new Quad4 );\n elem_bottom->set_node(0) = _mesh->node_ptr(4);\n elem_bottom->set_node(1) = _mesh->node_ptr(5);\n elem_bottom->set_node(2) = _mesh->node_ptr(1);\n elem_bottom->set_node(3) = _mesh->node_ptr(0);\n\n Elem* edge = _mesh->add_elem( new Edge2 );\n edge->set_node(0) = _mesh->node_ptr(0);\n edge->set_node(1) = _mesh->node_ptr(1);\n }\n\n \/\/ libMesh will renumber, but we numbered according to its scheme\n \/\/ anyway. We do this because when we call uniformly_refine subsequently,\n \/\/ it's going use skip_renumber=false.\n _mesh->prepare_for_use(false \/*skip_renumber*\/);\n }\n\npublic:\n void setUp()\n {\n this->build_mesh();\n }\n\n void tearDown()\n {\n delete _mesh;\n }\n\n void testMesh()\n {\n \/\/ There'd better be 3 elements\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() );\n\n \/\/ There'd better be only 6 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the bottom edge of the top QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) );\n\n \/* The nodes for the EDGE2 element should have the same global ids\n as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) );\n }\n\n void testDofOrdering()\n {\n EquationSystems es(*_mesh);\n es.add_system(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices );\n dof_map.dof_indices( _mesh->elem(2), edge_dof_indices );\n\n \/* The dofs for the EDGE2 element should be the same\n as the bottom edge of the top QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] );\n\n \/* The dofs for the EDGE2 element should be the same\n as the top edge of the bottom QUAD4 dofs *\/\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] );\n\n \/* The nodes for the bottom edge of the top QUAD4 element should have\n the same global ids as the top edge of the bottom QUAD4 element *\/\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] );\n }\n\n void testPointLocatorList()\n {\n AutoPtr locator = PointLocatorBase::build(LIST,*_mesh);\n\n Point top_point(0.4, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n CPPUNIT_ASSERT(top_elem);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n CPPUNIT_ASSERT(bottom_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n\n \/\/ Now try to find the 1d element overlapping the interface edge\n Point interface_point(0.2, 0.0);\n const Elem* interface_elem = (*locator)(interface_point,1);\n\n CPPUNIT_ASSERT(interface_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );\n }\n\n void testPointLocatorTree()\n {\n AutoPtr locator = _mesh->sub_point_locator();\n\n Point top_point(0.5, 0.5);\n const Elem* top_elem = (*locator)(top_point);\n\n \/\/ We should have gotten back the top quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() );\n\n Point bottom_point(0.5, -0.5);\n const Elem* bottom_elem = (*locator)(bottom_point);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() );\n\n \/\/ Now try to find the 1d element overlapping the interface edge\n Point interface_point(0.2, 0.0);\n const Elem* interface_elem = (*locator)(interface_point,1);\n\n CPPUNIT_ASSERT(interface_elem);\n\n \/\/ We should have gotten back the bottom quad\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)2, interface_elem->id() );\n }\n\n};\n\nclass MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest {\n \/**\n * The goal of this test is the same as the previous, but now we do a\n * uniform refinement and make sure the result mesh is consistent. i.e.\n * the new node shared between the 1D elements is the same as the node\n * shared on the underlying quads, and so on.\n *\/\npublic:\n CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest );\n\n CPPUNIT_TEST( testMesh );\n CPPUNIT_TEST( testDofOrdering );\n\n CPPUNIT_TEST_SUITE_END();\n\n \/\/ Yes, this is necessary. Somewhere in those macros is a protected\/private\npublic:\n\n void setUp()\n {\n \/*\n\n 3-------10------2\n | | |\n | 5 | 6 |\n 8-------7-------9\n | | |\n | 3 | 4 |\n 0-------6-------1\n | | |\n | 9 | 10 |\n 13------12-------14\n | | |\n | 7 | 8 |\n 4-------11------5\n\n *\/\n this->build_mesh();\n#ifdef LIBMESH_ENABLE_AMR\n MeshRefinement(*_mesh).uniformly_refine(1);\n#endif\n }\n\n void testMesh()\n {\n#ifdef LIBMESH_ENABLE_AMR\n \/\/ We should have 13 total and 10 active elements.\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() );\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() );\n\n \/\/ We should have 15 nodes\n CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() );\n\n \/\/ EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) );\n\n \/\/ EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) );\n\n \/\/ EDGE2,id=11 should have same nodes of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) );\n\n \/\/ EDGE2,id=12 should have same nodes of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) );\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) );\n\n \/\/ Shared node between the EDGE2 elements should have the same global id\n CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) );\n#endif\n }\n\n void testDofOrdering()\n {\n#ifdef LIBMESH_ENABLE_AMR\n EquationSystems es(*_mesh);\n es.add_system(\"TestDofSystem\");\n es.get_system(\"TestDofSystem\").add_variable(\"u\",FIRST);\n es.init();\n\n DofMap& dof_map = es.get_system(\"TestDofSystem\").get_dof_map();\n\n std::vector top_quad3_dof_indices, top_quad4_dof_indices;\n std::vector bottom_quad9_dof_indices, bottom_quad10_dof_indices;\n std::vector edge11_dof_indices, edge12_dof_indices;\n\n dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices );\n dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices );\n dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices );\n dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices );\n dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices );\n dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices );\n\n \/\/ EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] );\n\n \/\/ EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] );\n\n \/\/ EDGE2,id=11 should have same dofs of top of QUAD4, id=9\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] );\n\n \/\/ EDGE2,id=12 should have same dofs of top of QUAD4, id=10\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] );\n CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] );\n\n \/\/EDGE2 elements should have same shared dof number\n CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] );\n#endif\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest );\nCPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );\n<|endoftext|>"} {"text":"\/\/ Source : https:\/\/leetcode.com\/problems\/reverse-vowels-of-a-string\/\n\/\/ Author : Calinescu Valentin\n\/\/ Date : 2016-04-30\n\n\/*************************************************************************************** \n *\n * Write a function that takes a string as input and reverse only the vowels of a \n * string.\n * \n * Example 1:\n * Given s = \"hello\", return \"holle\".\n * \n * Example 2:\n * Given s = \"leetcode\", return \"leotcede\".\n * \n ***************************************************************************************\/\nclass Solution {\npublic:\n string reverseVowels(string s) {\n list vowels;\n set vows;\n vows.insert('a');\n vows.insert('A');\n vows.insert('e');\n vows.insert('E');\n vows.insert('i');\n vows.insert('I');\n vows.insert('o');\n vows.insert('O');\n vows.insert('u');\n vows.insert('U');\n string result;\n for(int i = 0; i < s.size(); i++)\n {\n if(vows.find(s[i]) != vows.end())\n vowels.push_back(s[i]);\n }\n for(int i = 0; i < s.size(); i++)\n {\n if(vows.find(s[i]) != vows.end())\n {\n result.push_back(vowels.back());\n vowels.pop_back();\n }\n else\n result.push_back(s[i]);\n }\n return result;\n }\n};\nNew solution for \"Reverse Vowels of a String\"\/\/ Source : https:\/\/leetcode.com\/problems\/reverse-vowels-of-a-string\/\n\/\/ Author : Calinescu Valentin, Hao Chen\n\/\/ Date : 2016-04-30\n\n\/*************************************************************************************** \n *\n * Write a function that takes a string as input and reverse only the vowels of a \n * string.\n * \n * Example 1:\n * Given s = \"hello\", return \"holle\".\n * \n * Example 2:\n * Given s = \"leetcode\", return \"leotcede\".\n * \n ***************************************************************************************\/\n\n\/\/Author: Calinescu Valentin\nclass Solution {\npublic:\n string reverseVowels(string s) {\n list vowels;\n set vows;\n vows.insert('a');\n vows.insert('A');\n vows.insert('e');\n vows.insert('E');\n vows.insert('i');\n vows.insert('I');\n vows.insert('o');\n vows.insert('O');\n vows.insert('u');\n vows.insert('U');\n string result;\n for(int i = 0; i < s.size(); i++)\n {\n if(vows.find(s[i]) != vows.end())\n vowels.push_back(s[i]);\n }\n for(int i = 0; i < s.size(); i++)\n {\n if(vows.find(s[i]) != vows.end())\n {\n result.push_back(vowels.back());\n vowels.pop_back();\n }\n else\n result.push_back(s[i]);\n }\n return result;\n }\n};\n\n\n\/\/ Author: Hao Chen\n\/\/ 1) preset a dictionary table to look up vowels\n\/\/ 2) we have two pointer, the `left` one search vowels from the beginning to then end, the `right` one search from the end to the beginning.\n\/\/ 3) swap the left one and the right one until left >= right.\nclass Solution {\nprivate:\n bool vowelsTable[256];\npublic:\n Solution(){\n memset(vowelsTable, 0, sizeof(vowelsTable));\n vowelsTable['a']=true;\n vowelsTable['e']=true;\n vowelsTable['i']=true;\n vowelsTable['o']=true;\n vowelsTable['u']=true;\n \n vowelsTable['A']=true;\n vowelsTable['E']=true;\n vowelsTable['I']=true;\n vowelsTable['O']=true;\n vowelsTable['U']=true;\n }\n bool isVowels(char ch) {\n return vowelsTable[ch];\n }\n string reverseVowels(string s) {\n int left=0, right=s.size()-1;\n while ( left < right ) {\n while( !isVowels( s[left]) ) left++;\n while( !isVowels( s[right] ) ) right--;\n if (left >= right) break;\n swap(s[left], s[right]);\n left++; right--;\n }\n return s;\n }\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"catch.hpp\"\n#include \"mfem.hpp\"\n\nusing namespace mfem;\n\nint dimension;\ndouble coeff(const Vector& x)\n{\n if (dimension == 2)\n {\n return 1.1 * x[0] + 2.0 * x[1];\n }\n else\n {\n return 1.1 * x[0] + 2.0 * x[1] + 3.0 * x[2];\n }\n}\n\nvoid vectorcoeff(const Vector& x, Vector& y)\n{\n y(0) = coeff(x);\n y(1) = -coeff(x);\n if (dimension == 3)\n {\n y(2) = 2.0 * coeff(x);\n }\n}\n\n\nTEST_CASE(\"ptransfer\")\n{\n\n for (int vectorspace = 0; vectorspace <= 1; ++vectorspace)\n {\n for (dimension = 2; dimension <= 3; ++dimension)\n {\n for (int ne = 1; ne <= 3; ++ne)\n {\n for (int order = 1; order <= 4; order *= 2)\n {\n for (int geometric = 0; geometric <= 1; ++geometric)\n {\n\n int fineOrder = (geometric == 1) ? order : 2 * order;\n\n std::cout << \"Testing transfer:\\n\"\n << \" Vectorspace: \" << vectorspace << \"\\n\"\n << \" Dimension: \" << dimension << \"\\n\"\n << \" Elements: \" << std::pow(ne, dimension) << \"\\n\"\n << \" Coarse order: \" << order << \"\\n\"\n << \" Fine order: \" << fineOrder << \"\\n\"\n << \" Geometric: \" << geometric << \"\\n\";\n\n Mesh* mesh;\n if (dimension == 2)\n {\n mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);\n }\n else\n {\n mesh =\n new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);\n }\n FiniteElementCollection* c_h1_fec =\n new H1_FECollection(order, dimension);\n FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new\n H1_FECollection(fineOrder, dimension);\n\n Mesh fineMesh(*mesh);\n if (geometric)\n {\n fineMesh.UniformRefinement();\n }\n\n int spaceDimension = 1;\n\n if (vectorspace == 1)\n {\n spaceDimension = dimension;\n }\n\n FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,\n spaceDimension);\n FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,\n spaceDimension);\n\n Operator* referenceOperator = nullptr;\n\n if (geometric == 0)\n {\n referenceOperator = new PRefinementTransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n }\n else\n {\n referenceOperator = new TransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n }\n\n TensorProductPRefinementTransferOperator tpTransferOperator(\n *c_h1_fespace, *f_h1_fespace);\n GridFunction X(c_h1_fespace);\n GridFunction X_cmp(c_h1_fespace);\n GridFunction Y_exact(f_h1_fespace);\n GridFunction Y_std(f_h1_fespace);\n GridFunction Y_tp(f_h1_fespace);\n\n if (vectorspace == 0)\n {\n FunctionCoefficient funcCoeff(&coeff);\n X.ProjectCoefficient(funcCoeff);\n Y_exact.ProjectCoefficient(funcCoeff);\n }\n else\n {\n VectorFunctionCoefficient funcCoeff(dimension, &vectorcoeff);\n X.ProjectCoefficient(funcCoeff);\n Y_exact.ProjectCoefficient(funcCoeff);\n }\n\n Y_std = 0.0;\n Y_tp = 0.0;\n\n referenceOperator->Mult(X, Y_std);\n\n Y_std -= Y_exact;\n REQUIRE(Y_std.Norml2() < 1e-12);\n\n if (vectorspace == 0 && geometric == 0)\n {\n tpTransferOperator.Mult(X, Y_tp);\n\n Y_tp -= Y_exact;\n REQUIRE(Y_tp.Norml2() < 1e-12);\n }\n\n if (vectorspace == 0 && geometric == 0)\n {\n referenceOperator->MultTranspose(Y_exact, X);\n tpTransferOperator.MultTranspose(Y_exact, X_cmp);\n\n X -= X_cmp;\n REQUIRE(X.Norml2() < 1e-12);\n }\n\n delete referenceOperator;\n delete f_h1_fespace;\n delete c_h1_fespace;\n if (geometric == 0)\n {\n delete f_h1_fec;\n }\n delete c_h1_fec;\n delete mesh;\n }\n }\n }\n }\n }\n}\nAdded tests for parallel grid transfers\/\/ Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"catch.hpp\"\n#include \"mfem.hpp\"\n\nusing namespace mfem;\n\nint dimension;\ndouble coeff(const Vector& x)\n{\n if (dimension == 2)\n {\n return 1.1 * x[0] + 2.0 * x[1];\n }\n else\n {\n return 1.1 * x[0] + 2.0 * x[1] + 3.0 * x[2];\n }\n}\n\nvoid vectorcoeff(const Vector& x, Vector& y)\n{\n y(0) = coeff(x);\n y(1) = -coeff(x);\n if (dimension == 3)\n {\n y(2) = 2.0 * coeff(x);\n }\n}\n\n\nTEST_CASE(\"transfer\")\n{\n for (int vectorspace = 0; vectorspace <= 1; ++vectorspace)\n {\n for (dimension = 2; dimension <= 3; ++dimension)\n {\n for (int ne = 1; ne <= 3; ++ne)\n {\n for (int order = 1; order <= 4; order *= 2)\n {\n for (int geometric = 0; geometric <= 1; ++geometric)\n {\n\n int fineOrder = (geometric == 1) ? order : 2 * order;\n\n std::cout << \"Testing transfer:\\n\"\n << \" Vectorspace: \" << vectorspace << \"\\n\"\n << \" Dimension: \" << dimension << \"\\n\"\n << \" Elements: \" << std::pow(ne, dimension) << \"\\n\"\n << \" Coarse order: \" << order << \"\\n\"\n << \" Fine order: \" << fineOrder << \"\\n\"\n << \" Geometric: \" << geometric << \"\\n\";\n\n Mesh* mesh;\n if (dimension == 2)\n {\n mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);\n }\n else\n {\n mesh =\n new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);\n }\n FiniteElementCollection* c_h1_fec =\n new H1_FECollection(order, dimension);\n FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new\n H1_FECollection(fineOrder, dimension);\n\n Mesh fineMesh(*mesh);\n if (geometric)\n {\n fineMesh.UniformRefinement();\n }\n\n int spaceDimension = 1;\n\n if (vectorspace == 1)\n {\n spaceDimension = dimension;\n }\n\n FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,\n spaceDimension);\n FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,\n spaceDimension);\n\n Operator* referenceOperator = nullptr;\n\n if (geometric == 0)\n {\n referenceOperator = new PRefinementTransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n }\n else\n {\n referenceOperator = new TransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n }\n\n TensorProductPRefinementTransferOperator tpTransferOperator(\n *c_h1_fespace, *f_h1_fespace);\n GridFunction X(c_h1_fespace);\n GridFunction X_cmp(c_h1_fespace);\n GridFunction Y_exact(f_h1_fespace);\n GridFunction Y_std(f_h1_fespace);\n GridFunction Y_tp(f_h1_fespace);\n\n if (vectorspace == 0)\n {\n FunctionCoefficient funcCoeff(&coeff);\n X.ProjectCoefficient(funcCoeff);\n Y_exact.ProjectCoefficient(funcCoeff);\n }\n else\n {\n VectorFunctionCoefficient funcCoeff(dimension, &vectorcoeff);\n X.ProjectCoefficient(funcCoeff);\n Y_exact.ProjectCoefficient(funcCoeff);\n }\n\n Y_std = 0.0;\n Y_tp = 0.0;\n\n referenceOperator->Mult(X, Y_std);\n\n Y_std -= Y_exact;\n REQUIRE(Y_std.Norml2() < 1e-12 * Y_exact.Norml2());\n\n if (vectorspace == 0 && geometric == 0)\n {\n tpTransferOperator.Mult(X, Y_tp);\n\n Y_tp -= Y_exact;\n REQUIRE(Y_tp.Norml2() < 1e-12 * Y_exact.Norml2());\n }\n\n if (vectorspace == 0 && geometric == 0)\n {\n referenceOperator->MultTranspose(Y_exact, X);\n tpTransferOperator.MultTranspose(Y_exact, X_cmp);\n\n X -= X_cmp;\n REQUIRE(X.Norml2() < 1e-12 * X_cmp.Norml2());\n }\n\n delete referenceOperator;\n delete f_h1_fespace;\n delete c_h1_fespace;\n if (geometric == 0)\n {\n delete f_h1_fec;\n }\n delete c_h1_fec;\n delete mesh;\n }\n }\n }\n }\n }\n}\n\n#ifdef MFEM_USE_MPI\n\nTEST_CASE(\"partransfer\", \"[Parallel]\")\n{\n for (dimension = 2; dimension <= 3; ++dimension)\n {\n for (int ne = 4; ne <= 5; ++ne)\n {\n for (int order = 1; order <= 4; order *= 2)\n {\n for (int geometric = 0; geometric <= 1; ++geometric)\n {\n int fineOrder = (geometric == 1) ? order : 2 * order;\n\n int num_procs;\n MPI_Comm_size(MPI_COMM_WORLD, &num_procs);\n int myid;\n MPI_Comm_rank(MPI_COMM_WORLD, &myid);\n\n if (myid == 0)\n {\n std::cout << \"Testing parallel transfer:\\n\"\n << \" Dimension: \" << dimension << \"\\n\"\n << \" Elements: \" << std::pow(ne, dimension) << \"\\n\"\n << \" Coarse order: \" << order << \"\\n\"\n << \" Fine order: \" << fineOrder << \"\\n\"\n << \" Geometric: \" << geometric << \"\\n\";\n }\n\n Mesh* mesh;\n if (dimension == 2)\n {\n mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0);\n }\n else\n {\n mesh =\n new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0);\n }\n\n Mesh fineMesh(*mesh);\n if (geometric)\n {\n fineMesh.UniformRefinement();\n }\n\n ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);\n ParMesh pfineMesh(MPI_COMM_WORLD, *mesh);\n if (geometric)\n {\n pfineMesh.UniformRefinement();\n }\n\n FiniteElementCollection* c_h1_fec =\n new H1_FECollection(order, dimension);\n FiniteElementCollection* f_h1_fec = (geometric == 1) ? c_h1_fec : new\n H1_FECollection(fineOrder, dimension);\n\n int spaceDimension = 1;\n\n double referenceRestrictionValue = 0.0;\n\n \/\/ Compute reference values in serial\n {\n FiniteElementSpace* c_h1_fespace = new FiniteElementSpace(mesh, c_h1_fec,\n spaceDimension);\n FiniteElementSpace* f_h1_fespace = new FiniteElementSpace(&fineMesh, f_h1_fec,\n spaceDimension);\n\n Operator* transferOperator = new TransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n GridFunction X(c_h1_fespace);\n GridFunction Y(f_h1_fespace);\n\n FunctionCoefficient funcCoeff(&coeff);\n Y.ProjectCoefficient(funcCoeff);\n X = 0.0;\n\n transferOperator->MultTranspose(Y, X);\n\n referenceRestrictionValue = std::sqrt(InnerProduct(X, X));\n\n delete transferOperator;\n delete f_h1_fespace;\n delete c_h1_fespace;\n }\n\n ParFiniteElementSpace* c_h1_fespace = new ParFiniteElementSpace(pmesh, c_h1_fec,\n spaceDimension);\n ParFiniteElementSpace* f_h1_fespace = new ParFiniteElementSpace(&pfineMesh,\n f_h1_fec,\n spaceDimension);\n\n Operator* transferOperator = new TrueTransferOperator(*c_h1_fespace,\n *f_h1_fespace);\n ParGridFunction X(c_h1_fespace);\n ParGridFunction Y_exact(f_h1_fespace);\n ParGridFunction Y(f_h1_fespace);\n\n FunctionCoefficient funcCoeff(&coeff);\n X.ProjectCoefficient(funcCoeff);\n Y_exact.ProjectCoefficient(funcCoeff);\n\n Y = 0.0;\n\n Vector X_true(c_h1_fespace->GetTrueVSize());\n Vector Y_true(f_h1_fespace->GetTrueVSize());\n\n c_h1_fespace->GetRestrictionMatrix()->Mult(X, X_true);\n transferOperator->Mult(X_true, Y_true);\n f_h1_fespace->GetProlongationMatrix()->Mult(Y_true, Y);\n\n Y -= Y_exact;\n REQUIRE(Y.Norml2() < 1e-12 * Y_exact.Norml2());\n\n f_h1_fespace->GetRestrictionMatrix()->Mult(Y_exact, Y_true);\n transferOperator->MultTranspose(Y_true, X_true);\n\n double restrictionValue = std::sqrt(InnerProduct(MPI_COMM_WORLD, X_true,\n X_true));\n REQUIRE(std::abs(restrictionValue - referenceRestrictionValue) < 1e-12 *\n std::abs(referenceRestrictionValue));\n\n delete transferOperator;\n delete f_h1_fespace;\n delete c_h1_fespace;\n if (geometric == 0)\n {\n delete f_h1_fec;\n }\n delete c_h1_fec;\n delete pmesh;\n delete mesh;\n }\n }\n }\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unotest.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 03:51:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n#ifndef _RTL_BOOTSTRAP_HXX_\n#include \"rtl\/bootstrap.hxx\"\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n\n#ifndef CPPUNIT_SIMPLEHEADER_HXX\n#include \n#endif\n\n#ifndef _CPPUHELPER_BOOTSTRAP_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_\n#include \n#endif\n\nnamespace css = com::sun::star;\nnamespace lang = css::lang;\nnamespace uno = css::uno;\nnamespace sax = css::xml::sax;\n\n\n\/\/ StringHelper\ninline void operator <<= (rtl::OString& _rAsciiString, const rtl::OUString& _rUnicodeString)\n{\n _rAsciiString = rtl::OUStringToOString(_rUnicodeString,RTL_TEXTENCODING_ASCII_US);\n}\n\n\nnamespace unotest\n{\n\/\/------------------------------------------------------------------------\n\/\/ testing constructors\n\/\/------------------------------------------------------------------------\n\n class ctor : public CppUnit::TestFixture\n {\n public:\n void ctor_001()\n {\n uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );\n if (xFactory.is())\n {\n \/\/ sample, get a xParser instance\n uno::Reference< sax::XParser > xParser;\n xParser = uno::Reference< sax::XParser > (\n xFactory->createInstance(\n ::rtl::OUString::createFromAscii(\"com.sun.star.xml.sax.Parser\")), uno::UNO_QUERY);\n\n CPPUNIT_ASSERT_MESSAGE(\"can't get sax::Parser\", xParser.is());\n }\n }\n\n CPPUNIT_TEST_SUITE(ctor);\n CPPUNIT_TEST(ctor_001);\n CPPUNIT_TEST_SUITE_END();\n };\n\n \/\/ -----------------------------------------------------------------------------\n CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(unotest::ctor, \"unotest\");\n} \/\/ unotest\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\n\n\nvoid RegisterAdditionalFunctions(FktRegFuncPtr _pFunc)\n{\n uno::Reference xMS;\n\n try\n {\n uno::Reference< uno::XComponentContext > xComponentContext = cppu::defaultBootstrap_InitialComponentContext();\n xMS.set(xComponentContext->getServiceManager(), uno::UNO_QUERY);\n comphelper::setProcessServiceFactory(xMS);\n }\n catch (::com::sun::star::uno::Exception e )\n {\n rtl::OString aError;\n aError <<= e.Message;\n printf(\"Error: %s\\n\", aError.getStr());\n }\n}\n\/\/ NOADDITIONAL;\nINTEGRATION: CWS rpt23fix02 (1.3.24); FILE MERGED 2007\/07\/23 11:16:00 lla 1.3.24.1: #i79902# make demos buildable\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: unotest.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2007-08-03 10:17:52 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_testshl2.hxx\"\n#ifndef _RTL_BOOTSTRAP_HXX_\n#include \"rtl\/bootstrap.hxx\"\n#endif\n\n#ifndef _COMPHELPER_PROCESSFACTORY_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n\n#ifndef CPPUNIT_SIMPLEHEADER_HXX\n#include \n#endif\n\n#ifndef _CPPUHELPER_BOOTSTRAP_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_XML_SAX_XPARSER_HPP_\n#include \n#endif\n\nnamespace css = com::sun::star;\nnamespace lang = css::lang;\nnamespace uno = css::uno;\nnamespace sax = css::xml::sax;\n\n\n\/\/ StringHelper\ninline void operator <<= (rtl::OString& _rAsciiString, const rtl::OUString& _rUnicodeString)\n{\n _rAsciiString = rtl::OUStringToOString(_rUnicodeString,RTL_TEXTENCODING_ASCII_US);\n}\n\n\nnamespace unotest\n{\n\/\/------------------------------------------------------------------------\n\/\/ testing constructors\n\/\/------------------------------------------------------------------------\n\n class ctor : public CppUnit::TestFixture\n {\n public:\n void ctor_001()\n {\n uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );\n if (xFactory.is())\n {\n \/\/ sample, get a xParser instance\n uno::Reference< sax::XParser > xParser;\n xParser = uno::Reference< sax::XParser > (\n xFactory->createInstance(\n ::rtl::OUString::createFromAscii(\"com.sun.star.xml.sax.Parser\")), uno::UNO_QUERY);\n\n CPPUNIT_ASSERT_MESSAGE(\"can't get sax::Parser\", xParser.is());\n }\n }\n\n CPPUNIT_TEST_SUITE(ctor);\n CPPUNIT_TEST(ctor_001);\n CPPUNIT_TEST_SUITE_END();\n };\n\n \/\/ -----------------------------------------------------------------------------\n CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(unotest::ctor, \"unotest\");\n} \/\/ unotest\n\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ this macro creates an empty function, which will called by the RegisterAllFunctions()\n\/\/ to let the user the possibility to also register some functions by hand.\n\n\nvoid RegisterAdditionalFunctions(FktRegFuncPtr _pFunc)\n{\n (void) _pFunc;\n uno::Reference xMS;\n\n try\n {\n uno::Reference< uno::XComponentContext > xComponentContext = cppu::defaultBootstrap_InitialComponentContext();\n xMS.set(xComponentContext->getServiceManager(), uno::UNO_QUERY);\n comphelper::setProcessServiceFactory(xMS);\n }\n catch (::com::sun::star::uno::Exception e )\n {\n rtl::OString aError;\n aError <<= e.Message;\n printf(\"Error: %s\\n\", aError.getStr());\n }\n}\n\/\/ NOADDITIONAL;\n<|endoftext|>"} {"text":"#include \"resultmodel.h\"\n#include \"resultscheduler.h\"\n#include \"..\/types.h\"\n#include \"task\/scheduledefinition.h\"\n#include \"scheduler\/scheduler.h\"\n#include \"client.h\"\n#include \"log\/logger.h\"\n\n#include \n#include \n#include \n\nLOGGER(\"ResultModel\");\n\nclass ResultModel::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(ResultModel *q)\n : q(q)\n {\n scheduler = Client::instance()->scheduler();\n }\n\n void sort(ExtResultList &list)\n {\n for (int n = 0; n taskByTaskId(TaskId(list.at(n).value(\"task_id\").toUInt())).method();\n QString valorI = scheduler->taskByTaskId(TaskId(list.at(i).value(\"task_id\").toUInt())).method();\n\n if (valorN.toUpper() > valorI.toUpper())\n {\n list.move(i, n);\n n = 0;\n }\n }\n }\n }\n\n ResultModel *q;\n\n QPointer resultScheduler;\n QPointer scheduler;\n\n QHash identToResult;\n ExtResultList results;\n\npublic slots:\n void resultAdded(const QVariantMap &result);\n void resultModified(const QVariantMap &result);\n};\n\nvoid ResultModel::Private::resultAdded(const QVariantMap &result)\n{\n int position = results.size();\n\n q->beginInsertRows(QModelIndex(), position, position);\n identToResult.insert(TaskId(result.value(\"task_id\").toInt()), position);\n results = resultScheduler->results();\n sort(results);\n q->endInsertRows();\n}\n\nvoid ResultModel::Private::resultModified(const QVariantMap &result)\n{\n int pos = identToResult.value(TaskId(result.value(\"task_id\").toInt()));\n\n if (pos == -1)\n {\n LOG_ERROR(\"invalid ident\");\n return;\n }\n\n results = resultScheduler->results();\n sort(results);\n\n QModelIndex index = q->indexFromTaskId(TaskId(result.value(\"task_id\").toInt()));\n\n if (!index.isValid())\n {\n LOG_ERROR(\"invalid index\");\n return;\n }\n\n emit q->dataChanged(index, index);\n}\n\nResultModel::ResultModel(QObject *parent)\n: QAbstractTableModel(parent)\n, d(new Private(this))\n{\n}\n\nResultModel::~ResultModel()\n{\n delete d;\n}\n\nvoid ResultModel::setScheduler(ResultScheduler *scheduler)\n{\n if (d->resultScheduler == scheduler)\n {\n return;\n }\n\n if (d->resultScheduler)\n {\n disconnect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));\n disconnect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));\n }\n\n d->resultScheduler = scheduler;\n\n if (d->resultScheduler)\n {\n connect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));\n connect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));\n }\n\n emit schedulerChanged();\n reset();\n}\n\nResultScheduler *ResultModel::scheduler() const\n{\n return d->resultScheduler;\n}\n\nQModelIndex ResultModel::indexFromTaskId(const TaskId &taskId) const\n{\n int pos = d->identToResult.value(taskId);\n\n if (pos == -1)\n {\n return QModelIndex();\n }\n else\n {\n return createIndex(pos, 0);\n }\n}\n\nvoid ResultModel::reset()\n{\n beginResetModel();\n\n if (!d->resultScheduler.isNull())\n {\n d->results = d->resultScheduler->results();\n d->sort(d->results);\n }\n\n endResetModel();\n}\n\nQVariant ResultModel::get(int index) const\n{\n if (index < 0 || index >= d->results.size())\n {\n return QVariant();\n }\n\n return d->results.at(index);\n}\n\nQHash ResultModel::roleNames() const\n{\n QHash roleNames;\n roleNames.insert(TaskIdRole, \"taskId\");\n roleNames.insert(DateTimeRole, \"dateTime\");\n roleNames.insert(ResultsRole, \"results\");\n roleNames.insert(MeasurementRole, \"name\");\n roleNames.insert(SecondColumnRole, \"secondColumn\");\n return roleNames;\n}\n\nint ResultModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return d->results.size();\n}\n\nint ResultModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 5;\n}\n\nQVariant ResultModel::data(const QModelIndex &index, int role) const\n{\n const QVariantMap &result = d->results.at(index.row());\n\n if (role == Qt::DisplayRole)\n {\n role = TaskIdRole + index.column();\n }\n\n switch (role)\n {\n case TaskIdRole:\n return result.value(\"task_id\").toInt();\n\n case DateTimeRole:\n return result.value(\"report_time\");\n \/\/case ResultsRole: return report->results(); \/\/ TODO: Scripting can't do anything with that\n\n case MeasurementRole:\n return d->scheduler->taskByTaskId(TaskId(result.value(\"task_id\").toInt())).method().toUpper();\n\n case SecondColumnRole:\n QVariantMap map = d->scheduler->taskByTaskId(TaskId(result.value(\"task_id\").toInt())).toVariant().toMap();\n QVariantMap options = map.value(\"options\").toMap();\n QString out;\n QStringList names;\n\n \/\/ option names for the second column may vary\n names << \"host\" << \"url\";\n\n foreach (const QString &name, names)\n {\n if (options.contains(name))\n {\n out = options.value(name).toString();\n break;\n }\n }\n\n \/\/ cut off last bit if it's too long\n if (out.length() > 35)\n {\n out = out.mid(0, 32) + \"...\";\n }\n\n return out;\n }\n\n return QVariant();\n}\n\nQVariant ResultModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole || orientation != Qt::Horizontal)\n {\n return QVariant();\n }\n\n section += TaskIdRole;\n\n switch (section)\n {\n case TaskIdRole:\n return tr(\"Task Id\");\n\n case DateTimeRole:\n return tr(\"Date-Time\");\n\n case ResultsRole:\n return tr(\"Results\");\n\n default:\n return QVariant();\n }\n}\n\n#include \"resultmodel.moc\"\nreplace bubble sort with std::sort#include \"resultmodel.h\"\n#include \"resultscheduler.h\"\n#include \"..\/types.h\"\n#include \"task\/scheduledefinition.h\"\n#include \"scheduler\/scheduler.h\"\n#include \"client.h\"\n#include \"log\/logger.h\"\n\n#include \n#include \n#include \n\nLOGGER(\"ResultModel\");\n\nclass ResultModel::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(ResultModel *q)\n : q(q)\n , methodSort(this)\n {\n scheduler = Client::instance()->scheduler();\n }\n\n struct MethodSort\n {\n ResultModel::Private *p;\n\n MethodSort(ResultModel::Private *p)\n : p(p)\n {}\n\n bool operator() (const QVariantMap &a, const QVariantMap &b)\n {\n \/\/ sort by method name, ascending\n return (p->scheduler->taskByTaskId(TaskId(a.value(\"task_id\").toUInt())).method() <\n p->scheduler->taskByTaskId(TaskId(b.value(\"task_id\").toUInt())).method());\n }\n };\n\n ResultModel *q;\n\n MethodSort methodSort;\n\n QPointer resultScheduler;\n QPointer scheduler;\n\n QHash identToResult;\n ExtResultList results;\n\npublic slots:\n void resultAdded(const QVariantMap &result);\n void resultModified(const QVariantMap &result);\n};\n\nvoid ResultModel::Private::resultAdded(const QVariantMap &result)\n{\n int position = results.size();\n\n q->beginInsertRows(QModelIndex(), position, position);\n identToResult.insert(TaskId(result.value(\"task_id\").toInt()), position);\n results = resultScheduler->results();\n std::sort(results.begin(), results.end(), methodSort);\n q->endInsertRows();\n}\n\nvoid ResultModel::Private::resultModified(const QVariantMap &result)\n{\n int pos = identToResult.value(TaskId(result.value(\"task_id\").toInt()));\n\n if (pos == -1)\n {\n LOG_ERROR(\"invalid ident\");\n return;\n }\n\n results = resultScheduler->results();\n std::sort(results.begin(), results.end(), methodSort);\n\n QModelIndex index = q->indexFromTaskId(TaskId(result.value(\"task_id\").toInt()));\n\n if (!index.isValid())\n {\n LOG_ERROR(\"invalid index\");\n return;\n }\n\n emit q->dataChanged(index, index);\n}\n\nResultModel::ResultModel(QObject *parent)\n: QAbstractTableModel(parent)\n, d(new Private(this))\n{\n}\n\nResultModel::~ResultModel()\n{\n delete d;\n}\n\nvoid ResultModel::setScheduler(ResultScheduler *scheduler)\n{\n if (d->resultScheduler == scheduler)\n {\n return;\n }\n\n if (d->resultScheduler)\n {\n disconnect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));\n disconnect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));\n }\n\n d->resultScheduler = scheduler;\n\n if (d->resultScheduler)\n {\n connect(d->resultScheduler.data(), SIGNAL(resultAdded(QVariantMap)), d, SLOT(resultAdded(QVariantMap)));\n connect(d->resultScheduler.data(), SIGNAL(resultModified(QVariantMap)), d, SLOT(resultModified(QVariantMap)));\n }\n\n emit schedulerChanged();\n reset();\n}\n\nResultScheduler *ResultModel::scheduler() const\n{\n return d->resultScheduler;\n}\n\nQModelIndex ResultModel::indexFromTaskId(const TaskId &taskId) const\n{\n int pos = d->identToResult.value(taskId);\n\n if (pos == -1)\n {\n return QModelIndex();\n }\n else\n {\n return createIndex(pos, 0);\n }\n}\n\nvoid ResultModel::reset()\n{\n beginResetModel();\n\n if (!d->resultScheduler.isNull())\n {\n d->results = d->resultScheduler->results();\n std::sort(d->results.begin(), d->results.end(), d->methodSort);\n }\n\n endResetModel();\n}\n\nQVariant ResultModel::get(int index) const\n{\n if (index < 0 || index >= d->results.size())\n {\n return QVariant();\n }\n\n return d->results.at(index);\n}\n\nQHash ResultModel::roleNames() const\n{\n QHash roleNames;\n roleNames.insert(TaskIdRole, \"taskId\");\n roleNames.insert(DateTimeRole, \"dateTime\");\n roleNames.insert(ResultsRole, \"results\");\n roleNames.insert(MeasurementRole, \"name\");\n roleNames.insert(SecondColumnRole, \"secondColumn\");\n return roleNames;\n}\n\nint ResultModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return d->results.size();\n}\n\nint ResultModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return 5;\n}\n\nQVariant ResultModel::data(const QModelIndex &index, int role) const\n{\n const QVariantMap &result = d->results.at(index.row());\n\n if (role == Qt::DisplayRole)\n {\n role = TaskIdRole + index.column();\n }\n\n switch (role)\n {\n case TaskIdRole:\n return result.value(\"task_id\").toInt();\n\n case DateTimeRole:\n return result.value(\"report_time\");\n \/\/case ResultsRole: return report->results(); \/\/ TODO: Scripting can't do anything with that\n\n case MeasurementRole:\n return d->scheduler->taskByTaskId(TaskId(result.value(\"task_id\").toInt())).method().toUpper();\n\n case SecondColumnRole:\n QVariantMap map = d->scheduler->taskByTaskId(TaskId(result.value(\"task_id\").toInt())).toVariant().toMap();\n QVariantMap options = map.value(\"options\").toMap();\n QString out;\n QStringList names;\n\n \/\/ option names for the second column may vary\n names << \"host\" << \"url\";\n\n foreach (const QString &name, names)\n {\n if (options.contains(name))\n {\n out = options.value(name).toString();\n break;\n }\n }\n\n \/\/ cut off last bit if it's too long\n if (out.length() > 35)\n {\n out = out.mid(0, 32) + \"...\";\n }\n\n return out;\n }\n\n return QVariant();\n}\n\nQVariant ResultModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if (role != Qt::DisplayRole || orientation != Qt::Horizontal)\n {\n return QVariant();\n }\n\n section += TaskIdRole;\n\n switch (section)\n {\n case TaskIdRole:\n return tr(\"Task Id\");\n\n case DateTimeRole:\n return tr(\"Date-Time\");\n\n case ResultsRole:\n return tr(\"Results\");\n\n default:\n return QVariant();\n }\n}\n\n#include \"resultmodel.moc\"\n<|endoftext|>"} {"text":"\/* Copyright 2015 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"bitmap_image.h\"\n#include \"bitmap_transparency.h\"\n#include \"astc_transparency.h\"\n\nnamespace gvr {\nBitmapImage::BitmapImage(int format) :\n Image(Image::BITMAP, format),mData(NULL),\n mBitmap(NULL), mJava(NULL), mHasTransparency(false)\n{\n}\n\nBitmapImage::~BitmapImage()\n{\n if (mJava)\n {\n std::lock_guard lock(mUpdateLock);\n clearData(getCurrentEnv(mJava));\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, int width, int height, jbyteArray data)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n mWidth = width;\n mHeight = height;\n mFormat = GL_RGBA; \/\/ PixelFormat::A8;\n mIsCompressed = false;\n\n if (data != NULL)\n {\n mData = static_cast(env->NewGlobalRef(data));\n signalUpdate();\n LOGV(\"Texture: BitmapImage::update(byteArray)\");\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, jobject bitmap, bool hasAlpha, int format)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n if (bitmap != NULL)\n {\n mBitmap = static_cast(env->NewGlobalRef(bitmap));\n mFormat = format;\n mIsBuffer = false;\n LOGV(\"Texture: BitmapImage::update(bitmap)\");\n if( hasAlpha ) {\n if(bitmap_has_transparency(env, bitmap)) {\n set_transparency(true);\n } else {\n \/\/ TODO: warning: bitmap has an alpha channel with no translucent\/transparent pixels.\n }\n }\n signalUpdate();\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, int xoffset, int yoffset, int width, int height, int format, int type, jobject buffer)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n if (buffer != NULL)\n {\n mXOffset = xoffset;\n mYOffset = yoffset;\n mWidth = width;\n mHeight = height;\n mFormat = format;\n mType = type;\n mBitmap = env->NewGlobalRef(buffer);\n mIsBuffer = true;\n LOGV(\"Texture: BitmapImage::update(buffer)\");\n signalUpdate();\n }\n}\n\nvoid BitmapImage::update(JNIEnv *env, int width, int height, int imageSize,\n jbyteArray data, int levels, const int* dataOffsets)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n mWidth = width;\n mHeight = height;\n mLevels = levels;\n mIsCompressed = true;\n mImageSize = imageSize;\n setDataOffsets(dataOffsets, levels);\n if (data != NULL)\n {\n mData = static_cast(env->NewGlobalRef(data));\n mPixels = env->GetByteArrayElements(mData, 0);\n LOGV(\"Texture: BitmapImage::update(byteArray, offsets)\");\n set_transparency(hasAlpha(mFormat));\n env->ReleaseByteArrayElements(mData, mPixels, 0);\n mPixels = NULL;\n signalUpdate();\n }\n}\n\nvoid BitmapImage::clearData(JNIEnv* env)\n{\n if (mData != NULL)\n {\n env->DeleteGlobalRef(mData);\n mData = NULL;\n }\n if (mBitmap != NULL)\n {\n env->DeleteGlobalRef(mBitmap);\n mBitmap = NULL;\n }\n mIsCompressed = false;\n}\n\nbool BitmapImage::hasAlpha(int format) {\n switch(format) {\n case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case GL_COMPRESSED_RG11_EAC:\n case GL_COMPRESSED_SIGNED_RG11_EAC:\n case GL_COMPRESSED_RGBA8_ETC2_EAC:\n case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:\n return true;\n break;\n case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:\n case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:\n case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:\n case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:\n case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:\n return astc_has_transparency(mPixels, mImageSize);\n break;\n default:\n return false;\n }\n}\n\n\n}\n\nFix for compressed textures not being shown if loaded again and again\/* Copyright 2015 Samsung Electronics Co., LTD\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"bitmap_image.h\"\n#include \"bitmap_transparency.h\"\n#include \"astc_transparency.h\"\n\nnamespace gvr {\nBitmapImage::BitmapImage(int format) :\n Image(Image::BITMAP, format),mData(NULL),\n mBitmap(NULL), mJava(NULL), mHasTransparency(false)\n{\n}\n\nBitmapImage::~BitmapImage()\n{\n if (mJava)\n {\n std::lock_guard lock(mUpdateLock);\n clearData(getCurrentEnv(mJava));\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, int width, int height, jbyteArray data)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n mWidth = width;\n mHeight = height;\n mFormat = GL_RGBA; \/\/ PixelFormat::A8;\n mIsCompressed = false;\n\n if (data != NULL)\n {\n mData = static_cast(env->NewGlobalRef(data));\n signalUpdate();\n LOGV(\"Texture: BitmapImage::update(byteArray)\");\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, jobject bitmap, bool hasAlpha, int format)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n if (bitmap != NULL)\n {\n mBitmap = static_cast(env->NewGlobalRef(bitmap));\n mFormat = format;\n mIsBuffer = false;\n LOGV(\"Texture: BitmapImage::update(bitmap)\");\n if( hasAlpha ) {\n if(bitmap_has_transparency(env, bitmap)) {\n set_transparency(true);\n } else {\n \/\/ TODO: warning: bitmap has an alpha channel with no translucent\/transparent pixels.\n }\n }\n signalUpdate();\n }\n}\n\nvoid BitmapImage::update(JNIEnv* env, int xoffset, int yoffset, int width, int height, int format, int type, jobject buffer)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n if (buffer != NULL)\n {\n mXOffset = xoffset;\n mYOffset = yoffset;\n mWidth = width;\n mHeight = height;\n mFormat = format;\n mType = type;\n mBitmap = env->NewGlobalRef(buffer);\n mIsBuffer = true;\n LOGV(\"Texture: BitmapImage::update(buffer)\");\n signalUpdate();\n }\n}\n\nvoid BitmapImage::update(JNIEnv *env, int width, int height, int imageSize,\n jbyteArray data, int levels, const int* dataOffsets)\n{\n std::lock_guard lock(mUpdateLock);\n env->GetJavaVM(&mJava);\n clearData(env);\n mWidth = width;\n mHeight = height;\n mLevels = levels;\n mIsCompressed = true;\n mImageSize = imageSize;\n setDataOffsets(dataOffsets, levels);\n if (data != NULL)\n {\n mData = static_cast(env->NewGlobalRef(data));\n mPixels = env->GetByteArrayElements(mData, 0);\n LOGV(\"Texture: BitmapImage::update(byteArray, offsets)\");\n set_transparency(hasAlpha(mFormat));\n env->ReleaseByteArrayElements(mData, mPixels, 0);\n mPixels = NULL;\n signalUpdate();\n }\n}\n\nvoid BitmapImage::clearData(JNIEnv* env)\n{\n if (mData != NULL)\n {\n env->DeleteGlobalRef(mData);\n mData = NULL;\n }\n if (mBitmap != NULL)\n {\n env->DeleteGlobalRef(mBitmap);\n mBitmap = NULL;\n }\n}\n\nbool BitmapImage::hasAlpha(int format) {\n switch(format) {\n case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:\n case GL_COMPRESSED_RG11_EAC:\n case GL_COMPRESSED_SIGNED_RG11_EAC:\n case GL_COMPRESSED_RGBA8_ETC2_EAC:\n case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:\n return true;\n break;\n case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:\n case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:\n case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:\n case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:\n case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:\n case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:\n case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:\n return astc_has_transparency(mPixels, mImageSize);\n break;\n default:\n return false;\n }\n}\n\n\n}\n\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"reloadpromptutils.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Utils;\n\nQTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer\n Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)\n{\n\n const QString title = QCoreApplication::translate(\"Utils::reloadPrompt\", \"File Changed\");\n QString msg;\n\n if (modified)\n msg = QCoreApplication::translate(\"Utils::reloadPrompt\",\n \"The unsaved file %1<\/i> has been changed outside Qt Creator. Do you want to reload it and discard your changes?\");\n else\n msg = QCoreApplication::translate(\"Utils::reloadPrompt\",\n \"The file %1<\/i> has changed outside Qt Creator. Do you want to reload it?\");\n msg = msg.arg(QFileInfo(fileName).fileName());\n return reloadPrompt(title, msg, QDir::toNativeSeparators(fileName), parent);\n}\n\nQTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer\n Utils::reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent)\n{\n QMessageBox msg(parent);\n msg.setStandardButtons(QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::No|QMessageBox::NoToAll);\n msg.setDefaultButton(QMessageBox::YesToAll);\n msg.setWindowTitle(title);\n msg.setText(prompt);\n msg.setDetailedText(details);\n\n switch (msg.exec()) {\n case QMessageBox::Yes:\n return ReloadCurrent;\n case QMessageBox::YesToAll:\n return ReloadAll;\n case QMessageBox::No:\n return ReloadSkipCurrent;\n default:\n break;\n }\n return ReloadNone;\n}\n\nQTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer\n Utils::fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent)\n{\n const QString title = QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"File has been removed\");\n QString msg;\n if (triggerExternally)\n msg = QCoreApplication::translate(\"Utils::fileDeletedPrompt\",\n \"The file %1 has been removed outside Qt Creator. Do you want to save it under a different name, or close the editor?\").arg(QDir::toNativeSeparators(fileName));\n else\n msg = QCoreApplication::translate(\"Utils::fileDeletedPrompt\",\n \"The file %1 was removed. Do you want to save it under a different name, or close the editor?\").arg(QDir::toNativeSeparators(fileName));\n QMessageBox box(QMessageBox::Question, title, msg, QMessageBox::NoButton, parent);\n QPushButton *close = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"Close\"), QMessageBox::RejectRole);\n QPushButton *saveas = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"Save as...\"), QMessageBox::ActionRole);\n QPushButton *save = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"Save\"), QMessageBox::AcceptRole);\n box.setDefaultButton(saveas);\n box.exec();\n QAbstractButton *clickedbutton = box.clickedButton();\n if (clickedbutton == close) {\n return FileDeletedClose;\n } else if (clickedbutton == saveas) {\n return FileDeletedSaveAs;\n } else if (clickedbutton == save) {\n return FileDeletedSave;\n }\n return FileDeletedClose;\n}\nadd keyboard accelerators to the \"file deleted\" prompt message box\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"reloadpromptutils.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Utils;\n\nQTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer\n Utils::reloadPrompt(const QString &fileName, bool modified, QWidget *parent)\n{\n\n const QString title = QCoreApplication::translate(\"Utils::reloadPrompt\", \"File Changed\");\n QString msg;\n\n if (modified)\n msg = QCoreApplication::translate(\"Utils::reloadPrompt\",\n \"The unsaved file %1<\/i> has been changed outside Qt Creator. Do you want to reload it and discard your changes?\");\n else\n msg = QCoreApplication::translate(\"Utils::reloadPrompt\",\n \"The file %1<\/i> has changed outside Qt Creator. Do you want to reload it?\");\n msg = msg.arg(QFileInfo(fileName).fileName());\n return reloadPrompt(title, msg, QDir::toNativeSeparators(fileName), parent);\n}\n\nQTCREATOR_UTILS_EXPORT Utils::ReloadPromptAnswer\n Utils::reloadPrompt(const QString &title, const QString &prompt, const QString &details, QWidget *parent)\n{\n QMessageBox msg(parent);\n msg.setStandardButtons(QMessageBox::Yes|QMessageBox::YesToAll|QMessageBox::No|QMessageBox::NoToAll);\n msg.setDefaultButton(QMessageBox::YesToAll);\n msg.setWindowTitle(title);\n msg.setText(prompt);\n msg.setDetailedText(details);\n\n switch (msg.exec()) {\n case QMessageBox::Yes:\n return ReloadCurrent;\n case QMessageBox::YesToAll:\n return ReloadAll;\n case QMessageBox::No:\n return ReloadSkipCurrent;\n default:\n break;\n }\n return ReloadNone;\n}\n\nQTCREATOR_UTILS_EXPORT Utils::FileDeletedPromptAnswer\n Utils::fileDeletedPrompt(const QString &fileName, bool triggerExternally, QWidget *parent)\n{\n const QString title = QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"File has been removed\");\n QString msg;\n if (triggerExternally)\n msg = QCoreApplication::translate(\"Utils::fileDeletedPrompt\",\n \"The file %1 has been removed outside Qt Creator. Do you want to save it under a different name, or close the editor?\").arg(QDir::toNativeSeparators(fileName));\n else\n msg = QCoreApplication::translate(\"Utils::fileDeletedPrompt\",\n \"The file %1 was removed. Do you want to save it under a different name, or close the editor?\").arg(QDir::toNativeSeparators(fileName));\n QMessageBox box(QMessageBox::Question, title, msg, QMessageBox::NoButton, parent);\n QPushButton *close = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"&Close\"), QMessageBox::RejectRole);\n QPushButton *saveas = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"Save &as...\"), QMessageBox::ActionRole);\n QPushButton *save = box.addButton(QCoreApplication::translate(\"Utils::fileDeletedPrompt\", \"&Save\"), QMessageBox::AcceptRole);\n box.setDefaultButton(saveas);\n box.exec();\n QAbstractButton *clickedbutton = box.clickedButton();\n if (clickedbutton == close) {\n return FileDeletedClose;\n } else if (clickedbutton == saveas) {\n return FileDeletedSaveAs;\n } else if (clickedbutton == save) {\n return FileDeletedSave;\n }\n return FileDeletedClose;\n}\n<|endoftext|>"} {"text":"#include \"AssembledSystem.h\"\n#include \n\n#include \n\nnamespace sofa {\nnamespace component {\nnamespace linearsolver {\n\n\nAssembledSystem::AssembledSystem(unsigned m, unsigned n) \n\t: m(m), \n\t n(n),\n\t dt(0)\n{\n\tif( !m ) return;\n\t\t\t\t\n\t\/\/ M.resize(m, m);\n\t\/\/ K.resize(m, m);\n\n\tH.resize(m, m);\n\tP.resize(m, m);\n\t\t\t\n\tf = vec::Zero( m );\n\tv = vec::Zero( m );\n\tp = vec::Zero( m );\n\t\t\t\t\n\tif( n ) {\n\t\tJ.resize(n, m);\n\n\t\tC.resize(n, n);\n\t\tphi = vec::Zero(n); \n\t\tlambda = vec::Zero(n); \n\t\t\n\t}\n\t\t\t\t\n}\n\nunsigned AssembledSystem::size() const { return m + n; }\n\t\t\t\n\nvoid AssembledSystem::debug(SReal \/*thres*\/) const {\n\n\tstd::cerr << \"f: \" << std::endl\n\t << f.transpose() << std::endl\n\t << \"v: \" << std::endl\n\t << v.transpose() << std::endl\n\t << \"p:\" << std::endl\n\t << p.transpose() << std::endl;\n\t\n\tstd::cerr << \"H:\" << std::endl\n\t << H << std::endl\n\t << \"P:\" << std::endl\n\t << P << std::endl;\n\tif( n ) { \n\t\tstd::cerr << \"phi:\" << std::endl\n\t\t << phi.transpose() << std::endl;\n\n\t\tstd::cerr << \"lambda:\" << std::endl\n\t\t << lambda.transpose() << std::endl;\n\t\t\n\t\tstd::cerr << \"J:\" << std::endl \n\t\t << J << std::endl\n\t\t << \"C:\" << std::endl\n\t\t << C << std::endl;\n\t}\n\n}\n\n\nbool AssembledSystem::isDiagonalDominant() const\n{\n typedef typename mat::Index Index;\n\n mat PH = P*H;\n\n if( n )\n {\n mat PJt = P*J.transpose();\n\n for( unsigned i=0 ; i d ) return false;\n }\n\n for( unsigned i=0 ; i d ) return false;\n }\n }\n else\n {\n for( unsigned i=0 ; i d ) return false;\n }\n }\n\n return true;\n}\n\n}\n}\n}\nr9753\/sofa : Compliant: fixed compilation on gcc-4.4#include \"AssembledSystem.h\"\n#include \n\n#include \n\nnamespace sofa {\nnamespace component {\nnamespace linearsolver {\n\n\nAssembledSystem::AssembledSystem(unsigned m, unsigned n) \n\t: m(m), \n\t n(n),\n\t dt(0)\n{\n\tif( !m ) return;\n\t\t\t\t\n\t\/\/ M.resize(m, m);\n\t\/\/ K.resize(m, m);\n\n\tH.resize(m, m);\n\tP.resize(m, m);\n\t\t\t\n\tf = vec::Zero( m );\n\tv = vec::Zero( m );\n\tp = vec::Zero( m );\n\t\t\t\t\n\tif( n ) {\n\t\tJ.resize(n, m);\n\n\t\tC.resize(n, n);\n\t\tphi = vec::Zero(n); \n\t\tlambda = vec::Zero(n); \n\t\t\n\t}\n\t\t\t\t\n}\n\nunsigned AssembledSystem::size() const { return m + n; }\n\t\t\t\n\nvoid AssembledSystem::debug(SReal \/*thres*\/) const {\n\n\tstd::cerr << \"f: \" << std::endl\n\t << f.transpose() << std::endl\n\t << \"v: \" << std::endl\n\t << v.transpose() << std::endl\n\t << \"p:\" << std::endl\n\t << p.transpose() << std::endl;\n\t\n\tstd::cerr << \"H:\" << std::endl\n\t << H << std::endl\n\t << \"P:\" << std::endl\n\t << P << std::endl;\n\tif( n ) { \n\t\tstd::cerr << \"phi:\" << std::endl\n\t\t << phi.transpose() << std::endl;\n\n\t\tstd::cerr << \"lambda:\" << std::endl\n\t\t << lambda.transpose() << std::endl;\n\t\t\n\t\tstd::cerr << \"J:\" << std::endl \n\t\t << J << std::endl\n\t\t << \"C:\" << std::endl\n\t\t << C << std::endl;\n\t}\n\n}\n\n\nbool AssembledSystem::isDiagonalDominant() const\n{\n typedef mat::Index Index;\n \n mat PH = P*H;\n\n if( n )\n {\n mat PJt = P*J.transpose();\n\n for( unsigned i=0 ; i d ) return false;\n }\n\n for( unsigned i=0 ; i d ) return false;\n }\n }\n else\n {\n for( unsigned i=0 ; i d ) return false;\n }\n }\n\n return true;\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\n\nnamespace {\n\n#define ERR_LEN 512\nextern char errorMessage[ERR_LEN];\n\ntemplate \nvoid testNaked(Val val) {\n auto protocol =\n std::make_shared(std::make_shared());\n\n GenericIO::write(protocol, val);\n protocol->getTransport()->flush();\n Val out;\n GenericIO::read(protocol, out);\n if (out != val) {\n snprintf(\n errorMessage,\n ERR_LEN,\n \"Invalid naked test (type: %s)\",\n ClassNames::getName());\n throw TLibraryException(errorMessage);\n }\n}\n\ntemplate \nvoid testField(const Val& val) {\n auto protocol =\n std::make_shared(std::make_shared());\n\n protocol->writeStructBegin(\"test_struct\");\n protocol->writeFieldBegin(\"test_field\", type, (int16_t)15);\n\n GenericIO::write(protocol, val);\n\n protocol->writeFieldEnd();\n protocol->writeStructEnd();\n protocol->getTransport()->flush();\n\n std::string name;\n protocol::TType fieldType;\n int16_t fieldId;\n\n protocol->readStructBegin(name);\n protocol->readFieldBegin(name, fieldType, fieldId);\n\n if (fieldId != 15) {\n snprintf(\n errorMessage, ERR_LEN, \"Invalid ID (type: %s)\", typeid(val).name());\n throw TLibraryException(errorMessage);\n }\n if (fieldType != type) {\n snprintf(\n errorMessage,\n ERR_LEN,\n \"Invalid Field Type (type: %s)\",\n typeid(val).name());\n throw TLibraryException(errorMessage);\n }\n\n Val out;\n GenericIO::read(protocol, out);\n\n if (out != val) {\n snprintf(\n errorMessage,\n ERR_LEN,\n \"Invalid value read (type: %s)\",\n typeid(val).name());\n throw TLibraryException(errorMessage);\n }\n\n protocol->readFieldEnd();\n protocol->readStructEnd();\n}\n\ntemplate \nvoid testMessage() {\n struct TMessage {\n const char* name;\n protocol::TMessageType type;\n int32_t seqid;\n };\n std::array messages{{\n {\"short message name\", protocol::T_CALL, 0},\n {\"1\", protocol::T_REPLY, 12345},\n {\"loooooooooooooooooooooooooooooooooong\", protocol::T_EXCEPTION, 1 << 16},\n {\"Janky\", protocol::T_CALL, 0},\n }};\n\n for (int i = 0; i < 4; i++) {\n auto protocol =\n std::make_shared(std::make_shared());\n\n protocol->writeMessageBegin(\n messages[i].name, messages[i].type, messages[i].seqid);\n protocol->writeMessageEnd();\n protocol->getTransport()->flush();\n\n std::string name;\n protocol::TMessageType type;\n int32_t seqid;\n\n protocol->readMessageBegin(name, type, seqid);\n if (name != messages[i].name || type != messages[i].type ||\n seqid != messages[i].seqid) {\n throw TLibraryException(\"readMessageBegin failed.\");\n }\n }\n}\n\ntemplate \nvoid testProtocol(const char* protoname) {\n try {\n testNaked((int8_t)123);\n\n for (int32_t i = 0; i < 128; i++) {\n testField((int8_t)i);\n testField((int8_t)-i);\n }\n\n testNaked((int16_t)0);\n testNaked((int16_t)1);\n testNaked((int16_t)15000);\n testNaked((int16_t)0x7fff);\n testNaked((int16_t)-1);\n testNaked((int16_t)-15000);\n testNaked((int16_t)-0x7fff);\n testNaked(std::numeric_limits::min());\n testNaked(std::numeric_limits::max());\n\n testField((int16_t)0);\n testField((int16_t)1);\n testField((int16_t)7);\n testField((int16_t)150);\n testField((int16_t)15000);\n testField((int16_t)0x7fff);\n testField((int16_t)-1);\n testField((int16_t)-7);\n testField((int16_t)-150);\n testField((int16_t)-15000);\n testField((int16_t)-0x7fff);\n\n testNaked(0);\n testNaked(1);\n testNaked(15000);\n testNaked(0xffff);\n testNaked(-1);\n testNaked(-15000);\n testNaked(-0xffff);\n testNaked(std::numeric_limits::min());\n testNaked(std::numeric_limits::max());\n\n testField(0);\n testField(1);\n testField(7);\n testField(150);\n testField(15000);\n testField(31337);\n testField(0xffff);\n testField(0xffffff);\n testField(-1);\n testField(-7);\n testField(-150);\n testField(-15000);\n testField(-0xffff);\n testField(-0xffffff);\n testNaked(std::numeric_limits::min());\n testNaked(std::numeric_limits::max());\n testNaked(std::numeric_limits::min() + 10);\n testNaked(std::numeric_limits::max() - 16);\n testNaked(std::numeric_limits::min());\n testNaked(std::numeric_limits::max());\n\n testNaked(0);\n for (int64_t i = 0; i < 62; i++) {\n testNaked(1L << i);\n testNaked(-(1L << i));\n }\n\n testField(0);\n for (int i = 0; i < 62; i++) {\n testField(1L << i);\n testField(-(1L << i));\n }\n\n testNaked(123.456);\n\n testNaked(\"\");\n testNaked(\"short\");\n testNaked(\"borderlinetiny\");\n testNaked(\"a bit longer than the smallest possible\");\n testNaked(\n \"\\x1\\x2\\x3\\x4\\x5\\x6\\x7\\x8\\x9\\xA\"); \/\/ kinda binary test\n\n testField(\"\");\n testField(\"short\");\n testField(\"borderlinetiny\");\n testField(\n \"a bit longer than the smallest possible\");\n\n testMessage();\n\n printf(\"%s => OK\\n\", protoname);\n } catch (const TException& e) {\n snprintf(\n errorMessage, ERR_LEN, \"%s => Test FAILED: %s\", protoname, e.what());\n throw TLibraryException(errorMessage);\n }\n}\n\nchar errorMessage[ERR_LEN];\n\n} \/\/ namespace\n\nint main(int argc, char** argv) {\n folly::init(&argc, &argv);\n\n try {\n testProtocol(\"TBinaryProtocol\");\n testProtocol(\"TCompactProtocol\");\n testProtocol(\"THeaderProtocol\");\n testProtocol(\"TJSONProtocol\");\n } catch (const TException& e) {\n printf(\"%s\\n\", e.what());\n return 1;\n }\n return 0;\n}\nKill AllProtocolTests<|endoftext|>"} {"text":"#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH\n#define DUNE_STUFF_FUNCTION_EXPRESSION_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"expression\/base.hh\"\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Function {\n\n\ntemplate< class DomainFieldImp, int domainDim,\n class RangeFieldImp, int rangeDim >\nclass Expression\n : public ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n , public Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n{\npublic:\n typedef Expression< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n typedef ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > InterfaceType;\n\n using typename InterfaceType::DomainFieldType;\n using InterfaceType::dimDomain;\n typedef typename InterfaceType::DomainType DomainType;\n using typename InterfaceType::RangeFieldType;\n using InterfaceType::dimRange;\n typedef typename InterfaceType::RangeType RangeType;\n\n Expression(const std::string _variable,\n const std::string _expression,\n const int _order = -1,\n const std::string _name = \"function.expression\")\n : BaseType(_variable, _expression)\n , order_(_order)\n , name_(_name)\n {}\n\n Expression(const std::string _variable,\n const std::vector< std::string > _expressions,\n const int _order = -1,\n const std::string _name = \"function.expression\")\n : BaseType(_variable, _expressions)\n , order_(_order)\n , name_(_name)\n {}\n\n Expression(const ThisType& other)\n : BaseType(other)\n , order_(other.order())\n , name_(other.name())\n {}\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n BaseType::operator=(other);\n order_ = other.order();\n name_ = other.name();\n }\n return this;\n } \/\/ ThisType& operator=(const ThisType& other)\n\n static Dune::ParameterTree createSampleDescription(const std::string prefix = \"\")\n {\n Dune::ParameterTree description;\n description[prefix + \"variable\"] = \"x\";\n description[prefix + \"expression\"] = \"x[0]\";\n description[prefix + \"order\"] = \"1\";\n description[prefix + \"name\"] = \"function.expression\";\n return description;\n }\n\n static ThisType createFromDescription(const Dune::ParameterTree& _description)\n {\n const Dune::Stuff::Common::ExtendedParameterTree description(_description);\n \/\/ get necessary\n const std::string _variable = description.get< std::string >(\"variable\");\n const std::vector< std::string > _expressions = description.getVector< std::string >(\"expression\",\n InterfaceType::dimRange);\n \/\/ get optional\n const int _order = description.get< int >(\"order\", -1);\n const std::string _name = description.get< std::string >(\"name\", \"function.expression\");\n \/\/ create and return\n return ThisType(_variable, _expressions, _order, _name);\n } \/\/ static ThisType createFromDescription(const Dune::ParameterTree& _description)\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual void evaluate(const DomainType& _x, RangeType& _ret) const\n {\n BaseType::evaluate(_x, _ret);\n }\n\nprivate:\n int order_;\n std::string name_;\n}; \/\/ class Expression\n\n\n} \/\/ namespace Function\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_EXPRESSION_HH\n[function.expression] fixed createSampleDescription() and createFromDescription()#ifndef DUNE_STUFF_FUNCTION_EXPRESSION_HH\n#define DUNE_STUFF_FUNCTION_EXPRESSION_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"expression\/base.hh\"\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Function {\n\n\ntemplate< class DomainFieldImp, int domainDim,\n class RangeFieldImp, int rangeDim >\nclass Expression\n : public ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n , public Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim >\n{\npublic:\n typedef Expression< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;\n typedef ExpressionBase< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > BaseType;\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, rangeDim > InterfaceType;\n\n using typename InterfaceType::DomainFieldType;\n using InterfaceType::dimDomain;\n typedef typename InterfaceType::DomainType DomainType;\n using typename InterfaceType::RangeFieldType;\n using InterfaceType::dimRange;\n typedef typename InterfaceType::RangeType RangeType;\n\n Expression(const std::string _variable,\n const std::string _expression,\n const int _order = -1,\n const std::string _name = \"function.expression\")\n : BaseType(_variable, _expression)\n , order_(_order)\n , name_(_name)\n {}\n\n Expression(const std::string _variable,\n const std::vector< std::string > _expressions,\n const int _order = -1,\n const std::string _name = \"function.expression\")\n : BaseType(_variable, _expressions)\n , order_(_order)\n , name_(_name)\n {}\n\n Expression(const ThisType& other)\n : BaseType(other)\n , order_(other.order())\n , name_(other.name())\n {}\n\n ThisType& operator=(const ThisType& other)\n {\n if (this != &other) {\n BaseType::operator=(other);\n order_ = other.order();\n name_ = other.name();\n }\n return this;\n } \/\/ ThisType& operator=(const ThisType& other)\n\n static Dune::ParameterTree createSampleDescription(const std::string subName = \"\")\n {\n Dune::ParameterTree description;\n description[\"variable\"] = \"x\";\n description[\"expression\"] = \"[x[0]; sin(x[0])]\";\n description[\"order\"] = \"1\";\n description[\"name\"] = \"function.expression\";\n if (subName.empty())\n return description;\n else {\n Dune::Stuff::Common::ExtendedParameterTree extendedDescription;\n extendedDescription.add(description, subName);\n return extendedDescription;\n }\n }\n\n static ThisType createFromDescription(const Dune::ParameterTree& _description)\n {\n const Dune::Stuff::Common::ExtendedParameterTree description(_description);\n \/\/ get necessary\n const std::string _variable = description.get< std::string >(\"variable\", \"x\");\n std::vector< std::string > _expressions;\n \/\/ lets see, if there is a key or vector\n if (description.hasVector(\"expression\")) {\n const std::vector< std::string > expr = description.getVector< std::string >(\"expression\", 1);\n for (size_t ii = 0; ii < expr.size(); ++ii)\n _expressions.push_back(expr[ii]);\n } else if (description.hasKey(\"expression\")) {\n const std::string expr = description.get< std::string >(\"expression\");\n _expressions.push_back(expr);\n } else\n DUNE_THROW(Dune::IOError,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" neither key nor vector 'expression' found in the following description:\\n\"\n << description.reportString(\" \"));\n \/\/ get optional\n const int _order = description.get< int >(\"order\", -1);\n const std::string _name = description.get< std::string >(\"name\", \"function.expression\");\n \/\/ create and return\n return ThisType(_variable, _expressions, _order, _name);\n } \/\/ static ThisType createFromDescription(const Dune::ParameterTree& _description)\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual void evaluate(const DomainType& _x, RangeType& _ret) const\n {\n BaseType::evaluate(_x, _ret);\n }\n\nprivate:\n int order_;\n std::string name_;\n}; \/\/ class Expression\n\n\n} \/\/ namespace Function\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_EXPRESSION_HH\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* import_defaults_editor.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"import_defaults_editor.h\"\n\nclass ImportDefaultsEditorSettings : public Object {\n\tGDCLASS(ImportDefaultsEditorSettings, Object)\n\tfriend class ImportDefaultsEditor;\n\tList properties;\n\tMap values;\n\tMap default_values;\n\n\tRef importer;\n\nprotected:\n\tbool _set(const StringName &p_name, const Variant &p_value) {\n\t\tif (values.has(p_name)) {\n\t\t\tvalues[p_name] = p_value;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\tbool _get(const StringName &p_name, Variant &r_ret) const {\n\t\tif (values.has(p_name)) {\n\t\t\tr_ret = values[p_name];\n\t\t\treturn true;\n\t\t} else {\n\t\t\tr_ret = Variant();\n\t\t\treturn false;\n\t\t}\n\t}\n\tvoid _get_property_list(List *p_list) const {\n\t\tif (importer.is_null()) {\n\t\t\treturn;\n\t\t}\n\t\tfor (const List::Element *E = properties.front(); E; E = E->next()) {\n\t\t\tif (importer->get_option_visibility(E->get().name, values)) {\n\t\t\t\tp_list->push_back(E->get());\n\t\t\t}\n\t\t}\n\t}\n};\n\nvoid ImportDefaultsEditor::_reset() {\n\tif (settings->importer.is_valid()) {\n\t\tsettings->values = settings->default_values;\n\t\tsettings->notify_property_list_changed();\n\t}\n}\nvoid ImportDefaultsEditor::_save() {\n\tif (settings->importer.is_valid()) {\n\t\tDictionary modified;\n\n\t\tfor (Map::Element *E = settings->values.front(); E; E = E->next()) {\n\t\t\tif (E->get() != settings->default_values[E->key()]) {\n\t\t\t\tmodified[E->key()] = E->get();\n\t\t\t}\n\t\t}\n\n\t\tif (modified.size()) {\n\t\t\tProjectSettings::get_singleton()->set(\"importer_defaults\/\" + settings->importer->get_importer_name(), modified);\n\t\t} else {\n\t\t\tProjectSettings::get_singleton()->set(\"importer_defaults\/\" + settings->importer->get_importer_name(), Variant());\n\t\t}\n\n\t\temit_signal(\"project_settings_changed\");\n\t}\n}\n\nvoid ImportDefaultsEditor::_update_importer() {\n\tList> importer_list;\n\tResourceFormatImporter::get_singleton()->get_importers(&importer_list);\n\tRef importer;\n\tfor (List>::Element *E = importer_list.front(); E; E = E->next()) {\n\t\tif (E->get()->get_visible_name() == importers->get_item_text(importers->get_selected())) {\n\t\t\timporter = E->get();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tsettings->properties.clear();\n\tsettings->values.clear();\n\tsettings->importer = importer;\n\n\tif (importer.is_valid()) {\n\t\tList options;\n\t\timporter->get_import_options(&options);\n\t\tDictionary d;\n\t\tif (ProjectSettings::get_singleton()->has_setting(\"importer_defaults\/\" + importer->get_importer_name())) {\n\t\t\td = ProjectSettings::get_singleton()->get(\"importer_defaults\/\" + importer->get_importer_name());\n\t\t}\n\n\t\tfor (List::Element *E = options.front(); E; E = E->next()) {\n\t\t\tsettings->properties.push_back(E->get().option);\n\t\t\tif (d.has(E->get().option.name)) {\n\t\t\t\tsettings->values[E->get().option.name] = d[E->get().option.name];\n\t\t\t} else {\n\t\t\t\tsettings->values[E->get().option.name] = E->get().default_value;\n\t\t\t}\n\t\t\tsettings->default_values[E->get().option.name] = E->get().default_value;\n\t\t}\n\n\t\tsave_defaults->set_disabled(false);\n\t\treset_defaults->set_disabled(false);\n\n\t} else {\n\t\tsave_defaults->set_disabled(true);\n\t\treset_defaults->set_disabled(true);\n\t}\n\n\tsettings->notify_property_list_changed();\n\n\tinspector->edit(settings);\n}\nvoid ImportDefaultsEditor::_importer_selected(int p_index) {\n\t_update_importer();\n}\nvoid ImportDefaultsEditor::clear() {\n\timporters->clear();\n\timporters->add_item(\"<\" + TTR(\"Select Importer\") + \">\");\n\tList> importer_list;\n\tResourceFormatImporter::get_singleton()->get_importers(&importer_list);\n\tVector names;\n\tfor (List>::Element *E = importer_list.front(); E; E = E->next()) {\n\t\tString vn = E->get()->get_visible_name();\n\t\tnames.push_back(vn);\n\t}\n\tnames.sort();\n\n\tfor (int i = 0; i < names.size(); i++) {\n\t\timporters->add_item(names[i]);\n\t}\n}\nvoid ImportDefaultsEditor::_bind_methods() {\n\tADD_SIGNAL(MethodInfo(\"project_settings_changed\"));\n}\nImportDefaultsEditor::ImportDefaultsEditor() {\n\tHBoxContainer *hb = memnew(HBoxContainer);\n\thb->add_child(memnew(Label(TTR(\"Importer:\"))));\n\timporters = memnew(OptionButton);\n\thb->add_child(importers);\n\thb->add_spacer();\n\timporters->connect(\"item_selected\", callable_mp(this, &ImportDefaultsEditor::_importer_selected));\n\treset_defaults = memnew(Button);\n\treset_defaults->set_text(TTR(\"Reset to Defaults\"));\n\treset_defaults->set_disabled(true);\n\treset_defaults->connect(\"pressed\", callable_mp(this, &ImportDefaultsEditor::_reset));\n\thb->add_child(reset_defaults);\n\tadd_child(hb);\n\tinspector = memnew(EditorInspector);\n\tadd_child(inspector);\n\tinspector->set_v_size_flags(SIZE_EXPAND_FILL);\n\tCenterContainer *cc = memnew(CenterContainer);\n\tsave_defaults = memnew(Button);\n\tsave_defaults->set_text(TTR(\"Save\"));\n\tsave_defaults->connect(\"pressed\", callable_mp(this, &ImportDefaultsEditor::_save));\n\tcc->add_child(save_defaults);\n\tadd_child(cc);\n\n\tsettings = memnew(ImportDefaultsEditorSettings);\n}\n\nImportDefaultsEditor::~ImportDefaultsEditor() {\n\tinspector->edit(nullptr);\n\tmemdelete(settings);\n}\nFix import selector resetting in Import Defaults Editor\/*************************************************************************\/\n\/* import_defaults_editor.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"import_defaults_editor.h\"\n\nclass ImportDefaultsEditorSettings : public Object {\n\tGDCLASS(ImportDefaultsEditorSettings, Object)\n\tfriend class ImportDefaultsEditor;\n\tList properties;\n\tMap values;\n\tMap default_values;\n\n\tRef importer;\n\nprotected:\n\tbool _set(const StringName &p_name, const Variant &p_value) {\n\t\tif (values.has(p_name)) {\n\t\t\tvalues[p_name] = p_value;\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\tbool _get(const StringName &p_name, Variant &r_ret) const {\n\t\tif (values.has(p_name)) {\n\t\t\tr_ret = values[p_name];\n\t\t\treturn true;\n\t\t} else {\n\t\t\tr_ret = Variant();\n\t\t\treturn false;\n\t\t}\n\t}\n\tvoid _get_property_list(List *p_list) const {\n\t\tif (importer.is_null()) {\n\t\t\treturn;\n\t\t}\n\t\tfor (const List::Element *E = properties.front(); E; E = E->next()) {\n\t\t\tif (importer->get_option_visibility(E->get().name, values)) {\n\t\t\t\tp_list->push_back(E->get());\n\t\t\t}\n\t\t}\n\t}\n};\n\nvoid ImportDefaultsEditor::_reset() {\n\tif (settings->importer.is_valid()) {\n\t\tsettings->values = settings->default_values;\n\t\tsettings->notify_property_list_changed();\n\t}\n}\n\nvoid ImportDefaultsEditor::_save() {\n\tif (settings->importer.is_valid()) {\n\t\tDictionary modified;\n\n\t\tfor (Map::Element *E = settings->values.front(); E; E = E->next()) {\n\t\t\tif (E->get() != settings->default_values[E->key()]) {\n\t\t\t\tmodified[E->key()] = E->get();\n\t\t\t}\n\t\t}\n\n\t\tif (modified.size()) {\n\t\t\tProjectSettings::get_singleton()->set(\"importer_defaults\/\" + settings->importer->get_importer_name(), modified);\n\t\t} else {\n\t\t\tProjectSettings::get_singleton()->set(\"importer_defaults\/\" + settings->importer->get_importer_name(), Variant());\n\t\t}\n\n\t\temit_signal(\"project_settings_changed\");\n\t}\n}\n\nvoid ImportDefaultsEditor::_update_importer() {\n\tList> importer_list;\n\tResourceFormatImporter::get_singleton()->get_importers(&importer_list);\n\tRef importer;\n\tfor (List>::Element *E = importer_list.front(); E; E = E->next()) {\n\t\tif (E->get()->get_visible_name() == importers->get_item_text(importers->get_selected())) {\n\t\t\timporter = E->get();\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tsettings->properties.clear();\n\tsettings->values.clear();\n\tsettings->importer = importer;\n\n\tif (importer.is_valid()) {\n\t\tList options;\n\t\timporter->get_import_options(&options);\n\t\tDictionary d;\n\t\tif (ProjectSettings::get_singleton()->has_setting(\"importer_defaults\/\" + importer->get_importer_name())) {\n\t\t\td = ProjectSettings::get_singleton()->get(\"importer_defaults\/\" + importer->get_importer_name());\n\t\t}\n\n\t\tfor (List::Element *E = options.front(); E; E = E->next()) {\n\t\t\tsettings->properties.push_back(E->get().option);\n\t\t\tif (d.has(E->get().option.name)) {\n\t\t\t\tsettings->values[E->get().option.name] = d[E->get().option.name];\n\t\t\t} else {\n\t\t\t\tsettings->values[E->get().option.name] = E->get().default_value;\n\t\t\t}\n\t\t\tsettings->default_values[E->get().option.name] = E->get().default_value;\n\t\t}\n\n\t\tsave_defaults->set_disabled(false);\n\t\treset_defaults->set_disabled(false);\n\n\t} else {\n\t\tsave_defaults->set_disabled(true);\n\t\treset_defaults->set_disabled(true);\n\t}\n\n\tsettings->notify_property_list_changed();\n\n\tinspector->edit(settings);\n}\n\nvoid ImportDefaultsEditor::_importer_selected(int p_index) {\n\t_update_importer();\n}\n\nvoid ImportDefaultsEditor::clear() {\n\tString last_selected;\n\tif (importers->get_selected() > 0) {\n\t\tlast_selected = importers->get_item_text(importers->get_selected());\n\t}\n\n\timporters->clear();\n\n\timporters->add_item(\"<\" + TTR(\"Select Importer\") + \">\");\n\timporters->set_item_disabled(0, true);\n\n\tList> importer_list;\n\tResourceFormatImporter::get_singleton()->get_importers(&importer_list);\n\tVector names;\n\tfor (List>::Element *E = importer_list.front(); E; E = E->next()) {\n\t\tString vn = E->get()->get_visible_name();\n\t\tnames.push_back(vn);\n\t}\n\tnames.sort();\n\n\tfor (int i = 0; i < names.size(); i++) {\n\t\timporters->add_item(names[i]);\n\n\t\tif (names[i] == last_selected) {\n\t\t\timporters->select(i + 1);\n\t\t}\n\t}\n}\n\nvoid ImportDefaultsEditor::_bind_methods() {\n\tADD_SIGNAL(MethodInfo(\"project_settings_changed\"));\n}\n\nImportDefaultsEditor::ImportDefaultsEditor() {\n\tHBoxContainer *hb = memnew(HBoxContainer);\n\thb->add_child(memnew(Label(TTR(\"Importer:\"))));\n\timporters = memnew(OptionButton);\n\thb->add_child(importers);\n\thb->add_spacer();\n\timporters->connect(\"item_selected\", callable_mp(this, &ImportDefaultsEditor::_importer_selected));\n\treset_defaults = memnew(Button);\n\treset_defaults->set_text(TTR(\"Reset to Defaults\"));\n\treset_defaults->set_disabled(true);\n\treset_defaults->connect(\"pressed\", callable_mp(this, &ImportDefaultsEditor::_reset));\n\thb->add_child(reset_defaults);\n\tadd_child(hb);\n\tinspector = memnew(EditorInspector);\n\tadd_child(inspector);\n\tinspector->set_v_size_flags(SIZE_EXPAND_FILL);\n\tCenterContainer *cc = memnew(CenterContainer);\n\tsave_defaults = memnew(Button);\n\tsave_defaults->set_text(TTR(\"Save\"));\n\tsave_defaults->connect(\"pressed\", callable_mp(this, &ImportDefaultsEditor::_save));\n\tcc->add_child(save_defaults);\n\tadd_child(cc);\n\n\tsettings = memnew(ImportDefaultsEditorSettings);\n}\n\nImportDefaultsEditor::~ImportDefaultsEditor() {\n\tinspector->edit(nullptr);\n\tmemdelete(settings);\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*\n* \"@(#) $Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008\/10\/01 05:33:43 cparedes Exp $\"\n*\n*\/\n\n\n#include \n\nACE_RCSID(acstestcomp, acstestcompErrorExplorerImpl, \"$Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008\/10\/01 05:33:43 cparedes Exp $\")\n\nusing namespace baci;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ErrorExplorerImpl\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nErrorExplorerImpl::ErrorExplorerImpl( \n\t\t\t const ACE_CString &name,\n\t\t\t maci::ContainerServices * containerServices) :\n CharacteristicComponentImpl(name,containerServices),\n m_explorerDoubleProperty_sp(new RWdouble(name+\":explorerDoubleProperty\", getComponent()),this)\n{\n ACS_TRACE(\"::ErrorExplorerImpl::ErrorExplorerImpl\"); \n}\n\n\nErrorExplorerImpl::~ErrorExplorerImpl()\n{\n ACS_TRACE(\"::ErrorExplorerImpl::~ErrorExplorerImpl\");\n}\n\nACS::RWdouble_ptr\nErrorExplorerImpl::explorerDoubleProperty()\n{\n if (m_explorerDoubleProperty_sp == 0)\n\t{\n\treturn ACS::RWdouble::_nil();\n\t}\n \n ACS::RWdouble_var prop = ACS::RWdouble::_narrow(m_explorerDoubleProperty_sp->getCORBAReference());\n return prop._retn();\n}\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n\n#include \nMACI_DLL_SUPPORT_FUNCTIONS(ErrorExplorerImpl)\n\n\nupgraded to aCE+TAO 6.3.0 ICT-4152 - removed ACE_RCSID\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n*\n*\n* \"@(#) $Id: acstestcompErrorExplorerImpl.cpp,v 1.2 2008\/10\/01 05:33:43 cparedes Exp $\"\n*\n*\/\n\n\n#include \n\n\nusing namespace baci;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ ErrorExplorerImpl\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nErrorExplorerImpl::ErrorExplorerImpl( \n\t\t\t const ACE_CString &name,\n\t\t\t maci::ContainerServices * containerServices) :\n CharacteristicComponentImpl(name,containerServices),\n m_explorerDoubleProperty_sp(new RWdouble(name+\":explorerDoubleProperty\", getComponent()),this)\n{\n ACS_TRACE(\"::ErrorExplorerImpl::ErrorExplorerImpl\"); \n}\n\n\nErrorExplorerImpl::~ErrorExplorerImpl()\n{\n ACS_TRACE(\"::ErrorExplorerImpl::~ErrorExplorerImpl\");\n}\n\nACS::RWdouble_ptr\nErrorExplorerImpl::explorerDoubleProperty()\n{\n if (m_explorerDoubleProperty_sp == 0)\n\t{\n\treturn ACS::RWdouble::_nil();\n\t}\n \n ACS::RWdouble_var prop = ACS::RWdouble::_narrow(m_explorerDoubleProperty_sp->getCORBAReference());\n return prop._retn();\n}\n\n\/* --------------- [ MACI DLL support functions ] -----------------*\/\n\n#include \nMACI_DLL_SUPPORT_FUNCTIONS(ErrorExplorerImpl)\n\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ VideoPlayer.cpp\n\/\/ Chilli Source\n\/\/ Created by Ian Copland on 10\/08\/2012.\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2012 Tag Games Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ChilliSource\n{\n namespace Android\n {\n \tCS_DEFINE_NAMEDTYPE(VideoPlayer);\n \/\/--------------------------------------------------------------\n \/\/--------------------------------------------------------------\n VideoPlayer::VideoPlayer()\n \t: m_currentSubtitleTimeMS(0), m_isPlaying(false)\n {\n }\n\t\t\/\/--------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------\n\t\tbool VideoPlayer::IsA(Core::InterfaceIDType in_interfaceId) const\n\t\t{\n\t\t\treturn (in_interfaceId == Video::VideoPlayer::InterfaceID || in_interfaceId == VideoPlayer::InterfaceID);\n\t\t}\n \/\/--------------------------------------------------------------\n \/\/--------------------------------------------------------------\n void VideoPlayer::Present(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const VideoCompleteDelegate& in_delegate, bool in_dismissWithTap,\n \t\tconst Core::Colour& in_backgroundColour)\n {\n \tCS_ASSERT(m_isPlaying == false, \"Cannot present a video while one is already playing.\");\n \tm_isPlaying = true;\n \tm_completionDelegate = in_delegate;\n\n \t\/\/calculate the storage location and full filename.\n \tbool isPackage = false;\n \tstd::string fileName;\n \tif (in_storageLocation == Core::StorageLocation::k_package)\n \t{\n \t\tisPackage = true;\n \t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, in_fileName);\n \t}\n \telse if (in_storageLocation == Core::StorageLocation::k_DLC)\n\t\t\t{\n \t\tif (Core::Application::Get()->GetFileSystem()->DoesFileExistInCachedDLC(in_fileName) == true)\n \t\t{\n \t\t\tisPackage = false;\n \t\t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(Core::StorageLocation::k_DLC) + in_fileName;\n \t\t}\n \t\telse\n \t\t{\n \t\t\tisPackage = true;\n \t\t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, Core::Application::Get()->GetFileSystem()->GetPackageDLCPath() + in_fileName);\n \t\t}\n\t\t\t}\n \telse\n \t{\n \t\tisPackage = false;\n \t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(in_storageLocation) + in_fileName;\n \t}\n\n \t\/\/start the video\n \tm_javaInterface->Present(isPackage, fileName, in_dismissWithTap, in_backgroundColour, Core::MakeDelegate(this, &VideoPlayer::OnVideoComplete));\n }\n \/\/--------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------\n\t\tvoid VideoPlayer::PresentWithSubtitles(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const Video::SubtitlesCSPtr& in_subtitles, const VideoCompleteDelegate& in_delegate,\n bool in_dismissWithTap, const Core::Colour& in_backgroundColour)\n\t\t{\n\t\t\tm_subtitles = in_subtitles;\n\t\t\tm_javaInterface->SetUpdateSubtitlesDelegate(Core::MakeDelegate(this, &VideoPlayer::OnUpdateSubtitles));\n\t\t\tPresent(in_storageLocation, in_fileName, in_delegate, in_dismissWithTap, in_backgroundColour);\n\t\t}\n \/\/-------------------------------------------------------\n \/\/-------------------------------------------------------\n void VideoPlayer::OnInit()\n {\n \t\/\/get the media player java interface or create it if it doesn't yet exist.\n\t\t\tm_javaInterface = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface();\n\t\t\tif (m_javaInterface == nullptr)\n\t\t\t{\n\t\t\t\tm_javaInterface = VideoPlayerJavaInterfaceSPtr(new VideoPlayerJavaInterface());\n\t\t\t\tJavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_javaInterface);\n\t\t\t}\n }\n \/\/---------------------------------------------------------------\n \/\/---------------------------------------------------------------\n void VideoPlayer::OnVideoComplete()\n {\n \tm_javaInterface->SetUpdateSubtitlesDelegate(nullptr);\n \tm_subtitles.reset();\n \tm_isPlaying = false;\n\n \tif (m_completionDelegate != nullptr)\n \t{\n \t\tm_completionDelegate();\n \t}\n }\n\t\t\/\/---------------------------------------------------------------\n\t\t\/\/---------------------------------------------------------------\n\t\tvoid VideoPlayer::OnUpdateSubtitles()\n\t\t{\n\t\t\t\/\/only update if the position in the video has changed.\n\t\t\tf32 position = m_javaInterface->GetTime();\n\t\t\tTimeIntervalMs currentTimeMS = (TimeIntervalMs)(position * 1000.0f);\n\t\t\tif (m_currentSubtitleTimeMS != currentTimeMS)\n\t\t\t{\n\t\t\t\tm_currentSubtitleTimeMS = currentTimeMS;\n\n\t\t\t\t\/\/get the current subtitles\n\t\t\t\tauto subtitleArray = m_subtitles->GetSubtitlesAtTime(m_currentSubtitleTimeMS);\n\n\t\t\t\t\/\/add any new subtitles\n\t\t\t\tfor (auto it = subtitleArray.begin(); it != subtitleArray.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tauto mapEntry = m_subtitleMap.find(*it);\n\t\t\t\t\tif (mapEntry == m_subtitleMap.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tCore::UTF8String text = Core::LocalisedText::GetText((*it)->m_textId);\n\t\t\t\t\t\tconst Video::Subtitles::Style* style = m_subtitles->GetStyleWithName((*it)->m_styleName);\n\t\t\t\t\t\ts64 subtitleID = m_javaInterface->CreateSubtitle(text, style->m_fontName, style->m_fontSize, Rendering::StringFromAlignmentAnchor(style->m_alignment), style->m_bounds.vOrigin.x, style->m_bounds.vOrigin.y, style->m_bounds.vSize.x, style->m_bounds.vSize.y);\n\t\t\t\t\t\tm_javaInterface->SetSubtitleColour(subtitleID, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\t\t\t\t\tm_subtitleMap.insert(std::make_pair(*it, subtitleID));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/update the current text views\n\t\t\t\tfor (auto it = m_subtitleMap.begin(); it != m_subtitleMap.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tUpdateSubtitle(it->first, it->second, m_currentSubtitleTimeMS);\n\t\t\t\t}\n\n\t\t\t\t\/\/removes any text views that are no longer needed.\n\t\t\t\tfor (auto it = m_subtitlesToRemove.begin(); it != m_subtitlesToRemove.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tauto mapEntry = m_subtitleMap.find(*it);\n\t\t\t\t\tif (mapEntry != m_subtitleMap.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tm_javaInterface->RemoveSubtitle(mapEntry->second);\n\t\t\t\t\t\tm_subtitleMap.erase(mapEntry);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm_subtitlesToRemove.clear();\n\t\t\t}\n\t\t}\n\t\t\/\/---------------------------------------------------------------\n\t\t\/\/---------------------------------------------------------------\n\t\tvoid VideoPlayer::UpdateSubtitle(const Video::Subtitles::Subtitle* in_subtitle, s64 in_subtitleID, TimeIntervalMs in_timeMS)\n\t\t{\n\t\t\tconst Video::Subtitles::Style* style = m_subtitles->GetStyleWithName(in_subtitle->m_styleName);\n\n\t\t\tf32 fade = 0.0f;\n\t\t\ts64 relativeTime = ((s64)in_timeMS) - ((s64)in_subtitle->m_startTimeMS);\n\t\t\ts64 displayTime = ((s64)in_subtitle->m_endTimeMS) - ((s64)in_subtitle->m_startTimeMS);\n\n\t\t\t\/\/subtitle should not be displayed yet so remove\n\t\t\tif (relativeTime < 0)\n\t\t\t{\n\t\t\t\tm_subtitlesToRemove.push_back(in_subtitle);\n\t\t\t}\n\n\t\t\t\/\/fading in\n\t\t\telse if (relativeTime < style->m_fadeTimeMS)\n\t\t\t{\n\t\t\t\tfade = ((f32)relativeTime) \/ ((f32)style->m_fadeTimeMS);\n\t\t\t}\n\n\t\t\t\/\/active\n\t\t\telse if (relativeTime < displayTime - style->m_fadeTimeMS)\n\t\t\t{\n\t\t\t\tfade = 1.0f;\n\t\t\t}\n\n\t\t\t\/\/fading out\n\t\t\telse if (relativeTime < displayTime)\n\t\t\t{\n\t\t\t\tfade = 1.0f - (((f32)relativeTime - (displayTime - style->m_fadeTimeMS)) \/ ((f32)style->m_fadeTimeMS));\n\t\t\t}\n\n\t\t\t\/\/should no longer be displayed so remove\n\t\t\telse if (relativeTime >= displayTime)\n\t\t\t{\n\t\t\t\tm_subtitlesToRemove.push_back(in_subtitle);\n\t\t\t}\n\n\t\t\tm_javaInterface->SetSubtitleColour(in_subtitleID, style->m_colour.r, style->m_colour.g, style->m_colour.b, fade * style->m_colour.a);\n\t\t}\n \/\/-------------------------------------------------------\n \/\/-------------------------------------------------------\n void VideoPlayer::OnDestroy()\n {\n \tm_javaInterface.reset();\n }\n }\n}\nApply localised text changed to Android\/\/\n\/\/ VideoPlayer.cpp\n\/\/ Chilli Source\n\/\/ Created by Ian Copland on 10\/08\/2012.\n\/\/\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2012 Tag Games Limited\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ChilliSource\n{\n namespace Android\n {\n \tCS_DEFINE_NAMEDTYPE(VideoPlayer);\n \/\/--------------------------------------------------------------\n \/\/--------------------------------------------------------------\n VideoPlayer::VideoPlayer()\n \t: m_currentSubtitleTimeMS(0), m_isPlaying(false)\n {\n }\n\t\t\/\/--------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------\n\t\tbool VideoPlayer::IsA(Core::InterfaceIDType in_interfaceId) const\n\t\t{\n\t\t\treturn (in_interfaceId == Video::VideoPlayer::InterfaceID || in_interfaceId == VideoPlayer::InterfaceID);\n\t\t}\n \/\/--------------------------------------------------------------\n \/\/--------------------------------------------------------------\n void VideoPlayer::Present(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const VideoCompleteDelegate& in_delegate, bool in_dismissWithTap,\n \t\tconst Core::Colour& in_backgroundColour)\n {\n \tCS_ASSERT(m_isPlaying == false, \"Cannot present a video while one is already playing.\");\n \tm_isPlaying = true;\n \tm_completionDelegate = in_delegate;\n\n \t\/\/calculate the storage location and full filename.\n \tbool isPackage = false;\n \tstd::string fileName;\n \tif (in_storageLocation == Core::StorageLocation::k_package)\n \t{\n \t\tisPackage = true;\n \t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, in_fileName);\n \t}\n \telse if (in_storageLocation == Core::StorageLocation::k_DLC)\n\t\t\t{\n \t\tif (Core::Application::Get()->GetFileSystem()->DoesFileExistInCachedDLC(in_fileName) == true)\n \t\t{\n \t\t\tisPackage = false;\n \t\t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(Core::StorageLocation::k_DLC) + in_fileName;\n \t\t}\n \t\telse\n \t\t{\n \t\t\tisPackage = true;\n \t\t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToFile(Core::StorageLocation::k_package, Core::Application::Get()->GetFileSystem()->GetPackageDLCPath() + in_fileName);\n \t\t}\n\t\t\t}\n \telse\n \t{\n \t\tisPackage = false;\n \t\tfileName = Core::Application::Get()->GetFileSystem()->GetAbsolutePathToStorageLocation(in_storageLocation) + in_fileName;\n \t}\n\n \t\/\/start the video\n \tm_javaInterface->Present(isPackage, fileName, in_dismissWithTap, in_backgroundColour, Core::MakeDelegate(this, &VideoPlayer::OnVideoComplete));\n }\n \/\/--------------------------------------------------------------\n\t\t\/\/--------------------------------------------------------------\n\t\tvoid VideoPlayer::PresentWithSubtitles(Core::StorageLocation in_storageLocation, const std::string& in_fileName, const Video::SubtitlesCSPtr& in_subtitles, const VideoCompleteDelegate& in_delegate,\n bool in_dismissWithTap, const Core::Colour& in_backgroundColour)\n\t\t{\n\t\t\tm_subtitles = in_subtitles;\n\t\t\tm_javaInterface->SetUpdateSubtitlesDelegate(Core::MakeDelegate(this, &VideoPlayer::OnUpdateSubtitles));\n\t\t\tPresent(in_storageLocation, in_fileName, in_delegate, in_dismissWithTap, in_backgroundColour);\n\t\t}\n \/\/-------------------------------------------------------\n \/\/-------------------------------------------------------\n void VideoPlayer::OnInit()\n {\n \t\/\/get the media player java interface or create it if it doesn't yet exist.\n\t\t\tm_javaInterface = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface();\n\t\t\tif (m_javaInterface == nullptr)\n\t\t\t{\n\t\t\t\tm_javaInterface = VideoPlayerJavaInterfaceSPtr(new VideoPlayerJavaInterface());\n\t\t\t\tJavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_javaInterface);\n\t\t\t}\n }\n \/\/---------------------------------------------------------------\n \/\/---------------------------------------------------------------\n void VideoPlayer::OnVideoComplete()\n {\n \tm_javaInterface->SetUpdateSubtitlesDelegate(nullptr);\n \tm_subtitles.reset();\n \tm_isPlaying = false;\n\n \tif (m_completionDelegate != nullptr)\n \t{\n \t\tm_completionDelegate();\n \t}\n }\n\t\t\/\/---------------------------------------------------------------\n\t\t\/\/---------------------------------------------------------------\n\t\tvoid VideoPlayer::OnUpdateSubtitles()\n\t\t{\n\t\t\t\/\/only update if the position in the video has changed.\n\t\t\tf32 position = m_javaInterface->GetTime();\n\t\t\tTimeIntervalMs currentTimeMS = (TimeIntervalMs)(position * 1000.0f);\n\t\t\tif (m_currentSubtitleTimeMS != currentTimeMS)\n\t\t\t{\n\t\t\t\tm_currentSubtitleTimeMS = currentTimeMS;\n\n\t\t\t\t\/\/get the current subtitles\n\t\t\t\tauto subtitleArray = m_subtitles->GetSubtitlesAtTime(m_currentSubtitleTimeMS);\n\n\t\t\t\t\/\/add any new subtitles\n\t\t\t\tfor (auto it = subtitleArray.begin(); it != subtitleArray.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tauto mapEntry = m_subtitleMap.find(*it);\n\t\t\t\t\tif (mapEntry == m_subtitleMap.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tconst Core::UTF8String& text = (*it)->m_localisedText->GetText((*it)->m_localisedTextId);\n\t\t\t\t\t\tconst Video::Subtitles::Style* style = m_subtitles->GetStyleWithName((*it)->m_styleName);\n\t\t\t\t\t\ts64 subtitleID = m_javaInterface->CreateSubtitle(text, style->m_fontName, style->m_fontSize, Rendering::StringFromAlignmentAnchor(style->m_alignment), style->m_bounds.vOrigin.x, style->m_bounds.vOrigin.y, style->m_bounds.vSize.x, style->m_bounds.vSize.y);\n\t\t\t\t\t\tm_javaInterface->SetSubtitleColour(subtitleID, 0.0f, 0.0f, 0.0f, 0.0f);\n\t\t\t\t\t\tm_subtitleMap.insert(std::make_pair(*it, subtitleID));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t\/\/update the current text views\n\t\t\t\tfor (auto it = m_subtitleMap.begin(); it != m_subtitleMap.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tUpdateSubtitle(it->first, it->second, m_currentSubtitleTimeMS);\n\t\t\t\t}\n\n\t\t\t\t\/\/removes any text views that are no longer needed.\n\t\t\t\tfor (auto it = m_subtitlesToRemove.begin(); it != m_subtitlesToRemove.end(); ++it)\n\t\t\t\t{\n\t\t\t\t\tauto mapEntry = m_subtitleMap.find(*it);\n\t\t\t\t\tif (mapEntry != m_subtitleMap.end())\n\t\t\t\t\t{\n\t\t\t\t\t\tm_javaInterface->RemoveSubtitle(mapEntry->second);\n\t\t\t\t\t\tm_subtitleMap.erase(mapEntry);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tm_subtitlesToRemove.clear();\n\t\t\t}\n\t\t}\n\t\t\/\/---------------------------------------------------------------\n\t\t\/\/---------------------------------------------------------------\n\t\tvoid VideoPlayer::UpdateSubtitle(const Video::Subtitles::Subtitle* in_subtitle, s64 in_subtitleID, TimeIntervalMs in_timeMS)\n\t\t{\n\t\t\tconst Video::Subtitles::Style* style = m_subtitles->GetStyleWithName(in_subtitle->m_styleName);\n\n\t\t\tf32 fade = 0.0f;\n\t\t\ts64 relativeTime = ((s64)in_timeMS) - ((s64)in_subtitle->m_startTimeMS);\n\t\t\ts64 displayTime = ((s64)in_subtitle->m_endTimeMS) - ((s64)in_subtitle->m_startTimeMS);\n\n\t\t\t\/\/subtitle should not be displayed yet so remove\n\t\t\tif (relativeTime < 0)\n\t\t\t{\n\t\t\t\tm_subtitlesToRemove.push_back(in_subtitle);\n\t\t\t}\n\n\t\t\t\/\/fading in\n\t\t\telse if (relativeTime < style->m_fadeTimeMS)\n\t\t\t{\n\t\t\t\tfade = ((f32)relativeTime) \/ ((f32)style->m_fadeTimeMS);\n\t\t\t}\n\n\t\t\t\/\/active\n\t\t\telse if (relativeTime < displayTime - style->m_fadeTimeMS)\n\t\t\t{\n\t\t\t\tfade = 1.0f;\n\t\t\t}\n\n\t\t\t\/\/fading out\n\t\t\telse if (relativeTime < displayTime)\n\t\t\t{\n\t\t\t\tfade = 1.0f - (((f32)relativeTime - (displayTime - style->m_fadeTimeMS)) \/ ((f32)style->m_fadeTimeMS));\n\t\t\t}\n\n\t\t\t\/\/should no longer be displayed so remove\n\t\t\telse if (relativeTime >= displayTime)\n\t\t\t{\n\t\t\t\tm_subtitlesToRemove.push_back(in_subtitle);\n\t\t\t}\n\n\t\t\tm_javaInterface->SetSubtitleColour(in_subtitleID, style->m_colour.r, style->m_colour.g, style->m_colour.b, fade * style->m_colour.a);\n\t\t}\n \/\/-------------------------------------------------------\n \/\/-------------------------------------------------------\n void VideoPlayer::OnDestroy()\n {\n \tm_javaInterface.reset();\n }\n }\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: cc50_solaris_intel.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-05-19 13:09:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n#include \n\ntypedef struct _uno_Any uno_Any;\ntypedef struct _uno_Mapping uno_Mapping;\n\n\/\/ private C50 structures and functions\nnamespace __Crun\n{\n struct static_type_info\n {\n char* m_pClassName;\n int m_nSkip1; \/\/ must be 0\n void* m_pMagic; \/\/ points to some magic data\n int m_nMagic[ 4 ];\n int m_nSkip2[2]; \/\/ must be 0\n };\n void* ex_alloc(unsigned);\n void ex_throw( void*, const static_type_info*, void(*)(void*));\n void* ex_get();\n void ex_rethrow_q();\n}\n\nnamespace __Cimpl\n{\n const char* ex_name();\n}\n\nextern \"C\" void _ex_register( void*, int );\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\n\/\/##################################################################################################\n\/\/#### exceptions ##################################################################################\n\/\/##################################################################################################\n\nvoid cc50_solaris_intel_raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\nvoid cc50_solaris_intel_fillUnoException(\n void*, const char*,\n typelib_TypeDescription * pExcTypeDescr,\n uno_Any*, uno_Mapping * pCpp2Uno );\n}\n\nINTEGRATION: CWS sb34 (1.2.70); FILE MERGED 2005\/06\/28 15:23:47 sb 1.2.70.1: #b6280765# Adapted Solaris C++--UNO bridge code to be compliant with libCrun (problems with ex_alloc\/ex_throw usage, and pointers within RTTI structures).\/*************************************************************************\n *\n * $RCSfile: cc50_solaris_intel.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2005-07-01 12:15:35 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n#include \n\ntypedef struct _uno_Any uno_Any;\ntypedef struct _uno_Mapping uno_Mapping;\n\n\/\/ private C50 structures and functions\nnamespace __Crun\n{\n struct static_type_info\n {\n std::ptrdiff_t m_pClassName;\n int m_nSkip1; \/\/ must be 0\n void* m_pMagic; \/\/ points to some magic data\n int m_nMagic[ 4 ];\n int m_nSkip2[2]; \/\/ must be 0\n };\n void* ex_alloc(unsigned);\n void ex_throw( void*, const static_type_info*, void(*)(void*));\n void* ex_get();\n void ex_rethrow_q();\n}\n\nnamespace __Cimpl\n{\n const char* ex_name();\n}\n\nextern \"C\" void _ex_register( void*, int );\n\nnamespace CPPU_CURRENT_NAMESPACE\n{\n\n\/\/##################################################################################################\n\/\/#### exceptions ##################################################################################\n\/\/##################################################################################################\n\nvoid cc50_solaris_intel_raiseException(\n uno_Any * pUnoExc, uno_Mapping * pUno2Cpp );\n\nvoid cc50_solaris_intel_fillUnoException(\n void*, const char*,\n uno_Any*, uno_Mapping * pCpp2Uno );\n}\n\n<|endoftext|>"} {"text":"\/* medViewContainerMulti.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Wed Mar 17 11:01:46 2010 (+0100)\n * Version: $Id$\n * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)\n * By: Julien Wintz\n * Update #: 56\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"medViewContainer_p.h\"\n#include \"medViewContainerMulti.h\"\n#include \"medViewPool.h\"\n\n#include \n\n#include \n#include \n\nmedViewContainerSingle2::~medViewContainerSingle2()\n{\n}\n\nvoid medViewContainerSingle2::setView (dtkAbstractView *view)\n{\n d->layout->setContentsMargins(0, 0, 0, 0); \n d->layout->addWidget(view->widget(), 0, 0);\n d->view = view;\n\n \/\/ d->pool->appendView (view); \/\/ only difference with medViewContainerSingle: do not add the view to the pool\n connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n}\n\nbool medViewContainerSingle2::isLeaf(void) const\n{\n return true;\n}\n\nvoid medViewContainerSingle2::onViewClosing (void)\n{\n if (d->view) {\n d->layout->removeWidget(d->view->widget());\n d->view->widget()->hide();\n disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n \/\/ d->pool->removeView (d->view); \/\/ do not remove it from the pool\n d->view = NULL;\n }\n\n \/\/ qDebug() << this << __func__;\n \/\/ qDebug() << \"isRoot: \" << this->isRoot();\n \/\/ qDebug() << \"isLeaf: \" << this->isLeaf();\n \/\/ qDebug() << \"isEmpty: \" << this->isEmpty();\n \/\/ qDebug() << \"isCurrent: \" << this->isCurrent();\n}\n\n\nclass medViewContainerMultiPrivate\n{\npublic:\n QList views;\n};\n\nmedViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)\n{\n}\n\nmedViewContainerMulti::~medViewContainerMulti()\n{\n medViewContainer::setView(0);\n \n delete d2;\n d2 = NULL;\n}\n\n\nvoid medViewContainerMulti::split(int rows, int cols)\n{\n Q_UNUSED(rows);\n Q_UNUSED(cols);\n\n \/\/ Don't split a multi view container\n\n return;\n}\n\ndtkAbstractView *medViewContainerMulti::view(void) const\n{\n return NULL;\n}\n\nQList medViewContainerMulti::views (void) const\n{\n return d2->views;\n}\n\nvoid medViewContainerMulti::setView(dtkAbstractView *view)\n{\n if (!view)\n return;\n\n if (d2->views.contains (view))\n return;\n \n QList content;\n for(int i = 0; i < d->layout->rowCount() ; i++) {\n for(int j = 0; j < d->layout->columnCount() ; j++) {\n if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n content << item->widget();\n d->layout->removeItem(item);\n }\n }\n }\n \n medViewContainer *container = new medViewContainerSingle2(this);\n container->setAcceptDrops(false);\n container->setView(view);\n content << container;\n this->layout(content);\n\n medViewContainer::setView (view);\n\n d2->views << view;\n \n \/\/ d->view = view; \/\/ set in medViewContainer::setView(view)\n\n \/\/ d->view->reset();\n\t\n if (medAbstractView *medView = dynamic_cast (view))\n d->pool->appendView (medView);\n \n connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));\n connect (view, SIGNAL (changeDaddy(bool)),\n this, SLOT (onDaddyChanged(bool)));\n\n this->setCurrent( container );\n emit viewAdded (view);\n}\n\nvoid medViewContainerMulti::layout(QList content)\n{\n int row = 0;\n int col = 0, colmax = 0;\n \n for(int i = 0; i < content.count()-1; i++) {\n \n if(((col+1)*(row+1)) <= content.count()-1) {\n \n qreal rratio = qMin(((qreal)this->height()\/(qreal)(row+2)), ((qreal)this->width()\/(qreal)(col+1)));\n qreal cratio = qMin(((qreal)this->height()\/(qreal)(row+1)), ((qreal)this->width()\/(qreal)(col+2)));\n \n if(rratio > cratio) {\n row++;\n col = 0;\n } else {\n col++;\n }\n \n colmax = qMax(col, colmax);\n }\n }\n \n int layout_row = 0;\n int layout_col = 0;\n \n for(int i = 0; i < content.size(); i++) {\n \n d->layout->addWidget(content.at(i), layout_row, layout_col);\n \n if(layout_col == colmax) {\n layout_row++;\n layout_col = 0;\n } else {\n layout_col++;\n }\n }\n}\n\nvoid medViewContainerMulti::onViewClosing (void)\n{\n if (dtkAbstractView *view =\n dynamic_cast(this->sender())) {\n\n \/\/ needed for selecting another container as current afterwards\n QWidget * predContainer = NULL;\n QWidget * succContainer = NULL;\n bool closedItemFound = false;\n\n QWidget * closedContainer =\n dynamic_cast< QWidget * >( view->widget()->parent() );\n QList content;\n for (int i = 0; i < d->layout->rowCount(); i++) {\n for (int j = 0; j < d->layout->columnCount(); j++) {\n QLayoutItem * item = d->layout->itemAtPosition(i, j);\n if ( item != NULL ) {\n QWidget * container = item->widget();\n if ( container == closedContainer ) {\n container->hide();\n closedItemFound = true;\n }\n else {\n content << container; \/\/ keep the container in layout\n container->show(); \/\/ in case view was hidden\n\n \/\/ remember the predecessor resp. successor of\n \/\/ the closed container\n if ( closedItemFound ) {\n if ( succContainer == NULL )\n succContainer = container;\n }\n else\n predContainer = container;\n }\n\n d->layout->removeItem(item);\n }\n }\n }\n\n disconnect (view, SIGNAL (closing()),\n this, SLOT (onViewClosing()));\n disconnect (view, SIGNAL (fullScreen(bool)),\n this, SLOT (onViewFullScreen(bool)));\n disconnect (view, SIGNAL (changeDaddy(bool)),\n this, SLOT (onDaddyChanged(bool)));\n\n if (medAbstractView *medView = dynamic_cast (view))\n d->pool->removeView (medView);\n\n d2->views.removeOne (view);\n\n emit viewRemoved (view);\n\n view->close();\n\n delete closedContainer;\n\n this->layout (content);\n\n medViewContainer * current =\n dynamic_cast< medViewContainer * >( succContainer );\n if ( current == NULL )\n current = dynamic_cast< medViewContainer * >( predContainer );\n if ( current == NULL )\n current = this;\n\n this->setCurrent(current);\n\n current->onViewFocused( true );\n\n this->update();\n\n \/\/ qDebug() << this << __func__;\n \/\/ qDebug() << \"isRoot: \" << this->isRoot();\n \/\/ qDebug() << \"isLeaf: \" << this->isLeaf();\n \/\/ qDebug() << \"isEmpty: \" << this->isEmpty();\n \/\/ qDebug() << \"isCurrent: \" << this->isCurrent();\n }\n}\n\nvoid medViewContainerMulti::onViewFullScreen (bool value)\n{\n if (dtkAbstractView *view = dynamic_cast(this->sender())) {\n if (value) {\n QList content;\n\t for(int i = 0; i < d->layout->rowCount() ; i++) {\n for(int j = 0; j < d->layout->columnCount() ; j++) {\n\t if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n\t\tif(item->widget()!=view->widget()->parent())\n\t\t item->widget()->hide();\n\t }\n }\n\t } \n }\n else {\n\tQList content;\n\tfor(int i = 0; i < d->layout->rowCount() ; i++) {\n\t for(int j = 0; j < d->layout->columnCount() ; j++) {\n\t if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n\t if(item->widget()!=view->widget()->parent())\n\t\titem->widget()->show();\n\t }\n\t } \n\t}\n }\n }\n}\n\nvoid medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)\n{\n medViewContainer::dragEnterEvent(event);\n}\n\nvoid medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)\n{\n medViewContainer::dragMoveEvent(event);\n}\n\nvoid medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)\n{\n medViewContainer::dragLeaveEvent(event);\n}\n\nvoid medViewContainerMulti::dropEvent(QDropEvent *event)\n{\n if(medViewContainerMulti *container = dynamic_cast(this->parentWidget())) {\n this->setCurrent(container);\n }\n else {\n this->setCurrent(this);\n }\n\n medViewContainer::dropEvent(event);\n}\n\nvoid medViewContainerMulti::focusInEvent(QFocusEvent *event)\n{\n Q_UNUSED(event);\n}\n\nvoid medViewContainerMulti::focusOutEvent(QFocusEvent *event)\n{\n Q_UNUSED(event);\n}\nCorrect setCurrent that was going too deep\/* medViewContainerMulti.cpp --- \n * \n * Author: Julien Wintz\n * Copyright (C) 2008 - Julien Wintz, Inria.\n * Created: Wed Mar 17 11:01:46 2010 (+0100)\n * Version: $Id$\n * Last-Updated: Mon Dec 20 11:26:25 2010 (+0100)\n * By: Julien Wintz\n * Update #: 56\n *\/\n\n\/* Commentary: \n * \n *\/\n\n\/* Change log:\n * \n *\/\n\n#include \"medViewContainer_p.h\"\n#include \"medViewContainerMulti.h\"\n#include \"medViewPool.h\"\n\n#include \n\n#include \n#include \n\nmedViewContainerSingle2::~medViewContainerSingle2()\n{\n}\n\nvoid medViewContainerSingle2::setView (dtkAbstractView *view)\n{\n d->layout->setContentsMargins(0, 0, 0, 0); \n d->layout->addWidget(view->widget(), 0, 0);\n d->view = view;\n\n \/\/ d->pool->appendView (view); \/\/ only difference with medViewContainerSingle: do not add the view to the pool\n connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n}\n\nbool medViewContainerSingle2::isLeaf(void) const\n{\n return true;\n}\n\nvoid medViewContainerSingle2::onViewClosing (void)\n{\n if (d->view) {\n d->layout->removeWidget(d->view->widget());\n d->view->widget()->hide();\n disconnect (d->view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n \/\/ d->pool->removeView (d->view); \/\/ do not remove it from the pool\n d->view = NULL;\n }\n\n \/\/ qDebug() << this << __func__;\n \/\/ qDebug() << \"isRoot: \" << this->isRoot();\n \/\/ qDebug() << \"isLeaf: \" << this->isLeaf();\n \/\/ qDebug() << \"isEmpty: \" << this->isEmpty();\n \/\/ qDebug() << \"isCurrent: \" << this->isCurrent();\n}\n\n\nclass medViewContainerMultiPrivate\n{\npublic:\n QList views;\n};\n\nmedViewContainerMulti::medViewContainerMulti (QWidget *parent) : medViewContainer (parent), d2 (new medViewContainerMultiPrivate)\n{\n}\n\nmedViewContainerMulti::~medViewContainerMulti()\n{\n medViewContainer::setView(0);\n \n delete d2;\n d2 = NULL;\n}\n\n\nvoid medViewContainerMulti::split(int rows, int cols)\n{\n Q_UNUSED(rows);\n Q_UNUSED(cols);\n\n \/\/ Don't split a multi view container\n\n return;\n}\n\ndtkAbstractView *medViewContainerMulti::view(void) const\n{\n return NULL;\n}\n\nQList medViewContainerMulti::views (void) const\n{\n return d2->views;\n}\n\nvoid medViewContainerMulti::setView(dtkAbstractView *view)\n{\n if (!view)\n return;\n\n if (d2->views.contains (view))\n return;\n \n QList content;\n for(int i = 0; i < d->layout->rowCount() ; i++) {\n for(int j = 0; j < d->layout->columnCount() ; j++) {\n if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n content << item->widget();\n d->layout->removeItem(item);\n }\n }\n }\n \n medViewContainer *container = new medViewContainerSingle2(this);\n container->setAcceptDrops(false);\n container->setView(view);\n content << container;\n this->layout(content);\n\n medViewContainer::setView (view);\n\n d2->views << view;\n \n \/\/ d->view = view; \/\/ set in medViewContainer::setView(view)\n\n \/\/ d->view->reset();\n\t\n if (medAbstractView *medView = dynamic_cast (view))\n d->pool->appendView (medView);\n \n connect (view, SIGNAL (closing()), this, SLOT (onViewClosing()));\n connect (view, SIGNAL (fullScreen(bool)), this, SLOT (onViewFullScreen(bool)));\n connect (view, SIGNAL (changeDaddy(bool)),\n this, SLOT (onDaddyChanged(bool)));\n\n this->setCurrent( container );\n emit viewAdded (view);\n}\n\nvoid medViewContainerMulti::layout(QList content)\n{\n int row = 0;\n int col = 0, colmax = 0;\n \n for(int i = 0; i < content.count()-1; i++) {\n \n if(((col+1)*(row+1)) <= content.count()-1) {\n \n qreal rratio = qMin(((qreal)this->height()\/(qreal)(row+2)), ((qreal)this->width()\/(qreal)(col+1)));\n qreal cratio = qMin(((qreal)this->height()\/(qreal)(row+1)), ((qreal)this->width()\/(qreal)(col+2)));\n \n if(rratio > cratio) {\n row++;\n col = 0;\n } else {\n col++;\n }\n \n colmax = qMax(col, colmax);\n }\n }\n \n int layout_row = 0;\n int layout_col = 0;\n \n for(int i = 0; i < content.size(); i++) {\n \n d->layout->addWidget(content.at(i), layout_row, layout_col);\n \n if(layout_col == colmax) {\n layout_row++;\n layout_col = 0;\n } else {\n layout_col++;\n }\n }\n}\n\nvoid medViewContainerMulti::onViewClosing (void)\n{\n if (dtkAbstractView *view =\n dynamic_cast(this->sender())) {\n\n \/\/ needed for selecting another container as current afterwards\n QWidget * predContainer = NULL;\n QWidget * succContainer = NULL;\n bool closedItemFound = false;\n\n QWidget * closedContainer =\n dynamic_cast< QWidget * >( view->widget()->parent() );\n QList content;\n for (int i = 0; i < d->layout->rowCount(); i++) {\n for (int j = 0; j < d->layout->columnCount(); j++) {\n QLayoutItem * item = d->layout->itemAtPosition(i, j);\n if ( item != NULL ) {\n QWidget * container = item->widget();\n if ( container == closedContainer ) {\n container->hide();\n closedItemFound = true;\n }\n else {\n content << container; \/\/ keep the container in layout\n container->show(); \/\/ in case view was hidden\n\n \/\/ remember the predecessor resp. successor of\n \/\/ the closed container\n if ( closedItemFound ) {\n if ( succContainer == NULL )\n succContainer = container;\n }\n else\n predContainer = container;\n }\n\n d->layout->removeItem(item);\n }\n }\n }\n\n disconnect (view, SIGNAL (closing()),\n this, SLOT (onViewClosing()));\n disconnect (view, SIGNAL (fullScreen(bool)),\n this, SLOT (onViewFullScreen(bool)));\n disconnect (view, SIGNAL (changeDaddy(bool)),\n this, SLOT (onDaddyChanged(bool)));\n\n if (medAbstractView *medView = dynamic_cast (view))\n d->pool->removeView (medView);\n\n d2->views.removeOne (view);\n\n emit viewRemoved (view);\n\n view->close();\n\n delete closedContainer;\n\n this->layout (content);\n\n medViewContainer * current =\n dynamic_cast< medViewContainer * >( succContainer );\n if ( current == NULL )\n current = dynamic_cast< medViewContainer * >( predContainer );\n if ( current == NULL )\n current = this;\n\n this->setCurrent(this);\n\n current->onViewFocused( true );\n\n this->update();\n\n \/\/ qDebug() << this << __func__;\n \/\/ qDebug() << \"isRoot: \" << this->isRoot();\n \/\/ qDebug() << \"isLeaf: \" << this->isLeaf();\n \/\/ qDebug() << \"isEmpty: \" << this->isEmpty();\n \/\/ qDebug() << \"isCurrent: \" << this->isCurrent();\n }\n}\n\nvoid medViewContainerMulti::onViewFullScreen (bool value)\n{\n if (dtkAbstractView *view = dynamic_cast(this->sender())) {\n if (value) {\n QList content;\n\t for(int i = 0; i < d->layout->rowCount() ; i++) {\n for(int j = 0; j < d->layout->columnCount() ; j++) {\n\t if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n\t\tif(item->widget()!=view->widget()->parent())\n\t\t item->widget()->hide();\n\t }\n }\n\t } \n }\n else {\n\tQList content;\n\tfor(int i = 0; i < d->layout->rowCount() ; i++) {\n\t for(int j = 0; j < d->layout->columnCount() ; j++) {\n\t if(QLayoutItem *item = d->layout->itemAtPosition(i, j)) {\n\t if(item->widget()!=view->widget()->parent())\n\t\titem->widget()->show();\n\t }\n\t } \n\t}\n }\n }\n}\n\nvoid medViewContainerMulti::dragEnterEvent(QDragEnterEvent *event)\n{\n medViewContainer::dragEnterEvent(event);\n}\n\nvoid medViewContainerMulti::dragMoveEvent(QDragMoveEvent *event)\n{\n medViewContainer::dragMoveEvent(event);\n}\n\nvoid medViewContainerMulti::dragLeaveEvent(QDragLeaveEvent *event)\n{\n medViewContainer::dragLeaveEvent(event);\n}\n\nvoid medViewContainerMulti::dropEvent(QDropEvent *event)\n{\n if(medViewContainerMulti *container = dynamic_cast(this->parentWidget())) {\n this->setCurrent(container);\n }\n else {\n this->setCurrent(this);\n }\n\n medViewContainer::dropEvent(event);\n}\n\nvoid medViewContainerMulti::focusInEvent(QFocusEvent *event)\n{\n Q_UNUSED(event);\n}\n\nvoid medViewContainerMulti::focusOutEvent(QFocusEvent *event)\n{\n Q_UNUSED(event);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file gpsfailure.cpp\n * Helper class for gpsfailure mode according to the OBC rules\n *\n * @author Thomas Gubler \n *\/\n\n#include \"gpsfailure.h\"\n#include \"navigator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing matrix::Eulerf;\nusing matrix::Quatf;\n\nGpsFailure::GpsFailure(Navigator *navigator) :\n\tMissionBlock(navigator),\n\tModuleParams(navigator)\n{\n}\n\nvoid\nGpsFailure::on_inactive()\n{\n\t\/* reset GPSF state only if setpoint moved *\/\n\tif (!_navigator->get_can_loiter_at_sp()) {\n\t\t_gpsf_state = GPSF_STATE_NONE;\n\t}\n}\n\nvoid\nGpsFailure::on_activation()\n{\n\t_gpsf_state = GPSF_STATE_NONE;\n\t_timestamp_activation = hrt_absolute_time();\n\tadvance_gpsf();\n\tset_gpsf_item();\n}\n\nvoid\nGpsFailure::on_active()\n{\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_LOITER: {\n\t\t\t\/* Position controller does not run in this mode:\n\t\t\t * navigator has to publish an attitude setpoint *\/\n\t\t\tvehicle_attitude_setpoint_s att_sp = {};\n\t\t\tatt_sp.timestamp = hrt_absolute_time();\n\t\t\tatt_sp.roll_body = math::radians(_param_nav_gpsf_r.get());\n\t\t\tatt_sp.pitch_body = math::radians(_param_nav_gpsf_p.get());\n\t\t\tatt_sp.thrust_body[0] = _param_nav_gpsf_tr.get();\n\n\t\t\tQuatf q(Eulerf(att_sp.roll_body, att_sp.pitch_body, 0.0f));\n\t\t\tq.copyTo(att_sp.q_d);\n\n\t\t\tif (_navigator->get_vstatus()->is_vtol) {\n\t\t\t\t_fw_virtual_att_sp_pub.publish(att_sp);\n\n\t\t\t} else {\n\t\t\t\t_att_sp_pub.publish(att_sp);\n\n\t\t\t}\n\n\t\t\t\/* Measure time *\/\n\t\t\tif ((_param_nav_gpsf_lt.get() > FLT_EPSILON) &&\n\t\t\t (hrt_elapsed_time(&_timestamp_activation) > _param_nav_gpsf_lt.get() * 1e6f)) {\n\t\t\t\t\/* no recovery, advance the state machine *\/\n\t\t\t\tPX4_WARN(\"GPS not recovered, switching to next failure state\");\n\t\t\t\tadvance_gpsf();\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\tcase GPSF_STATE_TERMINATE:\n\t\tset_gpsf_item();\n\t\tadvance_gpsf();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid\nGpsFailure::set_gpsf_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t\/* Set pos sp triplet to invalid to stop pos controller *\/\n\tpos_sp_triplet->previous.valid = false;\n\tpos_sp_triplet->current.valid = false;\n\tpos_sp_triplet->next.valid = false;\n\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_TERMINATE: {\n\t\t\t\/* Request flight termination from commander *\/\n\t\t\t_navigator->get_mission_result()->flight_termination = true;\n\t\t\t_navigator->set_mission_result_updated();\n\t\t\tPX4_WARN(\"GPS failure: request flight termination\");\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nGpsFailure::advance_gpsf()\n{\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_NONE:\n\t\t_gpsf_state = GPSF_STATE_LOITER;\n\t\tmavlink_log_critical(_navigator->get_mavlink_log_pub(), \"Global position failure: fixed bank loiter\");\n\t\tbreak;\n\n\tcase GPSF_STATE_LOITER:\n\t\t_gpsf_state = GPSF_STATE_TERMINATE;\n\t\tmavlink_log_emergency(_navigator->get_mavlink_log_pub(), \"no GPS recovery, terminating flight\");\n\t\tbreak;\n\n\tcase GPSF_STATE_TERMINATE:\n\t\tPX4_WARN(\"terminate\");\n\t\t_gpsf_state = GPSF_STATE_END;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\nChange wording in GPS failure handling This matches better the different platforms that are using this functionality.\/****************************************************************************\n *\n * Copyright (c) 2013-2014 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file gpsfailure.cpp\n * Helper class for gpsfailure mode according to the OBC rules\n *\n * @author Thomas Gubler \n *\/\n\n#include \"gpsfailure.h\"\n#include \"navigator.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing matrix::Eulerf;\nusing matrix::Quatf;\n\nGpsFailure::GpsFailure(Navigator *navigator) :\n\tMissionBlock(navigator),\n\tModuleParams(navigator)\n{\n}\n\nvoid\nGpsFailure::on_inactive()\n{\n\t\/* reset GPSF state only if setpoint moved *\/\n\tif (!_navigator->get_can_loiter_at_sp()) {\n\t\t_gpsf_state = GPSF_STATE_NONE;\n\t}\n}\n\nvoid\nGpsFailure::on_activation()\n{\n\t_gpsf_state = GPSF_STATE_NONE;\n\t_timestamp_activation = hrt_absolute_time();\n\tadvance_gpsf();\n\tset_gpsf_item();\n}\n\nvoid\nGpsFailure::on_active()\n{\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_LOITER: {\n\t\t\t\/* Position controller does not run in this mode:\n\t\t\t * navigator has to publish an attitude setpoint *\/\n\t\t\tvehicle_attitude_setpoint_s att_sp = {};\n\t\t\tatt_sp.timestamp = hrt_absolute_time();\n\t\t\tatt_sp.roll_body = math::radians(_param_nav_gpsf_r.get());\n\t\t\tatt_sp.pitch_body = math::radians(_param_nav_gpsf_p.get());\n\t\t\tatt_sp.thrust_body[0] = _param_nav_gpsf_tr.get();\n\n\t\t\tQuatf q(Eulerf(att_sp.roll_body, att_sp.pitch_body, 0.0f));\n\t\t\tq.copyTo(att_sp.q_d);\n\n\t\t\tif (_navigator->get_vstatus()->is_vtol) {\n\t\t\t\t_fw_virtual_att_sp_pub.publish(att_sp);\n\n\t\t\t} else {\n\t\t\t\t_att_sp_pub.publish(att_sp);\n\n\t\t\t}\n\n\t\t\t\/* Measure time *\/\n\t\t\tif ((_param_nav_gpsf_lt.get() > FLT_EPSILON) &&\n\t\t\t (hrt_elapsed_time(&_timestamp_activation) > _param_nav_gpsf_lt.get() * 1e6f)) {\n\t\t\t\t\/* no recovery, advance the state machine *\/\n\t\t\t\tPX4_WARN(\"GPS not recovered, switching to next failure state\");\n\t\t\t\tadvance_gpsf();\n\t\t\t}\n\n\t\t\tbreak;\n\t\t}\n\n\tcase GPSF_STATE_TERMINATE:\n\t\tset_gpsf_item();\n\t\tadvance_gpsf();\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n\nvoid\nGpsFailure::set_gpsf_item()\n{\n\tstruct position_setpoint_triplet_s *pos_sp_triplet = _navigator->get_position_setpoint_triplet();\n\n\t\/* Set pos sp triplet to invalid to stop pos controller *\/\n\tpos_sp_triplet->previous.valid = false;\n\tpos_sp_triplet->current.valid = false;\n\tpos_sp_triplet->next.valid = false;\n\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_TERMINATE: {\n\t\t\t\/* Request flight termination from commander *\/\n\t\t\t_navigator->get_mission_result()->flight_termination = true;\n\t\t\t_navigator->set_mission_result_updated();\n\t\t\tPX4_WARN(\"GPS failure: request flight termination\");\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n\n\t_navigator->set_position_setpoint_triplet_updated();\n}\n\nvoid\nGpsFailure::advance_gpsf()\n{\n\tswitch (_gpsf_state) {\n\tcase GPSF_STATE_NONE:\n\t\t_gpsf_state = GPSF_STATE_LOITER;\n\t\tmavlink_log_critical(_navigator->get_mavlink_log_pub(), \"Global position failure: loitering\");\n\t\tbreak;\n\n\tcase GPSF_STATE_LOITER:\n\t\t_gpsf_state = GPSF_STATE_TERMINATE;\n\t\tmavlink_log_emergency(_navigator->get_mavlink_log_pub(), \"no GPS recovery, terminating flight\");\n\t\tbreak;\n\n\tcase GPSF_STATE_TERMINATE:\n\t\tPX4_WARN(\"terminate\");\n\t\t_gpsf_state = GPSF_STATE_END;\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n\t}\n}\n<|endoftext|>"} {"text":"#include \"ResourceManager.hpp\"\n\n\nusing namespace morda;\n\n\n\nnamespace{\n\nstd::string DResTag(\"res\");\nstd::string DIncludeTag(\"include\");\n\n\n\n\/\/fi path should be set to resource script for resolving includes.\n\/\/return pointer to the last child node of the script\nstob::Node* ResolveIncludes(ting::fs::File& fi, stob::Node* root){\n\tstd::pair n = root->Child(DIncludeTag);\n\tfor(; n.second;){\n\t\tASSERT(n.second)\n\t\tstob::Node* incPathNode = n.second->Child();\n\t\tif(!incPathNode){\n\t\t\tthrow Exc(\"include tag without value encountered in resource script\");\n\t\t}\n\t\t\n\t\tfi.SetPath(fi.ExtractDirectory() + incPathNode->Value());\n\t\tting::Ptr incNode = stob::Load(fi);\n\t\t\n\t\t\/\/recursive call\n\t\tstob::Node* lastChild = ResolveIncludes(fi, incNode.operator->());\n\t\t\n\t\t\/\/substitute includes\n\t\tif(!n.first){\n\t\t\t\/\/include tag is the very first tag\n\t\t\troot->RemoveFirstChild();\n\t\t\t\n\t\t\tif(lastChild){\n\t\t\t\tASSERT(!lastChild->Next())\n\t\t\t\tASSERT(incNode->Child())\n\t\t\t\tlastChild->InsertNext(root->RemoveChildren());\n\t\t\t\troot->SetChildren(incNode->RemoveChildren());\n\t\t\t\tn = lastChild->Next(DIncludeTag);\n\t\t\t}else{\n\t\t\t\tASSERT(!incNode->Child())\n\t\t\t\tn = n.second->Next(DIncludeTag);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}else{\n\t\t\t\/\/include tag is not the first one\n\t\t\t\n\t\t\tn.first->RemoveNext();\n\t\t\tif(lastChild){\n\t\t\t\tASSERT(!lastChild->Next())\n\t\t\t\tASSERT(incNode->Child())\n\t\t\t\tting::Ptr tail = n.first->ChopNext();\n\t\t\t\tn.first->SetNext(incNode->RemoveChildren());\n\t\t\t\tlastChild->SetNext(tail);\n\t\t\t\tn = lastChild->Next(DIncludeTag);\n\t\t\t}else{\n\t\t\t\tASSERT(!incNode->Child())\n\t\t\t\tn = n.second->Next(DIncludeTag);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn n.first;\n}\n\n}\/\/~namespace\n\n\n\nvoid ResourceManager::MountResPack(ting::Ptr fi){\n\tASSERT(fi)\n\tASSERT(!fi->IsOpened())\n\n\tResPackEntry rpe;\n\n\trpe.fi = fi;\n\n\tASS(rpe.fi)->SetPath(\"main.res\");\n\t\n\tting::Ptr resScript = stob::Load(*(rpe.fi));\n\n\t\/\/handle includes\n\tResolveIncludes(*(rpe.fi), resScript.operator->());\n\t\n\trpe.resScript = resScript;\n\n\tthis->resPacks.push_back(rpe);\n\tASSERT(this->resPacks.back().fi.IsValid())\n\tASSERT(this->resPacks.back().resScript.IsValid())\n}\n\n\n\nResourceManager::FindInScriptRet ResourceManager::FindResourceInScript(const std::string& resName){\n\/\/\tTRACE(<< \"ResourceManager::FindResourceInScript(): resName = \" << (resName.c_str()) << std::endl)\n\n\tfor(T_ResPackList::iterator i = this->resPacks.begin(); i != this->resPacks.end(); ++i){\n\t\tfor(const stob::Node* e = i->resScript->Child(DResTag).second; e; e = e->Next(DResTag).second){\n\/\/\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): searching for 'name' property\" << std::endl)\n\t\t\tconst stob::Node* nameProp = e->GetProperty(\"name\");\n\t\t\tif(!nameProp){\n\/\/\t\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): WARNING! no 'name' property in resource\" << std::endl)\n\t\t\t\tcontinue;\n\t\t\t}\n\/\/\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): name = \" << name << std::endl)\n\t\t\tif(resName.compare(nameProp->Value()) == 0){\n\/\/\t\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): resource found\" << std::endl)\n\t\t\t\treturn FindInScriptRet(&(*i), e, nameProp);\n\t\t\t}\n\t\t}\/\/~for(res)\n\t}\/\/~for(resPack)\n\tTRACE(<< \"resource name not found in mounted resource packs: \" << resName << std::endl)\n\tthrow ResourceManager::Exc(\"resource name not found in mounted resource packs\");\n}\n\n\n\nvoid ResourceManager::AddResource(const ting::Ref& res, const stob::Node* node){\n\tASSERT(res)\n\t\n\t\/\/add the resource to the resources map of ResMan\n\tstd::pair pr = this->resMap->rm.insert(\n\t\t\tstd::pair >(\n\t\t\t\t\t&node->Value(),\n\t\t\t\t\tres.GetWeakRef()\n\t\t\t\t)\n\t\t);\n\t\n\tASSERT(pr.second == true) \/\/make sure that the new element was added but not the old one rewritten\n\n#ifdef DEBUG\n\tfor(T_ResMap::iterator i = this->resMap->rm.begin(); i != this->resMap->rm.end(); ++i){\n\t\tTRACE(<< \"\\t\" << *(*i).first << std::endl)\n\t}\n#endif\n\t\n\tres->it = pr.first;\n\tres->rm = this->resMap; \/\/save weak reference to resource map\n}\ndebug output commented#include \"ResourceManager.hpp\"\n\n\nusing namespace morda;\n\n\n\nnamespace{\n\nstd::string DResTag(\"res\");\nstd::string DIncludeTag(\"include\");\n\n\n\n\/\/fi path should be set to resource script for resolving includes.\n\/\/return pointer to the last child node of the script\nstob::Node* ResolveIncludes(ting::fs::File& fi, stob::Node* root){\n\tstd::pair n = root->Child(DIncludeTag);\n\tfor(; n.second;){\n\t\tASSERT(n.second)\n\t\tstob::Node* incPathNode = n.second->Child();\n\t\tif(!incPathNode){\n\t\t\tthrow Exc(\"include tag without value encountered in resource script\");\n\t\t}\n\t\t\n\t\tfi.SetPath(fi.ExtractDirectory() + incPathNode->Value());\n\t\tting::Ptr incNode = stob::Load(fi);\n\t\t\n\t\t\/\/recursive call\n\t\tstob::Node* lastChild = ResolveIncludes(fi, incNode.operator->());\n\t\t\n\t\t\/\/substitute includes\n\t\tif(!n.first){\n\t\t\t\/\/include tag is the very first tag\n\t\t\troot->RemoveFirstChild();\n\t\t\t\n\t\t\tif(lastChild){\n\t\t\t\tASSERT(!lastChild->Next())\n\t\t\t\tASSERT(incNode->Child())\n\t\t\t\tlastChild->InsertNext(root->RemoveChildren());\n\t\t\t\troot->SetChildren(incNode->RemoveChildren());\n\t\t\t\tn = lastChild->Next(DIncludeTag);\n\t\t\t}else{\n\t\t\t\tASSERT(!incNode->Child())\n\t\t\t\tn = n.second->Next(DIncludeTag);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}else{\n\t\t\t\/\/include tag is not the first one\n\t\t\t\n\t\t\tn.first->RemoveNext();\n\t\t\tif(lastChild){\n\t\t\t\tASSERT(!lastChild->Next())\n\t\t\t\tASSERT(incNode->Child())\n\t\t\t\tting::Ptr tail = n.first->ChopNext();\n\t\t\t\tn.first->SetNext(incNode->RemoveChildren());\n\t\t\t\tlastChild->SetNext(tail);\n\t\t\t\tn = lastChild->Next(DIncludeTag);\n\t\t\t}else{\n\t\t\t\tASSERT(!incNode->Child())\n\t\t\t\tn = n.second->Next(DIncludeTag);\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn n.first;\n}\n\n}\/\/~namespace\n\n\n\nvoid ResourceManager::MountResPack(ting::Ptr fi){\n\tASSERT(fi)\n\tASSERT(!fi->IsOpened())\n\n\tResPackEntry rpe;\n\n\trpe.fi = fi;\n\n\tASS(rpe.fi)->SetPath(\"main.res\");\n\t\n\tting::Ptr resScript = stob::Load(*(rpe.fi));\n\n\t\/\/handle includes\n\tResolveIncludes(*(rpe.fi), resScript.operator->());\n\t\n\trpe.resScript = resScript;\n\n\tthis->resPacks.push_back(rpe);\n\tASSERT(this->resPacks.back().fi.IsValid())\n\tASSERT(this->resPacks.back().resScript.IsValid())\n}\n\n\n\nResourceManager::FindInScriptRet ResourceManager::FindResourceInScript(const std::string& resName){\n\/\/\tTRACE(<< \"ResourceManager::FindResourceInScript(): resName = \" << (resName.c_str()) << std::endl)\n\n\tfor(T_ResPackList::iterator i = this->resPacks.begin(); i != this->resPacks.end(); ++i){\n\t\tfor(const stob::Node* e = i->resScript->Child(DResTag).second; e; e = e->Next(DResTag).second){\n\/\/\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): searching for 'name' property\" << std::endl)\n\t\t\tconst stob::Node* nameProp = e->GetProperty(\"name\");\n\t\t\tif(!nameProp){\n\/\/\t\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): WARNING! no 'name' property in resource\" << std::endl)\n\t\t\t\tcontinue;\n\t\t\t}\n\/\/\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): name = \" << name << std::endl)\n\t\t\tif(resName.compare(nameProp->Value()) == 0){\n\/\/\t\t\t\tTRACE(<< \"ResourceManager::FindResourceInScript(): resource found\" << std::endl)\n\t\t\t\treturn FindInScriptRet(&(*i), e, nameProp);\n\t\t\t}\n\t\t}\/\/~for(res)\n\t}\/\/~for(resPack)\n\tTRACE(<< \"resource name not found in mounted resource packs: \" << resName << std::endl)\n\tthrow ResourceManager::Exc(\"resource name not found in mounted resource packs\");\n}\n\n\n\nvoid ResourceManager::AddResource(const ting::Ref& res, const stob::Node* node){\n\tASSERT(res)\n\t\n\t\/\/add the resource to the resources map of ResMan\n\tstd::pair pr = this->resMap->rm.insert(\n\t\t\tstd::pair >(\n\t\t\t\t\t&node->Value(),\n\t\t\t\t\tres.GetWeakRef()\n\t\t\t\t)\n\t\t);\n\t\n\tASSERT(pr.second == true) \/\/make sure that the new element was added but not the old one rewritten\n\n\/\/#ifdef DEBUG\n\/\/\tfor(T_ResMap::iterator i = this->resMap->rm.begin(); i != this->resMap->rm.end(); ++i){\n\/\/\t\tTRACE(<< \"\\t\" << *(*i).first << std::endl)\n\/\/\t}\n\/\/#endif\n\t\n\tres->it = pr.first;\n\tres->rm = this->resMap; \/\/save weak reference to resource map\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"..\/group\/Pile.hpp\"\n\nnamespace morda{\n\n\/**\n * @brief Container to be used for intercepting keyboard key events.\n * From GUI scripts it can be instantiated as \"KeyProxy\".\n *\/\nclass KeyProxy : public Pile{\npublic:\n\tKeyProxy(const stob::Node* chain = nullptr) :\n\t\t\tWidget(chain),\n\t\t\tPile(chain)\n\t{}\n\t\n\tKeyProxy(const KeyProxy&) = delete;\n\tKeyProxy& operator=(const KeyProxy&) = delete;\n\t\n\t\/**\n\t * @brief Keyboard key signal.\n\t * Emitted when a keyboard key event reaches this widget.\n\t *\/\n\tstd::function key;\n\t\n\tvirtual bool on_key(bool isDown, morda::key keyCode)override;\n};\n\n}\nstuff#pragma once\n\n#include \"..\/group\/Pile.hpp\"\n\nnamespace morda{\n\n\/**\n * @brief Container to be used for intercepting keyboard key events.\n * From GUI scripts it can be instantiated as \"KeyProxy\".\n *\/\nclass KeyProxy : public Pile{\npublic:\n\tKeyProxy(const puu::forest& desc) :\n\t\t\twidget(desc),\n\t\t\tPile(desc)\n\t{}\n\tKeyProxy(const stob::Node* chain) : KeyProxy(stob_to_puu(chain)){}\n\t\n\tKeyProxy(const KeyProxy&) = delete;\n\tKeyProxy& operator=(const KeyProxy&) = delete;\n\t\n\t\/**\n\t * @brief Keyboard key signal.\n\t * Emitted when a keyboard key event reaches this widget.\n\t *\/\n\tstd::function key;\n\t\n\tvirtual bool on_key(bool isDown, morda::key keyCode)override;\n};\n\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"rtabmap\/core\/util3d.h\"\n#include \"rtabmap\/core\/util3d_filtering.h\"\n#include \"rtabmap\/core\/util3d_mapping.h\"\n#include \"rtabmap\/core\/util3d_transforms.h\"\n\nnamespace rtabmap_ros\n{\n\nclass ObstaclesDetection : public nodelet::Nodelet\n{\npublic:\n\tObstaclesDetection() :\n\t\tframeId_(\"base_link\"),\n\t\tnormalEstimationRadius_(0.05),\n\t\tgroundNormalAngle_(M_PI_4),\n\t\tminClusterSize_(20),\n\t\tmaxFloorHeight_(-1),\n\t\tmaxObstaclesHeight_(1.5),\n\t\twaitForTransform_(false),\n\t\tsimpleSegmentation_(false)\n\t{}\n\n\tvirtual ~ObstaclesDetection()\n\t{}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 10;\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\tpnh.param(\"normal_estimation_radius\", normalEstimationRadius_, normalEstimationRadius_);\n\t\tpnh.param(\"ground_normal_angle\", groundNormalAngle_, groundNormalAngle_);\n\t\tpnh.param(\"min_cluster_size\", minClusterSize_, minClusterSize_);\n\t\tpnh.param(\"max_obstacles_height\", maxObstaclesHeight_, maxObstaclesHeight_);\n\t\tpnh.param(\"max_floor_height\", maxFloorHeight_, maxFloorHeight_);\n\t\tpnh.param(\"wait_for_transform\", waitForTransform_, waitForTransform_);\n\t\tpnh.param(\"simple_segmentation\", simpleSegmentation_, simpleSegmentation_);\n\n\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &ObstaclesDetection::callback, this);\n\n\t\tgroundPub_ = nh.advertise(\"ground\", 1);\n\t\tobstaclesPub_ = nh.advertise(\"obstacles\", 1);\n\n\t\tthis->_lastFrameTime = ros::Time::now();\n\t}\n\n\n\n\tvoid callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)\n\t\t{\n\t\t\t\/\/ no one wants the results\n\t\t\treturn;\n\t\t}\n\n\t\trtabmap::Transform localTransform;\n\t\ttry\n\t\t{\n\t\t\tif(waitForTransform_)\n\t\t\t{\n\t\t\t\tif(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Could not get transform from %s to %s after 1 second!\", frameId_.c_str(), cloudMsg->header.frame_id.c_str());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttf::StampedTransform tmp;\n\t\t\ttfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);\n\t\t\tlocalTransform = rtabmap_ros::transformFromTF(tmp);\n\t\t}\n\t\tcatch(tf::TransformException & ex)\n\t\t{\n\t\t\tROS_ERROR(\"%s\",ex.what());\n\t\t\treturn;\n\t\t}\n\n\n\t\tpcl::PointCloud::Ptr originalCloud(new pcl::PointCloud);\n\t\tpcl::fromROSMsg(*cloudMsg, *originalCloud);\n\t\tif(originalCloud->size() == 0)\n\t\t{\n\t\t\tROS_ERROR(\"Recieved empty point cloud!\");\n\t\t\treturn;\n\t\t}\n\t\toriginalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tpcl::PointCloud::Ptr hypotheticalGroundCloud(new pcl::PointCloud);\n\t\thypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", std::numeric_limits::min(), maxFloorHeight_);\n\n\t\tpcl::PointCloud::Ptr obstaclesCloud(new pcl::PointCloud);\n\t\tobstaclesCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", maxFloorHeight_, maxObstaclesHeight_);\n\n\t\tros::Time lasttime = ros::Time::now();\n\n\t\tpcl::IndicesPtr ground, obstacles;\n\t\tpcl::PointCloud::Ptr groundCloud(new pcl::PointCloud);\n\n\t\tif (!simpleSegmentation_){\n\t\t\trtabmap::util3d::segmentObstaclesFromGround(hypotheticalGroundCloud,\n\t\t\t\t\tground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);\n\n\t\t\tif(ground.get() && ground->size())\n\t\t\t{\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);\n\t\t\t}\n\t\t\tif(obstacles.get() && obstacles->size())\n\t\t\t{\n\t\t\t\tpcl::PointCloud::Ptr obstaclesNearFloorCloud(new pcl::PointCloud);\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);\n\t\t\t\t*obstaclesCloud += *obstaclesNearFloorCloud;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tgroundCloud = hypotheticalGroundCloud;\n\t\t}\n\n\n\t\tif(groundPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*groundCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tgroundPub_.publish(rosCloud);\n\t\t}\n\n\t\tif(obstaclesPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*obstaclesCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tobstaclesPub_.publish(rosCloud);\n\t\t}\n\n\t\tros::Time curtime = ros::Time::now();\n\n\t\tros::Duration process_duration = curtime - lasttime;\n\t\tros::Duration between_frames = curtime - this->_lastFrameTime;\n\t\tthis->_lastFrameTime = curtime;\n\t\tstd::stringstream buffer;\n\t\tbuffer << \"cloud=\" << originalCloud->size() << \" ground=\" << hypotheticalGroundCloud->size() << \" floor=\" << ground->size() << \" obst=\" << obstacles->size();\n\t\tbuffer << \" t=\" << process_duration.toSec() << \"s; \" << (1.\/between_frames.toSec()) << \"Hz\";\n\t\t\/\/ROS_ERROR(\"3%s: %s\", this->getName().c_str(), buffer.str().c_str());\n\n\t}\n\nprivate:\n\tstd::string frameId_;\n\tdouble normalEstimationRadius_;\n\tdouble groundNormalAngle_;\n\tint minClusterSize_;\n\tdouble maxObstaclesHeight_;\n\tdouble maxFloorHeight_;\n\tbool waitForTransform_;\n\tbool simpleSegmentation_;\n\n\ttf::TransformListener tfListener_;\n\n\tros::Publisher groundPub_;\n\tros::Publisher obstaclesPub_;\n\n\tros::Subscriber cloudSub_;\n\tros::Time _lastFrameTime;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);\n}\n\nComment for debugging\/*\nCopyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n * Neither the name of the Universite de Sherbrooke nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"rtabmap\/core\/util3d.h\"\n#include \"rtabmap\/core\/util3d_filtering.h\"\n#include \"rtabmap\/core\/util3d_mapping.h\"\n#include \"rtabmap\/core\/util3d_transforms.h\"\n\nnamespace rtabmap_ros\n{\n\nclass ObstaclesDetection : public nodelet::Nodelet\n{\npublic:\n\tObstaclesDetection() :\n\t\tframeId_(\"base_link\"),\n\t\tnormalEstimationRadius_(0.05),\n\t\tgroundNormalAngle_(M_PI_4),\n\t\tminClusterSize_(20),\n\t\tmaxFloorHeight_(-1),\n\t\tmaxObstaclesHeight_(1.5),\n\t\twaitForTransform_(false),\n\t\tsimpleSegmentation_(false)\n\t{}\n\n\tvirtual ~ObstaclesDetection()\n\t{}\n\nprivate:\n\tvirtual void onInit()\n\t{\n\t\tros::NodeHandle & nh = getNodeHandle();\n\t\tros::NodeHandle & pnh = getPrivateNodeHandle();\n\n\t\tint queueSize = 10;\n\t\tpnh.param(\"queue_size\", queueSize, queueSize);\n\t\tpnh.param(\"frame_id\", frameId_, frameId_);\n\t\tpnh.param(\"normal_estimation_radius\", normalEstimationRadius_, normalEstimationRadius_);\n\t\tpnh.param(\"ground_normal_angle\", groundNormalAngle_, groundNormalAngle_);\n\t\tpnh.param(\"min_cluster_size\", minClusterSize_, minClusterSize_);\n\t\tpnh.param(\"max_obstacles_height\", maxObstaclesHeight_, maxObstaclesHeight_);\n\t\tpnh.param(\"max_floor_height\", maxFloorHeight_, maxFloorHeight_);\n\t\tpnh.param(\"wait_for_transform\", waitForTransform_, waitForTransform_);\n\t\tpnh.param(\"simple_segmentation\", simpleSegmentation_, simpleSegmentation_);\n\n\t\tcloudSub_ = nh.subscribe(\"cloud\", 1, &ObstaclesDetection::callback, this);\n\n\t\tgroundPub_ = nh.advertise(\"ground\", 1);\n\t\tobstaclesPub_ = nh.advertise(\"obstacles\", 1);\n\n\t\tthis->_lastFrameTime = ros::Time::now();\n\t}\n\n\n\n\tvoid callback(const sensor_msgs::PointCloud2ConstPtr & cloudMsg)\n\t{\n\t\tif (groundPub_.getNumSubscribers() == 0 && obstaclesPub_.getNumSubscribers() == 0)\n\t\t{\n\t\t\t\/\/ no one wants the results\n\t\t\treturn;\n\t\t}\n\n\t\tROS_ERROR(\"1111111111111111111111\");\n\n\n\t\trtabmap::Transform localTransform;\n\t\ttry\n\t\t{\n\t\t\tif(waitForTransform_)\n\t\t\t{\n\t\t\t\tif(!tfListener_.waitForTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, ros::Duration(1)))\n\t\t\t\t{\n\t\t\t\t\tROS_ERROR(\"Could not get transform from %s to %s after 1 second!\", frameId_.c_str(), cloudMsg->header.frame_id.c_str());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tROS_ERROR(\"2222222222222222222222222222222\");\n\n\t\t\ttf::StampedTransform tmp;\n\t\t\ttfListener_.lookupTransform(frameId_, cloudMsg->header.frame_id, cloudMsg->header.stamp, tmp);\n\t\t\tlocalTransform = rtabmap_ros::transformFromTF(tmp);\n\t\t}\n\t\tcatch(tf::TransformException & ex)\n\t\t{\n\t\t\tROS_ERROR(\"%s\",ex.what());\n\t\t\treturn;\n\t\t}\n\n\n\t\tpcl::PointCloud::Ptr originalCloud(new pcl::PointCloud);\n\t\tpcl::fromROSMsg(*cloudMsg, *originalCloud);\n\t\tif(originalCloud->size() == 0)\n\t\t{\n\t\t\tROS_ERROR(\"Recieved empty point cloud!\");\n\t\t\treturn;\n\t\t}\n\t\toriginalCloud = rtabmap::util3d::transformPointCloud(originalCloud, localTransform);\n\n\t\tROS_ERROR(\"3333333333333333333333333\");\n\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\t\tpcl::PointCloud::Ptr hypotheticalGroundCloud(new pcl::PointCloud);\n\t\thypotheticalGroundCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", std::numeric_limits::min(), maxFloorHeight_);\n\n\t\tpcl::PointCloud::Ptr obstaclesCloud(new pcl::PointCloud);\n\t\tobstaclesCloud = rtabmap::util3d::passThrough(originalCloud, \"z\", maxFloorHeight_, maxObstaclesHeight_);\n\n\t\tros::Time lasttime = ros::Time::now();\n\n\t\tpcl::IndicesPtr ground, obstacles;\n\t\tpcl::PointCloud::Ptr groundCloud(new pcl::PointCloud);\n\n\t\tif (!simpleSegmentation_){\n\t\t\tROS_ERROR(\"44444444444444444444444444444\");\n\n\t\t\trtabmap::util3d::segmentObstaclesFromGround(hypotheticalGroundCloud,\n\t\t\t\t\tground, obstacles, normalEstimationRadius_, groundNormalAngle_, minClusterSize_);\n\n\t\t\tif(ground.get() && ground->size())\n\t\t\t{\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *ground, *groundCloud);\n\t\t\t}\n\t\t\tif(obstacles.get() && obstacles->size())\n\t\t\t{\n\t\t\t\tpcl::PointCloud::Ptr obstaclesNearFloorCloud(new pcl::PointCloud);\n\t\t\t\tpcl::copyPointCloud(*hypotheticalGroundCloud, *obstacles, *obstaclesNearFloorCloud);\n\t\t\t\t*obstaclesCloud += *obstaclesNearFloorCloud;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tROS_ERROR(\"555555555555555555555555\");\n\t\t\tgroundCloud = hypotheticalGroundCloud;\n\t\t}\n\n\n\t\tif(groundPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*groundCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tgroundPub_.publish(rosCloud);\n\t\t}\n\n\t\tif(obstaclesPub_.getNumSubscribers())\n\t\t{\n\t\t\tsensor_msgs::PointCloud2 rosCloud;\n\t\t\tpcl::toROSMsg(*obstaclesCloud, rosCloud);\n\t\t\trosCloud.header.stamp = cloudMsg->header.stamp;\n\t\t\trosCloud.header.frame_id = frameId_;\n\n\t\t\t\/\/publish the message\n\t\t\tobstaclesPub_.publish(rosCloud);\n\t\t}\n\n\t\tros::Time curtime = ros::Time::now();\n\n\t\tros::Duration process_duration = curtime - lasttime;\n\t\tros::Duration between_frames = curtime - this->_lastFrameTime;\n\t\tthis->_lastFrameTime = curtime;\n\t\tstd::stringstream buffer;\n\t\tbuffer << \"cloud=\" << originalCloud->size() << \" ground=\" << hypotheticalGroundCloud->size() << \" floor=\" << ground->size() << \" obst=\" << obstacles->size();\n\t\tbuffer << \" t=\" << process_duration.toSec() << \"s; \" << (1.\/between_frames.toSec()) << \"Hz\";\n\t\t\/\/ROS_ERROR(\"3%s: %s\", this->getName().c_str(), buffer.str().c_str());\n\n\t}\n\nprivate:\n\tstd::string frameId_;\n\tdouble normalEstimationRadius_;\n\tdouble groundNormalAngle_;\n\tint minClusterSize_;\n\tdouble maxObstaclesHeight_;\n\tdouble maxFloorHeight_;\n\tbool waitForTransform_;\n\tbool simpleSegmentation_;\n\n\ttf::TransformListener tfListener_;\n\n\tros::Publisher groundPub_;\n\tros::Publisher obstaclesPub_;\n\n\tros::Subscriber cloudSub_;\n\tros::Time _lastFrameTime;\n};\n\nPLUGINLIB_EXPORT_CLASS(rtabmap_ros::ObstaclesDetection, nodelet::Nodelet);\n}\n\n<|endoftext|>"} {"text":"\/*\nAUTHOR: Michael Fulton\nDATE: 2\/2\/15\n*\/\n\n#include \n#include \n#include \n\nusing namespace std;\n\nvoid minmax(int[], int);\n\nint main(int argc, char * args[]){\n\t\n\t\/\/File I\/O setup.\n\tifstream in;\n\tin.open(args[1]);\n\t\n\n\t\/\/Read in number of numbers we're using.\n\tint length;\t\t\n\tin >> length;\n\tcout <> input[i];\n\t}\n\n\tminmax(input, length);\n\t\n\n\tin.close();\n\n\n}\n\nvoid minmax(int numbers[], int len){\n\n\tint max=numbers[0];\n\tint min=numbers[0];\n\tint count=0;\n\t\n\t\/\/If the current number is bigger than the max, make it the new max. \n\t\/\/If it isn't, see if it's smaller than the min. If it is, it's the new min.\n\t\/\/Since we don't test min until we know it's not max, we CAN save cost operations.\n\t\/\/This algorithm's worst case is 2N-2.\n\tfor(int i=1; i < len; i++){\n\t\tcount++;\n\t\tif(numbers[i] > max){\n\t\t\tmax = numbers[i];\n\t\t}\t\n\n\t\telse {\n\t\t\tcount++;\n\t\t\tif(numbers[i] < min){\n\t\t\t\tmin = numbers[i];\n\t\t\t}\t\n\t\t}\n\t\t\n\t}\n\n\tcout<<\"The max is: \"<added iterative base cases\/*\nAUTHOR: Michael Fulton\nDATE: 2\/2\/15\n*\/\n\n#include \n#include \n#include \n\nusing namespace std;\n\nvoid minmax(int[], int);\n\nint main(int argc, char * args[]){\n\t\n\t\/\/File I\/O setup.\n\tifstream in;\n\tin.open(args[1]);\n\t\n\n\t\/\/Read in number of numbers we're using.\n\tint length;\t\t\n\tin >> length;\n\tcout <> input[i];\n\t}\n\n\tminmax(input, length);\n\t\n\n\tin.close();\n\n\n}\n\nvoid minmax(int numbers[], int len){\n\n\tint max=numbers[0];\n\tint min=numbers[0];\n\tint count=0;\n\n\tif(len==1){\n\t\tmax=numbers[0];\n\t\tmin=numbers[0];\n\t\treturn;\n\t}\n\telse if(len==2){\n\t\tif(numbers[0] > numbers[1]){\n\t\t\tmax= numbers[0];\n\t\t\tmin= numbers[1];\n\t\t}\n\t\telse{\n\t\t\tmax= numbers[1];\n\t\t\tmin= numbers[0];\n\t\t}\n\t\treturn;\n\t}\n\n\t\/\/If the current number is bigger than the max, make it the new max. \n\t\/\/If it isn't, see if it's smaller than the min. If it is, it's the new min.\n\t\/\/Since we don't test min until we know it's not max, we CAN save cost operations.\n\t\/\/This algorithm's worst case is 2N-2.\n\tfor(int i=1; i < len; i++){\n\t\tcount++;\n\t\tif(numbers[i] > max){\n\t\t\tmax = numbers[i];\n\t\t}\t\n\t\telse {\n\t\t\tcount++;\n\t\t\tif(numbers[i] < min){\n\t\t\t\tmin = numbers[i];\n\t\t\t}\t\n\t\t}\n\t\t\n\t}\n\n\tcout<<\"The max is: \"<"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/extensions\/feature_switch.h\"\n#include \"chrome\/common\/extensions\/features\/base_feature_provider.h\"\n#include \"chrome\/common\/extensions\/features\/complex_feature.h\"\n#include \"chrome\/common\/extensions\/features\/feature.h\"\n#include \"chrome\/common\/extensions\/features\/simple_feature.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nnamespace chrome {\n\nnamespace {\n\nconst char kExtensionId[] = \"ddchlicdkolnonkihahngkmmmjnjlkkf\";\n\nclass TabCaptureApiTest : public ExtensionApiTest {\n public:\n TabCaptureApiTest() {}\n\n void AddExtensionToCommandLineWhitelist() {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kWhitelistedExtensionID, kExtensionId);\n }\n};\n\n} \/\/ namespace\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_ApiTests DISABLED_ApiTests\n#else\n#define MAYBE_ApiTests ApiTests\n#endif\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ApiTests) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests.html\")) << message_;\n}\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_ApiTestsAudio DISABLED_ApiTestsAudio\n#else\n#define MAYBE_ApiTestsAudio ApiTestsAudio\n#endif\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ApiTestsAudio) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests_audio.html\")) << message_;\n}\n\n\/\/ TODO(miu): Disabled until the two most-likely sources of the \"flaky timeouts\"\n\/\/ are resolved: 1) http:\/\/crbug.com\/177163 and 2) http:\/\/crbug.com\/174519.\n\/\/ See http:\/\/crbug.com\/174640.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, DISABLED_EndToEnd) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"end_to_end.html\")) << message_;\n}\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest\n#else\n#define MAYBE_GetUserMediaTest GetUserMediaTest\n#endif\n\/\/ Test that we can't get tabCapture streams using GetUserMedia directly.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {\n ExtensionTestMessageListener listener(\"ready\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"get_user_media_test.html\")) << message_;\n\n EXPECT_TRUE(listener.WaitUntilSatisfied());\n\n content::OpenURLParams params(GURL(\"about:blank\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n\n content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();\n int render_process_id = rvh->GetProcess()->GetID();\n int routing_id = rvh->GetRoutingID();\n\n listener.Reply(base::StringPrintf(\"%i:%i\", render_process_id, routing_id));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission\n#else\n#define MAYBE_ActiveTabPermission ActiveTabPermission\n#endif\n\/\/ Make sure tabCapture.capture only works if the tab has been granted\n\/\/ permission via an extension icon click or the extension is whitelisted.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {\n ExtensionTestMessageListener before_open_tab(\"ready1\", true);\n ExtensionTestMessageListener before_grant_permission(\"ready2\", true);\n ExtensionTestMessageListener before_open_new_tab(\"ready3\", true);\n ExtensionTestMessageListener before_whitelist_extension(\"ready4\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\n \"tab_capture\/experimental\", \"active_tab_permission_test.html\"))\n << message_;\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());\n content::OpenURLParams params(GURL(\"http:\/\/google.com\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n before_open_tab.Reply(\"\");\n\n \/\/ Grant permission and make sure capture succeeds.\n EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());\n ExtensionService* extension_service =\n Profile::FromBrowserContext(web_contents->GetBrowserContext())\n ->GetExtensionService();\n const extensions::Extension* extension =\n extension_service->GetExtensionById(kExtensionId, false);\n extensions::TabHelper::FromWebContents(web_contents)\n ->active_tab_permission_granter()->GrantIfRequested(extension);\n before_grant_permission.Reply(\"\");\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());\n browser()->OpenURL(params);\n before_open_new_tab.Reply(\"\");\n\n \/\/ Add extension to whitelist and make sure capture succeeds.\n EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());\n AddExtensionToCommandLineWhitelist();\n before_whitelist_extension.Reply(\"\");\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace chrome\nRevert 198738 \"Disables TabCaptureApiTest.ApiTests and\"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/tab_helper.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/chrome_version_info.h\"\n#include \"chrome\/common\/extensions\/feature_switch.h\"\n#include \"chrome\/common\/extensions\/features\/base_feature_provider.h\"\n#include \"chrome\/common\/extensions\/features\/complex_feature.h\"\n#include \"chrome\/common\/extensions\/features\/feature.h\"\n#include \"chrome\/common\/extensions\/features\/simple_feature.h\"\n#include \"content\/public\/browser\/render_process_host.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/common\/content_switches.h\"\n\nnamespace chrome {\n\nnamespace {\n\nconst char kExtensionId[] = \"ddchlicdkolnonkihahngkmmmjnjlkkf\";\n\nclass TabCaptureApiTest : public ExtensionApiTest {\n public:\n TabCaptureApiTest() {}\n\n void AddExtensionToCommandLineWhitelist() {\n CommandLine::ForCurrentProcess()->AppendSwitchASCII(\n switches::kWhitelistedExtensionID, kExtensionId);\n }\n};\n\n} \/\/ namespace\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n\n#if defined(OS_WIN)\n \/\/ TODO(justinlin): Disabled for WinXP due to timeout issues.\n if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n return;\n }\n#endif\n\n AddExtensionToCommandLineWhitelist();\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"api_tests_audio.html\")) << message_;\n}\n\n\/\/ TODO(miu): Disabled until the two most-likely sources of the \"flaky timeouts\"\n\/\/ are resolved: 1) http:\/\/crbug.com\/177163 and 2) http:\/\/crbug.com\/174519.\n\/\/ See http:\/\/crbug.com\/174640.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, DISABLED_EndToEnd) {\n extensions::FeatureSwitch::ScopedOverride tab_capture(\n extensions::FeatureSwitch::tab_capture(), true);\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"end_to_end.html\")) << message_;\n}\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest\n#else\n#define MAYBE_GetUserMediaTest GetUserMediaTest\n#endif\n\/\/ Test that we can't get tabCapture streams using GetUserMedia directly.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {\n ExtensionTestMessageListener listener(\"ready\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\"tab_capture\/experimental\",\n \"get_user_media_test.html\")) << message_;\n\n EXPECT_TRUE(listener.WaitUntilSatisfied());\n\n content::OpenURLParams params(GURL(\"about:blank\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n\n content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();\n int render_process_id = rvh->GetProcess()->GetID();\n int routing_id = rvh->GetRoutingID();\n\n listener.Reply(base::StringPrintf(\"%i:%i\", render_process_id, routing_id));\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n\/\/ Flaky http:\/\/crbug.com\/224249\n#if defined(OS_WIN)\n#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission\n#else\n#define MAYBE_ActiveTabPermission ActiveTabPermission\n#endif\n\/\/ Make sure tabCapture.capture only works if the tab has been granted\n\/\/ permission via an extension icon click or the extension is whitelisted.\nIN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {\n ExtensionTestMessageListener before_open_tab(\"ready1\", true);\n ExtensionTestMessageListener before_grant_permission(\"ready2\", true);\n ExtensionTestMessageListener before_open_new_tab(\"ready3\", true);\n ExtensionTestMessageListener before_whitelist_extension(\"ready4\", true);\n\n ASSERT_TRUE(RunExtensionSubtest(\n \"tab_capture\/experimental\", \"active_tab_permission_test.html\"))\n << message_;\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());\n content::OpenURLParams params(GURL(\"http:\/\/google.com\"), content::Referrer(),\n NEW_FOREGROUND_TAB,\n content::PAGE_TRANSITION_LINK, false);\n content::WebContents* web_contents = browser()->OpenURL(params);\n before_open_tab.Reply(\"\");\n\n \/\/ Grant permission and make sure capture succeeds.\n EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());\n ExtensionService* extension_service =\n Profile::FromBrowserContext(web_contents->GetBrowserContext())\n ->GetExtensionService();\n const extensions::Extension* extension =\n extension_service->GetExtensionById(kExtensionId, false);\n extensions::TabHelper::FromWebContents(web_contents)\n ->active_tab_permission_granter()->GrantIfRequested(extension);\n before_grant_permission.Reply(\"\");\n\n \/\/ Open a new tab and make sure capture is denied.\n EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());\n browser()->OpenURL(params);\n before_open_new_tab.Reply(\"\");\n\n \/\/ Add extension to whitelist and make sure capture succeeds.\n EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());\n AddExtensionToCommandLineWhitelist();\n before_whitelist_extension.Reply(\"\");\n\n ResultCatcher catcher;\n catcher.RestrictToProfile(browser()->profile());\n EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\n} \/\/ namespace chrome\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/api\/web_request\/web_request_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/login\/login_prompt.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebInputEvent.h\"\n\nusing content::WebContents;\n\nnamespace {\n\nclass CancelLoginDialog : public content::NotificationObserver {\n public:\n CancelLoginDialog() {\n registrar_.Add(this,\n chrome::NOTIFICATION_AUTH_NEEDED,\n content::NotificationService::AllSources());\n }\n\n virtual ~CancelLoginDialog() {}\n\n virtual void Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n LoginHandler* handler =\n content::Details(details).ptr()->handler();\n handler->CancelAuth();\n }\n\n private:\n content::NotificationRegistrar registrar_;\n\n DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);\n};\n\n} \/\/ namespace\n\nclass ExtensionWebRequestApiTest : public ExtensionApiTest {\n public:\n virtual void SetUpInProcessBrowserTestFixture() {\n \/\/ TODO(battre): remove this when declarative webRequest API becomes stable.\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ExtensionApiTest::SetUpInProcessBrowserTestFixture();\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_api.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_simple.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_complex.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {\n CancelLoginDialog login_dialog_helper;\n\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_auth_required.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestBlocking) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_blocking.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_newTab.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"newTab\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ There's a link on a.html with target=_blank. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarative) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_declarative.html\")) <<\n message_;\n}\nDisable ExtensionWebRequestApiTest.WebRequestBlocking on Windows. It times out regularly on win_rel trybots.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/api\/web_request\/web_request_api.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/login\/login_prompt.h\"\n#include \"chrome\/common\/chrome_notification_types.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/notification_registrar.h\"\n#include \"content\/public\/browser\/notification_service.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n#include \"third_party\/WebKit\/Source\/WebKit\/chromium\/public\/WebInputEvent.h\"\n\nusing content::WebContents;\n\nnamespace {\n\nclass CancelLoginDialog : public content::NotificationObserver {\n public:\n CancelLoginDialog() {\n registrar_.Add(this,\n chrome::NOTIFICATION_AUTH_NEEDED,\n content::NotificationService::AllSources());\n }\n\n virtual ~CancelLoginDialog() {}\n\n virtual void Observe(int type,\n const content::NotificationSource& source,\n const content::NotificationDetails& details) {\n LoginHandler* handler =\n content::Details(details).ptr()->handler();\n handler->CancelAuth();\n }\n\n private:\n content::NotificationRegistrar registrar_;\n\n DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog);\n};\n\n} \/\/ namespace\n\nclass ExtensionWebRequestApiTest : public ExtensionApiTest {\n public:\n virtual void SetUpInProcessBrowserTestFixture() {\n \/\/ TODO(battre): remove this when declarative webRequest API becomes stable.\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ExtensionApiTest::SetUpInProcessBrowserTestFixture();\n host_resolver()->AddRule(\"*\", \"127.0.0.1\");\n ASSERT_TRUE(StartTestServer());\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_api.html\")) << message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestSimple) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_simple.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestComplex) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_complex.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestAuthRequired) {\n CancelLoginDialog login_dialog_helper;\n\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_auth_required.html\")) <<\n message_;\n}\n\n\/\/ This test times out regularly on win_rel trybots. See http:\/\/crbug.com\/122178\n#if defined(OS_WIN)\n#define MAYBE_WebRequestBlocking DISABLED_WebRequestBlocking\n#else\n#define MAYBE_WebRequestBlocking WebRequestBlocking\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestBlocking) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_blocking.html\")) <<\n message_;\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) {\n \/\/ Wait for the extension to set itself up and return control to us.\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_newTab.html\"))\n << message_;\n\n WebContents* tab = browser()->GetSelectedWebContents();\n ui_test_utils::WaitForLoadStop(tab);\n\n ResultCatcher catcher;\n\n ExtensionService* service = browser()->profile()->GetExtensionService();\n const Extension* extension =\n service->GetExtensionById(last_loaded_extension_id_, false);\n GURL url = extension->GetResourceURL(\"newTab\/a.html\");\n\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ There's a link on a.html with target=_blank. Click on it to open it in a\n \/\/ new tab.\n WebKit::WebMouseEvent mouse_event;\n mouse_event.type = WebKit::WebInputEvent::MouseDown;\n mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;\n mouse_event.x = 7;\n mouse_event.y = 7;\n mouse_event.clickCount = 1;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n mouse_event.type = WebKit::WebInputEvent::MouseUp;\n tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarative) {\n ASSERT_TRUE(RunExtensionSubtest(\"webrequest\", \"test_declarative.html\")) <<\n message_;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) DataStax, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"integration.hpp\"\n#include \"cassandra.h\"\n\n#include \n#include \n\nclass DcAwarePolicyTest : public Integration {\npublic:\n void SetUp() {\n \/\/ Create a cluster with 2 DCs with 2 nodes in each\n number_dc1_nodes_ = 2;\n number_dc2_nodes_ = 2;\n Integration::SetUp();\n\n \/\/ Create a test table and add test data to it\n session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), \"int\", \"text\"));\n session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), \"1\", \"'one'\"));\n session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), \"2\", \"'two'\"));\n }\n\n std::vector validate(Session session) {\n std::vector attempted_hosts, temp;\n Result result;\n\n result = session.execute(select_statement(\"1\"));\n temp = result.attempted_hosts();\n std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts));\n EXPECT_EQ(result.first_row().next().as(), Varchar(\"one\"));\n\n result = session.execute(select_statement(\"2\"));\n temp = result.attempted_hosts();\n std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts));\n EXPECT_EQ(result.first_row().next().as(), Varchar(\"two\"));\n\n return attempted_hosts;\n }\n\n Statement select_statement(const std::string& key) {\n Statement statement(format_string(CASSANDRA_SELECT_VALUE_FORMAT, table_name_.c_str(), key.c_str()));\n statement.set_consistency(CASS_CONSISTENCY_ONE);\n statement.set_record_attempted_hosts(true);\n return statement;\n }\n\n bool contains(const std::string& host, const std::vector& attempted_hosts) {\n return std::count(attempted_hosts.begin(), attempted_hosts.end(), host) > 0;\n }\n};\n\n\/**\n * Verify that the \"used hosts per remote DC\" setting allows queries to use the\n * remote DC nodes when the local DC nodes are unavailable.\n *\n * This ensures that the DC aware policy correctly uses remote hosts when\n * \"used hosts per remote DC\" has a value greater than 0.\n *\n * @since 2.8.1\n * @jira_ticket CPP-572\n * @test_category load_balancing_policy:dc_aware\n *\/\nCASSANDRA_INTEGRATION_TEST_F(DcAwarePolicyTest, UsedHostsRemoteDc) {\n CHECK_FAILURE\n\n Cluster cluster(default_cluster());\n\n \/\/ Use up to one of the remote DC nodes if no local nodes are available.\n ASSERT_EQ(cass_cluster_set_load_balance_dc_aware(cluster.get(), \"dc1\", 1, cass_false), CASS_OK);\n\n Session session = cluster.connect(keyspace_name_);\n\n { \/\/ Run queries using the local DC\n std::vector attempted_hosts = validate(session);\n\n \/\/ Verify that local DC hosts were used\n EXPECT_TRUE(contains(ccm_->get_ip_prefix() + \"1\", attempted_hosts) || contains(ccm_->get_ip_prefix() + \"2\", attempted_hosts));\n\n \/\/ Verify that no remote DC hosts were used\n EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + \"3\", attempted_hosts) && !contains(ccm_->get_ip_prefix() + \"4\", attempted_hosts));\n }\n\n \/\/ Stop the whole local DC\n ccm_->stop_node(1, true);\n ccm_->stop_node(2, true);\n\n { \/\/ Run queries using the remote DC\n std::vector attempted_hosts = validate(session);\n\n \/\/ Verify that remote DC hosts were used\n EXPECT_TRUE(contains(ccm_->get_ip_prefix() + \"3\", attempted_hosts) || contains(ccm_->get_ip_prefix() + \"4\", attempted_hosts));\n\n \/\/ Verify that no local DC hosts where used\n EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + \"1\", attempted_hosts) && !contains(ccm_->get_ip_prefix() + \"2\", attempted_hosts));\n }\n}\ntest: Update DC aware policy test to create only one session\/*\n Copyright (c) DataStax, Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"integration.hpp\"\n#include \"cassandra.h\"\n\n#include \n#include \n\nclass DcAwarePolicyTest : public Integration {\npublic:\n void SetUp() {\n \/\/ Create a cluster with 2 DCs with 2 nodes in each\n number_dc1_nodes_ = 2;\n number_dc2_nodes_ = 2;\n is_session_requested_ = false;\n Integration::SetUp();\n }\n\n void initialize() {\n session_.execute(format_string(CASSANDRA_KEY_VALUE_TABLE_FORMAT, table_name_.c_str(), \"int\", \"text\"));\n session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), \"1\", \"'one'\"));\n session_.execute(format_string(CASSANDRA_KEY_VALUE_INSERT_FORMAT, table_name_.c_str(), \"2\", \"'two'\"));\n }\n\n std::vector validate() {\n std::vector attempted_hosts, temp;\n Result result;\n\n result = session_.execute(select_statement(\"1\"));\n temp = result.attempted_hosts();\n std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts));\n EXPECT_EQ(result.first_row().next().as(), Varchar(\"one\"));\n\n result = session_.execute(select_statement(\"2\"));\n temp = result.attempted_hosts();\n std::copy(temp.begin(), temp.end(), std::back_inserter(attempted_hosts));\n EXPECT_EQ(result.first_row().next().as(), Varchar(\"two\"));\n\n return attempted_hosts;\n }\n\n Statement select_statement(const std::string& key) {\n Statement statement(format_string(CASSANDRA_SELECT_VALUE_FORMAT, table_name_.c_str(), key.c_str()));\n statement.set_consistency(CASS_CONSISTENCY_ONE);\n statement.set_record_attempted_hosts(true);\n return statement;\n }\n\n bool contains(const std::string& host, const std::vector& attempted_hosts) {\n return std::count(attempted_hosts.begin(), attempted_hosts.end(), host) > 0;\n }\n};\n\n\/**\n * Verify that the \"used hosts per remote DC\" setting allows queries to use the\n * remote DC nodes when the local DC nodes are unavailable.\n *\n * This ensures that the DC aware policy correctly uses remote hosts when\n * \"used hosts per remote DC\" has a value greater than 0.\n *\n * @since 2.8.1\n * @jira_ticket CPP-572\n * @test_category load_balancing_policy:dc_aware\n *\/\nCASSANDRA_INTEGRATION_TEST_F(DcAwarePolicyTest, UsedHostsRemoteDc) {\n CHECK_FAILURE\n\n \/\/ Use up to one of the remote DC nodes if no local nodes are available.\n cluster_ = default_cluster();\n cluster_.with_load_balance_dc_aware(\"dc1\", 1, false);\n connect(cluster_);\n\n \/\/ Create a test table and add test data to it\n initialize();\n\n { \/\/ Run queries using the local DC\n std::vector attempted_hosts = validate();\n\n \/\/ Verify that local DC hosts were used\n EXPECT_TRUE(contains(ccm_->get_ip_prefix() + \"1\", attempted_hosts) || contains(ccm_->get_ip_prefix() + \"2\", attempted_hosts));\n\n \/\/ Verify that no remote DC hosts were used\n EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + \"3\", attempted_hosts) && !contains(ccm_->get_ip_prefix() + \"4\", attempted_hosts));\n }\n\n \/\/ Stop the whole local DC\n ccm_->stop_node(1, true);\n ccm_->stop_node(2, true);\n\n { \/\/ Run queries using the remote DC\n std::vector attempted_hosts = validate();\n\n \/\/ Verify that remote DC hosts were used\n EXPECT_TRUE(contains(ccm_->get_ip_prefix() + \"3\", attempted_hosts) || contains(ccm_->get_ip_prefix() + \"4\", attempted_hosts));\n\n \/\/ Verify that no local DC hosts where used\n EXPECT_TRUE(!contains(ccm_->get_ip_prefix() + \"1\", attempted_hosts) && !contains(ccm_->get_ip_prefix() + \"2\", attempted_hosts));\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass FeatureCloud\n{\n public:\n \/\/ A bit of shorthand\n typedef pcl::PointCloud PointCloud;\n typedef pcl::PointCloud SurfaceNormals;\n typedef pcl::PointCloud LocalFeatures;\n typedef pcl::search::KdTree SearchMethod;\n\n FeatureCloud () :\n search_method_xyz_ (new SearchMethod),\n normal_radius_ (0.02f),\n feature_radius_ (0.02f)\n {}\n\n ~FeatureCloud () {}\n\n \/\/ Process the given cloud\n void\n setInputCloud (PointCloud::Ptr xyz)\n {\n xyz_ = xyz;\n processInput ();\n }\n\n \/\/ Load and process the cloud in the given PCD file\n void\n loadInputCloud (const std::string &pcd_file)\n {\n xyz_ = PointCloud::Ptr (new PointCloud);\n pcl::io::loadPCDFile (pcd_file, *xyz_);\n processInput ();\n }\n\n \/\/ Get a pointer to the cloud 3D points\n PointCloud::Ptr\n getPointCloud () const\n {\n return (xyz_);\n }\n\n \/\/ Get a pointer to the cloud of 3D surface normals\n SurfaceNormals::Ptr\n getSurfaceNormals () const\n {\n return (normals_);\n }\n\n \/\/ Get a pointer to the cloud of feature descriptors\n LocalFeatures::Ptr\n getLocalFeatures () const\n {\n return (features_);\n }\n\n protected:\n \/\/ Compute the surface normals and local features\n void\n processInput ()\n {\n computeSurfaceNormals ();\n computeLocalFeatures ();\n }\n\n \/\/ Compute the surface normals\n void\n computeSurfaceNormals ()\n {\n normals_ = SurfaceNormals::Ptr (new SurfaceNormals);\n\n pcl::NormalEstimation norm_est;\n norm_est.setInputCloud (xyz_);\n norm_est.setSearchMethod (search_method_xyz_);\n norm_est.setRadiusSearch (normal_radius_);\n norm_est.compute (*normals_);\n }\n\n \/\/ Compute the local feature descriptors\n void\n computeLocalFeatures ()\n {\n features_ = LocalFeatures::Ptr (new LocalFeatures);\n\n pcl::FPFHEstimation fpfh_est;\n fpfh_est.setInputCloud (xyz_);\n fpfh_est.setInputNormals (normals_);\n fpfh_est.setSearchMethod (search_method_xyz_);\n fpfh_est.setRadiusSearch (feature_radius_);\n fpfh_est.compute (*features_);\n }\n\n private:\n \/\/ Point cloud data\n PointCloud::Ptr xyz_;\n SurfaceNormals::Ptr normals_;\n LocalFeatures::Ptr features_;\n SearchMethod::Ptr search_method_xyz_;\n\n \/\/ Parameters\n float normal_radius_;\n float feature_radius_;\n};\n\nclass TemplateAlignment\n{\n public:\n\n \/\/ A struct for storing alignment results\n struct Result\n {\n float fitness_score;\n Eigen::Matrix4f final_transformation;\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n };\n\n TemplateAlignment () :\n min_sample_distance_ (0.05f),\n max_correspondence_distance_ (0.01f*0.01f),\n nr_iterations_ (500)\n {\n \/\/ Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm\n sac_ia_.setMinSampleDistance (min_sample_distance_);\n sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_);\n sac_ia_.setMaximumIterations (nr_iterations_);\n }\n\n ~TemplateAlignment () {}\n\n \/\/ Set the given cloud as the target to which the templates will be aligned\n void\n setTargetCloud (FeatureCloud &target_cloud)\n {\n target_ = target_cloud;\n sac_ia_.setInputTarget (target_cloud.getPointCloud ());\n sac_ia_.setTargetFeatures (target_cloud.getLocalFeatures ());\n }\n\n \/\/ Add the given cloud to the list of template clouds\n void\n addTemplateCloud (FeatureCloud &template_cloud)\n {\n templates_.push_back (template_cloud);\n }\n\n \/\/ Align the given template cloud to the target specified by setTargetCloud ()\n void\n align (FeatureCloud &template_cloud, TemplateAlignment::Result &result)\n {\n sac_ia_.setInputCloud (template_cloud.getPointCloud ());\n sac_ia_.setSourceFeatures (template_cloud.getLocalFeatures ());\n\n pcl::PointCloud registration_output;\n sac_ia_.align (registration_output);\n\n result.fitness_score = (float) sac_ia_.getFitnessScore (max_correspondence_distance_);\n result.final_transformation = sac_ia_.getFinalTransformation ();\n }\n\n \/\/ Align all of template clouds set by addTemplateCloud to the target specified by setTargetCloud ()\n void\n alignAll (std::vector > &results)\n {\n results.resize (templates_.size ());\n for (size_t i = 0; i < templates_.size (); ++i)\n {\n align (templates_[i], results[i]);\n }\n }\n\n \/\/ Align all of template clouds to the target cloud to find the one with best alignment score\n int\n findBestAlignment (TemplateAlignment::Result &result)\n {\n \/\/ Align all of the templates to the target cloud\n std::vector > results;\n alignAll (results);\n\n \/\/ Find the template with the best (lowest) fitness score\n float lowest_score = std::numeric_limits::infinity ();\n int best_template = 0;\n for (size_t i = 0; i < results.size (); ++i)\n {\n const Result &r = results[i];\n if (r.fitness_score < lowest_score)\n {\n lowest_score = r.fitness_score;\n best_template = (int) i;\n }\n }\n\n \/\/ Output the best alignment\n result = results[best_template];\n return (best_template);\n }\n\n private:\n \/\/ A list of template clouds and the target to which they will be aligned\n std::vector templates_;\n FeatureCloud target_;\n\n \/\/ The Sample Consensus Initial Alignment (SAC-IA) registration routine and its parameters\n pcl::SampleConsensusInitialAlignment sac_ia_;\n float min_sample_distance_;\n float max_correspondence_distance_;\n int nr_iterations_;\n};\n\n\/\/ Align a collection of object templates to a sample point cloud\nint\nmain (int argc, char **argv)\n{\n if (argc < 3)\n {\n printf (\"No target PCD file given!\\n\");\n return (-1);\n }\n\n \/\/ Load the object templates specified in the object_templates.txt file\n std::vector object_templates;\n std::ifstream input_stream (argv[1]);\n object_templates.resize (0);\n std::string pcd_filename;\n while (input_stream.good ())\n {\n std::getline (input_stream, pcd_filename);\n if (pcd_filename.empty () || pcd_filename.at (0) == '#') \/\/ Skip blank lines or comments\n continue;\n\n FeatureCloud template_cloud;\n template_cloud.loadInputCloud (pcd_filename);\n object_templates.push_back (template_cloud);\n }\n input_stream.close ();\n\n \/\/ Load the target cloud PCD file\n pcl::PointCloud::Ptr cloud (new pcl::PointCloud);\n pcl::io::loadPCDFile (argv[2], *cloud);\n\n \/\/ Preprocess the cloud by...\n \/\/ ...removing distant points\n const float depth_limit = 1.0;\n pcl::PassThrough pass;\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (0, depth_limit);\n pass.filter (*cloud);\n\n \/\/ ... and downsampling the point cloud\n const float voxel_grid_size = 0.005f;\n pcl::VoxelGrid vox_grid;\n vox_grid.setInputCloud (cloud);\n vox_grid.setLeafSize (voxel_grid_size, voxel_grid_size, voxel_grid_size);\n vox_grid.filter (*cloud);\n\n \/\/ Assign to the target FeatureCloud\n FeatureCloud target_cloud;\n target_cloud.setInputCloud (cloud);\n\n \/\/ Set the TemplateAlignment inputs\n TemplateAlignment template_align;\n for (size_t i = 0; i < object_templates.size (); ++i)\n {\n template_align.addTemplateCloud (object_templates[i]);\n }\n template_align.setTargetCloud (target_cloud);\n\n \/\/ Find the best template alignment\n TemplateAlignment::Result best_alignment;\n int best_index = template_align.findBestAlignment (best_alignment);\n const FeatureCloud &best_template = object_templates[best_index];\n\n \/\/ Print the alignment fitness score (values less than 0.00002 are good)\n printf (\"Best fitness score: %f\\n\", best_alignment.fitness_score);\n\n \/\/ Print the rotation matrix and translation vector\n Eigen::Matrix3f rotation = best_alignment.final_transformation.block<3,3>(0, 0);\n Eigen::Vector3f translation = best_alignment.final_transformation.block<3,1>(0, 3);\n\n printf (\"\\n\");\n printf (\" | %6.3f %6.3f %6.3f | \\n\", rotation (0,0), rotation (0,1), rotation (0,2));\n printf (\"R = | %6.3f %6.3f %6.3f | \\n\", rotation (1,0), rotation (1,1), rotation (1,2));\n printf (\" | %6.3f %6.3f %6.3f | \\n\", rotation (2,0), rotation (2,1), rotation (2,2));\n printf (\"\\n\");\n printf (\"t = < %0.3f, %0.3f, %0.3f >\\n\", translation (0), translation (1), translation (2));\n\n \/\/ Save the aligned template for visualization\n pcl::PointCloud transformed_cloud;\n pcl::transformPointCloud (*best_template.getPointCloud (), transformed_cloud, best_alignment.final_transformation);\n pcl::io::savePCDFileBinary (\"output.pcd\", transformed_cloud);\n\n return (0);\n}\nfix for template_alignment (thanks Adnan)#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass FeatureCloud\n{\n public:\n \/\/ A bit of shorthand\n typedef pcl::PointCloud PointCloud;\n typedef pcl::PointCloud SurfaceNormals;\n typedef pcl::PointCloud LocalFeatures;\n typedef pcl::search::KdTree SearchMethod;\n\n FeatureCloud () :\n search_method_xyz_ (new SearchMethod),\n normal_radius_ (0.02f),\n feature_radius_ (0.02f)\n {}\n\n ~FeatureCloud () {}\n\n \/\/ Process the given cloud\n void\n setInputCloud (PointCloud::Ptr xyz)\n {\n xyz_ = xyz;\n processInput ();\n }\n\n \/\/ Load and process the cloud in the given PCD file\n void\n loadInputCloud (const std::string &pcd_file)\n {\n xyz_ = PointCloud::Ptr (new PointCloud);\n pcl::io::loadPCDFile (pcd_file, *xyz_);\n processInput ();\n }\n\n \/\/ Get a pointer to the cloud 3D points\n PointCloud::Ptr\n getPointCloud () const\n {\n return (xyz_);\n }\n\n \/\/ Get a pointer to the cloud of 3D surface normals\n SurfaceNormals::Ptr\n getSurfaceNormals () const\n {\n return (normals_);\n }\n\n \/\/ Get a pointer to the cloud of feature descriptors\n LocalFeatures::Ptr\n getLocalFeatures () const\n {\n return (features_);\n }\n\n protected:\n \/\/ Compute the surface normals and local features\n void\n processInput ()\n {\n computeSurfaceNormals ();\n computeLocalFeatures ();\n }\n\n \/\/ Compute the surface normals\n void\n computeSurfaceNormals ()\n {\n normals_ = SurfaceNormals::Ptr (new SurfaceNormals);\n\n pcl::NormalEstimation norm_est;\n norm_est.setInputCloud (xyz_);\n norm_est.setSearchMethod (search_method_xyz_);\n norm_est.setRadiusSearch (normal_radius_);\n norm_est.compute (*normals_);\n }\n\n \/\/ Compute the local feature descriptors\n void\n computeLocalFeatures ()\n {\n features_ = LocalFeatures::Ptr (new LocalFeatures);\n\n pcl::FPFHEstimation fpfh_est;\n fpfh_est.setInputCloud (xyz_);\n fpfh_est.setInputNormals (normals_);\n fpfh_est.setSearchMethod (search_method_xyz_);\n fpfh_est.setRadiusSearch (feature_radius_);\n fpfh_est.compute (*features_);\n }\n\n private:\n \/\/ Point cloud data\n PointCloud::Ptr xyz_;\n SurfaceNormals::Ptr normals_;\n LocalFeatures::Ptr features_;\n SearchMethod::Ptr search_method_xyz_;\n\n \/\/ Parameters\n float normal_radius_;\n float feature_radius_;\n};\n\nclass TemplateAlignment\n{\n public:\n\n \/\/ A struct for storing alignment results\n struct Result\n {\n float fitness_score;\n Eigen::Matrix4f final_transformation;\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n };\n\n TemplateAlignment () :\n min_sample_distance_ (0.05f),\n max_correspondence_distance_ (0.01f*0.01f),\n nr_iterations_ (500)\n {\n \/\/ Intialize the parameters in the Sample Consensus Intial Alignment (SAC-IA) algorithm\n sac_ia_.setMinSampleDistance (min_sample_distance_);\n sac_ia_.setMaxCorrespondenceDistance (max_correspondence_distance_);\n sac_ia_.setMaximumIterations (nr_iterations_);\n }\n\n ~TemplateAlignment () {}\n\n \/\/ Set the given cloud as the target to which the templates will be aligned\n void\n setTargetCloud (FeatureCloud &target_cloud)\n {\n target_ = target_cloud;\n sac_ia_.setInputTarget (target_cloud.getPointCloud ());\n sac_ia_.setTargetFeatures (target_cloud.getLocalFeatures ());\n }\n\n \/\/ Add the given cloud to the list of template clouds\n void\n addTemplateCloud (FeatureCloud &template_cloud)\n {\n templates_.push_back (template_cloud);\n }\n\n \/\/ Align the given template cloud to the target specified by setTargetCloud ()\n void\n align (FeatureCloud &template_cloud, TemplateAlignment::Result &result)\n {\n sac_ia_.setInputCloud (template_cloud.getPointCloud ());\n sac_ia_.setSourceFeatures (template_cloud.getLocalFeatures ());\n\n pcl::PointCloud registration_output;\n sac_ia_.align (registration_output);\n\n result.fitness_score = (float) sac_ia_.getFitnessScore (max_correspondence_distance_);\n result.final_transformation = sac_ia_.getFinalTransformation ();\n }\n\n \/\/ Align all of template clouds set by addTemplateCloud to the target specified by setTargetCloud ()\n void\n alignAll (std::vector > &results)\n {\n results.resize (templates_.size ());\n for (size_t i = 0; i < templates_.size (); ++i)\n {\n align (templates_[i], results[i]);\n }\n }\n\n \/\/ Align all of template clouds to the target cloud to find the one with best alignment score\n int\n findBestAlignment (TemplateAlignment::Result &result)\n {\n \/\/ Align all of the templates to the target cloud\n std::vector > results;\n alignAll (results);\n\n \/\/ Find the template with the best (lowest) fitness score\n float lowest_score = std::numeric_limits::infinity ();\n int best_template = 0;\n for (size_t i = 0; i < results.size (); ++i)\n {\n const Result &r = results[i];\n if (r.fitness_score < lowest_score)\n {\n lowest_score = r.fitness_score;\n best_template = (int) i;\n }\n }\n\n \/\/ Output the best alignment\n result = results[best_template];\n return (best_template);\n }\n\n private:\n \/\/ A list of template clouds and the target to which they will be aligned\n std::vector templates_;\n FeatureCloud target_;\n\n \/\/ The Sample Consensus Initial Alignment (SAC-IA) registration routine and its parameters\n pcl::SampleConsensusInitialAlignment sac_ia_;\n float min_sample_distance_;\n float max_correspondence_distance_;\n int nr_iterations_;\n};\n\n\/\/ Align a collection of object templates to a sample point cloud\nint\nmain (int argc, char **argv)\n{\n if (argc < 3)\n {\n printf (\"No target PCD file given!\\n\");\n return (-1);\n }\n\n \/\/ Load the object templates specified in the object_templates.txt file\n std::vector object_templates;\n std::ifstream input_stream (argv[1]);\n object_templates.resize (0);\n std::string pcd_filename;\n while (input_stream.good ())\n {\n std::getline (input_stream, pcd_filename);\n if (pcd_filename.empty () || pcd_filename.at (0) == '#') \/\/ Skip blank lines or comments\n continue;\n\n FeatureCloud template_cloud;\n template_cloud.loadInputCloud (pcd_filename);\n object_templates.push_back (template_cloud);\n }\n input_stream.close ();\n\n \/\/ Load the target cloud PCD file\n pcl::PointCloud::Ptr cloud (new pcl::PointCloud);\n pcl::io::loadPCDFile (argv[2], *cloud);\n\n \/\/ Preprocess the cloud by...\n \/\/ ...removing distant points\n const float depth_limit = 1.0;\n pcl::PassThrough pass;\n pass.setInputCloud (cloud);\n pass.setFilterFieldName (\"z\");\n pass.setFilterLimits (0, depth_limit);\n pass.filter (*cloud);\n\n \/\/ ... and downsampling the point cloud\n const float voxel_grid_size = 0.005f;\n pcl::VoxelGrid vox_grid;\n vox_grid.setInputCloud (cloud);\n vox_grid.setLeafSize (voxel_grid_size, voxel_grid_size, voxel_grid_size);\n \/\/vox_grid.filter (*cloud); \/\/ Please see this http:\/\/www.pcl-developers.org\/Possible-problem-in-new-VoxelGrid-implementation-from-PCL-1-5-0-td5490361.html\n pcl::PointCloud::Ptr tempCloud (new pcl::PointCloud); \n vox_grid.filter (*tempCloud);\n cloud = tempCloud; \n\n \/\/ Assign to the target FeatureCloud\n FeatureCloud target_cloud;\n target_cloud.setInputCloud (cloud);\n\n \/\/ Set the TemplateAlignment inputs\n TemplateAlignment template_align;\n for (size_t i = 0; i < object_templates.size (); ++i)\n {\n template_align.addTemplateCloud (object_templates[i]);\n }\n template_align.setTargetCloud (target_cloud);\n\n \/\/ Find the best template alignment\n TemplateAlignment::Result best_alignment;\n int best_index = template_align.findBestAlignment (best_alignment);\n const FeatureCloud &best_template = object_templates[best_index];\n\n \/\/ Print the alignment fitness score (values less than 0.00002 are good)\n printf (\"Best fitness score: %f\\n\", best_alignment.fitness_score);\n\n \/\/ Print the rotation matrix and translation vector\n Eigen::Matrix3f rotation = best_alignment.final_transformation.block<3,3>(0, 0);\n Eigen::Vector3f translation = best_alignment.final_transformation.block<3,1>(0, 3);\n\n printf (\"\\n\");\n printf (\" | %6.3f %6.3f %6.3f | \\n\", rotation (0,0), rotation (0,1), rotation (0,2));\n printf (\"R = | %6.3f %6.3f %6.3f | \\n\", rotation (1,0), rotation (1,1), rotation (1,2));\n printf (\" | %6.3f %6.3f %6.3f | \\n\", rotation (2,0), rotation (2,1), rotation (2,2));\n printf (\"\\n\");\n printf (\"t = < %0.3f, %0.3f, %0.3f >\\n\", translation (0), translation (1), translation (2));\n\n \/\/ Save the aligned template for visualization\n pcl::PointCloud transformed_cloud;\n pcl::transformPointCloud (*best_template.getPointCloud (), transformed_cloud, best_alignment.final_transformation);\n pcl::io::savePCDFileBinary (\"output.pcd\", transformed_cloud);\n\n return (0);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_SYMBIAN\n#include \n#include \n#include \n#endif\n\n#define MARKER_HEIGHT 36\n#define MARKER_WIDTH 25\n#define MARKER_PIN_LEN 10\n\nQTM_USE_NAMESPACE\n\nMapWidget::MapWidget(QGeoMappingManager *manager)\n : QGeoMapWidget(manager),\n panActive(false) {}\n\nMapWidget::~MapWidget() {}\n\nvoid MapWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)\n{\n setFocus();\n if (event->button() == Qt::LeftButton) {\n panActive = true;\n startPanning();\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)\n{\n if (event->button() == Qt::LeftButton) {\n panActive = false;\n stopPanning();\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)\n{\n if (panActive) {\n int deltaLeft = event->lastPos().x() - event->pos().x();\n int deltaTop = event->lastPos().y() - event->pos().y();\n pan(deltaLeft, deltaTop);\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)\n{\n setFocus();\n\n pan(event->lastPos().x() - size().width() \/ 2.0, event->lastPos().y() - size().height() \/ 2.0);\n if (zoomLevel() < maximumZoomLevel())\n setZoomLevel(zoomLevel() + 1);\n\n event->accept();\n}\n\nvoid MapWidget::keyPressEvent(QKeyEvent *event)\n{\n if (event->key() == Qt::Key_Minus) {\n if (zoomLevel() > minimumZoomLevel()) {\n setZoomLevel(zoomLevel() - 1);\n }\n } else if (event->key() == Qt::Key_Plus) {\n if (zoomLevel() < maximumZoomLevel()) {\n setZoomLevel(zoomLevel() + 1);\n }\n }\n\n event->accept();\n}\n\nvoid MapWidget::wheelEvent(QGraphicsSceneWheelEvent* event)\n{\n if (event->delta() > 0) { \/\/zoom in\n if (zoomLevel() < maximumZoomLevel()) {\n setZoomLevel(zoomLevel() + 1);\n }\n } else { \/\/zoom out\n if (zoomLevel() > minimumZoomLevel()) {\n setZoomLevel(zoomLevel() - 1);\n }\n }\n event->accept();\n}\n\n\/**************************************************************************************\n**************************************************************************************\/\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n m_serviceProvider(0),\n m_popupMenu(0)\n{\n ui->setupUi(this);\n\n QNetworkProxyFactory::setUseSystemConfiguration(true);\n\n setProvider(\"nokia\");\n\n qgv = new QGraphicsView(this);\n qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n qgv->setVisible(true);\n qgv->setGeometry(QRect(0, 0, width(), height()));\n qgv->setInteractive(true);\n\n QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());\n qgv->setScene(scene);\n\n createMarkerIcon();\n\n m_mapWidget = new MapWidget(m_mapManager);\n qgv->scene()->addItem(m_mapWidget);\n m_mapWidget->setGeometry(0, 0, width(), height());\n \/\/m_mapWidget->setZoomLevel(8);\n m_mapWidget->setCenter(QGeoCoordinate(52.5,13.0));\n\n setContextMenuPolicy(Qt::CustomContextMenu);\n QObject::connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),\n this, SLOT(customContextMenuRequest(const QPoint&)));\n\n setWindowTitle(tr(\"Map Viewer Demo\"));\n\n QTimer::singleShot(0, this, SLOT(delayedInit()));\n}\n\nMainWindow::~MainWindow()\n{\n delete m_serviceProvider;\n delete ui;\n}\n\nvoid MainWindow::delayedInit()\n{\n \/\/ TODO: remove this dirty, dirty hack\n m_mapWidget->setZoomLevel(m_mapWidget->zoomLevel());\n m_mapWidget->update();\n}\n\nvoid MainWindow::setProvider(QString providerId)\n{\n if (m_serviceProvider)\n delete m_serviceProvider ;\n m_serviceProvider = new QGeoServiceProvider(providerId);\n if (m_serviceProvider->error() != QGeoServiceProvider::NoError) {\n QMessageBox::information(this, tr(\"MapViewer Example\"), tr(\n \"Unable to find the %1 geoservices plugin.\").arg(providerId));\n qApp->quit();\n return;\n }\n\n m_mapManager = m_serviceProvider->mappingManager();\n m_routingManager = m_serviceProvider->routingManager();\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent* event)\n{\n qgv->resize(event->size());\n qgv->setSceneRect(0, 0, event->size().width(), event->size().height());\n m_mapWidget->resize(event->size());\n}\n\nvoid MainWindow::changeEvent(QEvent *e)\n{\n QMainWindow::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nvoid MainWindow::createMenus()\n{\n QAction* menuItem;\n m_popupMenu = new QMenu(this);\n\n menuItem = new QAction(tr(\"Set marker\"), this);\n m_popupMenu->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawMarker(bool)));\n\n QMenu* subMenuItem = new QMenu(tr(\"Draw\"), this);\n m_popupMenu->addMenu(subMenuItem);\n\n menuItem = new QAction(tr(\"Rectangle\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawRect(bool)));\n\n menuItem = new QAction(tr(\"Polyline\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawPolyline(bool)));\n\n menuItem = new QAction(tr(\"Polygon\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawPolygon(bool)));\n\n subMenuItem = new QMenu(tr(\"Route\"), this);\n m_popupMenu->addMenu(subMenuItem);\n\n menuItem = new QAction(tr(\"Calculate route\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(calcRoute(bool)));\n}\n\nvoid MainWindow::drawRect(bool \/*checked*\/)\n{\n while (markers.count() >= 2) {\n QPoint p1 = markers.takeFirst();\n QPoint p2 = markers.takeFirst();\n QPen pen(Qt::white);\n pen.setWidth(2);\n QColor fill(Qt::black);\n fill.setAlpha(65);\n QGeoMapRectangleObject *rectangle = new QGeoMapRectangleObject(m_mapWidget->screenPositionToCoordinate(p1),\n m_mapWidget->screenPositionToCoordinate(p2));\n rectangle->setPen(pen);\n rectangle->setBrush(QBrush(fill));\n m_mapWidget->addMapObject(rectangle);\n }\n\n markers.clear();\n removeMarkers();\n}\n\nvoid MainWindow::drawPolyline(bool \/*checked*\/)\n{\n QList path;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n path.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QPen pen(Qt::white);\n pen.setWidth(2);\n QGeoMapPolylineObject *polyline = new QGeoMapPolylineObject();\n polyline->setPen(pen);\n polyline->setPath(path);\n m_mapWidget->addMapObject(polyline);\n\n removeMarkers();\n}\n\nvoid MainWindow::drawPolygon(bool \/*checked*\/)\n{\n QList path;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n path.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QPen pen(Qt::white);\n pen.setWidth(2);\n QGeoMapPolygonObject *polygon = new QGeoMapPolygonObject();\n polygon->setPen(pen);\n QColor fill(Qt::black);\n fill.setAlpha(65);\n polygon->setBrush(QBrush(fill));\n polygon->setPath(path);\n m_mapWidget->addMapObject(polygon);\n\n removeMarkers();\n}\n\nvoid MainWindow::drawMarker(bool \/*checked*\/)\n{\n QGeoMapMarkerObject *marker = new QGeoMapMarkerObject(m_mapWidget->screenPositionToCoordinate(lastClicked), \n QPoint(-(MARKER_WIDTH \/ 2), -MARKER_HEIGHT), m_markerIcon);\n m_mapWidget->addMapObject(marker);\n markers.append(lastClicked);\n markerObjects.append(marker);\n}\n\nvoid MainWindow::removeMarkers()\n{\n while (markerObjects.size() > 0) {\n QGeoMapMarkerObject *marker = markerObjects.takeFirst();\n m_mapWidget->removeMapObject(marker);\n }\n}\n\nvoid MainWindow::customContextMenuRequest(const QPoint& point)\n{\n lastClicked = point;\n\n if (focusWidget() == qgv) {\n\n if (!m_popupMenu)\n createMenus();\n\n m_popupMenu->popup(mapToGlobal(point));\n }\n}\n\nvoid MainWindow::createMarkerIcon()\n{\n m_markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT);\n m_markerIcon.fill(Qt::transparent);\n QPainter painter(&m_markerIcon);\n\n QPointF p1(MARKER_WIDTH \/ 2, MARKER_HEIGHT - 1);\n QPointF p2(MARKER_WIDTH \/ 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN);\n QPen pen(Qt::black);\n pen.setWidth(2);\n painter.setPen(pen);\n painter.drawLine(p1, p2);\n QRectF ellipse(0, 0, MARKER_WIDTH - 1, MARKER_WIDTH - 1);\n pen.setWidth(1);\n painter.setPen(pen);\n QColor color(Qt::green);\n color.setAlpha(127);\n QBrush brush(color);\n painter.setBrush(brush);\n painter.drawEllipse(ellipse);\n}\n\nvoid MainWindow::calcRoute(bool \/*checked*\/)\n{\n if (markers.count() < 2)\n return;\n\n QList waypoints;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n waypoints.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QGeoRouteRequest req(waypoints);\n QGeoRouteReply *reply = m_routingManager->calculateRoute(req);\n\n QObject::connect(reply, SIGNAL(finished()),\n this, SLOT(routeFinished()));\n\n \/\/removeMarkers();\n}\n\nvoid MainWindow::routeFinished()\n{\n QGeoRouteReply *reply = static_cast(sender());\n\n if (!reply)\n return;\n\n if (reply->routes().size() < 1)\n return;\n\n QGeoMapRouteObject *route = new QGeoMapRouteObject(reply->routes().at(0));\n QColor routeColor(Qt::blue);\n routeColor.setAlpha(127); \/\/semi-transparent\n QPen pen(routeColor);\n pen.setWidth(7);\n pen.setCapStyle(Qt::RoundCap);\n route->setPen(pen);\n m_mapWidget->addMapObject(route);\n}\n\nRemove markers after route has been requested\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef Q_OS_SYMBIAN\n#include \n#include \n#include \n#endif\n\n#define MARKER_HEIGHT 36\n#define MARKER_WIDTH 25\n#define MARKER_PIN_LEN 10\n\nQTM_USE_NAMESPACE\n\nMapWidget::MapWidget(QGeoMappingManager *manager)\n : QGeoMapWidget(manager),\n panActive(false) {}\n\nMapWidget::~MapWidget() {}\n\nvoid MapWidget::mousePressEvent(QGraphicsSceneMouseEvent* event)\n{\n setFocus();\n if (event->button() == Qt::LeftButton) {\n panActive = true;\n startPanning();\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseReleaseEvent(QGraphicsSceneMouseEvent* event)\n{\n if (event->button() == Qt::LeftButton) {\n panActive = false;\n stopPanning();\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseMoveEvent(QGraphicsSceneMouseEvent* event)\n{\n if (panActive) {\n int deltaLeft = event->lastPos().x() - event->pos().x();\n int deltaTop = event->lastPos().y() - event->pos().y();\n pan(deltaLeft, deltaTop);\n }\n\n event->accept();\n}\n\nvoid MapWidget::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)\n{\n setFocus();\n\n pan(event->lastPos().x() - size().width() \/ 2.0, event->lastPos().y() - size().height() \/ 2.0);\n if (zoomLevel() < maximumZoomLevel())\n setZoomLevel(zoomLevel() + 1);\n\n event->accept();\n}\n\nvoid MapWidget::keyPressEvent(QKeyEvent *event)\n{\n if (event->key() == Qt::Key_Minus) {\n if (zoomLevel() > minimumZoomLevel()) {\n setZoomLevel(zoomLevel() - 1);\n }\n } else if (event->key() == Qt::Key_Plus) {\n if (zoomLevel() < maximumZoomLevel()) {\n setZoomLevel(zoomLevel() + 1);\n }\n }\n\n event->accept();\n}\n\nvoid MapWidget::wheelEvent(QGraphicsSceneWheelEvent* event)\n{\n if (event->delta() > 0) { \/\/zoom in\n if (zoomLevel() < maximumZoomLevel()) {\n setZoomLevel(zoomLevel() + 1);\n }\n } else { \/\/zoom out\n if (zoomLevel() > minimumZoomLevel()) {\n setZoomLevel(zoomLevel() - 1);\n }\n }\n event->accept();\n}\n\n\/**************************************************************************************\n**************************************************************************************\/\n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow),\n m_serviceProvider(0),\n m_popupMenu(0)\n{\n ui->setupUi(this);\n\n QNetworkProxyFactory::setUseSystemConfiguration(true);\n\n setProvider(\"nokia\");\n\n qgv = new QGraphicsView(this);\n qgv->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n qgv->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);\n qgv->setVisible(true);\n qgv->setGeometry(QRect(0, 0, width(), height()));\n qgv->setInteractive(true);\n\n QGraphicsScene* scene = new QGraphicsScene(0, 0, width(), height());\n qgv->setScene(scene);\n\n createMarkerIcon();\n\n m_mapWidget = new MapWidget(m_mapManager);\n qgv->scene()->addItem(m_mapWidget);\n m_mapWidget->setGeometry(0, 0, width(), height());\n \/\/m_mapWidget->setZoomLevel(8);\n m_mapWidget->setCenter(QGeoCoordinate(52.5,13.0));\n\n setContextMenuPolicy(Qt::CustomContextMenu);\n QObject::connect(this, SIGNAL(customContextMenuRequested(const QPoint&)),\n this, SLOT(customContextMenuRequest(const QPoint&)));\n\n setWindowTitle(tr(\"Map Viewer Demo\"));\n\n QTimer::singleShot(0, this, SLOT(delayedInit()));\n}\n\nMainWindow::~MainWindow()\n{\n delete m_serviceProvider;\n delete ui;\n}\n\nvoid MainWindow::delayedInit()\n{\n \/\/ TODO: remove this dirty, dirty hack\n m_mapWidget->setZoomLevel(m_mapWidget->zoomLevel());\n m_mapWidget->update();\n}\n\nvoid MainWindow::setProvider(QString providerId)\n{\n if (m_serviceProvider)\n delete m_serviceProvider ;\n m_serviceProvider = new QGeoServiceProvider(providerId);\n if (m_serviceProvider->error() != QGeoServiceProvider::NoError) {\n QMessageBox::information(this, tr(\"MapViewer Example\"), tr(\n \"Unable to find the %1 geoservices plugin.\").arg(providerId));\n qApp->quit();\n return;\n }\n\n m_mapManager = m_serviceProvider->mappingManager();\n m_routingManager = m_serviceProvider->routingManager();\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent* event)\n{\n qgv->resize(event->size());\n qgv->setSceneRect(0, 0, event->size().width(), event->size().height());\n m_mapWidget->resize(event->size());\n}\n\nvoid MainWindow::changeEvent(QEvent *e)\n{\n QMainWindow::changeEvent(e);\n switch (e->type()) {\n case QEvent::LanguageChange:\n ui->retranslateUi(this);\n break;\n default:\n break;\n }\n}\n\nvoid MainWindow::createMenus()\n{\n QAction* menuItem;\n m_popupMenu = new QMenu(this);\n\n menuItem = new QAction(tr(\"Set marker\"), this);\n m_popupMenu->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawMarker(bool)));\n\n QMenu* subMenuItem = new QMenu(tr(\"Draw\"), this);\n m_popupMenu->addMenu(subMenuItem);\n\n menuItem = new QAction(tr(\"Rectangle\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawRect(bool)));\n\n menuItem = new QAction(tr(\"Polyline\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawPolyline(bool)));\n\n menuItem = new QAction(tr(\"Polygon\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(drawPolygon(bool)));\n\n subMenuItem = new QMenu(tr(\"Route\"), this);\n m_popupMenu->addMenu(subMenuItem);\n\n menuItem = new QAction(tr(\"Calculate route\"), this);\n subMenuItem->addAction(menuItem);\n QObject::connect(menuItem, SIGNAL(triggered(bool)),\n this, SLOT(calcRoute(bool)));\n}\n\nvoid MainWindow::drawRect(bool \/*checked*\/)\n{\n while (markers.count() >= 2) {\n QPoint p1 = markers.takeFirst();\n QPoint p2 = markers.takeFirst();\n QPen pen(Qt::white);\n pen.setWidth(2);\n QColor fill(Qt::black);\n fill.setAlpha(65);\n QGeoMapRectangleObject *rectangle = new QGeoMapRectangleObject(m_mapWidget->screenPositionToCoordinate(p1),\n m_mapWidget->screenPositionToCoordinate(p2));\n rectangle->setPen(pen);\n rectangle->setBrush(QBrush(fill));\n m_mapWidget->addMapObject(rectangle);\n }\n\n markers.clear();\n removeMarkers();\n}\n\nvoid MainWindow::drawPolyline(bool \/*checked*\/)\n{\n QList path;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n path.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QPen pen(Qt::white);\n pen.setWidth(2);\n QGeoMapPolylineObject *polyline = new QGeoMapPolylineObject();\n polyline->setPen(pen);\n polyline->setPath(path);\n m_mapWidget->addMapObject(polyline);\n\n removeMarkers();\n}\n\nvoid MainWindow::drawPolygon(bool \/*checked*\/)\n{\n QList path;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n path.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QPen pen(Qt::white);\n pen.setWidth(2);\n QGeoMapPolygonObject *polygon = new QGeoMapPolygonObject();\n polygon->setPen(pen);\n QColor fill(Qt::black);\n fill.setAlpha(65);\n polygon->setBrush(QBrush(fill));\n polygon->setPath(path);\n m_mapWidget->addMapObject(polygon);\n\n removeMarkers();\n}\n\nvoid MainWindow::drawMarker(bool \/*checked*\/)\n{\n QGeoMapMarkerObject *marker = new QGeoMapMarkerObject(m_mapWidget->screenPositionToCoordinate(lastClicked), \n QPoint(-(MARKER_WIDTH \/ 2), -MARKER_HEIGHT), m_markerIcon);\n m_mapWidget->addMapObject(marker);\n markers.append(lastClicked);\n markerObjects.append(marker);\n}\n\nvoid MainWindow::removeMarkers()\n{\n while (markerObjects.size() > 0) {\n QGeoMapMarkerObject *marker = markerObjects.takeFirst();\n m_mapWidget->removeMapObject(marker);\n marker->deleteLater();\n }\n}\n\nvoid MainWindow::customContextMenuRequest(const QPoint& point)\n{\n lastClicked = point;\n\n if (focusWidget() == qgv) {\n\n if (!m_popupMenu)\n createMenus();\n\n m_popupMenu->popup(mapToGlobal(point));\n }\n}\n\nvoid MainWindow::createMarkerIcon()\n{\n m_markerIcon = QPixmap(MARKER_WIDTH, MARKER_HEIGHT);\n m_markerIcon.fill(Qt::transparent);\n QPainter painter(&m_markerIcon);\n\n QPointF p1(MARKER_WIDTH \/ 2, MARKER_HEIGHT - 1);\n QPointF p2(MARKER_WIDTH \/ 2, MARKER_HEIGHT - 1 - MARKER_PIN_LEN);\n QPen pen(Qt::black);\n pen.setWidth(2);\n painter.setPen(pen);\n painter.drawLine(p1, p2);\n QRectF ellipse(0, 0, MARKER_WIDTH - 1, MARKER_WIDTH - 1);\n pen.setWidth(1);\n painter.setPen(pen);\n QColor color(Qt::green);\n color.setAlpha(127);\n QBrush brush(color);\n painter.setBrush(brush);\n painter.drawEllipse(ellipse);\n}\n\nvoid MainWindow::calcRoute(bool \/*checked*\/)\n{\n if (markers.count() < 2)\n return;\n\n QList waypoints;\n\n while (markers.count() >= 1) {\n QPoint p = markers.takeFirst();\n waypoints.append(m_mapWidget->screenPositionToCoordinate(p));\n }\n\n QGeoRouteRequest req(waypoints);\n QGeoRouteReply *reply = m_routingManager->calculateRoute(req);\n\n QObject::connect(reply, SIGNAL(finished()),\n this, SLOT(routeFinished()));\n\n removeMarkers();\n}\n\nvoid MainWindow::routeFinished()\n{\n QGeoRouteReply *reply = static_cast(sender());\n\n if (!reply)\n return;\n\n if (reply->routes().size() < 1)\n return;\n\n QGeoMapRouteObject *route = new QGeoMapRouteObject(reply->routes().at(0));\n QColor routeColor(Qt::blue);\n routeColor.setAlpha(127); \/\/semi-transparent\n QPen pen(routeColor);\n pen.setWidth(7);\n pen.setCapStyle(Qt::RoundCap);\n route->setPen(pen);\n m_mapWidget->addMapObject(route);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/internal\/roudi_environment\/runtime_test_interface.hpp\"\n#include \"iceoryx_posh\/runtime\/posh_runtime.hpp\"\n#include \"iceoryx_utils\/cxx\/helplets.hpp\"\n\nnamespace iox\n{\nnamespace roudi\n{\nusing runtime::PoshRuntime;\n\nthread_local PoshRuntime* RuntimeTestInterface::t_activeRuntime{nullptr};\nthread_local std::atomic RuntimeTestInterface::t_currentRouDiContext{0};\nstd::atomic RuntimeTestInterface::s_currentRouDiContext{0};\n\nstd::mutex RuntimeTestInterface::s_runtimeAccessMutex;\n\nstd::map RuntimeTestInterface::s_runtimes;\n\nRuntimeTestInterface::RuntimeTestInterface()\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n PoshRuntime::setRuntimeFactory(RuntimeTestInterface::runtimeFactoryGetInstance);\n}\n\nRuntimeTestInterface::~RuntimeTestInterface()\n{\n if (m_doCleanupOnDestruction)\n {\n \/\/ cleanup holds its own lock\n cleanupRuntimes();\n\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n PoshRuntime::setRuntimeFactory(PoshRuntime::defaultRuntimeFactory);\n }\n}\n\nRuntimeTestInterface::RuntimeTestInterface(RuntimeTestInterface&& rhs)\n{\n rhs.m_doCleanupOnDestruction = false;\n}\nRuntimeTestInterface& RuntimeTestInterface::operator=(RuntimeTestInterface&& rhs)\n{\n rhs.m_doCleanupOnDestruction = false;\n return *this;\n}\n\nvoid RuntimeTestInterface::cleanupRuntimes()\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n for (const auto& e : RuntimeTestInterface::s_runtimes)\n {\n delete e.second;\n }\n RuntimeTestInterface::s_runtimes.clear();\n RuntimeTestInterface::s_currentRouDiContext.operator++(std::memory_order_relaxed);\n}\n\nvoid RuntimeTestInterface::eraseRuntime(const ProcessName_t& name)\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n auto iter = RuntimeTestInterface::s_runtimes.find(name);\n if (iter != RuntimeTestInterface::s_runtimes.end())\n {\n delete iter->second;\n RuntimeTestInterface::s_runtimes.erase(name);\n }\n}\n\nPoshRuntime& RuntimeTestInterface::runtimeFactoryGetInstance(cxx::optional name)\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n auto currentRouDiContext = RuntimeTestInterface::s_currentRouDiContext.load(std::memory_order_relaxed);\n if (RuntimeTestInterface::t_currentRouDiContext.load(std::memory_order_relaxed) != currentRouDiContext)\n {\n RuntimeTestInterface::t_currentRouDiContext.store(currentRouDiContext, std::memory_order_relaxed);\n RuntimeTestInterface::t_activeRuntime = nullptr;\n }\n\n bool nameIsNullopt{!name.has_value()};\n bool invalidGetRuntimeAccess{RuntimeTestInterface::t_activeRuntime == nullptr && nameIsNullopt};\n cxx::Expects(!invalidGetRuntimeAccess);\n\n if (RuntimeTestInterface::t_activeRuntime != nullptr && nameIsNullopt)\n {\n return *RuntimeTestInterface::t_activeRuntime;\n }\n\n if (nameIsNullopt)\n {\n ProcessName_t* emptyName;\n name.emplace(emptyName);\n }\n\n auto iter = RuntimeTestInterface::s_runtimes.find(*name.value());\n if (iter != RuntimeTestInterface::s_runtimes.end())\n {\n RuntimeTestInterface::t_activeRuntime = iter->second;\n }\n else\n {\n auto runtimeImpl = new runtime::PoshRuntime(name, false);\n RuntimeTestInterface::s_runtimes.insert({*name.value(), runtimeImpl});\n\n RuntimeTestInterface::t_activeRuntime = runtimeImpl;\n }\n\n return *RuntimeTestInterface::t_activeRuntime;\n}\n\n} \/\/ namespace roudi\n} \/\/ namespace iox\niox-#382 remove unnecessary nullopt check\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_posh\/internal\/roudi_environment\/runtime_test_interface.hpp\"\n#include \"iceoryx_posh\/runtime\/posh_runtime.hpp\"\n#include \"iceoryx_utils\/cxx\/helplets.hpp\"\n\nnamespace iox\n{\nnamespace roudi\n{\nusing runtime::PoshRuntime;\n\nthread_local PoshRuntime* RuntimeTestInterface::t_activeRuntime{nullptr};\nthread_local std::atomic RuntimeTestInterface::t_currentRouDiContext{0};\nstd::atomic RuntimeTestInterface::s_currentRouDiContext{0};\n\nstd::mutex RuntimeTestInterface::s_runtimeAccessMutex;\n\nstd::map RuntimeTestInterface::s_runtimes;\n\nRuntimeTestInterface::RuntimeTestInterface()\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n PoshRuntime::setRuntimeFactory(RuntimeTestInterface::runtimeFactoryGetInstance);\n}\n\nRuntimeTestInterface::~RuntimeTestInterface()\n{\n if (m_doCleanupOnDestruction)\n {\n \/\/ cleanup holds its own lock\n cleanupRuntimes();\n\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n PoshRuntime::setRuntimeFactory(PoshRuntime::defaultRuntimeFactory);\n }\n}\n\nRuntimeTestInterface::RuntimeTestInterface(RuntimeTestInterface&& rhs)\n{\n rhs.m_doCleanupOnDestruction = false;\n}\nRuntimeTestInterface& RuntimeTestInterface::operator=(RuntimeTestInterface&& rhs)\n{\n rhs.m_doCleanupOnDestruction = false;\n return *this;\n}\n\nvoid RuntimeTestInterface::cleanupRuntimes()\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n for (const auto& e : RuntimeTestInterface::s_runtimes)\n {\n delete e.second;\n }\n RuntimeTestInterface::s_runtimes.clear();\n RuntimeTestInterface::s_currentRouDiContext.operator++(std::memory_order_relaxed);\n}\n\nvoid RuntimeTestInterface::eraseRuntime(const ProcessName_t& name)\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n auto iter = RuntimeTestInterface::s_runtimes.find(name);\n if (iter != RuntimeTestInterface::s_runtimes.end())\n {\n delete iter->second;\n RuntimeTestInterface::s_runtimes.erase(name);\n }\n}\n\nPoshRuntime& RuntimeTestInterface::runtimeFactoryGetInstance(cxx::optional name)\n{\n std::lock_guard lock(RuntimeTestInterface::s_runtimeAccessMutex);\n\n auto currentRouDiContext = RuntimeTestInterface::s_currentRouDiContext.load(std::memory_order_relaxed);\n if (RuntimeTestInterface::t_currentRouDiContext.load(std::memory_order_relaxed) != currentRouDiContext)\n {\n RuntimeTestInterface::t_currentRouDiContext.store(currentRouDiContext, std::memory_order_relaxed);\n RuntimeTestInterface::t_activeRuntime = nullptr;\n }\n\n bool nameIsNullopt{!name.has_value()};\n bool invalidGetRuntimeAccess{RuntimeTestInterface::t_activeRuntime == nullptr && nameIsNullopt};\n cxx::Expects(!invalidGetRuntimeAccess);\n\n if (RuntimeTestInterface::t_activeRuntime != nullptr && nameIsNullopt)\n {\n return *RuntimeTestInterface::t_activeRuntime;\n }\n\n \/\/ if (nameIsNullopt)\n \/\/{\n \/\/ ProcessName_t* emptyName;\n \/\/ name.emplace(emptyName);\n \/\/}\n\n auto iter = RuntimeTestInterface::s_runtimes.find(*name.value());\n if (iter != RuntimeTestInterface::s_runtimes.end())\n {\n RuntimeTestInterface::t_activeRuntime = iter->second;\n }\n else\n {\n auto runtimeImpl = new runtime::PoshRuntime(name, false);\n RuntimeTestInterface::s_runtimes.insert({*name.value(), runtimeImpl});\n\n RuntimeTestInterface::t_activeRuntime = runtimeImpl;\n }\n\n return *RuntimeTestInterface::t_activeRuntime;\n}\n\n} \/\/ namespace roudi\n} \/\/ namespace iox\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \"posix-stack.hh\"\n#include \"net.hh\"\n#include \"packet.hh\"\n#include \"api.hh\"\n\nnamespace net {\n\nclass posix_connected_socket_impl final : public connected_socket_impl {\n pollable_fd _fd;\nprivate:\n explicit posix_connected_socket_impl(pollable_fd fd) : _fd(std::move(fd)) {}\npublic:\n virtual input_stream input() override { return input_stream(posix_data_source(_fd)); }\n virtual output_stream output() override { return output_stream(posix_data_sink(_fd), 8192); }\n friend class posix_server_socket_impl;\n friend class posix_ap_server_socket_impl;\n friend class posix_reuseport_server_socket_impl;\n friend class posix_network_stack;\n friend class posix_ap_network_stack;\n};\n\nfuture\nposix_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n static unsigned balance = 0;\n auto cpu = balance++ % smp::count;\n\n if (cpu == engine.cpu_id()) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(\n connected_socket(std::move(csi)), sa);\n } else {\n smp::submit_to(cpu, [this, fd = std::move(fd.get_file_desc()), sa] () mutable {\n posix_ap_server_socket_impl::move_connected_socket(_sa, pollable_fd(std::move(fd)), sa);\n });\n return accept();\n }\n });\n}\n\nfuture posix_ap_server_socket_impl::accept() {\n auto conni = conn_q.find(_sa.as_posix_sockaddr_in());\n if (conni != conn_q.end()) {\n connection c = std::move(conni->second);\n conn_q.erase(conni);\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(c.fd)));\n return make_ready_future(connected_socket(std::move(csi)), std::move(c.addr));\n } else {\n auto i = sockets.emplace(std::piecewise_construct, std::make_tuple(_sa.as_posix_sockaddr_in()), std::make_tuple());\n assert(i.second);\n return i.first->second.get_future();\n }\n}\n\nfuture\nposix_reuseport_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(\n connected_socket(std::move(csi)), sa);\n });\n}\n\nvoid posix_ap_server_socket_impl::move_connected_socket(socket_address sa, pollable_fd fd, socket_address addr) {\n auto i = sockets.find(sa.as_posix_sockaddr_in());\n if (i != sockets.end()) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n i->second.set_value(connected_socket(std::move(csi)), std::move(addr));\n sockets.erase(i);\n } else {\n conn_q.emplace(std::piecewise_construct, std::make_tuple(sa.as_posix_sockaddr_in()), std::make_tuple(std::move(fd), std::move(addr)));\n }\n}\n\ndata_source posix_data_source(pollable_fd& fd) {\n return data_source(std::make_unique(fd));\n}\n\nfuture>\nposix_data_source_impl::get() {\n return _fd.read_some(_buf.get_write(), _buf_size).then([this] (size_t size) {\n _buf.trim(size);\n auto ret = std::move(_buf);\n _buf = temporary_buffer(_buf_size);\n return make_ready_future>(std::move(ret));\n });\n}\n\ndata_sink posix_data_sink(pollable_fd& fd) {\n return data_sink(std::make_unique(fd));\n}\n\nstd::vector to_iovec(const packet& p) {\n std::vector v;\n v.reserve(p.nr_frags());\n for (auto&& f : p.fragments()) {\n v.push_back({.iov_base = f.base, .iov_len = f.size});\n }\n return v;\n}\n\nstd::vector to_iovec(std::vector>& buf_vec) {\n std::vector v;\n v.reserve(buf_vec.size());\n for (auto& buf : buf_vec) {\n v.push_back({.iov_base = buf.get_write(), .iov_len = buf.size()});\n }\n return v;\n}\n\nfuture<>\nposix_data_sink_impl::put(temporary_buffer buf) {\n return _fd.write_all(buf.get(), buf.size()).then([d = buf.release()] {});\n}\n\nfuture<>\nposix_data_sink_impl::put(packet p) {\n _p = std::move(p);\n return _fd.write_all(_p).then([this] { _p.reset(); });\n}\n\nserver_socket\nposix_network_stack::listen(socket_address sa, listen_options opt) {\n if (_reuseport)\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n else\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n}\n\nfuture\nposix_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(connected_socket(std::move(csi)));\n });\n}\n\nthread_local std::unordered_map<::sockaddr_in, promise> posix_ap_server_socket_impl::sockets;\nthread_local std::unordered_multimap<::sockaddr_in, posix_ap_server_socket_impl::connection> posix_ap_server_socket_impl::conn_q;\n\nserver_socket\nposix_ap_network_stack::listen(socket_address sa, listen_options opt) {\n if (_reuseport)\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n else\n return server_socket(std::make_unique(sa));\n}\n\nfuture\nposix_ap_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(connected_socket(std::move(csi)));\n });\n}\n\nstruct cmsg_with_pktinfo {\n struct cmsghdrcmh;\n struct in_pktinfo pktinfo;\n};\n\nclass posix_udp_channel : public udp_channel_impl {\nprivate:\n static constexpr int MAX_DATAGRAM_SIZE = 65507;\n struct recv_ctx {\n struct msghdr _hdr;\n struct iovec _iov;\n socket_address _src_addr;\n char* _buffer;\n cmsg_with_pktinfo _cmsg;\n\n recv_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_iov = &_iov;\n _hdr.msg_iovlen = 1;\n _hdr.msg_name = &_src_addr.u.sa;\n _hdr.msg_namelen = sizeof(_src_addr.u.sas);\n memset(&_cmsg, 0, sizeof(_cmsg));\n _hdr.msg_control = &_cmsg;\n _hdr.msg_controllen = sizeof(_cmsg);\n }\n\n void prepare() {\n _buffer = new char[MAX_DATAGRAM_SIZE];\n _iov.iov_base = _buffer;\n _iov.iov_len = MAX_DATAGRAM_SIZE;\n }\n };\n struct send_ctx {\n struct msghdr _hdr;\n std::vector _iovecs;\n socket_address _dst;\n packet _p;\n\n send_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_name = &_dst.u.sa;\n _hdr.msg_namelen = sizeof(_dst.u.sas);\n }\n\n void prepare(ipv4_addr dst, packet p) {\n _dst = make_ipv4_address(dst);\n _p = std::move(p);\n _iovecs = std::move(to_iovec(_p));\n _hdr.msg_iov = _iovecs.data();\n _hdr.msg_iovlen = _iovecs.size();\n }\n };\n std::unique_ptr _fd;\n ipv4_addr _address;\n recv_ctx _recv;\n send_ctx _send;\n bool _closed;\npublic:\n posix_udp_channel(ipv4_addr bind_address)\n : _closed(false) {\n auto sa = make_ipv4_address(bind_address);\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n fd.setsockopt(SOL_IP, IP_PKTINFO, true);\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n _address = ipv4_addr(fd.get_address());\n _fd = std::make_unique(std::move(fd));\n }\n virtual ~posix_udp_channel() {};\n virtual future receive() override;\n virtual future<> send(ipv4_addr dst, const char *msg);\n virtual future<> send(ipv4_addr dst, packet p);\n virtual void close() override {\n _closed = true;\n _fd.reset();\n }\n virtual bool is_closed() const override { return _closed; }\n};\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, const char *message) {\n auto len = strlen(message);\n return _fd->sendto(make_ipv4_address(dst), message, len)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, packet p) {\n auto len = p.len();\n _send.prepare(dst, std::move(p));\n return _fd->sendmsg(&_send._hdr)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nudp_channel\nposix_network_stack::make_udp_channel(ipv4_addr addr) {\n return udp_channel(std::make_unique(addr));\n}\n\nclass posix_datagram : public udp_datagram_impl {\nprivate:\n ipv4_addr _src;\n ipv4_addr _dst;\n packet _p;\npublic:\n posix_datagram(ipv4_addr src, ipv4_addr dst, packet p) : _src(src), _dst(dst), _p(std::move(p)) {}\n virtual ipv4_addr get_src() override { return _src; }\n virtual ipv4_addr get_dst() override { return _dst; }\n virtual uint16_t get_dst_port() override { return _dst.port; }\n virtual packet& get_data() override { return _p; }\n};\n\nfuture\nposix_udp_channel::receive() {\n _recv.prepare();\n return _fd->recvmsg(&_recv._hdr).then([this] (size_t size) {\n auto dst = ipv4_addr(_recv._cmsg.pktinfo.ipi_addr.s_addr, _address.port);\n return make_ready_future(udp_datagram(std::make_unique(\n _recv._src_addr, dst, packet(fragment{_recv._buffer, size}, [buf = _recv._buffer] { delete[] buf; }))));\n });\n}\n\nnetwork_stack_registrator nsr_posix{\"posix\",\n boost::program_options::options_description(),\n [](boost::program_options::variables_map ops) {\n return smp::main_thread() ? posix_network_stack::create(ops) : posix_ap_network_stack::create(ops);\n },\n true\n};\n\n}\nnet: implemented SO_REUSEPORT support on UDP\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#include \"posix-stack.hh\"\n#include \"net.hh\"\n#include \"packet.hh\"\n#include \"api.hh\"\n\nnamespace net {\n\nclass posix_connected_socket_impl final : public connected_socket_impl {\n pollable_fd _fd;\nprivate:\n explicit posix_connected_socket_impl(pollable_fd fd) : _fd(std::move(fd)) {}\npublic:\n virtual input_stream input() override { return input_stream(posix_data_source(_fd)); }\n virtual output_stream output() override { return output_stream(posix_data_sink(_fd), 8192); }\n friend class posix_server_socket_impl;\n friend class posix_ap_server_socket_impl;\n friend class posix_reuseport_server_socket_impl;\n friend class posix_network_stack;\n friend class posix_ap_network_stack;\n};\n\nfuture\nposix_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n static unsigned balance = 0;\n auto cpu = balance++ % smp::count;\n\n if (cpu == engine.cpu_id()) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(\n connected_socket(std::move(csi)), sa);\n } else {\n smp::submit_to(cpu, [this, fd = std::move(fd.get_file_desc()), sa] () mutable {\n posix_ap_server_socket_impl::move_connected_socket(_sa, pollable_fd(std::move(fd)), sa);\n });\n return accept();\n }\n });\n}\n\nfuture posix_ap_server_socket_impl::accept() {\n auto conni = conn_q.find(_sa.as_posix_sockaddr_in());\n if (conni != conn_q.end()) {\n connection c = std::move(conni->second);\n conn_q.erase(conni);\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(c.fd)));\n return make_ready_future(connected_socket(std::move(csi)), std::move(c.addr));\n } else {\n auto i = sockets.emplace(std::piecewise_construct, std::make_tuple(_sa.as_posix_sockaddr_in()), std::make_tuple());\n assert(i.second);\n return i.first->second.get_future();\n }\n}\n\nfuture\nposix_reuseport_server_socket_impl::accept() {\n return _lfd.accept().then([this] (pollable_fd fd, socket_address sa) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(\n connected_socket(std::move(csi)), sa);\n });\n}\n\nvoid posix_ap_server_socket_impl::move_connected_socket(socket_address sa, pollable_fd fd, socket_address addr) {\n auto i = sockets.find(sa.as_posix_sockaddr_in());\n if (i != sockets.end()) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n i->second.set_value(connected_socket(std::move(csi)), std::move(addr));\n sockets.erase(i);\n } else {\n conn_q.emplace(std::piecewise_construct, std::make_tuple(sa.as_posix_sockaddr_in()), std::make_tuple(std::move(fd), std::move(addr)));\n }\n}\n\ndata_source posix_data_source(pollable_fd& fd) {\n return data_source(std::make_unique(fd));\n}\n\nfuture>\nposix_data_source_impl::get() {\n return _fd.read_some(_buf.get_write(), _buf_size).then([this] (size_t size) {\n _buf.trim(size);\n auto ret = std::move(_buf);\n _buf = temporary_buffer(_buf_size);\n return make_ready_future>(std::move(ret));\n });\n}\n\ndata_sink posix_data_sink(pollable_fd& fd) {\n return data_sink(std::make_unique(fd));\n}\n\nstd::vector to_iovec(const packet& p) {\n std::vector v;\n v.reserve(p.nr_frags());\n for (auto&& f : p.fragments()) {\n v.push_back({.iov_base = f.base, .iov_len = f.size});\n }\n return v;\n}\n\nstd::vector to_iovec(std::vector>& buf_vec) {\n std::vector v;\n v.reserve(buf_vec.size());\n for (auto& buf : buf_vec) {\n v.push_back({.iov_base = buf.get_write(), .iov_len = buf.size()});\n }\n return v;\n}\n\nfuture<>\nposix_data_sink_impl::put(temporary_buffer buf) {\n return _fd.write_all(buf.get(), buf.size()).then([d = buf.release()] {});\n}\n\nfuture<>\nposix_data_sink_impl::put(packet p) {\n _p = std::move(p);\n return _fd.write_all(_p).then([this] { _p.reset(); });\n}\n\nserver_socket\nposix_network_stack::listen(socket_address sa, listen_options opt) {\n if (_reuseport)\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n else\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n}\n\nfuture\nposix_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(connected_socket(std::move(csi)));\n });\n}\n\nthread_local std::unordered_map<::sockaddr_in, promise> posix_ap_server_socket_impl::sockets;\nthread_local std::unordered_multimap<::sockaddr_in, posix_ap_server_socket_impl::connection> posix_ap_server_socket_impl::conn_q;\n\nserver_socket\nposix_ap_network_stack::listen(socket_address sa, listen_options opt) {\n if (_reuseport)\n return server_socket(std::make_unique(sa, engine.posix_listen(sa, opt)));\n else\n return server_socket(std::make_unique(sa));\n}\n\nfuture\nposix_ap_network_stack::connect(socket_address sa) {\n return engine.posix_connect(sa).then([] (pollable_fd fd) {\n std::unique_ptr csi(new posix_connected_socket_impl(std::move(fd)));\n return make_ready_future(connected_socket(std::move(csi)));\n });\n}\n\nstruct cmsg_with_pktinfo {\n struct cmsghdrcmh;\n struct in_pktinfo pktinfo;\n};\n\nclass posix_udp_channel : public udp_channel_impl {\nprivate:\n static constexpr int MAX_DATAGRAM_SIZE = 65507;\n struct recv_ctx {\n struct msghdr _hdr;\n struct iovec _iov;\n socket_address _src_addr;\n char* _buffer;\n cmsg_with_pktinfo _cmsg;\n\n recv_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_iov = &_iov;\n _hdr.msg_iovlen = 1;\n _hdr.msg_name = &_src_addr.u.sa;\n _hdr.msg_namelen = sizeof(_src_addr.u.sas);\n memset(&_cmsg, 0, sizeof(_cmsg));\n _hdr.msg_control = &_cmsg;\n _hdr.msg_controllen = sizeof(_cmsg);\n }\n\n void prepare() {\n _buffer = new char[MAX_DATAGRAM_SIZE];\n _iov.iov_base = _buffer;\n _iov.iov_len = MAX_DATAGRAM_SIZE;\n }\n };\n struct send_ctx {\n struct msghdr _hdr;\n std::vector _iovecs;\n socket_address _dst;\n packet _p;\n\n send_ctx() {\n memset(&_hdr, 0, sizeof(_hdr));\n _hdr.msg_name = &_dst.u.sa;\n _hdr.msg_namelen = sizeof(_dst.u.sas);\n }\n\n void prepare(ipv4_addr dst, packet p) {\n _dst = make_ipv4_address(dst);\n _p = std::move(p);\n _iovecs = std::move(to_iovec(_p));\n _hdr.msg_iov = _iovecs.data();\n _hdr.msg_iovlen = _iovecs.size();\n }\n };\n std::unique_ptr _fd;\n ipv4_addr _address;\n recv_ctx _recv;\n send_ctx _send;\n bool _closed;\npublic:\n posix_udp_channel(ipv4_addr bind_address)\n : _closed(false) {\n auto sa = make_ipv4_address(bind_address);\n file_desc fd = file_desc::socket(sa.u.sa.sa_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n fd.setsockopt(SOL_IP, IP_PKTINFO, true);\n if (engine.posix_reuseport_available()) {\n fd.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1);\n }\n fd.bind(sa.u.sa, sizeof(sa.u.sas));\n _address = ipv4_addr(fd.get_address());\n _fd = std::make_unique(std::move(fd));\n }\n virtual ~posix_udp_channel() {};\n virtual future receive() override;\n virtual future<> send(ipv4_addr dst, const char *msg);\n virtual future<> send(ipv4_addr dst, packet p);\n virtual void close() override {\n _closed = true;\n _fd.reset();\n }\n virtual bool is_closed() const override { return _closed; }\n};\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, const char *message) {\n auto len = strlen(message);\n return _fd->sendto(make_ipv4_address(dst), message, len)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nfuture<> posix_udp_channel::send(ipv4_addr dst, packet p) {\n auto len = p.len();\n _send.prepare(dst, std::move(p));\n return _fd->sendmsg(&_send._hdr)\n .then([len] (size_t size) { assert(size == len); });\n}\n\nudp_channel\nposix_network_stack::make_udp_channel(ipv4_addr addr) {\n return udp_channel(std::make_unique(addr));\n}\n\nclass posix_datagram : public udp_datagram_impl {\nprivate:\n ipv4_addr _src;\n ipv4_addr _dst;\n packet _p;\npublic:\n posix_datagram(ipv4_addr src, ipv4_addr dst, packet p) : _src(src), _dst(dst), _p(std::move(p)) {}\n virtual ipv4_addr get_src() override { return _src; }\n virtual ipv4_addr get_dst() override { return _dst; }\n virtual uint16_t get_dst_port() override { return _dst.port; }\n virtual packet& get_data() override { return _p; }\n};\n\nfuture\nposix_udp_channel::receive() {\n _recv.prepare();\n return _fd->recvmsg(&_recv._hdr).then([this] (size_t size) {\n auto dst = ipv4_addr(_recv._cmsg.pktinfo.ipi_addr.s_addr, _address.port);\n return make_ready_future(udp_datagram(std::make_unique(\n _recv._src_addr, dst, packet(fragment{_recv._buffer, size}, [buf = _recv._buffer] { delete[] buf; }))));\n });\n}\n\nnetwork_stack_registrator nsr_posix{\"posix\",\n boost::program_options::options_description(),\n [](boost::program_options::variables_map ops) {\n return smp::main_thread() ? posix_network_stack::create(ops) : posix_ap_network_stack::create(ops);\n },\n true\n};\n\n}\n<|endoftext|>"} {"text":"\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2020 Morwenn\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"distributions.h\"\n#include \"move_only.h\"\n\nTEMPLATE_TEST_CASE( \"test extended compatibility with LWG 3031\", \"[sorters]\",\n cppsort::block_sorter>,\n cppsort::default_sorter,\n cppsort::drop_merge_sorter,\n cppsort::grail_sorter<>,\n cppsort::heap_sorter,\n cppsort::insertion_sorter,\n cppsort::merge_insertion_sorter,\n cppsort::merge_sorter,\n cppsort::pdq_sorter,\n cppsort::poplar_sorter,\n cppsort::quick_merge_sorter,\n cppsort::quick_sorter,\n cppsort::selection_sorter,\n cppsort::smooth_sorter,\n cppsort::spin_sorter,\n cppsort::split_sorter,\n cppsort::std_sorter,\n cppsort::tim_sorter,\n cppsort::verge_sorter )\n{\n \/\/ LWG3031 allows algorithms taking a predicate to work correctly when\n \/\/ said predicate takes non-const references on either side as long as\n \/\/ it doesn't modify its parameters\n\n std::vector collection;\n collection.reserve(50);\n auto distribution = dist::shuffled{};\n distribution(std::back_inserter(collection), 0, 25);\n\n std::mt19937 engine(Catch::rngSeed());\n std::shuffle(std::begin(collection), std::end(collection), engine);\n\n auto sort = TestType{};\n sort(collection, [](const int& lhs, const int& rhs) { return lhs < rhs; });\n \/\/sort(collection, [](const int& lhs, int& rhs) { return lhs < rhs; });\n \/\/sort(collection, [](int& lhs, const int& rhs) { return lhs < rhs; });\n sort(collection, [](int& lhs, int& rhs) { return lhs < rhs; });\n CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );\n}\nCleanup every_sorter_non_const_compare test\/*\n * The MIT License (MIT)\n *\n * Copyright (c) 2020 Morwenn\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"distributions.h\"\n\nTEMPLATE_TEST_CASE( \"test extended compatibility with LWG 3031\", \"[sorters]\",\n cppsort::block_sorter>,\n cppsort::default_sorter,\n cppsort::drop_merge_sorter,\n cppsort::grail_sorter<>,\n cppsort::heap_sorter,\n cppsort::insertion_sorter,\n cppsort::merge_insertion_sorter,\n cppsort::merge_sorter,\n cppsort::pdq_sorter,\n cppsort::poplar_sorter,\n cppsort::quick_merge_sorter,\n cppsort::quick_sorter,\n cppsort::selection_sorter,\n cppsort::smooth_sorter,\n cppsort::spin_sorter,\n cppsort::split_sorter,\n cppsort::std_sorter,\n cppsort::tim_sorter,\n cppsort::verge_sorter )\n{\n \/\/ LWG3031 allows algorithms taking a predicate to work correctly when\n \/\/ said predicate takes non-const references on either side as long as\n \/\/ it doesn't modify its parameters\n\n std::vector collection;\n collection.reserve(50);\n auto distribution = dist::shuffled{};\n distribution(std::back_inserter(collection), 50, -25);\n\n TestType sorter;\n sorter(collection, [](int& lhs, int& rhs) { return lhs < rhs; });\n CHECK( std::is_sorted(std::begin(collection), std::end(collection)) );\n}\n<|endoftext|>"} {"text":"#include \"third_party\/nghttp2\/src\/lib\/includes\/nghttp2\/nghttp2.h\"\n#include \"http2\/adapter\/mock_nghttp2_callbacks.h\"\n#include \"http2\/adapter\/test_frame_sequence.h\"\n#include \"http2\/adapter\/test_utils.h\"\n#include \"common\/platform\/api\/quiche_test.h\"\n\nnamespace http2 {\nnamespace adapter {\nnamespace test {\nnamespace {\n\nusing testing::_;\n\nenum FrameType {\n DATA,\n HEADERS,\n PRIORITY,\n RST_STREAM,\n SETTINGS,\n PUSH_PROMISE,\n PING,\n GOAWAY,\n WINDOW_UPDATE,\n};\n\nnghttp2_option* GetOptions() {\n nghttp2_option* options;\n nghttp2_option_new(&options);\n \/\/ Set some common options for compatibility.\n nghttp2_option_set_no_closed_streams(options, 1);\n nghttp2_option_set_no_auto_window_update(options, 1);\n nghttp2_option_set_max_send_header_block_length(options, 0x2000000);\n nghttp2_option_set_max_outbound_ack(options, 10000);\n return options;\n}\n\n\/\/ Verifies nghttp2 behavior when acting as a client.\nTEST(Nghttp2ClientTest, ClientReceivesUnexpectedHeaders) {\n testing::StrictMock mock_callbacks;\n auto nghttp2_callbacks = MockNghttp2Callbacks::GetCallbacks();\n nghttp2_option* options = GetOptions();\n nghttp2_session* ptr;\n nghttp2_session_client_new2(&ptr, nghttp2_callbacks.get(), &mock_callbacks,\n options);\n\n auto client_session = MakeSessionPtr(ptr);\n\n const std::string initial_frames = TestFrameSequence()\n .ServerPreface()\n .Ping(42)\n .WindowUpdate(0, 1000)\n .Serialize();\n\n testing::InSequence seq;\n EXPECT_CALL(mock_callbacks, OnBeginFrame(HasFrameHeader(0, SETTINGS, 0)));\n EXPECT_CALL(mock_callbacks, OnFrameRecv(IsSettings(testing::IsEmpty())));\n EXPECT_CALL(mock_callbacks, OnBeginFrame(HasFrameHeader(0, PING, 0)));\n EXPECT_CALL(mock_callbacks, OnFrameRecv(IsPing(42)));\n EXPECT_CALL(mock_callbacks,\n OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, 0)));\n EXPECT_CALL(mock_callbacks, OnFrameRecv(IsWindowUpdate(1000)));\n\n nghttp2_session_mem_recv(client_session.get(),\n ToUint8Ptr(initial_frames.data()),\n initial_frames.size());\n\n const std::string unexpected_stream_frames =\n TestFrameSequence()\n .Headers(1,\n {{\":status\", \"200\"},\n {\"server\", \"my-fake-server\"},\n {\"date\", \"Tue, 6 Apr 2021 12:54:01 GMT\"}},\n \/*fin=*\/false)\n .Data(1, \"This is the response body.\")\n .RstStream(3, Http2ErrorCode::INTERNAL_ERROR)\n .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, \"calm down!!\")\n .Serialize();\n\n EXPECT_CALL(mock_callbacks, OnBeginFrame(HasFrameHeader(1, HEADERS, _)));\n EXPECT_CALL(mock_callbacks, OnInvalidFrameRecv(IsHeaders(1, _, _), _));\n \/\/ No events from the DATA, RST_STREAM or GOAWAY.\n\n nghttp2_session_mem_recv(client_session.get(),\n ToUint8Ptr(unexpected_stream_frames.data()),\n unexpected_stream_frames.size());\n\n nghttp2_option_del(options);\n}\n\n} \/\/ namespace\n} \/\/ namespace test\n} \/\/ namespace adapter\n} \/\/ namespace http2\nAdds a vanilla nghttp2 test case that submits a request to a client session.#include \"third_party\/nghttp2\/src\/lib\/includes\/nghttp2\/nghttp2.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"http2\/adapter\/mock_nghttp2_callbacks.h\"\n#include \"http2\/adapter\/nghttp2_util.h\"\n#include \"http2\/adapter\/test_frame_sequence.h\"\n#include \"http2\/adapter\/test_utils.h\"\n#include \"common\/platform\/api\/quiche_test.h\"\n\nnamespace http2 {\nnamespace adapter {\nnamespace test {\nnamespace {\n\nusing testing::_;\n\nenum FrameType {\n DATA,\n HEADERS,\n PRIORITY,\n RST_STREAM,\n SETTINGS,\n PUSH_PROMISE,\n PING,\n GOAWAY,\n WINDOW_UPDATE,\n};\n\nnghttp2_option* GetOptions() {\n nghttp2_option* options;\n nghttp2_option_new(&options);\n \/\/ Set some common options for compatibility.\n nghttp2_option_set_no_closed_streams(options, 1);\n nghttp2_option_set_no_auto_window_update(options, 1);\n nghttp2_option_set_max_send_header_block_length(options, 0x2000000);\n nghttp2_option_set_max_outbound_ack(options, 10000);\n return options;\n}\n\nclass TestDataSource {\n public:\n explicit TestDataSource(std::string data) : data_(std::move(data)) {}\n\n absl::string_view ReadNext(size_t size) {\n const size_t to_send = std::min(size, remaining_.size());\n auto ret = remaining_.substr(0, to_send);\n remaining_.remove_prefix(to_send);\n return ret;\n }\n\n size_t SelectPayloadLength(size_t max_length) {\n return std::min(max_length, remaining_.size());\n }\n\n bool empty() const { return remaining_.empty(); }\n\n private:\n const std::string data_;\n absl::string_view remaining_ = data_;\n};\n\nclass Nghttp2Test : public testing::Test {\n public:\n Nghttp2Test() : session_(MakeSessionPtr(nullptr)) {}\n\n void SetUp() override { InitializeSession(); }\n\n virtual Perspective GetPerspective() = 0;\n\n void InitializeSession() {\n auto nghttp2_callbacks = MockNghttp2Callbacks::GetCallbacks();\n nghttp2_option* options = GetOptions();\n nghttp2_session* ptr;\n if (GetPerspective() == Perspective::kClient) {\n nghttp2_session_client_new2(&ptr, nghttp2_callbacks.get(),\n &mock_callbacks_, options);\n } else {\n nghttp2_session_server_new2(&ptr, nghttp2_callbacks.get(),\n &mock_callbacks_, options);\n }\n nghttp2_option_del(options);\n\n \/\/ Sets up the Send() callback to append to |serialized_|.\n EXPECT_CALL(mock_callbacks_, Send(_, _, _))\n .WillRepeatedly([this](const uint8_t* data, size_t length, int flags) {\n absl::StrAppend(&serialized_, ToStringView(data, length));\n return length;\n });\n \/\/ Sets up the SendData() callback to fetch and append data from a\n \/\/ TestDataSource.\n EXPECT_CALL(mock_callbacks_, SendData(_, _, _, _))\n .WillRepeatedly([this](nghttp2_frame* frame, const uint8_t* framehd,\n size_t length, nghttp2_data_source* source) {\n QUICHE_LOG(INFO) << \"Appending frame header and \" << length\n << \" bytes of data\";\n auto* s = static_cast(source->ptr);\n absl::StrAppend(&serialized_, ToStringView(framehd, 9),\n s->ReadNext(length));\n return 0;\n });\n session_.reset(ptr);\n }\n\n testing::StrictMock mock_callbacks_;\n nghttp2_session_unique_ptr session_;\n std::string serialized_;\n};\n\nclass Nghttp2ClientTest : public Nghttp2Test {\n public:\n Perspective GetPerspective() override { return Perspective::kClient; }\n};\n\n\/\/ Verifies nghttp2 behavior when acting as a client.\nTEST_F(Nghttp2ClientTest, ClientReceivesUnexpectedHeaders) {\n const std::string initial_frames = TestFrameSequence()\n .ServerPreface()\n .Ping(42)\n .WindowUpdate(0, 1000)\n .Serialize();\n\n testing::InSequence seq;\n EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, SETTINGS, 0)));\n EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsSettings(testing::IsEmpty())));\n EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, PING, 0)));\n EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsPing(42)));\n EXPECT_CALL(mock_callbacks_,\n OnBeginFrame(HasFrameHeader(0, WINDOW_UPDATE, 0)));\n EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsWindowUpdate(1000)));\n\n ssize_t result = nghttp2_session_mem_recv(\n session_.get(), ToUint8Ptr(initial_frames.data()), initial_frames.size());\n ASSERT_EQ(result, initial_frames.size());\n\n const std::string unexpected_stream_frames =\n TestFrameSequence()\n .Headers(1,\n {{\":status\", \"200\"},\n {\"server\", \"my-fake-server\"},\n {\"date\", \"Tue, 6 Apr 2021 12:54:01 GMT\"}},\n \/*fin=*\/false)\n .Data(1, \"This is the response body.\")\n .RstStream(3, Http2ErrorCode::INTERNAL_ERROR)\n .GoAway(5, Http2ErrorCode::ENHANCE_YOUR_CALM, \"calm down!!\")\n .Serialize();\n\n EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(1, HEADERS, _)));\n EXPECT_CALL(mock_callbacks_, OnInvalidFrameRecv(IsHeaders(1, _, _), _));\n \/\/ No events from the DATA, RST_STREAM or GOAWAY.\n\n nghttp2_session_mem_recv(session_.get(),\n ToUint8Ptr(unexpected_stream_frames.data()),\n unexpected_stream_frames.size());\n}\n\n\/\/ Tests the request-sending behavior of nghttp2 when acting as a client.\nTEST_F(Nghttp2ClientTest, ClientSendsRequest) {\n int result = nghttp2_session_send(session_.get());\n ASSERT_EQ(result, 0);\n\n EXPECT_THAT(serialized_, testing::StrEq(spdy::kHttp2ConnectionHeaderPrefix));\n serialized_.clear();\n\n const std::string initial_frames =\n TestFrameSequence().ServerPreface().Serialize();\n testing::InSequence s;\n\n \/\/ Server preface (empty SETTINGS)\n EXPECT_CALL(mock_callbacks_, OnBeginFrame(HasFrameHeader(0, SETTINGS, 0)));\n EXPECT_CALL(mock_callbacks_, OnFrameRecv(IsSettings(testing::IsEmpty())));\n\n ssize_t recv_result = nghttp2_session_mem_recv(\n session_.get(), ToUint8Ptr(initial_frames.data()), initial_frames.size());\n EXPECT_EQ(initial_frames.size(), recv_result);\n\n \/\/ Client wants to send a SETTINGS ack.\n EXPECT_CALL(mock_callbacks_, BeforeFrameSend(IsSettings(testing::IsEmpty())));\n EXPECT_CALL(mock_callbacks_, OnFrameSend(IsSettings(testing::IsEmpty())));\n EXPECT_TRUE(nghttp2_session_want_write(session_.get()));\n result = nghttp2_session_send(session_.get());\n EXPECT_THAT(serialized_, EqualsFrames({spdy::SpdyFrameType::SETTINGS}));\n serialized_.clear();\n\n EXPECT_FALSE(nghttp2_session_want_write(session_.get()));\n\n \/\/ The following sets up the client request.\n std::vector> headers = {\n {\":method\", \"POST\"},\n {\":scheme\", \"http\"},\n {\":authority\", \"example.com\"},\n {\":path\", \"\/this\/is\/request\/one\"}};\n std::vector nvs;\n for (const auto& h : headers) {\n nvs.push_back({.name = ToUint8Ptr(h.first.data()),\n .value = ToUint8Ptr(h.second.data()),\n .namelen = h.first.size(),\n .valuelen = h.second.size()});\n }\n const absl::string_view kBody = \"This is an example request body.\";\n TestDataSource source{std::string(kBody)};\n nghttp2_data_provider provider{\n .source = {.ptr = &source},\n .read_callback = [](nghttp2_session*, int32_t, uint8_t*, size_t length,\n uint32_t* data_flags, nghttp2_data_source* source,\n void*) {\n auto* s = static_cast(source->ptr);\n const ssize_t ret = s->SelectPayloadLength(length);\n if (ret < length) {\n *data_flags |= NGHTTP2_DATA_FLAG_EOF;\n }\n *data_flags |= NGHTTP2_DATA_FLAG_NO_COPY;\n return ret;\n }};\n \/\/ After submitting the request, the client will want to write.\n int stream_id =\n nghttp2_submit_request(session_.get(), nullptr \/* pri_spec *\/, nvs.data(),\n nvs.size(), &provider, nullptr \/* stream_data *\/);\n EXPECT_GT(stream_id, 0);\n EXPECT_TRUE(nghttp2_session_want_write(session_.get()));\n\n \/\/ We expect that the client will want to write HEADERS, then DATA.\n EXPECT_CALL(mock_callbacks_, BeforeFrameSend(IsHeaders(stream_id, _, _)));\n EXPECT_CALL(mock_callbacks_, OnFrameSend(IsHeaders(stream_id, _, _)));\n EXPECT_CALL(mock_callbacks_, OnFrameSend(IsData(stream_id, kBody.size(), _)));\n nghttp2_session_send(session_.get());\n EXPECT_THAT(serialized_, EqualsFrames({spdy::SpdyFrameType::HEADERS,\n spdy::SpdyFrameType::DATA}));\n EXPECT_THAT(serialized_, testing::HasSubstr(kBody));\n\n \/\/ Once the request is flushed, the client no longer wants to write.\n EXPECT_FALSE(nghttp2_session_want_write(session_.get()));\n}\n\n} \/\/ namespace\n} \/\/ namespace test\n} \/\/ namespace adapter\n} \/\/ namespace http2\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008-2016 Juli Mallett. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#define\tEVENT_SYSTEM_WORKER_MAX\t\t8\n\nEventSystem::EventSystem(void)\n: td_(\"EventThread\"),\n poll_(),\n timeout_(),\n destroy_(),\n threads_(),\n interest_queue_mtx_(\"EventSystem::interest_queue\"),\n interest_queue_(),\n workers_()\n{ }\n\nAction *\nEventSystem::register_interest(const EventInterest& interest, SimpleCallback *cb)\n{\n\tScopedLock _(&interest_queue_mtx_);\n\tCallbackQueue *cbq = interest_queue_[interest];\n\tif (cbq == NULL) {\n\t\tcbq = new CallbackQueue();\n\t\tinterest_queue_[interest] = cbq;\n\t}\n\tAction *a = cbq->schedule(cb);\n\treturn (a);\n}\n\n\/*\n * Request an EventThread to submit work to.\n *\n * For now these are primarily for known long-running or demanding tasks,\n * and normal stff goes through the EventThread instead. Eventually, we\n * want something like this to be the norm, and to have categories for\n * them, so that we can increase locality of reference, or even have a\n * variety of strategies available so that we could ensure heterogenous\n * workloads to maximize parallelism.\n *\n * XXX All kinds of configuration and seatbelts needed here.\n *\n * For now we allow up to EVENT_SYSTEM_WORKER_MAX threads to be created.\n *\/\nCallbackScheduler *\nEventSystem::worker(void)\n{\n\tstatic unsigned wcnt;\n\n\tif (workers_.size() < EVENT_SYSTEM_WORKER_MAX) {\n\t\tCallbackThread *td = new CallbackThread(\"EventWorker\");\n\t\tworkers_.push_back(td);\n\n\t\tthread_wait(td);\n\n\t\treturn (td);\n\t}\n\n\tCallbackThread *td = workers_[wcnt];\n\twcnt = (wcnt + 1) % EVENT_SYSTEM_WORKER_MAX;\n\treturn (td);\n}\n\nvoid\nEventSystem::stop(void)\n{\n\t\/*\n\t * If we have been told to stop, fire all shutdown events.\n\t *\/\n\tinterest_queue_mtx_.lock();\n\tCallbackQueue *q = interest_queue_[EventInterestStop];\n\tif (q != NULL)\n\t\tinterest_queue_.erase(EventInterestStop);\n\tinterest_queue_mtx_.unlock();\n\tif (q != NULL && !q->empty()) {\n\t\tINFO(\"\/event\/system\") << \"Queueing stop handlers.\";\n\t\tq->drain();\n\t}\n\n\t\/*\n\t * Pass stop notification on to all threads.\n\t *\/\n\tstd::deque::const_iterator it;\n\tfor (it = threads_.begin(); it != threads_.end(); ++it) {\n\t\tThread *td = *it;\n\t\ttd->stop();\n\t}\n}\nLaunch worker threads on create.\/*\n * Copyright (c) 2008-2016 Juli Mallett. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#define\tEVENT_SYSTEM_WORKER_MAX\t\t8\n\nEventSystem::EventSystem(void)\n: td_(\"EventThread\"),\n poll_(),\n timeout_(),\n destroy_(),\n threads_(),\n interest_queue_mtx_(\"EventSystem::interest_queue\"),\n interest_queue_(),\n workers_()\n{ }\n\nAction *\nEventSystem::register_interest(const EventInterest& interest, SimpleCallback *cb)\n{\n\tScopedLock _(&interest_queue_mtx_);\n\tCallbackQueue *cbq = interest_queue_[interest];\n\tif (cbq == NULL) {\n\t\tcbq = new CallbackQueue();\n\t\tinterest_queue_[interest] = cbq;\n\t}\n\tAction *a = cbq->schedule(cb);\n\treturn (a);\n}\n\n\/*\n * Request an EventThread to submit work to.\n *\n * For now these are primarily for known long-running or demanding tasks,\n * and normal stff goes through the EventThread instead. Eventually, we\n * want something like this to be the norm, and to have categories for\n * them, so that we can increase locality of reference, or even have a\n * variety of strategies available so that we could ensure heterogenous\n * workloads to maximize parallelism.\n *\n * XXX All kinds of configuration and seatbelts needed here.\n *\n * For now we allow up to EVENT_SYSTEM_WORKER_MAX threads to be created.\n *\/\nCallbackScheduler *\nEventSystem::worker(void)\n{\n\tstatic unsigned wcnt;\n\n\tif (workers_.size() < EVENT_SYSTEM_WORKER_MAX) {\n\t\tCallbackThread *td = new CallbackThread(\"EventWorker\");\n\t\tworkers_.push_back(td);\n\n\t\ttd->start();\n\n\t\tthread_wait(td);\n\n\t\treturn (td);\n\t}\n\n\tCallbackThread *td = workers_[wcnt];\n\twcnt = (wcnt + 1) % EVENT_SYSTEM_WORKER_MAX;\n\treturn (td);\n}\n\nvoid\nEventSystem::stop(void)\n{\n\t\/*\n\t * If we have been told to stop, fire all shutdown events.\n\t *\/\n\tinterest_queue_mtx_.lock();\n\tCallbackQueue *q = interest_queue_[EventInterestStop];\n\tif (q != NULL)\n\t\tinterest_queue_.erase(EventInterestStop);\n\tinterest_queue_mtx_.unlock();\n\tif (q != NULL && !q->empty()) {\n\t\tINFO(\"\/event\/system\") << \"Queueing stop handlers.\";\n\t\tq->drain();\n\t}\n\n\t\/*\n\t * Pass stop notification on to all threads.\n\t *\/\n\tstd::deque::const_iterator it;\n\tfor (it = threads_.begin(); it != threads_.end(); ++it) {\n\t\tThread *td = *it;\n\t\ttd->stop();\n\t}\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \"includes.hpp\"\n\n#define TAGLIB_STATIC\n#include \n#include \n#include \n\nclass playlist : public Component, public FileDragAndDropTarget {\n struct playlistModel : public TableListBoxModel {\n\t\tbase::string paths, talbum, tartist, ttitle;\n\t\tstd::vector tyear, ttrack;\n\t\tstd::vector paths_i, talbum_i, tartist_i, ttitle_i;\n\n\t\tvoid init() {\n\t\t\tpaths_i.clear(); \/\/ this one first (getNumRows)\n\t\t\tpaths_i.push_back(0);\n\t\t\tpaths.clear();\n\t\t\ttalbum.clear();\n\t\t\ttartist.clear();\n\t\t\ttyear.clear();\n\t\t\tttitle.clear();\n\t\t\tttrack.clear();\n\t\t\ttalbum_i.clear();\n\t\t\ttalbum_i.push_back(0);\n\t\t\ttartist_i.clear();\n\t\t\ttartist_i.push_back(0);\n\t\t\tttitle_i.clear();\n\t\t\tttitle_i.push_back(0);\n\t\t}\n\n\t\tvoid addItem(const String &path) {\n\t\t\tpaths.append(path.toStdString());\n\t\t\tpaths_i.push_back(paths.size());\n\n\t\t\t\/\/ read tags from file\n\t\t\tTagLib::FileRef file(path.toRawUTF8());\n\t\t\tif (!file.isNull() && file.tag()) {\n\t\t\t\ttalbum.append(file.tag()->album().toCString());\n\t\t\t\ttartist.append(file.tag()->artist().toCString());\n\t\t\t\tttitle.append(file.tag()->title().toCString());\n\t\t\t\ttyear.push_back(file.tag()->year());\n\t\t\t\tttrack.push_back(file.tag()->track());\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttyear.push_back(0);\n\t\t\t\tttrack.push_back(0);\n\t\t\t}\n\t\t\ttalbum_i.push_back(talbum.size());\n\t\t\ttartist_i.push_back(tartist.size());\n\t\t\tttitle_i.push_back(ttitle.size());\n\t\t}\n\n\t\tbase::string getItemPath(size_t index) {\n\t\t\treturn base::string(paths.begin() + paths_i[index],\n\t\t\t\t\t\t\t\tpaths.begin() + paths_i[index + 1]);\n\t\t}\n\n\t\tuint getItemTrack(size_t index) {\n\t\t\treturn ttrack[index];\n\t\t}\n\n\t\tuint getItemYear(size_t index) {\n\t\t\treturn tyear[index];\n\t\t}\n\n\t\tbase::string getItemAlbum(size_t index) {\n\t\t\treturn base::string(talbum.begin() + talbum_i[index],\n\t\t\t\t\t\t\t\ttalbum.begin() + talbum_i[index + 1]);\n\t\t}\n\n\t\tbase::string getItemArtist(size_t index) {\n\t\t\treturn base::string(tartist.begin() + tartist_i[index],\n\t\t\t\t\t\t\t\ttartist.begin() + tartist_i[index + 1]);\n\t\t}\n\n\t\tbase::string getItemTitle(size_t index) {\n\t\t\treturn base::string(ttitle.begin() + ttitle_i[index],\n\t\t\t\t\t\t\t\tttitle.begin() + ttitle_i[index + 1]);\n\t\t}\n\n\t\t\/\/ GUI\n int getNumRows() override {\n return paths_i.size() - 1;\n }\n\n\t\t\/\/ This is overloaded from TableListBoxModel, and should fill in the background of the whole row\n\t\tvoid paintRowBackground(Graphics& g, int rowNumber, int \/*width*\/, int \/*height*\/, bool rowIsSelected) override {\n\t\t\tif (rowIsSelected)\n\t\t\t\tg.fillAll(Colours::lightblue);\n\t\t\telse if (rowNumber % 2)\n\t\t\t\tg.fillAll(Colour(0xffeeeeee));\n\t\t}\n\n\t\t\/\/ This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom\n\t\t\/\/ components.\n\t\tvoid paintCell(Graphics& g, int rowNumber, int columnId,\n\t\t\t\t\t\tint width, int height, bool \/*rowIsSelected*\/) override {\n\t\t\tg.setColour(Colours::black);\n\t\t\tg.setFont(height * 0.7f);\n\t\t\tif (columnId == 0)\n\t\t\t\tg.drawText(base::toStr(getItemTrack(rowNumber)), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 1)\n\t\t\t\tg.drawText(getItemAlbum(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 2)\n\t\t\t\tg.drawText(getItemArtist(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 3)\n\t\t\t\tg.drawText(getItemTitle(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 4)\n\t\t\t\tg.drawText(base::toStr(getItemYear(rowNumber)), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\tg.setColour(Colours::black.withAlpha(0.2f));\n\t\t\tg.fillRect(width - 1, 0, 1, height);\n\t\t}\n };\n\n\t\/\/ progress dialog\n\tclass progress : public ThreadWithProgressWindow {\n\t\tplaylistModel &m;\n\t\tStringArray files;\n\t\tstd::function onFinish;\n\tpublic:\n\t\tprogress(playlistModel &model, const StringArray &_files, std::function _onFinish)\n\t\t\t\t: ThreadWithProgressWindow(\"Importing music\", true, true),\n\t\t\t\t m(model), files(_files), onFinish(_onFinish) {\n\t\t\tsetStatusMessage(\"Importing music\");\n\t\t}\n\n\t\t\/\/ TODO: system codecs?\n\t\tbool isFileSupported(const String &fname) {\n\t\t\treturn fname.endsWith(\".mp3\")\n\t\t\t\t|| fname.endsWith(\".wav\")\n\t\t\t\t|| fname.endsWith(\".wma\")\n\t\t\t\t|| fname.endsWith(\".flac\")\n\t\t\t\t|| fname.endsWith(\".ogg\")\n\t\t\t\t|| fname.endsWith(\".ape\");\n\t\t}\n\n\t\tvoid run() override {\n\t\t\tsetProgress(-1.0);\n\t\t\tint nth = 0;\n\t\t\tfor (auto &fileName : files) {\n\t\t\t\tif (File(fileName).isDirectory()) {\n\t\t\t\t\t\/\/ recursively scan for files\n\t\t\t\t\tDirectoryIterator i(File(fileName), true, \"*.mp3;*.wav;*.wma;*.flac;*.ogg;*.ape\");\n\t\t\t\t\twhile (i.next()) {\n\t\t\t\t\t\tm.addItem(i.getFile().getFullPathName());\n\t\t\t\t\t\tif (nth++ == 50) {\n\t\t\t\t\t\t\tnth = 0;\n\t\t\t\t\t\t\tsetStatusMessage(i.getFile().getFullPathName());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ single file\n\t\t\t\t\tif (isFileSupported(fileName))\n\t\t\t\t\t\tm.addItem(fileName);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetStatusMessage(\"Done.\");\n\t\t}\n\n\t\tvoid threadComplete(bool\/* userPressedCancel*\/) override {\n\t\t\tonFinish();\n\t\t\tdelete this;\n\t\t}\n\t};\n\n TableListBox box;\n playlistModel model;\n JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);\n\npublic:\n playlist() : box(\"playlist-box\", nullptr) {\n\t\tmodel.init();\n\t\tbox.setModel(&model);\n\t\tbox.setMultipleSelectionEnabled(true);\n\t\tbox.getHeader().setStretchToFitActive(true);\n\t\taddAndMakeVisible(box);\n\n\t\tbox.getHeader().addColumn(\"track\", 0, 50, 20, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"album\", 1, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"artist\", 2, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"title\", 3, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"year\", 4, 70, 50, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.setMultipleSelectionEnabled(true);\n\t}\n\n void resized() override {\n\t\tbox.setBounds(getLocalBounds().reduced(0));\n\t}\n\n\tbool isInterestedInFileDrag(const StringArray& \/*files*\/) override {\n\t\treturn true;\n\t}\n\n\tvoid fileDragEnter(const StringArray& \/*files*\/, int \/*x*\/, int \/*y*\/) override {\n\t\trepaint();\n\t}\n\n\tvoid fileDragMove (const StringArray& \/*files*\/, int \/*x*\/, int \/*y*\/) override {}\n\n\tvoid fileDragExit (const StringArray& \/*files*\/) override {\n\t\trepaint();\n\t}\n\n\tvoid filesDropped (const StringArray& files, int \/*x*\/, int \/*y*\/) override {\n\t\t(new progress(model, files, [this](){\n\t\t\t\tbox.updateContent();\n\t\t\t\trepaint();\n\t\t\t}))->launchThread();\n\t}\n\n\tbase::string getSelectedRowString() {\n\t\treturn model.getItemPath(box.getSelectedRow());\n\t}\n\n\tbool store(const base::string &f) {\n\t\tbase::stream s;\n\t\ts.write(model.paths);\n\t\ts.write(model.talbum);\n\t\ts.write(model.tartist);\n\t\ts.write(model.ttitle);\n\t\ts.write(model.tyear);\n\t\ts.write(model.ttrack);\n\t\ts.write(model.paths_i);\n\t\ts.write(model.talbum_i);\n\t\ts.write(model.tartist_i);\n\t\ts.write(model.ttitle_i);\n\t\treturn base::fs::store(f, s);\n\t}\n\n\tbool load(const base::string &f) {\n\t\tbase::stream s = base::fs::load(f);\n\t\tbool result = s.read(model.paths) > 0\n\t\t\t&& s.read(model.talbum) > 0\n\t\t\t&& s.read(model.tartist) > 0\n\t\t\t&& s.read(model.ttitle) > 0\n\t\t\t&& s.read(model.tyear) > 0\n\t\t\t&& s.read(model.ttrack) > 0\n\t\t\t&& s.read(model.paths_i) > 0\n\t\t\t&& s.read(model.talbum_i) > 0\n\t\t\t&& s.read(model.tartist_i) > 0\n\t\t\t&& s.read(model.ttitle_i) > 0;\n\t\tbox.updateContent();\n\t\trepaint();\n\t\treturn result;\n\t}\n};\n+ custom tags serialization#pragma once\n#include \"includes.hpp\"\n\n#define TAGLIB_STATIC\n#include \n#include \n#include \n\nclass playlist : public Component, public FileDragAndDropTarget {\n struct playlistModel : public TableListBoxModel {\n\t\tbase::string paths, talbum, tartist, ttitle;\n\t\tstd::vector tyear, ttrack;\n\t\tstd::vector paths_i, talbum_i, tartist_i, ttitle_i;\n\n\t\t\/\/ persistent user defined tags map\n\t\tstd::map> tags;\n\n\t\tvoid init() {\n\t\t\tpaths_i.clear(); \/\/ this one first (getNumRows)\n\t\t\tpaths_i.push_back(0);\n\t\t\tpaths.clear();\n\t\t\ttalbum.clear();\n\t\t\ttartist.clear();\n\t\t\ttyear.clear();\n\t\t\tttitle.clear();\n\t\t\tttrack.clear();\n\t\t\ttalbum_i.clear();\n\t\t\ttalbum_i.push_back(0);\n\t\t\ttartist_i.clear();\n\t\t\ttartist_i.push_back(0);\n\t\t\tttitle_i.clear();\n\t\t\tttitle_i.push_back(0);\n\t\t}\n\n\t\tvoid addItem(const String &path) {\n\t\t\tpaths.append(path.toStdString());\n\t\t\tpaths_i.push_back(paths.size());\n\n\t\t\t\/\/ read tags from file\n\t\t\tTagLib::FileRef file(path.toRawUTF8());\n\t\t\tif (!file.isNull() && file.tag()) {\n\t\t\t\ttalbum.append(file.tag()->album().toCString());\n\t\t\t\ttartist.append(file.tag()->artist().toCString());\n\t\t\t\tttitle.append(file.tag()->title().toCString());\n\t\t\t\ttyear.push_back(file.tag()->year());\n\t\t\t\tttrack.push_back(file.tag()->track());\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttyear.push_back(0);\n\t\t\t\tttrack.push_back(0);\n\t\t\t}\n\t\t\ttalbum_i.push_back(talbum.size());\n\t\t\ttartist_i.push_back(tartist.size());\n\t\t\tttitle_i.push_back(ttitle.size());\n\t\t}\n\n\t\tbase::string getItemPath(size_t index) {\n\t\t\treturn base::string(paths.begin() + paths_i[index],\n\t\t\t\t\t\t\t\tpaths.begin() + paths_i[index + 1]);\n\t\t}\n\n\t\tuint getItemTrack(size_t index) {\n\t\t\treturn ttrack[index];\n\t\t}\n\n\t\tuint getItemYear(size_t index) {\n\t\t\treturn tyear[index];\n\t\t}\n\n\t\tbase::string getItemAlbum(size_t index) {\n\t\t\treturn base::string(talbum.begin() + talbum_i[index],\n\t\t\t\t\t\t\t\ttalbum.begin() + talbum_i[index + 1]);\n\t\t}\n\n\t\tbase::string getItemArtist(size_t index) {\n\t\t\treturn base::string(tartist.begin() + tartist_i[index],\n\t\t\t\t\t\t\t\ttartist.begin() + tartist_i[index + 1]);\n\t\t}\n\n\t\tbase::string getItemTitle(size_t index) {\n\t\t\treturn base::string(ttitle.begin() + ttitle_i[index],\n\t\t\t\t\t\t\t\tttitle.begin() + ttitle_i[index + 1]);\n\t\t}\n\n\t\t\/\/ GUI\n int getNumRows() override {\n return paths_i.size() - 1;\n }\n\n\t\t\/\/ This is overloaded from TableListBoxModel, and should fill in the background of the whole row\n\t\tvoid paintRowBackground(Graphics& g, int rowNumber, int \/*width*\/, int \/*height*\/, bool rowIsSelected) override {\n\t\t\tif (rowIsSelected)\n\t\t\t\tg.fillAll(Colours::lightblue);\n\t\t\telse if (rowNumber % 2)\n\t\t\t\tg.fillAll(Colour(0xffeeeeee));\n\t\t}\n\n\t\t\/\/ This is overloaded from TableListBoxModel, and must paint any cells that aren't using custom\n\t\t\/\/ components.\n\t\tvoid paintCell(Graphics& g, int rowNumber, int columnId,\n\t\t\t\t\t\tint width, int height, bool \/*rowIsSelected*\/) override {\n\t\t\tg.setColour(Colours::black);\n\t\t\tg.setFont(height * 0.7f);\n\t\t\tif (columnId == 0)\n\t\t\t\tg.drawText(base::toStr(getItemTrack(rowNumber)), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 1)\n\t\t\t\tg.drawText(getItemAlbum(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 2)\n\t\t\t\tg.drawText(getItemArtist(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 3)\n\t\t\t\tg.drawText(getItemTitle(rowNumber), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\telse if (columnId == 4)\n\t\t\t\tg.drawText(base::toStr(getItemYear(rowNumber)), 5, 0, width, height, Justification::centredLeft, true);\n\t\t\tg.setColour(Colours::black.withAlpha(0.2f));\n\t\t\tg.fillRect(width - 1, 0, 1, height);\n\t\t}\n };\n\n\t\/\/ progress dialog\n\tclass progress : public ThreadWithProgressWindow {\n\t\tplaylistModel &m;\n\t\tStringArray files;\n\t\tstd::function onFinish;\n\tpublic:\n\t\tprogress(playlistModel &model, const StringArray &_files, std::function _onFinish)\n\t\t\t\t: ThreadWithProgressWindow(\"Importing music\", true, true),\n\t\t\t\t m(model), files(_files), onFinish(_onFinish) {\n\t\t\tsetStatusMessage(\"Importing music\");\n\t\t}\n\n\t\t\/\/ TODO: system codecs?\n\t\tbool isFileSupported(const String &fname) {\n\t\t\treturn fname.endsWith(\".mp3\")\n\t\t\t\t|| fname.endsWith(\".wav\")\n\t\t\t\t|| fname.endsWith(\".wma\")\n\t\t\t\t|| fname.endsWith(\".flac\")\n\t\t\t\t|| fname.endsWith(\".ogg\")\n\t\t\t\t|| fname.endsWith(\".ape\");\n\t\t}\n\n\t\tvoid run() override {\n\t\t\tsetProgress(-1.0);\n\t\t\tint nth = 0;\n\t\t\tfor (auto &fileName : files) {\n\t\t\t\tif (File(fileName).isDirectory()) {\n\t\t\t\t\t\/\/ recursively scan for files\n\t\t\t\t\tDirectoryIterator i(File(fileName), true, \"*.mp3;*.wav;*.wma;*.flac;*.ogg;*.ape\");\n\t\t\t\t\twhile (i.next()) {\n\t\t\t\t\t\tm.addItem(i.getFile().getFullPathName());\n\t\t\t\t\t\tif (nth++ == 50) {\n\t\t\t\t\t\t\tnth = 0;\n\t\t\t\t\t\t\tsetStatusMessage(i.getFile().getFullPathName());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ single file\n\t\t\t\t\tif (isFileSupported(fileName))\n\t\t\t\t\t\tm.addItem(fileName);\n\t\t\t\t}\n\t\t\t}\n\t\t\tsetStatusMessage(\"Done.\");\n\t\t}\n\n\t\tvoid threadComplete(bool\/* userPressedCancel*\/) override {\n\t\t\tonFinish();\n\t\t\tdelete this;\n\t\t}\n\t};\n\n TableListBox box;\n playlistModel model;\n JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(playlist);\n\npublic:\n playlist() : box(\"playlist-box\", nullptr) {\n\t\tmodel.init();\n\t\tbox.setModel(&model);\n\t\tbox.setMultipleSelectionEnabled(true);\n\t\tbox.getHeader().setStretchToFitActive(true);\n\t\taddAndMakeVisible(box);\n\n\t\tbox.getHeader().addColumn(\"track\", 0, 50, 20, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"album\", 1, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"artist\", 2, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"title\", 3, 200, 150, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.getHeader().addColumn(\"year\", 4, 70, 50, 1000, TableHeaderComponent::defaultFlags);\n\t\tbox.setMultipleSelectionEnabled(true);\n\t}\n\n void resized() override {\n\t\tbox.setBounds(getLocalBounds().reduced(0));\n\t}\n\n\tbool isInterestedInFileDrag(const StringArray& \/*files*\/) override {\n\t\treturn true;\n\t}\n\n\tvoid fileDragEnter(const StringArray& \/*files*\/, int \/*x*\/, int \/*y*\/) override {\n\t\trepaint();\n\t}\n\n\tvoid fileDragMove (const StringArray& \/*files*\/, int \/*x*\/, int \/*y*\/) override {}\n\n\tvoid fileDragExit (const StringArray& \/*files*\/) override {\n\t\trepaint();\n\t}\n\n\tvoid filesDropped (const StringArray& files, int \/*x*\/, int \/*y*\/) override {\n\t\t(new progress(model, files, [this](){\n\t\t\t\tbox.updateContent();\n\t\t\t\trepaint();\n\t\t\t}))->launchThread();\n\t}\n\n\tbase::string getSelectedRowString() {\n\t\treturn model.getItemPath(box.getSelectedRow());\n\t}\n\n\tbool store(const base::string &f) {\n\t\tbase::stream s;\n\t\ts.write(model.paths);\n\t\ts.write(model.talbum);\n\t\ts.write(model.tartist);\n\t\ts.write(model.ttitle);\n\t\ts.write(model.tyear);\n\t\ts.write(model.ttrack);\n\t\ts.write(model.paths_i);\n\t\ts.write(model.talbum_i);\n\t\ts.write(model.tartist_i);\n\t\ts.write(model.ttitle_i);\n\t\treturn base::fs::store(f, s);\n\t}\n\n\tbool load(const base::string &f) {\n\t\tbase::stream s = base::fs::load(f);\n\t\tbool result = s.read(model.paths) > 0\n\t\t\t&& s.read(model.talbum) > 0\n\t\t\t&& s.read(model.tartist) > 0\n\t\t\t&& s.read(model.ttitle) > 0\n\t\t\t&& s.read(model.tyear) > 0\n\t\t\t&& s.read(model.ttrack) > 0\n\t\t\t&& s.read(model.paths_i) > 0\n\t\t\t&& s.read(model.talbum_i) > 0\n\t\t\t&& s.read(model.tartist_i) > 0\n\t\t\t&& s.read(model.ttitle_i) > 0;\n\t\tbox.updateContent();\n\t\trepaint();\n\t\treturn result;\n\t}\n\n\tbool storeTags(const base::string &f) {\n\t\tbase::stream s;\n\t\ts.write((uint32)model.tags.size());\n\t\tfor (const auto &e : model.tags) {\n\t\t\ts.write(e.first);\n\t\t\t\/\/ TODO: write returns \/ estimate size \/ write documentation on writing vectors?\n\t\t\ts.write(sizeof(uint32) + sizeof(base::cell) * e.second.size());\n\t\t\ts.write(e.second);\n\t\t}\n\t\treturn base::fs::store(f, s);\n\t}\n\n\tbool loadTags(const base::string &f) {\n\t\tmodel.tags.clear();\n\t\tbase::stream s = base::fs::load(f);\n\t\tuint32 mapSize;\n\t\tif (s.read(mapSize) == 0)\n\t\t\treturn false;\n\t\tfor (uint32 i = 0; i < mapSize; ++i) {\n\t\t\tbase::string key;\n\t\t\tif (s.read(key) == 0)\n\t\t\t\treturn false;\n\t\t\tauto &c = model.tags[key];\n\t\t\tuint32 cellsSize;\n\t\t\tif (s.read(cellsSize) == 0)\n\t\t\t\treturn false;\n\t\t\tif (s.read(c) != cellsSize)\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n};\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"generator\/internal\/metadata_decorator_generator.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"generator\/internal\/codegen_utils.h\"\n#include \"generator\/internal\/predicate_utils.h\"\n#include \"generator\/internal\/printer.h\"\n#include \n\nnamespace google {\nnamespace cloud {\nnamespace generator_internal {\n\nMetadataDecoratorGenerator::MetadataDecoratorGenerator(\n google::protobuf::ServiceDescriptor const* service_descriptor,\n VarsDictionary service_vars,\n std::map service_method_vars,\n google::protobuf::compiler::GeneratorContext* context)\n : ServiceCodeGenerator(\"metadata_header_path\", \"metadata_cc_path\",\n service_descriptor, std::move(service_vars),\n std::move(service_method_vars), context) {}\n\nStatus MetadataDecoratorGenerator::GenerateHeader() {\n HeaderPrint(CopyrightLicenseFileHeader());\n HeaderPrint( \/\/ clang-format off\n \"\\n\"\n \"\/\/ Generated by the Codegen C++ plugin.\\n\"\n \"\/\/ If you make any local changes, they will be lost.\\n\"\n \"\/\/ source: $proto_file_name$\\n\"\n \"\\n\"\n \"#ifndef $header_include_guard$\\n\"\n \"#define $header_include_guard$\\n\");\n \/\/ clang-format on\n\n \/\/ includes\n HeaderPrint(\"\\n\");\n HeaderLocalIncludes({vars(\"stub_header_path\"), \"google\/cloud\/version.h\"});\n HeaderSystemIncludes(\n {HasLongrunningMethod() ? \"google\/longrunning\/operations.grpc.pb.h\" : \"\",\n \"memory\", \"string\"});\n\n auto result = HeaderOpenNamespaces(NamespaceType::kInternal);\n if (!result.ok()) return result;\n\n \/\/ metadata decorator class\n HeaderPrint( \/\/ clang-format off\n \"\\n\"\n \"class $metadata_class_name$ : public $stub_class_name$ {\\n\"\n \" public:\\n\"\n \" ~$metadata_class_name$() override = default;\\n\"\n \" explicit $metadata_class_name$(std::shared_ptr<$stub_class_name$> child);\\n\");\n \/\/ clang-format on\n\n for (auto const& method : methods()) {\n if (IsStreamingWrite(method)) {\n HeaderPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\n std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<\n $request_type$,\n $response_type$>>\n $method_name$(\n std::unique_ptr context) override;\n)\"\"\");\n continue;\n }\n if (IsBidirStreaming(method)) {\n HeaderPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\n std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<\n $request_type$,\n $response_type$>>\n Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context) override;\n)\"\"\");\n continue;\n }\n HeaderPrintMethod(\n method,\n {MethodPattern({{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\n Status $method_name$(\\n\",\n \"\\n StatusOr<$response_type$> $method_name$(\\n\"},\n {\" grpc::ClientContext& context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n And(IsNonStreaming, Not(IsLongrunningOperation))),\n MethodPattern({{R\"\"\"(\n future> Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) override;\n)\"\"\"}},\n IsLongrunningOperation),\n MethodPattern(\n { \/\/ clang-format off\n {\"\\n\"\n \" std::unique_ptr>\\n\"\n \" $method_name$(\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n IsStreamingRead)},\n __FILE__, __LINE__);\n }\n\n for (auto const& method : async_methods()) {\n if (IsStreamingRead(method)) {\n auto constexpr kDeclaration = R\"\"\"(\n std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<\n $response_type$>>\n Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context,\n $request_type$ const& request) override;\n)\"\"\";\n HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);\n continue;\n }\n HeaderPrintMethod(\n method,\n {MethodPattern(\n {{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\n future Async$method_name$(\\n\",\n \"\\n future> Async$method_name$(\\n\"},\n {\" google::cloud::CompletionQueue& cq,\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n And(IsNonStreaming, Not(IsLongrunningOperation)))},\n __FILE__, __LINE__);\n }\n\n if (HasLongrunningMethod()) {\n HeaderPrint(\n R\"\"\"(\n future> AsyncGetOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::GetOperationRequest const& request) override;\n\n future AsyncCancelOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::CancelOperationRequest const& request) override;\n)\"\"\");\n }\n\n HeaderPrint(R\"\"\"(\n private:\n void SetMetadata(grpc::ClientContext& context,\n std::string const& request_params);\n void SetMetadata(grpc::ClientContext& context);\n\n std::shared_ptr<$stub_class_name$> child_;\n std::string api_client_header_;\n};\n)\"\"\");\n\n HeaderCloseNamespaces();\n \/\/ close header guard\n HeaderPrint(\"\\n#endif \/\/ $header_include_guard$\\n\");\n return {};\n}\n\nStatus MetadataDecoratorGenerator::GenerateCc() {\n CcPrint(CopyrightLicenseFileHeader());\n CcPrint( \/\/ clang-format off\n \"\\n\"\n \"\/\/ Generated by the Codegen C++ plugin.\\n\"\n \"\/\/ If you make any local changes, they will be lost.\\n\"\n \"\/\/ source: $proto_file_name$\\n\");\n \/\/ clang-format on\n\n \/\/ includes\n CcPrint(\"\\n\");\n CcLocalIncludes({vars(\"metadata_header_path\"),\n \"google\/cloud\/internal\/api_client_header.h\",\n \"google\/cloud\/common_options.h\",\n \"google\/cloud\/status_or.h\"});\n CcSystemIncludes({vars(\"proto_grpc_header_path\"), \"memory\"});\n\n auto result = CcOpenNamespaces(NamespaceType::kInternal);\n if (!result.ok()) return result;\n\n \/\/ constructor\n CcPrint( \/\/ clang-format off\n \"\\n\"\n \"$metadata_class_name$::$metadata_class_name$(\\n\"\n \" std::shared_ptr<$stub_class_name$> child)\\n\"\n \" : child_(std::move(child)),\\n\"\n \" api_client_header_(google::cloud::internal::ApiClientHeader(\\\"generator\\\")) {}\\n\");\n \/\/ clang-format on\n\n \/\/ metadata decorator class member methods\n for (auto const& method : methods()) {\n if (IsStreamingWrite(method)) {\n CcPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\nstd::unique_ptr<::google::cloud::internal::StreamingWriteRpc<\n $request_type$,\n $response_type$>>\n$metadata_class_name$::$method_name$(\n std::unique_ptr context) {\n SetMetadata(*context);\n return child_->$method_name$(std::move(context));\n}\n)\"\"\");\n continue;\n }\n if (IsBidirStreaming(method)) {\n CcPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\nstd::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<\n $request_type$,\n $response_type$>>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context) {\n SetMetadata(*context);\n return child_->Async$method_name$(cq, std::move(context));\n}\n)\"\"\");\n continue;\n }\n CcPrintMethod(\n method,\n {MethodPattern(\n {\n {IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\nStatus\\n\",\n \"\\nStatusOr<$response_type$>\\n\"},\n {\"$metadata_class_name$::$method_name$(\\n\"\n \" grpc::ClientContext& context,\\n\"\n \" $request_type$ const& request) {\\n\"},\n {HasRoutingHeader,\n \" SetMetadata(context, \\\"$method_request_param_key$=\\\" + request.$method_request_param_value$);\\n\",\n \" SetMetadata(context, {});\\n\"},\n {\" return child_->$method_name$(context, request);\\n\"\n \"}\\n\",}\n \/\/ clang-format on\n },\n And(IsNonStreaming, Not(IsLongrunningOperation))),\n MethodPattern({{HasRoutingHeader,\n R\"\"\"(\nfuture>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n SetMetadata(*context, \"$method_request_param_key$=\" + request.$method_request_param_value$);\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\",\n R\"\"\"(\nfuture>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n SetMetadata(*context, {});\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\"}},\n IsLongrunningOperation),\n MethodPattern(\n {\n \/\/ clang-format off\n {\"\\n\"\n \"std::unique_ptr>\\n\"\n \"$metadata_class_name$::$method_name$(\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) {\\n\"},\n {HasRoutingHeader,\n \" SetMetadata(*context, \\\"$method_request_param_key$=\\\" + request.$method_request_param_value$);\\n\",\n \" SetMetadata(*context, {});\\n\"},\n {\" return child_->$method_name$(std::move(context), request);\\n\"\n \"}\\n\",}\n \/\/ clang-format on\n },\n IsStreamingRead)},\n __FILE__, __LINE__);\n }\n\n for (auto const& method : async_methods()) {\n if (IsStreamingRead(method)) {\n auto constexpr kDefinition = R\"\"\"(\nstd::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<\n $response_type$>>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n SetMetadata(*context);\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\";\n CcPrintMethod(method, __FILE__, __LINE__, kDefinition);\n continue;\n }\n CcPrintMethod(\n method,\n {MethodPattern(\n {{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\nfuture\\n\",\n \"\\nfuture>\\n\"},\n {R\"\"\"($metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {)\"\"\"},\n {HasRoutingHeader, R\"\"\"(\n SetMetadata(*context, \"$method_request_param_key$=\" + request.$method_request_param_value$);)\"\"\",\n R\"\"\"(\n SetMetadata(*context, {});)\"\"\"}, {R\"\"\"(\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\"}},\n \/\/ clang-format on\n And(IsNonStreaming, Not(IsLongrunningOperation)))},\n __FILE__, __LINE__);\n }\n\n \/\/ long running operation support methods\n if (HasLongrunningMethod()) {\n CcPrint(R\"\"\"(\nfuture>\n$metadata_class_name$::AsyncGetOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::GetOperationRequest const& request) {\n SetMetadata(*context, \"name=\" + request.name());\n return child_->AsyncGetOperation(cq, std::move(context), request);\n}\n\nfuture $metadata_class_name$::AsyncCancelOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::CancelOperationRequest const& request) {\n SetMetadata(*context, \"name=\" + request.name());\n return child_->AsyncCancelOperation(cq, std::move(context), request);\n}\n)\"\"\");\n }\n\n CcPrint(R\"\"\"(\nvoid $metadata_class_name$::SetMetadata(grpc::ClientContext& context,\n std::string const& request_params) {\n context.AddMetadata(\"x-goog-request-params\", request_params);\n SetMetadata(context);\n}\n\nvoid $metadata_class_name$::SetMetadata(grpc::ClientContext& context) {\n context.AddMetadata(\"x-goog-api-client\", api_client_header_);\n auto const& options = internal::CurrentOptions();\n if (options.has()) {\n context.AddMetadata(\n \"x-goog-user-project\", options.get());\n }\n auto const& authority = options.get();\n if (!authority.empty()) context.set_authority(authority);\n}\n)\"\"\");\n\n CcCloseNamespaces();\n return {};\n}\n\n} \/\/ namespace generator_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\nfix(generator): async streaming read MD respects routing header (#8962)\/\/ Copyright 2020 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"generator\/internal\/metadata_decorator_generator.h\"\n#include \"google\/cloud\/internal\/absl_str_cat_quiet.h\"\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_split.h\"\n#include \"generator\/internal\/codegen_utils.h\"\n#include \"generator\/internal\/predicate_utils.h\"\n#include \"generator\/internal\/printer.h\"\n#include \n\nnamespace google {\nnamespace cloud {\nnamespace generator_internal {\n\nMetadataDecoratorGenerator::MetadataDecoratorGenerator(\n google::protobuf::ServiceDescriptor const* service_descriptor,\n VarsDictionary service_vars,\n std::map service_method_vars,\n google::protobuf::compiler::GeneratorContext* context)\n : ServiceCodeGenerator(\"metadata_header_path\", \"metadata_cc_path\",\n service_descriptor, std::move(service_vars),\n std::move(service_method_vars), context) {}\n\nStatus MetadataDecoratorGenerator::GenerateHeader() {\n HeaderPrint(CopyrightLicenseFileHeader());\n HeaderPrint( \/\/ clang-format off\n \"\\n\"\n \"\/\/ Generated by the Codegen C++ plugin.\\n\"\n \"\/\/ If you make any local changes, they will be lost.\\n\"\n \"\/\/ source: $proto_file_name$\\n\"\n \"\\n\"\n \"#ifndef $header_include_guard$\\n\"\n \"#define $header_include_guard$\\n\");\n \/\/ clang-format on\n\n \/\/ includes\n HeaderPrint(\"\\n\");\n HeaderLocalIncludes({vars(\"stub_header_path\"), \"google\/cloud\/version.h\"});\n HeaderSystemIncludes(\n {HasLongrunningMethod() ? \"google\/longrunning\/operations.grpc.pb.h\" : \"\",\n \"memory\", \"string\"});\n\n auto result = HeaderOpenNamespaces(NamespaceType::kInternal);\n if (!result.ok()) return result;\n\n \/\/ metadata decorator class\n HeaderPrint( \/\/ clang-format off\n \"\\n\"\n \"class $metadata_class_name$ : public $stub_class_name$ {\\n\"\n \" public:\\n\"\n \" ~$metadata_class_name$() override = default;\\n\"\n \" explicit $metadata_class_name$(std::shared_ptr<$stub_class_name$> child);\\n\");\n \/\/ clang-format on\n\n for (auto const& method : methods()) {\n if (IsStreamingWrite(method)) {\n HeaderPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\n std::unique_ptr<::google::cloud::internal::StreamingWriteRpc<\n $request_type$,\n $response_type$>>\n $method_name$(\n std::unique_ptr context) override;\n)\"\"\");\n continue;\n }\n if (IsBidirStreaming(method)) {\n HeaderPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\n std::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<\n $request_type$,\n $response_type$>>\n Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context) override;\n)\"\"\");\n continue;\n }\n HeaderPrintMethod(\n method,\n {MethodPattern({{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\n Status $method_name$(\\n\",\n \"\\n StatusOr<$response_type$> $method_name$(\\n\"},\n {\" grpc::ClientContext& context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n And(IsNonStreaming, Not(IsLongrunningOperation))),\n MethodPattern({{R\"\"\"(\n future> Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) override;\n)\"\"\"}},\n IsLongrunningOperation),\n MethodPattern(\n { \/\/ clang-format off\n {\"\\n\"\n \" std::unique_ptr>\\n\"\n \" $method_name$(\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n IsStreamingRead)},\n __FILE__, __LINE__);\n }\n\n for (auto const& method : async_methods()) {\n if (IsStreamingRead(method)) {\n auto constexpr kDeclaration = R\"\"\"(\n std::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<\n $response_type$>>\n Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context,\n $request_type$ const& request) override;\n)\"\"\";\n HeaderPrintMethod(method, __FILE__, __LINE__, kDeclaration);\n continue;\n }\n HeaderPrintMethod(\n method,\n {MethodPattern(\n {{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\n future Async$method_name$(\\n\",\n \"\\n future> Async$method_name$(\\n\"},\n {\" google::cloud::CompletionQueue& cq,\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) override;\\n\"\n \/\/ clang-format on\n }},\n And(IsNonStreaming, Not(IsLongrunningOperation)))},\n __FILE__, __LINE__);\n }\n\n if (HasLongrunningMethod()) {\n HeaderPrint(\n R\"\"\"(\n future> AsyncGetOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::GetOperationRequest const& request) override;\n\n future AsyncCancelOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::CancelOperationRequest const& request) override;\n)\"\"\");\n }\n\n HeaderPrint(R\"\"\"(\n private:\n void SetMetadata(grpc::ClientContext& context,\n std::string const& request_params);\n void SetMetadata(grpc::ClientContext& context);\n\n std::shared_ptr<$stub_class_name$> child_;\n std::string api_client_header_;\n};\n)\"\"\");\n\n HeaderCloseNamespaces();\n \/\/ close header guard\n HeaderPrint(\"\\n#endif \/\/ $header_include_guard$\\n\");\n return {};\n}\n\nStatus MetadataDecoratorGenerator::GenerateCc() {\n CcPrint(CopyrightLicenseFileHeader());\n CcPrint( \/\/ clang-format off\n \"\\n\"\n \"\/\/ Generated by the Codegen C++ plugin.\\n\"\n \"\/\/ If you make any local changes, they will be lost.\\n\"\n \"\/\/ source: $proto_file_name$\\n\");\n \/\/ clang-format on\n\n \/\/ includes\n CcPrint(\"\\n\");\n CcLocalIncludes({vars(\"metadata_header_path\"),\n \"google\/cloud\/internal\/api_client_header.h\",\n \"google\/cloud\/common_options.h\",\n \"google\/cloud\/status_or.h\"});\n CcSystemIncludes({vars(\"proto_grpc_header_path\"), \"memory\"});\n\n auto result = CcOpenNamespaces(NamespaceType::kInternal);\n if (!result.ok()) return result;\n\n \/\/ constructor\n CcPrint( \/\/ clang-format off\n \"\\n\"\n \"$metadata_class_name$::$metadata_class_name$(\\n\"\n \" std::shared_ptr<$stub_class_name$> child)\\n\"\n \" : child_(std::move(child)),\\n\"\n \" api_client_header_(google::cloud::internal::ApiClientHeader(\\\"generator\\\")) {}\\n\");\n \/\/ clang-format on\n\n \/\/ metadata decorator class member methods\n for (auto const& method : methods()) {\n if (IsStreamingWrite(method)) {\n CcPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\nstd::unique_ptr<::google::cloud::internal::StreamingWriteRpc<\n $request_type$,\n $response_type$>>\n$metadata_class_name$::$method_name$(\n std::unique_ptr context) {\n SetMetadata(*context);\n return child_->$method_name$(std::move(context));\n}\n)\"\"\");\n continue;\n }\n if (IsBidirStreaming(method)) {\n CcPrintMethod(method, __FILE__, __LINE__,\n R\"\"\"(\nstd::unique_ptr<::google::cloud::AsyncStreamingReadWriteRpc<\n $request_type$,\n $response_type$>>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context) {\n SetMetadata(*context);\n return child_->Async$method_name$(cq, std::move(context));\n}\n)\"\"\");\n continue;\n }\n CcPrintMethod(\n method,\n {MethodPattern(\n {\n {IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\nStatus\\n\",\n \"\\nStatusOr<$response_type$>\\n\"},\n {\"$metadata_class_name$::$method_name$(\\n\"\n \" grpc::ClientContext& context,\\n\"\n \" $request_type$ const& request) {\\n\"},\n {HasRoutingHeader,\n \" SetMetadata(context, \\\"$method_request_param_key$=\\\" + request.$method_request_param_value$);\\n\",\n \" SetMetadata(context, {});\\n\"},\n {\" return child_->$method_name$(context, request);\\n\"\n \"}\\n\",}\n \/\/ clang-format on\n },\n And(IsNonStreaming, Not(IsLongrunningOperation))),\n MethodPattern({{HasRoutingHeader,\n R\"\"\"(\nfuture>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n SetMetadata(*context, \"$method_request_param_key$=\" + request.$method_request_param_value$);\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\",\n R\"\"\"(\nfuture>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n SetMetadata(*context, {});\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\"}},\n IsLongrunningOperation),\n MethodPattern(\n {\n \/\/ clang-format off\n {\"\\n\"\n \"std::unique_ptr>\\n\"\n \"$metadata_class_name$::$method_name$(\\n\"\n \" std::unique_ptr context,\\n\"\n \" $request_type$ const& request) {\\n\"},\n {HasRoutingHeader,\n \" SetMetadata(*context, \\\"$method_request_param_key$=\\\" + request.$method_request_param_value$);\\n\",\n \" SetMetadata(*context, {});\\n\"},\n {\" return child_->$method_name$(std::move(context), request);\\n\"\n \"}\\n\",}\n \/\/ clang-format on\n },\n IsStreamingRead)},\n __FILE__, __LINE__);\n }\n\n for (auto const& method : async_methods()) {\n if (IsStreamingRead(method)) {\n auto const definition = absl::StrCat(\n R\"\"\"(\nstd::unique_ptr<::google::cloud::internal::AsyncStreamingReadRpc<\n $response_type$>>\n$metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue const& cq,\n std::unique_ptr context,\n $request_type$ const& request) {\n)\"\"\", \/\/ clang-format off\n HasRoutingHeader(method) ?\n\" SetMetadata(*context, \\\"$method_request_param_key$=\\\" + request.$method_request_param_value$);\" :\n\" SetMetadata(*context);\", \/\/ clang-format-on\n R\"\"\"(\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\");\n CcPrintMethod(method, __FILE__, __LINE__, definition);\n continue;\n }\n CcPrintMethod(\n method,\n {MethodPattern(\n {{IsResponseTypeEmpty,\n \/\/ clang-format off\n \"\\nfuture\\n\",\n \"\\nfuture>\\n\"},\n {R\"\"\"($metadata_class_name$::Async$method_name$(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n $request_type$ const& request) {)\"\"\"},\n {HasRoutingHeader, R\"\"\"(\n SetMetadata(*context, \"$method_request_param_key$=\" + request.$method_request_param_value$);)\"\"\",\n R\"\"\"(\n SetMetadata(*context, {});)\"\"\"}, {R\"\"\"(\n return child_->Async$method_name$(cq, std::move(context), request);\n}\n)\"\"\"}},\n \/\/ clang-format on\n And(IsNonStreaming, Not(IsLongrunningOperation)))},\n __FILE__, __LINE__);\n }\n\n \/\/ long running operation support methods\n if (HasLongrunningMethod()) {\n CcPrint(R\"\"\"(\nfuture>\n$metadata_class_name$::AsyncGetOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::GetOperationRequest const& request) {\n SetMetadata(*context, \"name=\" + request.name());\n return child_->AsyncGetOperation(cq, std::move(context), request);\n}\n\nfuture $metadata_class_name$::AsyncCancelOperation(\n google::cloud::CompletionQueue& cq,\n std::unique_ptr context,\n google::longrunning::CancelOperationRequest const& request) {\n SetMetadata(*context, \"name=\" + request.name());\n return child_->AsyncCancelOperation(cq, std::move(context), request);\n}\n)\"\"\");\n }\n\n CcPrint(R\"\"\"(\nvoid $metadata_class_name$::SetMetadata(grpc::ClientContext& context,\n std::string const& request_params) {\n context.AddMetadata(\"x-goog-request-params\", request_params);\n SetMetadata(context);\n}\n\nvoid $metadata_class_name$::SetMetadata(grpc::ClientContext& context) {\n context.AddMetadata(\"x-goog-api-client\", api_client_header_);\n auto const& options = internal::CurrentOptions();\n if (options.has()) {\n context.AddMetadata(\n \"x-goog-user-project\", options.get());\n }\n auto const& authority = options.get();\n if (!authority.empty()) context.set_authority(authority);\n}\n)\"\"\");\n\n CcCloseNamespaces();\n return {};\n}\n\n} \/\/ namespace generator_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"\/\/ bdldfp_decimalconvertutil.cpp -*-C++-*-\n#include \n\n#include \nBSLS_IDENT_RCSID(bdldfp_decimalconvertutil_cpp,\"$Id$ $CSID$\")\n\n#include \n\n#include \n\n#ifdef BDLDFP_DECIMALPLATFORM_C99_TR\n# ifndef __STDC_WANT_DEC_FP__\n# error __STDC_WANT_DEC_FP__ must be defined on the command line!\n char die[-42]; \/\/ if '#error' unsupported\n# endif\n#endif\n\n#include \n#include \n#include \n\nnamespace BloombergLP {\nnamespace bdldfp {\n\nnamespace {\n \/\/ Reverse Memory\n\nstatic void memrev(void *buffer, size_t count)\n \/\/ Reverse the order of the first specified 'count' bytes, at the beginning\n \/\/ of the specified 'buffer'. 'count % 2' must be zero.\n{\n unsigned char *b = static_cast(buffer);\n bsl::reverse(b, b + count);\n}\n\n \/\/ Mem copy with reversal functions\n\nunsigned char *memReverseIfNeeded(void *buffer, size_t count)\n \/\/ Reverse the first specified 'count' bytes from the specified 'buffer`,\n \/\/ if the host endian is different from network endian, and return the\n \/\/ address computed from 'static_cast(buffer) + count'.\n{\n#ifdef BDLDFP_DECIMALPLATFORM_LITTLE_ENDIAN\n \/\/ little endian, needs to do some byte juggling\n memrev(buffer, count);\n#endif\n return static_cast(buffer) + count;\n}\n\n \/\/ Decimal-network conversion functions\n\ntemplate \nconst unsigned char *decimalFromNetworkT(DECIMAL_TYPE *decimal,\n const unsigned char *buffer)\n \/\/ Construct into the specified 'decimal', the base-10 value represented by\n \/\/ the network-ordered bytes in the specified 'buffer', and return a raw\n \/\/ memory pointer, providing modifiable access, to one byte past the last\n \/\/ byte read from 'buffer'.\n{\n bsl::memcpy(decimal, buffer, sizeof(DECIMAL_TYPE));\n memReverseIfNeeded(decimal, sizeof(DECIMAL_TYPE));\n\n DecimalConvertUtil::decimalFromDPD(\n decimal,\n reinterpret_cast(decimal));\n\n return buffer + sizeof(DECIMAL_TYPE);\n}\n\n\ntemplate \nunsigned char *decimalToNetworkT(unsigned char *buffer, DECIMAL_TYPE decimal)\n \/\/ Construct into the specified 'buffer', the network-ordered byte\n \/\/ representation of the base-10 value of the specified 'decimal', and,\n \/\/ return a raw memory pointer, providing modifiable access, to one byte\n \/\/ past the last written byte of the 'buffer'.\n{\n DecimalConvertUtil::decimalToDPD(buffer, decimal);\n return memReverseIfNeeded(buffer, sizeof(DECIMAL_TYPE));\n}\n\n \/\/ =================\n \/\/ class StdioFormat\n \/\/ =================\n\ntemplate struct StdioFormat;\n \/\/ This 'struct' template provides a method, 'format', that returns a\n \/\/ 'printf'-style format string to format values of the template parameter\n \/\/ type 'FORMATTED_TYPE' that can be used to restore a decimal value that\n \/\/ was previously converted to this type.\n\ntemplate <>\nstruct StdioFormat {\n \/\/ This template specialization of 'StdioFormat' provides a function that\n \/\/ returns a 'printf'-style format string for 'float' values.\n\n static const char* format();\n \/\/ Return a 'printf'-style format string that can be used to restore a\n \/\/ decimal value that was previously converted to a 'float' value.\n \/\/ Refer to the documentation of 'decimalFromFloat' for the conversion\n \/\/ rules.\n};\n\ntemplate <>\nstruct StdioFormat {\n \/\/ This template specialization of 'StdioFormat' provides a function that\n \/\/ returns a 'printf'-style format string for 'double' values.\n\n static char const* format();\n \/\/ Return a 'printf'-style format string that can be used to restore a\n \/\/ decimal value that was previously converted to a 'double' value.\n \/\/ Refer to the documentation of 'decimalFromDouble' for the conversion\n \/\/ rules.\n};\n\n \/\/ -----------------\n \/\/ class StdioFormat\n \/\/ -----------------\n\nconst char* StdioFormat::format()\n{\n return \"%.6g\";\n}\n\nconst char* StdioFormat::format()\n{\n return \"%.15g\";\n}\n\n \/\/ ===================\n \/\/ class DecimalTraits\n \/\/ ===================\n\ntemplate struct DecimalTraits;\n \/\/ This 'struct' template provides a way to create an object of the\n \/\/ template parameter type 'DECIMAL_TYPE' though a consistent interface.\n\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides functions to\n \/\/ create 'Decimal32' values.\n\n typedef int SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal32'.\n\n static Decimal32 make(int significand, int exponent);\n \/\/ Return a 'Decimal32' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n};\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides utilities to\n \/\/ create 'Decimal64' values.\n\n typedef long long SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal64'.\n\n static Decimal64 make(long long significand, int exponent);\n \/\/ Return a 'Decimal64' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n\n};\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides utilities to\n \/\/ create 'Decimal128' values.\n\n typedef long long SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal128' if it's small enough to be convertible\n \/\/ to a double.\n\n static bdldfp::Decimal128 make(long long significand, int exponent);\n \/\/ Return a 'Decimal128' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n};\n\n \/\/ ===================\n \/\/ class DecimalTraits\n \/\/ ===================\n\nDecimal32 DecimalTraits::make(int significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw32(significand, exponent);\n}\n\nDecimal64 DecimalTraits::make(long long significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw64(significand, exponent);\n}\n\nDecimal128 DecimalTraits::make(long long significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw128(significand, exponent);\n}\n\n \/\/ Helpers for Restoring Decimal from Binary\n\ntemplate \nvoid restoreDecimalFromBinary(DECIMAL_TYPE *dfp, BINARY_TYPE bfp)\n \/\/ Construct, in the specified 'dfp', a decimal floating point\n \/\/ representation of the value of the binary floating point value specified\n \/\/ by 'bfp'.\n{\n\n if (bfp != bfp) {\n *dfp = bsl::numeric_limits::quiet_NaN();\n if (bfp < 0) {\n *dfp = -*dfp;\n }\n return; \/\/ RETURN\n }\n\n if (bfp == bsl::numeric_limits::infinity()) {\n *dfp = bsl::numeric_limits::infinity();\n return; \/\/ RETURN\n }\n\n if (bfp == -bsl::numeric_limits::infinity()) {\n *dfp = -bsl::numeric_limits::infinity();\n return; \/\/ RETURN\n }\n\n char buffer[48];\n snprintf(buffer, sizeof(buffer), StdioFormat::format(), bfp);\n\n typename DecimalTraits::SignificandType significand(0);\n int exponent(0);\n bool negative(false);\n\n char const* it(buffer);\n if (*it == '-') {\n negative = true;\n ++it;\n }\n for (; bsl::isdigit(static_cast(*it)); ++it) {\n significand = significand * 10 + (*it - '0');\n }\n if (*it == '.') {\n ++it;\n for (; bsl::isdigit(static_cast(*it)); ++it) {\n significand = significand * 10 + (*it - '0');\n --exponent;\n }\n }\n if (*it == 'e' || *it == 'E') {\n ++it;\n exponent += bsl::atoi(it);\n }\n\n *dfp = DecimalTraits::make(significand, exponent);\n\n \/\/ Because the significand is a signed integer, it can not represent the\n \/\/ value -0, which distinct from +0 in decimal floating point. So instead\n \/\/ of converting the significand to a signed value, we change the decimal\n \/\/ value based on the sign appropriately after the decimal value is\n \/\/ created.\n\n if (negative) {\n *dfp = -(*dfp);\n }\n}\n\n} \/\/ close unnamed namespace\n\n \/\/ Network format converters\n\n\/\/ Note that we do not use platform or bslsl supported converters because they\n\/\/ work in terms of integers, so they would probably bleed out on the\n\/\/ strict-aliasing rules. We may solve that later on using the \"union trick\"\n\/\/ and delegating to 'bsls_byteorder', but for now let's take it slow.\n\n \/\/ Conversion to Network functions\n\nunsigned char *DecimalConvertUtil::decimal32ToNetwork(unsigned char *buffer,\n Decimal32 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimal64ToNetwork(unsigned char *buffer,\n Decimal64 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimal128ToNetwork(unsigned char *buffer,\n Decimal128 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal32 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal64 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal128 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\n \/\/ Conversion to Network functions\n\nconst unsigned char *DecimalConvertUtil::decimal32FromNetwork(\n Decimal32 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimal64FromNetwork(\n Decimal64 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimal128FromNetwork(\n Decimal128 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal32 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal64 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal128 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\n \/\/ Restore a Decimal Floating-Point from a Binary\n\n\n \/\/ DecimalFromDouble functions\n\nDecimal32 DecimalConvertUtil::decimal32FromDouble(double binary)\n{\n Decimal32 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal64 DecimalConvertUtil::decimal64FromDouble(double binary)\n{\n Decimal64 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal128 DecimalConvertUtil::decimal128FromDouble(double binary)\n{\n Decimal128 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\n\n \/\/ DecimalFromFloat functions\n\nDecimal32 DecimalConvertUtil::decimal32FromFloat(float binary)\n{\n Decimal32 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal64 DecimalConvertUtil::decimal64FromFloat(float binary)\n{\n Decimal64 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal128 DecimalConvertUtil::decimal128FromFloat(float binary)\n{\n Decimal128 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\n\n} \/\/ close package namespace\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2014 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n[APPROVAL] INTERNAL pending\/master\/windows-build-failures-drqs-63540529 to master\/\/ bdldfp_decimalconvertutil.cpp -*-C++-*-\n#include \n\n#include \nBSLS_IDENT_RCSID(bdldfp_decimalconvertutil_cpp,\"$Id$ $CSID$\")\n\n#include \n\n#include \n\n#ifdef BDLDFP_DECIMALPLATFORM_C99_TR\n# ifndef __STDC_WANT_DEC_FP__\n# error __STDC_WANT_DEC_FP__ must be defined on the command line!\n char die[-42]; \/\/ if '#error' unsupported\n# endif\n#endif\n\n#include \n#include \n#include \n#include \n\nnamespace BloombergLP {\nnamespace bdldfp {\n\nnamespace {\n \/\/ Reverse Memory\n\nstatic void memrev(void *buffer, size_t count)\n \/\/ Reverse the order of the first specified 'count' bytes, at the beginning\n \/\/ of the specified 'buffer'. 'count % 2' must be zero.\n{\n unsigned char *b = static_cast(buffer);\n bsl::reverse(b, b + count);\n}\n\n \/\/ Mem copy with reversal functions\n\nunsigned char *memReverseIfNeeded(void *buffer, size_t count)\n \/\/ Reverse the first specified 'count' bytes from the specified 'buffer`,\n \/\/ if the host endian is different from network endian, and return the\n \/\/ address computed from 'static_cast(buffer) + count'.\n{\n#ifdef BDLDFP_DECIMALPLATFORM_LITTLE_ENDIAN\n \/\/ little endian, needs to do some byte juggling\n memrev(buffer, count);\n#endif\n return static_cast(buffer) + count;\n}\n\n \/\/ Decimal-network conversion functions\n\ntemplate \nconst unsigned char *decimalFromNetworkT(DECIMAL_TYPE *decimal,\n const unsigned char *buffer)\n \/\/ Construct into the specified 'decimal', the base-10 value represented by\n \/\/ the network-ordered bytes in the specified 'buffer', and return a raw\n \/\/ memory pointer, providing modifiable access, to one byte past the last\n \/\/ byte read from 'buffer'.\n{\n bsl::memcpy(decimal, buffer, sizeof(DECIMAL_TYPE));\n memReverseIfNeeded(decimal, sizeof(DECIMAL_TYPE));\n\n DecimalConvertUtil::decimalFromDPD(\n decimal,\n reinterpret_cast(decimal));\n\n return buffer + sizeof(DECIMAL_TYPE);\n}\n\n\ntemplate \nunsigned char *decimalToNetworkT(unsigned char *buffer, DECIMAL_TYPE decimal)\n \/\/ Construct into the specified 'buffer', the network-ordered byte\n \/\/ representation of the base-10 value of the specified 'decimal', and,\n \/\/ return a raw memory pointer, providing modifiable access, to one byte\n \/\/ past the last written byte of the 'buffer'.\n{\n DecimalConvertUtil::decimalToDPD(buffer, decimal);\n return memReverseIfNeeded(buffer, sizeof(DECIMAL_TYPE));\n}\n\n \/\/ =================\n \/\/ class StdioFormat\n \/\/ =================\n\ntemplate struct StdioFormat;\n \/\/ This 'struct' template provides a method, 'format', that returns a\n \/\/ 'printf'-style format string to format values of the template parameter\n \/\/ type 'FORMATTED_TYPE' that can be used to restore a decimal value that\n \/\/ was previously converted to this type.\n\ntemplate <>\nstruct StdioFormat {\n \/\/ This template specialization of 'StdioFormat' provides a function that\n \/\/ returns a 'printf'-style format string for 'float' values.\n\n static const char* format();\n \/\/ Return a 'printf'-style format string that can be used to restore a\n \/\/ decimal value that was previously converted to a 'float' value.\n \/\/ Refer to the documentation of 'decimalFromFloat' for the conversion\n \/\/ rules.\n};\n\ntemplate <>\nstruct StdioFormat {\n \/\/ This template specialization of 'StdioFormat' provides a function that\n \/\/ returns a 'printf'-style format string for 'double' values.\n\n static char const* format();\n \/\/ Return a 'printf'-style format string that can be used to restore a\n \/\/ decimal value that was previously converted to a 'double' value.\n \/\/ Refer to the documentation of 'decimalFromDouble' for the conversion\n \/\/ rules.\n};\n\n \/\/ -----------------\n \/\/ class StdioFormat\n \/\/ -----------------\n\nconst char* StdioFormat::format()\n{\n return \"%.6g\";\n}\n\nconst char* StdioFormat::format()\n{\n return \"%.15g\";\n}\n\n \/\/ ===================\n \/\/ class DecimalTraits\n \/\/ ===================\n\ntemplate struct DecimalTraits;\n \/\/ This 'struct' template provides a way to create an object of the\n \/\/ template parameter type 'DECIMAL_TYPE' though a consistent interface.\n\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides functions to\n \/\/ create 'Decimal32' values.\n\n typedef int SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal32'.\n\n static Decimal32 make(int significand, int exponent);\n \/\/ Return a 'Decimal32' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n};\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides utilities to\n \/\/ create 'Decimal64' values.\n\n typedef long long SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal64'.\n\n static Decimal64 make(long long significand, int exponent);\n \/\/ Return a 'Decimal64' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n\n};\n\ntemplate <>\nstruct DecimalTraits {\n \/\/ This template specialization of 'DecimalTraits' provides utilities to\n \/\/ create 'Decimal128' values.\n\n typedef long long SignificandType;\n \/\/ This 'typedef' defines a type that is large enough to hold the\n \/\/ significant of 'Decimal128' if it's small enough to be convertible\n \/\/ to a double.\n\n static bdldfp::Decimal128 make(long long significand, int exponent);\n \/\/ Return a 'Decimal128' value having the specified 'significand' and\n \/\/ the specified 'exponent'.\n};\n\n \/\/ ===================\n \/\/ class DecimalTraits\n \/\/ ===================\n\nDecimal32 DecimalTraits::make(int significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw32(significand, exponent);\n}\n\nDecimal64 DecimalTraits::make(long long significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw64(significand, exponent);\n}\n\nDecimal128 DecimalTraits::make(long long significand, int exponent)\n{\n return bdldfp::DecimalUtil::makeDecimalRaw128(significand, exponent);\n}\n\n \/\/ Helpers for Restoring Decimal from Binary\n\ntemplate \nvoid restoreDecimalFromBinary(DECIMAL_TYPE *dfp, BINARY_TYPE bfp)\n \/\/ Construct, in the specified 'dfp', a decimal floating point\n \/\/ representation of the value of the binary floating point value specified\n \/\/ by 'bfp'.\n{\n\n if (bfp != bfp) {\n *dfp = bsl::numeric_limits::quiet_NaN();\n if (bfp < 0) {\n *dfp = -*dfp;\n }\n return; \/\/ RETURN\n }\n\n if (bfp == bsl::numeric_limits::infinity()) {\n *dfp = bsl::numeric_limits::infinity();\n return; \/\/ RETURN\n }\n\n if (bfp == -bsl::numeric_limits::infinity()) {\n *dfp = -bsl::numeric_limits::infinity();\n return; \/\/ RETURN\n }\n\n#ifdef BSLS_PLATFORM_OS_WINDOWS\n# define snprintf _snprintf\n#endif\n char buffer[48];\n int rc = snprintf(buffer, sizeof(buffer), StdioFormat::format(), bfp);\n (void)rc;\n BSLS_ASSERT(0 <= rc && rc < sizeof(buffer)); \n \n typename DecimalTraits::SignificandType significand(0);\n int exponent(0);\n bool negative(false);\n\n char const* it(buffer);\n if (*it == '-') {\n negative = true;\n ++it;\n }\n for (; isdigit(static_cast(*it)); ++it) {\n significand = significand * 10 + (*it - '0');\n }\n if (*it == '.') {\n ++it;\n for (; isdigit(static_cast(*it)); ++it) {\n significand = significand * 10 + (*it - '0');\n --exponent;\n }\n }\n if (*it == 'e' || *it == 'E') {\n ++it;\n exponent += bsl::atoi(it);\n }\n\n *dfp = DecimalTraits::make(significand, exponent);\n\n \/\/ Because the significand is a signed integer, it can not represent the\n \/\/ value -0, which distinct from +0 in decimal floating point. So instead\n \/\/ of converting the significand to a signed value, we change the decimal\n \/\/ value based on the sign appropriately after the decimal value is\n \/\/ created.\n\n if (negative) {\n *dfp = -(*dfp);\n }\n}\n\n} \/\/ close unnamed namespace\n\n \/\/ Network format converters\n\n\/\/ Note that we do not use platform or bslsl supported converters because they\n\/\/ work in terms of integers, so they would probably bleed out on the\n\/\/ strict-aliasing rules. We may solve that later on using the \"union trick\"\n\/\/ and delegating to 'bsls_byteorder', but for now let's take it slow.\n\n \/\/ Conversion to Network functions\n\nunsigned char *DecimalConvertUtil::decimal32ToNetwork(unsigned char *buffer,\n Decimal32 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimal64ToNetwork(unsigned char *buffer,\n Decimal64 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimal128ToNetwork(unsigned char *buffer,\n Decimal128 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal32 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal64 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\nunsigned char *DecimalConvertUtil::decimalToNetwork(unsigned char *buffer,\n Decimal128 decimal)\n{\n BSLS_ASSERT(buffer != 0);\n return decimalToNetworkT(buffer, decimal);\n}\n\n \/\/ Conversion to Network functions\n\nconst unsigned char *DecimalConvertUtil::decimal32FromNetwork(\n Decimal32 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimal64FromNetwork(\n Decimal64 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimal128FromNetwork(\n Decimal128 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal32 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal64 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\nconst unsigned char *DecimalConvertUtil::decimalFromNetwork(\n Decimal128 *decimal,\n const unsigned char *buffer)\n{\n BSLS_ASSERT(decimal != 0);\n return decimalFromNetworkT(decimal, buffer);\n}\n\n \/\/ Restore a Decimal Floating-Point from a Binary\n\n\n \/\/ DecimalFromDouble functions\n\nDecimal32 DecimalConvertUtil::decimal32FromDouble(double binary)\n{\n Decimal32 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal64 DecimalConvertUtil::decimal64FromDouble(double binary)\n{\n Decimal64 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal128 DecimalConvertUtil::decimal128FromDouble(double binary)\n{\n Decimal128 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\n\n \/\/ DecimalFromFloat functions\n\nDecimal32 DecimalConvertUtil::decimal32FromFloat(float binary)\n{\n Decimal32 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal64 DecimalConvertUtil::decimal64FromFloat(float binary)\n{\n Decimal64 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\nDecimal128 DecimalConvertUtil::decimal128FromFloat(float binary)\n{\n Decimal128 rv;\n restoreDecimalFromBinary(&rv, binary);\n return rv;\n}\n\n} \/\/ close package namespace\n} \/\/ close enterprise namespace\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2014 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"#include \"PsfVm.h\"\r\n#include \"PsfLoader.h\"\r\n#include \"MemoryUtils.h\"\r\n#include \"CoffObjectFile.h\"\r\n#include \"StdStreamUtils.h\"\r\n#include \"Jitter.h\"\r\n#include \"Jitter_CodeGenFactory.h\"\r\n#include \"Jitter_CodeGen_x86_32.h\"\r\n#include \"MemStream.h\"\r\n#include \"Iop_PsfSubSystem.h\"\r\n#include \"ThreadPool.h\"\r\n#include \r\n#include \"Playlist.h\"\r\n\r\nnamespace filesystem = boost::filesystem;\r\n\r\nstruct FUNCTION_TABLE_ITEM\r\n{\r\n\tAOT_BLOCK_KEY\tkey;\r\n\tuint32\t\t\tsymbolIndex;\r\n};\r\ntypedef std::vector FunctionTable;\r\n\r\ntypedef std::map> AotBlockMap;\r\n\r\nextern \"C\" uint32 LWL_Proxy(uint32, uint32, CMIPS*);\r\nextern \"C\" uint32 LWR_Proxy(uint32, uint32, CMIPS*);\r\nextern \"C\" void SWL_Proxy(uint32, uint32, CMIPS*);\nextern \"C\" void SWR_Proxy(uint32, uint32, CMIPS*);\n\r\nvoid Gather(const char* archivePathName, const char* outputPathName)\r\n{\r\n\tFramework::CStdStream outputStream(outputPathName, \"wb\");\r\n\tCBasicBlock::SetAotBlockOutputStream(&outputStream);\r\n\r\n\t{\r\n\t\tFramework::CThreadPool threadPool(std::thread::hardware_concurrency());\r\n\r\n\t\tfilesystem::path archivePath = filesystem::path(archivePathName);\r\n\t\tauto archive = std::unique_ptr(CPsfArchive::CreateFromPath(archivePath));\r\n\r\n\t\tfor(auto fileInfoIterator = archive->GetFilesBegin();\r\n\t\t\tfileInfoIterator != archive->GetFilesEnd(); fileInfoIterator++)\r\n\t\t{\r\n\t\t\tfilesystem::path archiveItemPath = fileInfoIterator->name;\r\n\t\t\tfilesystem::path archiveItemExtension = archiveItemPath.extension();\r\n\t\t\tif(CPlaylist::IsLoadableExtension(archiveItemExtension.string().c_str() + 1))\r\n\t\t\t{\r\n\t\t\t\tthreadPool.Enqueue(\r\n\t\t\t\t\t[=] ()\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tprintf(\"Processing %s...\\r\\n\", archiveItemPath.string().c_str());\r\n\r\n\t\t\t\t\t\tCPsfVm virtualMachine;\r\n\r\n\t\t\t\t\t\tCPsfLoader::LoadPsf(virtualMachine, archiveItemPath, archivePath);\r\n\t\t\t\t\t\tint currentTime = 0;\r\n\t\t\t\t\t\tvirtualMachine.OnNewFrame.connect(\r\n\t\t\t\t\t\t\t[¤tTime] ()\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcurrentTime += 16;\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tvirtualMachine.Resume();\r\n\r\n#ifdef _DEBUG\r\n\t\t\t\t\t\tstatic const unsigned int executionTime = 1;\r\n#else\r\n\t\t\t\t\t\tstatic const unsigned int executionTime = 10;\r\n#endif\r\n\t\t\t\t\t\twhile(currentTime <= (executionTime * 60 * 1000))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tvirtualMachine.Pause();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tCBasicBlock::SetAotBlockOutputStream(nullptr);\r\n}\r\n\r\nunsigned int CompileFunction(CPsfVm& virtualMachine, const std::vector& blockCode, Jitter::CObjectFile& objectFile, const std::string& functionName, uint32 begin, uint32 end)\r\n{\r\n\tauto& context = virtualMachine.GetCpu();\r\n\r\n\tuint8* ram = virtualMachine.GetRam();\r\n\tfor(uint32 address = begin; address <= end; address += 4)\r\n\t{\r\n\t\t*reinterpret_cast(&ram[address]) = blockCode[(address - begin) \/ 4];\r\n\t}\r\n\r\n\t{\n\t\tFramework::CMemStream outputStream;\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL func;\r\n\n\t\tstatic CMipsJitter* jitter = nullptr;\n\t\tif(jitter == NULL)\n\t\t{\n\t\t\tJitter::CCodeGen* codeGen = new Jitter::CCodeGen_x86_32();\n\t\t\tcodeGen->SetExternalSymbolReferencedHandler(\n\t\t\t\t[&] (void* symbol, uint32 offset)\n\t\t\t\t{\n\t\t\t\t\tJitter::CObjectFile::SYMBOL_REFERENCE ref;\n\t\t\t\t\tref.offset\t\t= offset;\n\t\t\t\t\tref.type\t\t= Jitter::CObjectFile::SYMBOL_TYPE_EXTERNAL;\n\t\t\t\t\tref.symbolIndex\t= objectFile.GetExternalSymbolIndexByValue(symbol);\n\t\t\t\t\tfunc.symbolReferences.push_back(ref);\r\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tjitter = new CMipsJitter(codeGen);\n\n\t\t\tfor(unsigned int i = 0; i < 4; i++)\n\t\t\t{\n\t\t\t\tjitter->SetVariableAsConstant(\n\t\t\t\t\toffsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),\n\t\t\t\t\t0\n\t\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tjitter->SetStream(&outputStream);\n\t\tjitter->Begin();\n\n\t\tfor(uint32 address = begin; address <= end; address += 4)\n\t\t{\n\t\t\tcontext.m_pArch->CompileInstruction(address, jitter, &context);\n\t\t\t\/\/Sanity check\n\t\t\tassert(jitter->IsStackEmpty());\n\t\t}\n\n\t\tjitter->End();\n\n\t\tfunc.name\t\t= functionName;\r\n\t\tfunc.data\t\t= std::vector(outputStream.GetBuffer(), outputStream.GetBuffer() + outputStream.GetSize());\r\n\t\tfunc.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_TEXT;\r\n\t\treturn objectFile.AddInternalSymbol(func);\r\n\t}\n}\r\n\r\nAotBlockMap GetBlocksFromCache(const filesystem::path& blockCachePath)\r\n{\r\n\tAotBlockMap result;\r\n\r\n\tauto path_end = filesystem::directory_iterator();\r\n\tfor(auto pathIterator = filesystem::directory_iterator(blockCachePath); \r\n\t\tpathIterator != path_end; pathIterator++)\r\n\t{\r\n\t\tconst auto& filePath = (*pathIterator);\r\n\t\tprintf(\"Processing %s...\\r\\n\", filePath.path().string().c_str());\r\n\r\n\t\tauto blockCacheStream = Framework::CreateInputStdStream(filePath.path().native());\r\n\r\n\t\tuint32 fileSize = blockCacheStream.GetLength();\r\n\t\twhile(fileSize != 0)\r\n\t\t{\r\n\t\t\tAOT_BLOCK_KEY key = {};\r\n\t\t\tkey.crc\t\t= blockCacheStream.Read32();\r\n\t\t\tkey.begin\t= blockCacheStream.Read32();\r\n\t\t\tkey.end\t\t= blockCacheStream.Read32();\r\n\r\n\t\t\tif(key.begin > key.end)\r\n\t\t\t{\r\n\t\t\t\tassert(0);\r\n\t\t\t\tthrow std::runtime_error(\"Consistency error in block ranges.\");\r\n\t\t\t}\r\n\r\n\t\t\tuint32 blockSize = (key.end - key.begin) + 4;\r\n\r\n\t\t\tstd::vector blockCode(blockSize \/ 4);\r\n\t\t\tblockCacheStream.Read(blockCode.data(), blockSize);\r\n\r\n\t\t\tauto blockIterator = result.find(key);\r\n\t\t\tif(blockIterator == std::end(result))\r\n\t\t\t{\r\n\t\t\t\tresult.insert(std::make_pair(key, std::move(blockCode)));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(!std::equal(std::begin(blockCode), std::end(blockCode), std::begin(blockIterator->second)))\r\n\t\t\t\t{\r\n\t\t\t\t\tassert(0);\r\n\t\t\t\t\tthrow std::runtime_error(\"Block with same key already exists but with different data.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfileSize -= blockSize + 0x0C;\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Compile(const char* databasePathName, const char* outputPath)\r\n{\r\n\tCPsfVm virtualMachine;\r\n\tauto subSystem = std::make_shared(false);\r\n\tvirtualMachine.SetSubSystem(subSystem);\r\n\r\n\tauto objectFile = std::unique_ptr(new Jitter::CCoffObjectFile());\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetByteProxy\", &MemoryUtils_GetByteProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetHalfProxy\", &MemoryUtils_GetHalfProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetWordProxy\", &MemoryUtils_GetWordProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetByteProxy\", &MemoryUtils_SetByteProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetHalfProxy\", &MemoryUtils_SetHalfProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetWordProxy\", &MemoryUtils_SetWordProxy);\r\n\tobjectFile->AddExternalSymbol(\"_LWL_Proxy\", &LWL_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_LWR_Proxy\", &LWR_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_SWL_Proxy\", &SWL_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_SWR_Proxy\", &SWR_Proxy);\r\n\r\n\tfilesystem::path databasePath(databasePathName);\r\n\tauto blocks = GetBlocksFromCache(databasePath);\r\n\r\n\tprintf(\"Got %d blocks to compile.\\r\\n\", blocks.size());\r\n\r\n\tFunctionTable functionTable;\r\n\tfunctionTable.reserve(blocks.size());\r\n\r\n\tfor(const auto& blockCachePair : blocks)\r\n\t{\r\n\t\tconst auto& blockKey = blockCachePair.first;\r\n\r\n\t\tauto functionName = \"aotblock_\" + std::to_string(blockKey.crc) + \"_\" + std::to_string(blockKey.begin) + \"_\" + std::to_string(blockKey.end);\r\n\r\n\t\tunsigned int functionSymbolIndex = CompileFunction(virtualMachine, blockCachePair.second, *objectFile, functionName, blockKey.begin, blockKey.end);\r\n\r\n\t\tFUNCTION_TABLE_ITEM tableItem = { blockKey, functionSymbolIndex };\r\n\t\tfunctionTable.push_back(tableItem);\r\n\t}\r\n\r\n\tstd::sort(functionTable.begin(), functionTable.end(), \r\n\t\t[] (const FUNCTION_TABLE_ITEM& item1, const FUNCTION_TABLE_ITEM& item2)\r\n\t\t{\r\n\t\t\treturn item1.key < item2.key;\r\n\t\t}\r\n\t);\r\n\r\n\t{\r\n\t\tFramework::CMemStream blockTableStream;\r\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL blockTableSymbol;\r\n\t\tblockTableSymbol.name\t\t= \"__aot_firstBlock\";\r\n\t\tblockTableSymbol.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_DATA;\r\n\r\n\t\tfor(const auto& functionTableItem : functionTable)\r\n\t\t{\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.crc);\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.begin);\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.end);\r\n\t\t\t\r\n\t\t\t{\r\n\t\t\t\tJitter::CObjectFile::SYMBOL_REFERENCE ref;\r\n\t\t\t\tref.offset\t\t= static_cast(blockTableStream.Tell());\r\n\t\t\t\tref.type\t\t= Jitter::CObjectFile::SYMBOL_TYPE_INTERNAL;\r\n\t\t\t\tref.symbolIndex\t= functionTableItem.symbolIndex;\r\n\t\t\t\tblockTableSymbol.symbolReferences.push_back(ref);\r\n\t\t\t}\r\n\r\n\t\t\tblockTableStream.Write32(0);\r\n\t\t}\r\n\r\n\t\tblockTableSymbol.data = std::vector(blockTableStream.GetBuffer(), blockTableStream.GetBuffer() + blockTableStream.GetLength());\r\n\t\tobjectFile->AddInternalSymbol(blockTableSymbol);\r\n\t}\r\n\r\n\t{\r\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL blockCountSymbol;\r\n\t\tblockCountSymbol.name\t\t= \"__aot_blockCount\";\r\n\t\tblockCountSymbol.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_DATA;\r\n\t\tblockCountSymbol.data\t\t= std::vector(4);\r\n\t\t*reinterpret_cast(blockCountSymbol.data.data()) = functionTable.size();\r\n\t\tobjectFile->AddInternalSymbol(blockCountSymbol);\r\n\t}\r\n\r\n\tobjectFile->Write(Framework::CStdStream(outputPath, \"wb\"));\r\n}\r\n\r\nvoid PrintUsage()\r\n{\r\n\tprintf(\"PsfAot usage:\\r\\n\");\r\n\tprintf(\"\\tPsfAot gather [InputFile] [DatabasePath]\\r\\n\");\r\n\tprintf(\"\\tPsfAot compile [DatabasePath] [x86|x64|arm] [coff|macho] [OutputFile]\\r\\n\");\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tif(argc <= 2)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif(!strcmp(argv[1], \"gather\"))\r\n\t{\r\n\t\tif(argc < 4)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tGather(argv[2], argv[3]);\r\n\t\t}\r\n\t}\r\n\telse if(!strcmp(argv[1], \"compile\"))\r\n\t{\r\n\t\tif(argc < 6)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tCompile(argv[2], argv[5]);\r\n\t\t}\r\n\t\tcatch(const std::exception& exception)\r\n\t\t{\r\n\t\t\tprintf(\"Failed to compile: %s\\r\\n\", exception.what());\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\nPsfPlayer: Updated AOT builder to support ARM platforms and MachO object format.#include \"PsfVm.h\"\r\n#include \"PsfLoader.h\"\r\n#include \"MemoryUtils.h\"\r\n#include \"CoffObjectFile.h\"\r\n#include \"MachoObjectFile.h\"\r\n#include \"StdStreamUtils.h\"\r\n#include \"Jitter.h\"\r\n#include \"Jitter_CodeGen_x86_32.h\"\r\n#include \"Jitter_CodeGen_Arm.h\"\r\n#include \"MemStream.h\"\r\n#include \"Iop_PsfSubSystem.h\"\r\n#include \"ThreadPool.h\"\r\n#include \r\n#include \"Playlist.h\"\r\n#include \"make_unique.h\"\r\n\r\nnamespace filesystem = boost::filesystem;\r\n\r\nstruct FUNCTION_TABLE_ITEM\r\n{\r\n\tAOT_BLOCK_KEY\tkey;\r\n\tuint32\t\t\tsymbolIndex;\r\n};\r\ntypedef std::vector FunctionTable;\r\n\r\ntypedef std::map> AotBlockMap;\r\n\r\nextern \"C\" uint32 LWL_Proxy(uint32, uint32, CMIPS*);\r\nextern \"C\" uint32 LWR_Proxy(uint32, uint32, CMIPS*);\r\nextern \"C\" void SWL_Proxy(uint32, uint32, CMIPS*);\nextern \"C\" void SWR_Proxy(uint32, uint32, CMIPS*);\n\r\nvoid Gather(const char* archivePathName, const char* outputPathName)\r\n{\r\n\tFramework::CStdStream outputStream(outputPathName, \"wb\");\r\n\tCBasicBlock::SetAotBlockOutputStream(&outputStream);\r\n\r\n\t{\r\n\t\tFramework::CThreadPool threadPool(std::thread::hardware_concurrency());\r\n\r\n\t\tfilesystem::path archivePath = filesystem::path(archivePathName);\r\n\t\tauto archive = std::unique_ptr(CPsfArchive::CreateFromPath(archivePath));\r\n\r\n\t\tfor(const auto& fileInfo : archive->GetFiles())\r\n\t\t{\r\n\t\t\tfilesystem::path archiveItemPath = fileInfo.name;\r\n\t\t\tfilesystem::path archiveItemExtension = archiveItemPath.extension();\r\n\t\t\tif(CPlaylist::IsLoadableExtension(archiveItemExtension.string().c_str() + 1))\r\n\t\t\t{\r\n\t\t\t\tthreadPool.Enqueue(\r\n\t\t\t\t\t[=] ()\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tprintf(\"Processing %s...\\r\\n\", archiveItemPath.string().c_str());\r\n\r\n\t\t\t\t\t\tCPsfVm virtualMachine;\r\n\r\n\t\t\t\t\t\tCPsfLoader::LoadPsf(virtualMachine, archiveItemPath, archivePath);\r\n\t\t\t\t\t\tint currentTime = 0;\r\n\t\t\t\t\t\tvirtualMachine.OnNewFrame.connect(\r\n\t\t\t\t\t\t\t[¤tTime] ()\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tcurrentTime += 16;\r\n\t\t\t\t\t\t\t});\r\n\r\n\t\t\t\t\t\tvirtualMachine.Resume();\r\n\r\n#ifdef _DEBUG\r\n\t\t\t\t\t\tstatic const unsigned int executionTime = 1;\r\n#else\r\n\t\t\t\t\t\tstatic const unsigned int executionTime = 10;\r\n#endif\r\n\t\t\t\t\t\twhile(currentTime <= (executionTime * 60 * 1000))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(10));\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tvirtualMachine.Pause();\r\n\t\t\t\t\t}\r\n\t\t\t\t);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tCBasicBlock::SetAotBlockOutputStream(nullptr);\r\n}\r\n\r\nunsigned int CompileFunction(CPsfVm& virtualMachine, CMipsJitter* jitter, const std::vector& blockCode, Jitter::CObjectFile& objectFile, const std::string& functionName, uint32 begin, uint32 end)\r\n{\r\n\tauto& context = virtualMachine.GetCpu();\r\n\r\n\tuint8* ram = virtualMachine.GetRam();\r\n\tfor(uint32 address = begin; address <= end; address += 4)\r\n\t{\r\n\t\t*reinterpret_cast(&ram[address]) = blockCode[(address - begin) \/ 4];\r\n\t}\r\n\r\n\t{\n\t\tFramework::CMemStream outputStream;\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL func;\r\n\n\t\tjitter->GetCodeGen()->SetExternalSymbolReferencedHandler(\n\t\t\t[&] (void* symbol, uint32 offset)\n\t\t\t{\n\t\t\t\tJitter::CObjectFile::SYMBOL_REFERENCE ref;\n\t\t\t\tref.offset\t\t= offset;\n\t\t\t\tref.type\t\t= Jitter::CObjectFile::SYMBOL_TYPE_EXTERNAL;\n\t\t\t\tref.symbolIndex\t= objectFile.GetExternalSymbolIndexByValue(symbol);\n\t\t\t\tfunc.symbolReferences.push_back(ref);\r\n\t\t\t}\n\t\t);\n\n\t\tjitter->SetStream(&outputStream);\n\t\tjitter->Begin();\n\n\t\tfor(uint32 address = begin; address <= end; address += 4)\n\t\t{\n\t\t\tcontext.m_pArch->CompileInstruction(address, jitter, &context);\n\t\t\t\/\/Sanity check\n\t\t\tassert(jitter->IsStackEmpty());\n\t\t}\n\n\t\tjitter->End();\n\n\t\tfunc.name\t\t= functionName;\r\n\t\tfunc.data\t\t= std::vector(outputStream.GetBuffer(), outputStream.GetBuffer() + outputStream.GetSize());\r\n\t\tfunc.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_TEXT;\r\n\t\treturn objectFile.AddInternalSymbol(func);\r\n\t}\n}\r\n\r\nAotBlockMap GetBlocksFromCache(const filesystem::path& blockCachePath)\r\n{\r\n\tAotBlockMap result;\r\n\r\n\tauto path_end = filesystem::directory_iterator();\r\n\tfor(auto pathIterator = filesystem::directory_iterator(blockCachePath); \r\n\t\tpathIterator != path_end; pathIterator++)\r\n\t{\r\n\t\tconst auto& filePath = (*pathIterator);\r\n\t\tprintf(\"Processing %s...\\r\\n\", filePath.path().string().c_str());\r\n\r\n\t\tauto blockCacheStream = Framework::CreateInputStdStream(filePath.path().native());\r\n\r\n\t\tuint32 fileSize = blockCacheStream.GetLength();\r\n\t\twhile(fileSize != 0)\r\n\t\t{\r\n\t\t\tAOT_BLOCK_KEY key = {};\r\n\t\t\tkey.crc\t\t= blockCacheStream.Read32();\r\n\t\t\tkey.begin\t= blockCacheStream.Read32();\r\n\t\t\tkey.end\t\t= blockCacheStream.Read32();\r\n\r\n\t\t\tif(key.begin > key.end)\r\n\t\t\t{\r\n\t\t\t\tassert(0);\r\n\t\t\t\tthrow std::runtime_error(\"Consistency error in block ranges.\");\r\n\t\t\t}\r\n\r\n\t\t\tuint32 blockSize = (key.end - key.begin) + 4;\r\n\r\n\t\t\tstd::vector blockCode(blockSize \/ 4);\r\n\t\t\tblockCacheStream.Read(blockCode.data(), blockSize);\r\n\r\n\t\t\tauto blockIterator = result.find(key);\r\n\t\t\tif(blockIterator == std::end(result))\r\n\t\t\t{\r\n\t\t\t\tresult.insert(std::make_pair(key, std::move(blockCode)));\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tif(!std::equal(std::begin(blockCode), std::end(blockCode), std::begin(blockIterator->second)))\r\n\t\t\t\t{\r\n\t\t\t\t\tassert(0);\r\n\t\t\t\t\tthrow std::runtime_error(\"Block with same key already exists but with different data.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfileSize -= blockSize + 0x0C;\r\n\t\t}\r\n\t}\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid Compile(const char* databasePathName, const char* cpuArchName, const char* imageFormatName, const char* outputPath)\r\n{\r\n\tCPsfVm virtualMachine;\r\n\tauto subSystem = std::make_shared(false);\r\n\tvirtualMachine.SetSubSystem(subSystem);\r\n\r\n\tJitter::CCodeGen* codeGen = nullptr;\r\n\tJitter::CObjectFile::CPU_ARCH cpuArch = Jitter::CObjectFile::CPU_ARCH_X86;\r\n\tif(!strcmp(cpuArchName, \"x86\"))\r\n\t{\r\n\t\tcodeGen = new Jitter::CCodeGen_x86_32();\r\n\t\tcpuArch = Jitter::CObjectFile::CPU_ARCH_X86;\r\n\t}\r\n\telse if(!strcmp(cpuArchName, \"arm\"))\r\n\t{\r\n\t\tcodeGen = new Jitter::CCodeGen_Arm();\r\n\t\tcpuArch = Jitter::CObjectFile::CPU_ARCH_ARM;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tthrow std::runtime_error(\"Invalid cpu target.\");\r\n\t}\r\n\r\n\tstd::unique_ptr objectFile;\r\n\tif(!strcmp(imageFormatName, \"coff\"))\r\n\t{\r\n\t\tobjectFile = std::make_unique(cpuArch);\r\n\t}\r\n\telse if(!strcmp(imageFormatName, \"macho\"))\r\n\t{\r\n\t\tobjectFile = std::make_unique(cpuArch);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tthrow std::runtime_error(\"Invalid executable image type (must be coff or macho).\");\r\n\t}\r\n\r\n\tcodeGen->RegisterExternalSymbols(objectFile.get());\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetByteProxy\", &MemoryUtils_GetByteProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetHalfProxy\", &MemoryUtils_GetHalfProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_GetWordProxy\", &MemoryUtils_GetWordProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetByteProxy\", &MemoryUtils_SetByteProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetHalfProxy\", &MemoryUtils_SetHalfProxy);\r\n\tobjectFile->AddExternalSymbol(\"_MemoryUtils_SetWordProxy\", &MemoryUtils_SetWordProxy);\r\n\tobjectFile->AddExternalSymbol(\"_LWL_Proxy\", &LWL_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_LWR_Proxy\", &LWR_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_SWL_Proxy\", &SWL_Proxy);\r\n\tobjectFile->AddExternalSymbol(\"_SWR_Proxy\", &SWR_Proxy);\r\n\r\n\tfilesystem::path databasePath(databasePathName);\r\n\tauto blocks = GetBlocksFromCache(databasePath);\r\n\r\n\t\/\/Initialize Jitter Service\r\n\tauto jitter = new CMipsJitter(codeGen);\n\tfor(unsigned int i = 0; i < 4; i++)\n\t{\n\t\tjitter->SetVariableAsConstant(\n\t\t\toffsetof(CMIPS, m_State.nGPR[CMIPS::R0].nV[i]),\n\t\t\t0\n\t\t\t);\n\t}\n\r\n\tprintf(\"Got %d blocks to compile.\\r\\n\", blocks.size());\r\n\r\n\tFunctionTable functionTable;\r\n\tfunctionTable.reserve(blocks.size());\r\n\r\n\tfor(const auto& blockCachePair : blocks)\r\n\t{\r\n\t\tconst auto& blockKey = blockCachePair.first;\r\n\r\n\t\tauto functionName = \"aotblock_\" + std::to_string(blockKey.crc) + \"_\" + std::to_string(blockKey.begin) + \"_\" + std::to_string(blockKey.end);\r\n\r\n\t\tunsigned int functionSymbolIndex = CompileFunction(virtualMachine, jitter, blockCachePair.second, *objectFile, functionName, blockKey.begin, blockKey.end);\r\n\r\n\t\tFUNCTION_TABLE_ITEM tableItem = { blockKey, functionSymbolIndex };\r\n\t\tfunctionTable.push_back(tableItem);\r\n\t}\r\n\r\n\tstd::sort(functionTable.begin(), functionTable.end(), \r\n\t\t[] (const FUNCTION_TABLE_ITEM& item1, const FUNCTION_TABLE_ITEM& item2)\r\n\t\t{\r\n\t\t\treturn item1.key < item2.key;\r\n\t\t}\r\n\t);\r\n\r\n\t{\r\n\t\tFramework::CMemStream blockTableStream;\r\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL blockTableSymbol;\r\n\t\tblockTableSymbol.name\t\t= \"__aot_firstBlock\";\r\n\t\tblockTableSymbol.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_DATA;\r\n\r\n\t\tfor(const auto& functionTableItem : functionTable)\r\n\t\t{\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.crc);\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.begin);\r\n\t\t\tblockTableStream.Write32(functionTableItem.key.end);\r\n\t\t\t\r\n\t\t\t{\r\n\t\t\t\tJitter::CObjectFile::SYMBOL_REFERENCE ref;\r\n\t\t\t\tref.offset\t\t= static_cast(blockTableStream.Tell());\r\n\t\t\t\tref.type\t\t= Jitter::CObjectFile::SYMBOL_TYPE_INTERNAL;\r\n\t\t\t\tref.symbolIndex\t= functionTableItem.symbolIndex;\r\n\t\t\t\tblockTableSymbol.symbolReferences.push_back(ref);\r\n\t\t\t}\r\n\r\n\t\t\tblockTableStream.Write32(0);\r\n\t\t}\r\n\r\n\t\tblockTableSymbol.data = std::vector(blockTableStream.GetBuffer(), blockTableStream.GetBuffer() + blockTableStream.GetLength());\r\n\t\tobjectFile->AddInternalSymbol(blockTableSymbol);\r\n\t}\r\n\r\n\t{\r\n\t\tJitter::CObjectFile::INTERNAL_SYMBOL blockCountSymbol;\r\n\t\tblockCountSymbol.name\t\t= \"__aot_blockCount\";\r\n\t\tblockCountSymbol.location\t= Jitter::CObjectFile::INTERNAL_SYMBOL_LOCATION_DATA;\r\n\t\tblockCountSymbol.data\t\t= std::vector(4);\r\n\t\t*reinterpret_cast(blockCountSymbol.data.data()) = functionTable.size();\r\n\t\tobjectFile->AddInternalSymbol(blockCountSymbol);\r\n\t}\r\n\r\n\tobjectFile->Write(Framework::CStdStream(outputPath, \"wb\"));\r\n}\r\n\r\nvoid PrintUsage()\r\n{\r\n\tprintf(\"PsfAot usage:\\r\\n\");\r\n\tprintf(\"\\tPsfAot gather [InputFile] [DatabasePath]\\r\\n\");\r\n\tprintf(\"\\tPsfAot compile [DatabasePath] [x86|x64|arm] [coff|macho] [OutputFile]\\r\\n\");\r\n}\r\n\r\nint main(int argc, char** argv)\r\n{\r\n\tif(argc <= 2)\r\n\t{\r\n\t\tPrintUsage();\r\n\t\treturn -1;\r\n\t}\r\n\r\n\tif(!strcmp(argv[1], \"gather\"))\r\n\t{\r\n\t\tif(argc < 4)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tGather(argv[2], argv[3]);\r\n\t\t}\r\n\t}\r\n\telse if(!strcmp(argv[1], \"compile\"))\r\n\t{\r\n\t\tif(argc < 6)\r\n\t\t{\r\n\t\t\tPrintUsage();\r\n\t\t\treturn -1;\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tconst char* databasePath = argv[2];\r\n\t\t\tconst char* cpuArchName = argv[3];\r\n\t\t\tconst char* imageFormatName = argv[4];\r\n\t\t\tconst char* outputPath = argv[5];\r\n\t\t\tCompile(databasePath, cpuArchName, imageFormatName, outputPath);\r\n\t\t}\r\n\t\tcatch(const std::exception& exception)\r\n\t\t{\r\n\t\t\tprintf(\"Failed to compile: %s\\r\\n\", exception.what());\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t}\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n#include \"test_precomp.hpp\"\n#include \"test_intrin_utils.hpp\"\n\nnamespace opencv_test { namespace hal {\nCV_CPU_OPTIMIZATION_NAMESPACE_BEGIN\n\nvoid test_hal_intrin_float16()\n{\n TheTest()\n .test_loadstore_fp16()\n .test_float_cvt_fp16()\n ;\n}\n\nCV_CPU_OPTIMIZATION_NAMESPACE_END\n}} \/\/ namespace\ncore:test Fix fp16 build if AVX2 sets as baseline\/\/ This file is part of OpenCV project.\n\/\/ It is subject to the license terms in the LICENSE file found in the top-level directory\n\/\/ of this distribution and at http:\/\/opencv.org\/license.html.\n#include \"test_precomp.hpp\"\n#include \"test_intrin_utils.hpp\"\n\nnamespace opencv_test { namespace hal {\nCV_CPU_OPTIMIZATION_NAMESPACE_BEGIN\n\nvoid test_hal_intrin_float16()\n{\n TheTest()\n .test_loadstore_fp16()\n .test_float_cvt_fp16()\n ;\n}\n\nCV_CPU_OPTIMIZATION_NAMESPACE_END\n}} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/\n\/\/ C++ Implementation: sdlplayer\n\/\/\n\/\/ Description: \n\/\/\n\/\/\n\/\/ Author: FThauer FHammer , (C) 2007\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n#include \"sdlplayer.h\"\n\n#include \n\nusing namespace std;\n\nSDLPlayer::SDLPlayer(ConfigFile *c)\n: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c)\n{\n\tSDL_Init(SDL_INIT_AUDIO);\n\tinitAudio();\n}\n\n\nSDLPlayer::~SDLPlayer()\n{\n\tcloseAudio();\n\tSDL_Quit();\n}\n\nvoid SDLPlayer::initAudio() {\n\n\tif (!audioEnabled && myConfig->readConfigInt(\"PlaySoundEffects\"))\n\t{\n\t\taudio_rate = 44100;\n\t\taudio_format = AUDIO_S16; \/* 16-bit stereo *\/\n\t\taudio_channels = 2;\n\t\taudio_buffers = 4096;\n\t\tsound = NULL;\n\n\t\tif(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {\n\t\t\tMix_QuerySpec(&audio_rate, &audio_format, &audio_channels);\n\t\t\taudioEnabled = 1;\n\t\t}\n\t}\n}\n\nvoid SDLPlayer::playSound(string audioString, int playerID) {\n\n\tif(audioEnabled && myConfig->readConfigInt(\"PlaySoundEffects\")) {\n\t\t\n\t\tQFile myFile(\":sounds\/resources\/sounds\/\"+QString::fromStdString(audioString)+\".wav\");\n\t\n\t\tif(myFile.open(QIODevice::ReadOnly)) {\n\t\n\t\t\t\/\/set 3d position for player\n\t\t\tint position = 0;\n\t\t\tint distance = 0;\n\t\t\t\n\t\t\tswitch (playerID) {\n\n\t\t\tcase 0: { position = 180; distance = 10; }\n\t\t\tbreak;\n\t\t\tcase 1: { position = 281; distance = 30; }\n\t\t\tbreak;\n\t\t\tcase 2: { position = 315; distance = 90; }\n\t\t\tbreak;\n\t\t\tcase 3: { position = 338; distance = 130; }\n\t\t\tbreak;\n\t\t\tcase 4: { position = 23; distance = 130; }\n\t\t\tbreak;\n\t\t\tcase 5: { position = 45; distance = 90; }\n\t\t\tbreak;\n\t\t\tcase 6: { position = 79; distance = 30; }\n\t\t\tbreak;\n\t\t\tdefault: { position = 0; distance = 0; }\n\t\t\tbreak;\n\t\t\t}\n\n\t\t\taudioDone();\n\t\n\t\t\tQDataStream in(&myFile);\n\t\t\tsoundData = new Uint8[(int)myFile.size()];\n\t\t\tin.readRawData( (char*)soundData, (int)myFile.size() );\n\t\t\t\n\t\t\tsound = Mix_QuickLoad_WAV(soundData); \n\t\t\n\t\t\t \n \t\t\t\/\/ set channel 0 to settings volume\n\t\t\tMix_Volume(0,myConfig->readConfigInt(\"SoundVolume\")*10);\n\n\t\t\t\/\/ set 3d effect\n\t\t\tif(!Mix_SetPosition(0, position, distance)) {\n \t\t\t\tprintf(\"Mix_SetPosition: %s\\n\", Mix_GetError());\n \t\t\t\t\/\/ no position effect, is it ok?\n\t\t\t}\n\t\t\tcurrentChannel = Mix_PlayChannel(-1, sound,0);\n\t\t}\n\t\/\/ \telse cout << \"could not load \" << audioString << \".wav\" << endl;\n\t\n\t\t\/\/test\n\t\/\/\taudioDone(); \n\t\/\/\tsound = Mix_LoadWAV( QString(QString::fromStdString(audioString)+QString(\".wav\")).toStdString().c_str() ); \n\t\/\/\tcurrentChannel = Mix_PlayChannel(-1, sound,0);\n\n\t}\n}\n\nvoid SDLPlayer::audioDone() {\n\n\tif(audioEnabled) {\n\t\tMix_HaltChannel(currentChannel);\n\t\tMix_FreeChunk(sound);\n\t\tsound = NULL;\n\t\tdelete[] soundData;\n\t\tsoundData = NULL;\n\t}\n}\n\nvoid SDLPlayer::closeAudio() {\n\t\n\tif(audioEnabled) {\n\t\taudioDone();\n\t\tMix_CloseAudio();\n\t\taudioEnabled = false;\n\t}\n}\nwider 3d sound\/\/\n\/\/ C++ Implementation: sdlplayer\n\/\/\n\/\/ Description: \n\/\/\n\/\/\n\/\/ Author: FThauer FHammer , (C) 2007\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n#include \"sdlplayer.h\"\n\n#include \n\nusing namespace std;\n\nSDLPlayer::SDLPlayer(ConfigFile *c)\n: soundData(NULL), currentChannel(0) , audioEnabled(0), myConfig(c)\n{\n\tSDL_Init(SDL_INIT_AUDIO);\n\tinitAudio();\n}\n\n\nSDLPlayer::~SDLPlayer()\n{\n\tcloseAudio();\n\tSDL_Quit();\n}\n\nvoid SDLPlayer::initAudio() {\n\n\tif (!audioEnabled && myConfig->readConfigInt(\"PlaySoundEffects\"))\n\t{\n\t\taudio_rate = 44100;\n\t\taudio_format = AUDIO_S16; \/* 16-bit stereo *\/\n\t\taudio_channels = 2;\n\t\taudio_buffers = 4096;\n\t\tsound = NULL;\n\n\t\tif(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) == 0) {\n\t\t\tMix_QuerySpec(&audio_rate, &audio_format, &audio_channels);\n\t\t\taudioEnabled = 1;\n\t\t}\n\t}\n}\n\nvoid SDLPlayer::playSound(string audioString, int playerID) {\n\n\tif(audioEnabled && myConfig->readConfigInt(\"PlaySoundEffects\")) {\n\t\t\n\t\tQFile myFile(\":sounds\/resources\/sounds\/\"+QString::fromStdString(audioString)+\".wav\");\n\t\n\t\tif(myFile.open(QIODevice::ReadOnly)) {\n\t\n\t\t\t\/\/set 3d position for player\n\t\t\tint position = 0;\n\t\t\tint distance = 0;\n\t\t\t\n\t\t\tswitch (playerID) {\n\n\t\t\tcase 0: { position = 180; distance = 10; }\n\t\t\tbreak;\n\t\t\tcase 1: { position = 281; distance = 50; }\n\t\t\tbreak;\n\t\t\tcase 2: { position = 315; distance = 120; }\n\t\t\tbreak;\n\t\t\tcase 3: { position = 338; distance = 160; }\n\t\t\tbreak;\n\t\t\tcase 4: { position = 23; distance = 160; }\n\t\t\tbreak;\n\t\t\tcase 5: { position = 45; distance = 120; }\n\t\t\tbreak;\n\t\t\tcase 6: { position = 79; distance = 50; }\n\t\t\tbreak;\n\t\t\tdefault: { position = 0; distance = 0; }\n\t\t\tbreak;\n\t\t\t}\n\n\t\t\taudioDone();\n\t\n\t\t\tQDataStream in(&myFile);\n\t\t\tsoundData = new Uint8[(int)myFile.size()];\n\t\t\tin.readRawData( (char*)soundData, (int)myFile.size() );\n\t\t\t\n\t\t\tsound = Mix_QuickLoad_WAV(soundData); \n\t\t\n\t\t\t \n \t\t\t\/\/ set channel 0 to settings volume\n\t\t\tMix_Volume(0,myConfig->readConfigInt(\"SoundVolume\")*10);\n\n\t\t\t\/\/ set 3d effect\n\t\t\tif(!Mix_SetPosition(0, position, distance)) {\n \t\t\t\tprintf(\"Mix_SetPosition: %s\\n\", Mix_GetError());\n \t\t\t\t\/\/ no position effect, is it ok?\n\t\t\t}\n\t\t\tcurrentChannel = Mix_PlayChannel(-1, sound,0);\n\t\t}\n\t\/\/ \telse cout << \"could not load \" << audioString << \".wav\" << endl;\n\t\n\t\t\/\/test\n\t\/\/\taudioDone(); \n\t\/\/\tsound = Mix_LoadWAV( QString(QString::fromStdString(audioString)+QString(\".wav\")).toStdString().c_str() ); \n\t\/\/\tcurrentChannel = Mix_PlayChannel(-1, sound,0);\n\n\t}\n}\n\nvoid SDLPlayer::audioDone() {\n\n\tif(audioEnabled) {\n\t\tMix_HaltChannel(currentChannel);\n\t\tMix_FreeChunk(sound);\n\t\tsound = NULL;\n\t\tdelete[] soundData;\n\t\tsoundData = NULL;\n\t}\n}\n\nvoid SDLPlayer::closeAudio() {\n\t\n\tif(audioEnabled) {\n\t\taudioDone();\n\t\tMix_CloseAudio();\n\t\taudioEnabled = false;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"SkSurface.h\"\n#include \"SkTypeface.h\"\n\nnamespace skiagm {\n\nclass DFTextGM : public GM {\npublic:\n DFTextGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\n virtual ~DFTextGM() {\n }\n\nprotected:\n virtual uint32_t onGetFlags() const SK_OVERRIDE {\n return kGPUOnly_Flag;\n }\n\n virtual SkString onShortName() {\n return SkString(\"dftext\");\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(1024, 768);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* inputCanvas) {\n SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f };\n SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };\n\n \/\/ set up offscreen rendering with distance field text\n#if SK_SUPPORT_GPU\n GrContext* ctx = inputCanvas->getGrContext();\n SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());\n SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,\n SkSurfaceProps::kLegacyFontHost_InitType);\n SkAutoTUnref surface(SkSurface::NewRenderTarget(ctx, info, 0, &props));\n SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;\n#else\n SkCanvas* canvas = inputCanvas;\n#endif\n \n \/\/ apply global scale to test glyph positioning\n canvas->scale(1.05f, 1.05f);\n canvas->clear(0xffffffff);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setSubpixelText(true);\n#if !SK_SUPPORT_GPU\n paint.setDistanceFieldTextTEMP(true);\n#endif\n sk_tool_utils::set_portable_typeface(&paint, \"Times New Roman\", SkTypeface::kNormal);\n\n const char* text = \"Hamburgefons\";\n const size_t textLen = strlen(text);\n\n \/\/ check scaling up\n SkScalar x = SkIntToScalar(0);\n SkScalar y = SkIntToScalar(78);\n for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n canvas->scale(scales[i], scales[i]);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scales[i];\n }\n\n \/\/ check rotation\n for (size_t i = 0; i < 5; ++i) {\n SkScalar rotX = SkIntToScalar(10);\n SkScalar rotY = y;\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(10 + i * 200), -80);\n rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);\n for (int ps = 6; ps <= 32; ps += 3) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, rotX, rotY, paint);\n rotY += paint.getFontMetrics(NULL);\n }\n }\n\n \/\/ check scaling down\n paint.setLCDRenderText(true);\n x = SkIntToScalar(680);\n y = SkIntToScalar(20);\n size_t arraySize = SK_ARRAY_COUNT(textSizes);\n for (size_t i = 0; i < arraySize; ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);\n canvas->scale(scaleFactor, scaleFactor);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scaleFactor;\n }\n\n \/\/ check pos text\n {\n SkAutoCanvasRestore acr(canvas, true);\n\n canvas->scale(2.0f, 2.0f);\n\n SkAutoTArray pos(textLen);\n SkAutoTArray widths(textLen);\n paint.setTextSize(textSizes[0]);\n\n paint.getTextWidths(text, textLen, &widths[0]);\n\n SkScalar x = SkIntToScalar(340);\n SkScalar y = SkIntToScalar(75);\n for (unsigned int i = 0; i < textLen; ++i) {\n pos[i].set(x, y);\n x += widths[i];\n }\n\n canvas->drawPosText(text, textLen, &pos[0], paint);\n }\n\n\n \/\/ check gamma-corrected blending\n const SkColor fg[] = {\n 0xFFFFFFFF,\n 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,\n 0xFFFF0000, 0xFF00FF00, 0xFF0000FF,\n 0xFF000000,\n };\n\n paint.setColor(0xFFF1F1F1);\n SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(680);\n y = SkIntToScalar(270);\n paint.setTextSize(SkIntToScalar(22));\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n paint.setColor(0xFF1F1F1F);\n r = SkRect::MakeLTRB(820, 250, 970, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(830);\n y = SkIntToScalar(270);\n paint.setTextSize(SkIntToScalar(22));\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n#if SK_SUPPORT_GPU\n \/\/ render offscreen buffer\n if (surface) {\n SkImage* image = surface->newImageSnapshot();\n inputCanvas->drawImage(image, 0, 0, NULL);\n image->unref();\n }\n#endif\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new DFTextGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\nReduce sizes in dftext GM on Android to match desktop better.\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n#include \"SkSurface.h\"\n#include \"SkTypeface.h\"\n\nnamespace skiagm {\n\nclass DFTextGM : public GM {\npublic:\n DFTextGM() {\n this->setBGColor(0xFFFFFFFF);\n }\n\n virtual ~DFTextGM() {\n }\n\nprotected:\n virtual uint32_t onGetFlags() const SK_OVERRIDE {\n return kGPUOnly_Flag;\n }\n\n virtual SkString onShortName() {\n return SkString(\"dftext\");\n }\n\n virtual SkISize onISize() {\n return SkISize::Make(1024, 768);\n }\n\n static void rotate_about(SkCanvas* canvas,\n SkScalar degrees,\n SkScalar px, SkScalar py) {\n canvas->translate(px, py);\n canvas->rotate(degrees);\n canvas->translate(-px, -py);\n }\n\n virtual void onDraw(SkCanvas* inputCanvas) {\n#if SK_BUILD_FOR_ANDROID\n SkScalar textSizes[] = { 9.0f, 9.0f*2.0f, 9.0f*5.0f, 9.0f*2.0f*5.0f };\n#else\n SkScalar textSizes[] = { 11.0f, 11.0f*2.0f, 11.0f*5.0f, 11.0f*2.0f*5.0f };\n#endif\n SkScalar scales[] = { 2.0f*5.0f, 5.0f, 2.0f, 1.0f };\n\n \/\/ set up offscreen rendering with distance field text\n#if SK_SUPPORT_GPU\n GrContext* ctx = inputCanvas->getGrContext();\n SkImageInfo info = SkImageInfo::MakeN32Premul(onISize());\n SkSurfaceProps props(SkSurfaceProps::kUseDistanceFieldFonts_Flag,\n SkSurfaceProps::kLegacyFontHost_InitType);\n SkAutoTUnref surface(SkSurface::NewRenderTarget(ctx, info, 0, &props));\n SkCanvas* canvas = surface.get() ? surface->getCanvas() : inputCanvas;\n#else\n SkCanvas* canvas = inputCanvas;\n#endif\n \n \/\/ apply global scale to test glyph positioning\n canvas->scale(1.05f, 1.05f);\n canvas->clear(0xffffffff);\n\n SkPaint paint;\n paint.setAntiAlias(true);\n paint.setSubpixelText(true);\n#if !SK_SUPPORT_GPU\n paint.setDistanceFieldTextTEMP(true);\n#endif\n sk_tool_utils::set_portable_typeface(&paint, \"Times New Roman\", SkTypeface::kNormal);\n\n const char* text = \"Hamburgefons\";\n const size_t textLen = strlen(text);\n\n \/\/ check scaling up\n SkScalar x = SkIntToScalar(0);\n SkScalar y = SkIntToScalar(78);\n for (size_t i = 0; i < SK_ARRAY_COUNT(textSizes); ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n canvas->scale(scales[i], scales[i]);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scales[i];\n }\n\n \/\/ check rotation\n for (size_t i = 0; i < 5; ++i) {\n SkScalar rotX = SkIntToScalar(10);\n SkScalar rotY = y;\n\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(SkIntToScalar(10 + i * 200), -80);\n rotate_about(canvas, SkIntToScalar(i * 5), rotX, rotY);\n for (int ps = 6; ps <= 32; ps += 3) {\n paint.setTextSize(SkIntToScalar(ps));\n canvas->drawText(text, textLen, rotX, rotY, paint);\n rotY += paint.getFontMetrics(NULL);\n }\n }\n\n \/\/ check scaling down\n paint.setLCDRenderText(true);\n x = SkIntToScalar(680);\n y = SkIntToScalar(20);\n size_t arraySize = SK_ARRAY_COUNT(textSizes);\n for (size_t i = 0; i < arraySize; ++i) {\n SkAutoCanvasRestore acr(canvas, true);\n canvas->translate(x, y);\n SkScalar scaleFactor = SkScalarInvert(scales[arraySize - i - 1]);\n canvas->scale(scaleFactor, scaleFactor);\n paint.setTextSize(textSizes[i]);\n canvas->drawText(text, textLen, 0, 0, paint);\n y += paint.getFontMetrics(NULL)*scaleFactor;\n }\n\n \/\/ check pos text\n {\n SkAutoCanvasRestore acr(canvas, true);\n\n canvas->scale(2.0f, 2.0f);\n\n SkAutoTArray pos(textLen);\n SkAutoTArray widths(textLen);\n paint.setTextSize(textSizes[0]);\n\n paint.getTextWidths(text, textLen, &widths[0]);\n\n SkScalar x = SkIntToScalar(340);\n SkScalar y = SkIntToScalar(75);\n for (unsigned int i = 0; i < textLen; ++i) {\n pos[i].set(x, y);\n x += widths[i];\n }\n\n canvas->drawPosText(text, textLen, &pos[0], paint);\n }\n\n\n \/\/ check gamma-corrected blending\n const SkColor fg[] = {\n 0xFFFFFFFF,\n 0xFFFFFF00, 0xFFFF00FF, 0xFF00FFFF,\n 0xFFFF0000, 0xFF00FF00, 0xFF0000FF,\n 0xFF000000,\n };\n\n paint.setColor(0xFFF1F1F1);\n SkRect r = SkRect::MakeLTRB(670, 250, 820, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(680);\n y = SkIntToScalar(270);\n#if SK_BUILD_FOR_ANDROID\n paint.setTextSize(SkIntToScalar(19));\n#else\n paint.setTextSize(SkIntToScalar(22));\n#endif\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n paint.setColor(0xFF1F1F1F);\n r = SkRect::MakeLTRB(820, 250, 970, 460);\n canvas->drawRect(r, paint);\n\n x = SkIntToScalar(830);\n y = SkIntToScalar(270);\n#if SK_BUILD_FOR_ANDROID\n paint.setTextSize(SkIntToScalar(19));\n#else\n paint.setTextSize(SkIntToScalar(22));\n#endif\n for (size_t i = 0; i < SK_ARRAY_COUNT(fg); ++i) {\n paint.setColor(fg[i]);\n\n canvas->drawText(text, textLen, x, y, paint);\n y += paint.getFontMetrics(NULL);\n }\n\n#if SK_SUPPORT_GPU\n \/\/ render offscreen buffer\n if (surface) {\n SkImage* image = surface->newImageSnapshot();\n inputCanvas->drawImage(image, 0, 0, NULL);\n image->unref();\n }\n#endif\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new DFTextGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2020 Google LLC\n\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"hwy\/aligned_allocator.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Sample object that keeps track on an external counter of how many times was\n\/\/ the explicit constructor and destructor called.\ntemplate \nclass SampleObject {\n public:\n SampleObject() { data_[0] = 'a'; }\n explicit SampleObject(int* counter) : counter_(counter) {\n if (counter) (*counter)++;\n data_[0] = 'b';\n }\n\n ~SampleObject() {\n if (counter_) (*counter_)--;\n }\n\n static_assert(N > sizeof(int*), \"SampleObject size too small.\");\n int* counter_ = nullptr;\n char data_[N - sizeof(int*)];\n};\n\nclass FakeAllocator {\n public:\n \/\/ static AllocPtr and FreePtr member to be used with the alligned\n \/\/ allocator. These functions calls the private non-static members.\n static void* StaticAlloc(void* opaque, size_t bytes) {\n return reinterpret_cast(opaque)->Alloc(bytes);\n }\n static void StaticFree(void* opaque, void* memory) {\n return reinterpret_cast(opaque)->Free(memory);\n }\n\n \/\/ Returns the number of pending allocations to be freed.\n size_t PendingAllocs() { return allocs_.size(); }\n\n private:\n void* Alloc(size_t bytes) {\n void* ret = malloc(bytes);\n allocs_.insert(ret);\n return ret;\n }\n void Free(void* memory) {\n if (!memory) return;\n EXPECT_NE(allocs_.end(), allocs_.find(memory));\n free(memory);\n allocs_.erase(memory);\n }\n\n std::set allocs_;\n};\n\n} \/\/ namespace\n\nnamespace hwy {\n\nclass AlignedAllocatorTest : public testing::Test {};\n\nTEST(AlignedAllocatorTest, FreeNullptr) {\n \/\/ Calling free with a nullptr is always ok.\n FreeAlignedBytes(\/*aligned_pointer=*\/nullptr, \/*free_ptr=*\/nullptr,\n \/*opaque_ptr=*\/nullptr);\n}\n\nTEST(AlignedAllocatorTest, Log2) {\n EXPECT_EQ(0u, detail::ShiftCount(1));\n EXPECT_EQ(1u, detail::ShiftCount(2));\n EXPECT_EQ(3u, detail::ShiftCount(8));\n}\n\n\/\/ Allocator returns null when it detects overflow of items * sizeof(T).\nTEST(AlignedAllocatorTest, Overflow) {\n constexpr size_t max = ~size_t(0);\n constexpr size_t msb = (max >> 1) + 1;\n using Size5 = std::array;\n using Size10 = std::array;\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 2, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 3, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 4, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb + 1, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb \/ 4, nullptr, nullptr));\n}\n\nTEST(AlignedAllocatorTest, AllocDefaultPointers) {\n const size_t kSize = 7777;\n void* ptr = AllocateAlignedBytes(kSize, \/*alloc_ptr=*\/nullptr,\n \/*opaque_ptr=*\/nullptr);\n ASSERT_NE(nullptr, ptr);\n \/\/ Make sure the pointer is actually aligned.\n EXPECT_EQ(0U, reinterpret_cast(ptr) % HWY_ALIGNMENT);\n char* p = static_cast(ptr);\n size_t ret = 0;\n for (size_t i = 0; i < kSize; i++) {\n \/\/ Performs a computation using p[] to prevent it being optimized away.\n p[i] = static_cast(i & 0x7F);\n if (i) ret += static_cast(p[i] * p[i - 1]);\n }\n EXPECT_NE(0U, ret);\n FreeAlignedBytes(ptr, \/*free_ptr=*\/nullptr, \/*opaque_ptr=*\/nullptr);\n}\n\nTEST(AlignedAllocatorTest, EmptyAlignedUniquePtr) {\n AlignedUniquePtr> ptr(nullptr, AlignedDeleter());\n AlignedUniquePtr[]> arr(nullptr, AlignedDeleter());\n}\n\nTEST(AlignedAllocatorTest, EmptyAlignedFreeUniquePtr) {\n AlignedFreeUniquePtr> ptr(nullptr, AlignedFreer());\n AlignedFreeUniquePtr[]> arr(nullptr, AlignedFreer());\n}\n\nTEST(AlignedAllocatorTest, CustomAlloc) {\n FakeAllocator fake_alloc;\n\n const size_t kSize = 7777;\n void* ptr =\n AllocateAlignedBytes(kSize, &FakeAllocator::StaticAlloc, &fake_alloc);\n ASSERT_NE(nullptr, ptr);\n \/\/ We should have only requested one alloc from the allocator.\n EXPECT_EQ(1U, fake_alloc.PendingAllocs());\n \/\/ Make sure the pointer is actually aligned.\n EXPECT_EQ(0U, reinterpret_cast(ptr) % HWY_ALIGNMENT);\n FreeAlignedBytes(ptr, &FakeAllocator::StaticFree, &fake_alloc);\n EXPECT_EQ(0U, fake_alloc.PendingAllocs());\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedDefaultConstructor) {\n {\n auto ptr = MakeUniqueAligned>();\n \/\/ Default constructor sets the data_[0] to 'a'.\n EXPECT_EQ('a', ptr->data_[0]);\n EXPECT_EQ(nullptr, ptr->counter_);\n }\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAligned) {\n int counter = 0;\n {\n \/\/ Creates the object, initializes it with the explicit constructor and\n \/\/ returns an unique_ptr to it.\n auto ptr = MakeUniqueAligned>(&counter);\n EXPECT_EQ(1, counter);\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', ptr->data_[0]);\n }\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedArray) {\n int counter = 0;\n {\n \/\/ Creates the array of objects and initializes them with the explicit\n \/\/ constructor.\n auto arr = MakeUniqueAlignedArray>(7, &counter);\n EXPECT_EQ(7, counter);\n for (size_t i = 0; i < 7; i++) {\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', arr[i].data_[0]) << \"Where i = \" << i;\n }\n }\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, AllocSingleInt) {\n auto ptr = AllocateAligned(1);\n ASSERT_NE(nullptr, ptr.get());\n EXPECT_EQ(0U, reinterpret_cast(ptr.get()) % HWY_ALIGNMENT);\n \/\/ Force delete of the unique_ptr now to check that it doesn't crash.\n ptr.reset(nullptr);\n EXPECT_EQ(nullptr, ptr.get());\n}\n\nTEST(AlignedAllocatorTest, AllocMultipleInt) {\n const size_t kSize = 7777;\n auto ptr = AllocateAligned(kSize);\n ASSERT_NE(nullptr, ptr.get());\n EXPECT_EQ(0U, reinterpret_cast(ptr.get()) % HWY_ALIGNMENT);\n \/\/ ptr[i] is actually (*ptr.get())[i] which will use the operator[] of the\n \/\/ underlying type chosen by AllocateAligned() for the std::unique_ptr.\n EXPECT_EQ(&(ptr[0]) + 1, &(ptr[1]));\n\n size_t ret = 0;\n for (size_t i = 0; i < kSize; i++) {\n \/\/ Performs a computation using ptr[] to prevent it being optimized away.\n ptr[i] = static_cast(i);\n if (i) ret += ptr[i] * ptr[i - 1];\n }\n EXPECT_NE(0U, ret);\n}\n\nTEST(AlignedAllocatorTest, AllocateAlignedObjectWithoutDestructor) {\n int counter = 0;\n {\n \/\/ This doesn't call the constructor.\n auto obj = AllocateAligned>(1);\n obj[0].counter_ = &counter;\n }\n \/\/ Destroying the unique_ptr shouldn't have called the destructor of the\n \/\/ SampleObject<24>.\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedArrayWithCustomAlloc) {\n FakeAllocator fake_alloc;\n int counter = 0;\n {\n \/\/ Creates the array of objects and initializes them with the explicit\n \/\/ constructor.\n auto arr = MakeUniqueAlignedArrayWithAlloc>(\n 7, FakeAllocator::StaticAlloc, FakeAllocator::StaticFree, &fake_alloc,\n &counter);\n ASSERT_NE(nullptr, arr.get());\n \/\/ An array should still only call a single allocation.\n EXPECT_EQ(1u, fake_alloc.PendingAllocs());\n EXPECT_EQ(7, counter);\n for (size_t i = 0; i < 7; i++) {\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', arr[i].data_[0]) << \"Where i = \" << i;\n }\n }\n EXPECT_EQ(0, counter);\n EXPECT_EQ(0u, fake_alloc.PendingAllocs());\n}\n\nTEST(AlignedAllocatorTest, DefaultInit) {\n \/\/ The test is whether this compiles. Default-init is useful for output params\n \/\/ and per-thread storage.\n std::vector> ptrs;\n std::vector> free_ptrs;\n ptrs.resize(128);\n free_ptrs.resize(128);\n \/\/ The following is to prevent elision of the pointers.\n std::mt19937 rng(129); \/\/ Emscripten lacks random_device.\n std::uniform_int_distribution dist(0, 127);\n ptrs[dist(rng)] = MakeUniqueAlignedArray(123);\n free_ptrs[dist(rng)] = AllocateAligned(456);\n \/\/ \"Use\" pointer without resorting to printf. 0 == 0. Can't shift by 64.\n const auto addr1 = reinterpret_cast(ptrs[dist(rng)].get());\n const auto addr2 = reinterpret_cast(free_ptrs[dist(rng)].get());\n constexpr size_t kBits = sizeof(uintptr_t) * 8;\n EXPECT_EQ((addr1 >> (kBits - 1)) >> (kBits - 1),\n (addr2 >> (kBits - 1)) >> (kBits - 1));\n}\n\n} \/\/ namespace hwy\nfix spurious use after free warning. Fixes #891\/\/ Copyright 2020 Google LLC\n\/\/ SPDX-License-Identifier: Apache-2.0\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"hwy\/aligned_allocator.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Sample object that keeps track on an external counter of how many times was\n\/\/ the explicit constructor and destructor called.\ntemplate \nclass SampleObject {\n public:\n SampleObject() { data_[0] = 'a'; }\n explicit SampleObject(int* counter) : counter_(counter) {\n if (counter) (*counter)++;\n data_[0] = 'b';\n }\n\n ~SampleObject() {\n if (counter_) (*counter_)--;\n }\n\n static_assert(N > sizeof(int*), \"SampleObject size too small.\");\n int* counter_ = nullptr;\n char data_[N - sizeof(int*)];\n};\n\nclass FakeAllocator {\n public:\n \/\/ static AllocPtr and FreePtr member to be used with the alligned\n \/\/ allocator. These functions calls the private non-static members.\n static void* StaticAlloc(void* opaque, size_t bytes) {\n return reinterpret_cast(opaque)->Alloc(bytes);\n }\n static void StaticFree(void* opaque, void* memory) {\n return reinterpret_cast(opaque)->Free(memory);\n }\n\n \/\/ Returns the number of pending allocations to be freed.\n size_t PendingAllocs() { return allocs_.size(); }\n\n private:\n void* Alloc(size_t bytes) {\n void* ret = malloc(bytes);\n allocs_.insert(ret);\n return ret;\n }\n void Free(void* memory) {\n if (!memory) return;\n EXPECT_NE(allocs_.end(), allocs_.find(memory));\n allocs_.erase(memory);\n free(memory);\n }\n\n std::set allocs_;\n};\n\n} \/\/ namespace\n\nnamespace hwy {\n\nclass AlignedAllocatorTest : public testing::Test {};\n\nTEST(AlignedAllocatorTest, FreeNullptr) {\n \/\/ Calling free with a nullptr is always ok.\n FreeAlignedBytes(\/*aligned_pointer=*\/nullptr, \/*free_ptr=*\/nullptr,\n \/*opaque_ptr=*\/nullptr);\n}\n\nTEST(AlignedAllocatorTest, Log2) {\n EXPECT_EQ(0u, detail::ShiftCount(1));\n EXPECT_EQ(1u, detail::ShiftCount(2));\n EXPECT_EQ(3u, detail::ShiftCount(8));\n}\n\n\/\/ Allocator returns null when it detects overflow of items * sizeof(T).\nTEST(AlignedAllocatorTest, Overflow) {\n constexpr size_t max = ~size_t(0);\n constexpr size_t msb = (max >> 1) + 1;\n using Size5 = std::array;\n using Size10 = std::array;\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 2, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 3, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(max \/ 4, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb + 1, nullptr, nullptr));\n EXPECT_EQ(nullptr,\n detail::AllocateAlignedItems(msb \/ 4, nullptr, nullptr));\n}\n\nTEST(AlignedAllocatorTest, AllocDefaultPointers) {\n const size_t kSize = 7777;\n void* ptr = AllocateAlignedBytes(kSize, \/*alloc_ptr=*\/nullptr,\n \/*opaque_ptr=*\/nullptr);\n ASSERT_NE(nullptr, ptr);\n \/\/ Make sure the pointer is actually aligned.\n EXPECT_EQ(0U, reinterpret_cast(ptr) % HWY_ALIGNMENT);\n char* p = static_cast(ptr);\n size_t ret = 0;\n for (size_t i = 0; i < kSize; i++) {\n \/\/ Performs a computation using p[] to prevent it being optimized away.\n p[i] = static_cast(i & 0x7F);\n if (i) ret += static_cast(p[i] * p[i - 1]);\n }\n EXPECT_NE(0U, ret);\n FreeAlignedBytes(ptr, \/*free_ptr=*\/nullptr, \/*opaque_ptr=*\/nullptr);\n}\n\nTEST(AlignedAllocatorTest, EmptyAlignedUniquePtr) {\n AlignedUniquePtr> ptr(nullptr, AlignedDeleter());\n AlignedUniquePtr[]> arr(nullptr, AlignedDeleter());\n}\n\nTEST(AlignedAllocatorTest, EmptyAlignedFreeUniquePtr) {\n AlignedFreeUniquePtr> ptr(nullptr, AlignedFreer());\n AlignedFreeUniquePtr[]> arr(nullptr, AlignedFreer());\n}\n\nTEST(AlignedAllocatorTest, CustomAlloc) {\n FakeAllocator fake_alloc;\n\n const size_t kSize = 7777;\n void* ptr =\n AllocateAlignedBytes(kSize, &FakeAllocator::StaticAlloc, &fake_alloc);\n ASSERT_NE(nullptr, ptr);\n \/\/ We should have only requested one alloc from the allocator.\n EXPECT_EQ(1U, fake_alloc.PendingAllocs());\n \/\/ Make sure the pointer is actually aligned.\n EXPECT_EQ(0U, reinterpret_cast(ptr) % HWY_ALIGNMENT);\n FreeAlignedBytes(ptr, &FakeAllocator::StaticFree, &fake_alloc);\n EXPECT_EQ(0U, fake_alloc.PendingAllocs());\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedDefaultConstructor) {\n {\n auto ptr = MakeUniqueAligned>();\n \/\/ Default constructor sets the data_[0] to 'a'.\n EXPECT_EQ('a', ptr->data_[0]);\n EXPECT_EQ(nullptr, ptr->counter_);\n }\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAligned) {\n int counter = 0;\n {\n \/\/ Creates the object, initializes it with the explicit constructor and\n \/\/ returns an unique_ptr to it.\n auto ptr = MakeUniqueAligned>(&counter);\n EXPECT_EQ(1, counter);\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', ptr->data_[0]);\n }\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedArray) {\n int counter = 0;\n {\n \/\/ Creates the array of objects and initializes them with the explicit\n \/\/ constructor.\n auto arr = MakeUniqueAlignedArray>(7, &counter);\n EXPECT_EQ(7, counter);\n for (size_t i = 0; i < 7; i++) {\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', arr[i].data_[0]) << \"Where i = \" << i;\n }\n }\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, AllocSingleInt) {\n auto ptr = AllocateAligned(1);\n ASSERT_NE(nullptr, ptr.get());\n EXPECT_EQ(0U, reinterpret_cast(ptr.get()) % HWY_ALIGNMENT);\n \/\/ Force delete of the unique_ptr now to check that it doesn't crash.\n ptr.reset(nullptr);\n EXPECT_EQ(nullptr, ptr.get());\n}\n\nTEST(AlignedAllocatorTest, AllocMultipleInt) {\n const size_t kSize = 7777;\n auto ptr = AllocateAligned(kSize);\n ASSERT_NE(nullptr, ptr.get());\n EXPECT_EQ(0U, reinterpret_cast(ptr.get()) % HWY_ALIGNMENT);\n \/\/ ptr[i] is actually (*ptr.get())[i] which will use the operator[] of the\n \/\/ underlying type chosen by AllocateAligned() for the std::unique_ptr.\n EXPECT_EQ(&(ptr[0]) + 1, &(ptr[1]));\n\n size_t ret = 0;\n for (size_t i = 0; i < kSize; i++) {\n \/\/ Performs a computation using ptr[] to prevent it being optimized away.\n ptr[i] = static_cast(i);\n if (i) ret += ptr[i] * ptr[i - 1];\n }\n EXPECT_NE(0U, ret);\n}\n\nTEST(AlignedAllocatorTest, AllocateAlignedObjectWithoutDestructor) {\n int counter = 0;\n {\n \/\/ This doesn't call the constructor.\n auto obj = AllocateAligned>(1);\n obj[0].counter_ = &counter;\n }\n \/\/ Destroying the unique_ptr shouldn't have called the destructor of the\n \/\/ SampleObject<24>.\n EXPECT_EQ(0, counter);\n}\n\nTEST(AlignedAllocatorTest, MakeUniqueAlignedArrayWithCustomAlloc) {\n FakeAllocator fake_alloc;\n int counter = 0;\n {\n \/\/ Creates the array of objects and initializes them with the explicit\n \/\/ constructor.\n auto arr = MakeUniqueAlignedArrayWithAlloc>(\n 7, FakeAllocator::StaticAlloc, FakeAllocator::StaticFree, &fake_alloc,\n &counter);\n ASSERT_NE(nullptr, arr.get());\n \/\/ An array should still only call a single allocation.\n EXPECT_EQ(1u, fake_alloc.PendingAllocs());\n EXPECT_EQ(7, counter);\n for (size_t i = 0; i < 7; i++) {\n \/\/ Custom constructor sets the data_[0] to 'b'.\n EXPECT_EQ('b', arr[i].data_[0]) << \"Where i = \" << i;\n }\n }\n EXPECT_EQ(0, counter);\n EXPECT_EQ(0u, fake_alloc.PendingAllocs());\n}\n\nTEST(AlignedAllocatorTest, DefaultInit) {\n \/\/ The test is whether this compiles. Default-init is useful for output params\n \/\/ and per-thread storage.\n std::vector> ptrs;\n std::vector> free_ptrs;\n ptrs.resize(128);\n free_ptrs.resize(128);\n \/\/ The following is to prevent elision of the pointers.\n std::mt19937 rng(129); \/\/ Emscripten lacks random_device.\n std::uniform_int_distribution dist(0, 127);\n ptrs[dist(rng)] = MakeUniqueAlignedArray(123);\n free_ptrs[dist(rng)] = AllocateAligned(456);\n \/\/ \"Use\" pointer without resorting to printf. 0 == 0. Can't shift by 64.\n const auto addr1 = reinterpret_cast(ptrs[dist(rng)].get());\n const auto addr2 = reinterpret_cast(free_ptrs[dist(rng)].get());\n constexpr size_t kBits = sizeof(uintptr_t) * 8;\n EXPECT_EQ((addr1 >> (kBits - 1)) >> (kBits - 1),\n (addr2 >> (kBits - 1)) >> (kBits - 1));\n}\n\n} \/\/ namespace hwy\n<|endoftext|>"} {"text":"\/*\n * AtomsReader.cpp\n *****************************************************************************\n * Copyright (C) 2014 - VideoLAN authors\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n#include \"AtomsReader.hpp\"\n#include \"mpd\/Representation.h\"\n#include \"mpd\/MPD.h\"\n\nusing namespace dash::mp4;\nusing namespace dash::mpd;\n\nAtomsReader::AtomsReader(vlc_object_t *object_)\n{\n object = object_;\n rootbox = NULL;\n}\n\nAtomsReader::~AtomsReader()\n{\n while(rootbox && rootbox->p_first)\n {\n MP4_Box_t *p_next = rootbox->p_first->p_next;\n MP4_BoxFree( (stream_t *)object, rootbox->p_first );\n rootbox->p_first = p_next;\n }\n delete rootbox;\n}\n\nbool AtomsReader::parseBlock(void *buffer, size_t size, BaseRepresentation *rep)\n{\n if(!rep)\n return false;\n\n stream_t *stream = stream_MemoryNew( object, (uint8_t *)buffer, size, true);\n if (stream)\n {\n rootbox = new MP4_Box_t;\n if(!rootbox)\n {\n stream_Delete(stream);\n return false;\n }\n memset(rootbox, 0, sizeof(*rootbox));\n rootbox->i_type = ATOM_root;\n rootbox->i_size = size;\n if ( MP4_ReadBoxContainerChildren( stream, rootbox, 0 ) == 1 )\n {\n#ifndef NDEBUG\n MP4_BoxDumpStructure(stream, rootbox);\n#endif\n MP4_Box_t *sidxbox = MP4_BoxGet(rootbox, \"sidx\");\n if (sidxbox)\n {\n Representation::SplitPoint point;\n std::vector splitlist;\n MP4_Box_data_sidx_t *sidx = sidxbox->data.p_sidx;\n point.offset = sidx->i_first_offset;\n point.time = 0;\n for(uint16_t i=0; ii_reference_count; i++)\n {\n splitlist.push_back(point);\n point.offset += sidx->p_items[i].i_referenced_size;\n point.time += sidx->p_items[i].i_subsegment_duration;\n }\n rep->SplitUsingIndex(splitlist);\n rep->getPlaylist()->debug();\n }\n }\n stream_Delete(stream);\n }\n\n return true;\n}\ndemux: dash: index time is scaled\/*\n * AtomsReader.cpp\n *****************************************************************************\n * Copyright (C) 2014 - VideoLAN authors\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU Lesser General Public License as published\n * by the Free Software Foundation; either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.\n *****************************************************************************\/\n#include \"AtomsReader.hpp\"\n#include \"mpd\/Representation.h\"\n#include \"mpd\/MPD.h\"\n\nusing namespace dash::mp4;\nusing namespace dash::mpd;\n\nAtomsReader::AtomsReader(vlc_object_t *object_)\n{\n object = object_;\n rootbox = NULL;\n}\n\nAtomsReader::~AtomsReader()\n{\n while(rootbox && rootbox->p_first)\n {\n MP4_Box_t *p_next = rootbox->p_first->p_next;\n MP4_BoxFree( (stream_t *)object, rootbox->p_first );\n rootbox->p_first = p_next;\n }\n delete rootbox;\n}\n\nbool AtomsReader::parseBlock(void *buffer, size_t size, BaseRepresentation *rep)\n{\n if(!rep)\n return false;\n\n stream_t *stream = stream_MemoryNew( object, (uint8_t *)buffer, size, true);\n if (stream)\n {\n rootbox = new MP4_Box_t;\n if(!rootbox)\n {\n stream_Delete(stream);\n return false;\n }\n memset(rootbox, 0, sizeof(*rootbox));\n rootbox->i_type = ATOM_root;\n rootbox->i_size = size;\n if ( MP4_ReadBoxContainerChildren( stream, rootbox, 0 ) == 1 )\n {\n#ifndef NDEBUG\n MP4_BoxDumpStructure(stream, rootbox);\n#endif\n MP4_Box_t *sidxbox = MP4_BoxGet(rootbox, \"sidx\");\n if (sidxbox)\n {\n Representation::SplitPoint point;\n std::vector splitlist;\n MP4_Box_data_sidx_t *sidx = sidxbox->data.p_sidx;\n point.offset = sidx->i_first_offset;\n point.time = 0;\n for(uint16_t i=0; ii_reference_count && sidx->i_timescale; i++)\n {\n splitlist.push_back(point);\n point.offset += sidx->p_items[i].i_referenced_size;\n point.time += CLOCK_FREQ * sidx->p_items[i].i_subsegment_duration \/\n sidx->i_timescale;\n }\n rep->SplitUsingIndex(splitlist);\n rep->getPlaylist()->debug();\n }\n }\n stream_Delete(stream);\n }\n\n return true;\n}\n<|endoftext|>"} {"text":"\/\/===-- OsLogger.cpp --------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OsLogger.h\"\n\n#if LLDB_USE_OS_LOG\n\n#include \n\n#include \"DNBDefs.h\"\n#include \"DNBLog.h\"\n\n#define LLDB_OS_LOG_MAX_BUFFER_LENGTH 256\n\nnamespace {\n\/\/----------------------------------------------------------------------\n\/\/ Darwin os_log logging callback that can be registered with\n\/\/ DNBLogSetLogCallback\n\/\/----------------------------------------------------------------------\nvoid DarwinLogCallback(void *baton, uint32_t flags, const char *format,\n va_list args) {\n if (format == nullptr)\n return;\n\n static os_log_t g_logger;\n if (!g_logger) {\n g_logger = os_log_create(\"com.apple.dt.lldb\", \"debugserver\");\n if (!g_logger)\n return;\n }\n\n os_log_type_t log_type;\n if (flags & DNBLOG_FLAG_FATAL)\n log_type = OS_LOG_TYPE_FAULT;\n else if (flags & DNBLOG_FLAG_ERROR)\n log_type = OS_LOG_TYPE_ERROR;\n else if (flags & DNBLOG_FLAG_WARNING)\n log_type = OS_LOG_TYPE_DEFAULT;\n else if (flags & DNBLOG_FLAG_VERBOSE)\n log_type = OS_LOG_TYPE_DEBUG;\n else\n log_type = OS_LOG_TYPE_DEFAULT;\n\n \/\/ This code is unfortunate. os_log* only takes static strings, but\n \/\/ our current log API isn't set up to make use of that style.\n char buffer[LLDB_OS_LOG_MAX_BUFFER_LENGTH];\n vsnprintf(buffer, sizeof(buffer), format, args);\n os_log_with_type(g_logger, log_type, \"%{public}s\", buffer);\n}\n}\n\nDNBCallbackLog OsLogger::GetLogFunction() {\n return _os_log_impl ? DarwinLogCallback : nullptr;\n}\n\n#else\n\nDNBCallbackLog OsLogger::GetLogFunction() { return nullptr; }\n\n#endif\nConditionalized OsLogger.cpp on a modern SDK.\/\/===-- OsLogger.cpp --------------------------------------------*- C++ -*-===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"OsLogger.h\"\n#include \n\n#if (LLDB_USE_OS_LOG) && (__MAC_OS_X_VERSION_MAX_ALLOWED >= 101200)\n\n#include \n\n#include \"DNBDefs.h\"\n#include \"DNBLog.h\"\n\n#define LLDB_OS_LOG_MAX_BUFFER_LENGTH 256\n\nnamespace {\n\/\/----------------------------------------------------------------------\n\/\/ Darwin os_log logging callback that can be registered with\n\/\/ DNBLogSetLogCallback\n\/\/----------------------------------------------------------------------\nvoid DarwinLogCallback(void *baton, uint32_t flags, const char *format,\n va_list args) {\n if (format == nullptr)\n return;\n\n static os_log_t g_logger;\n if (!g_logger) {\n g_logger = os_log_create(\"com.apple.dt.lldb\", \"debugserver\");\n if (!g_logger)\n return;\n }\n\n os_log_type_t log_type;\n if (flags & DNBLOG_FLAG_FATAL)\n log_type = OS_LOG_TYPE_FAULT;\n else if (flags & DNBLOG_FLAG_ERROR)\n log_type = OS_LOG_TYPE_ERROR;\n else if (flags & DNBLOG_FLAG_WARNING)\n log_type = OS_LOG_TYPE_DEFAULT;\n else if (flags & DNBLOG_FLAG_VERBOSE)\n log_type = OS_LOG_TYPE_DEBUG;\n else\n log_type = OS_LOG_TYPE_DEFAULT;\n\n \/\/ This code is unfortunate. os_log* only takes static strings, but\n \/\/ our current log API isn't set up to make use of that style.\n char buffer[LLDB_OS_LOG_MAX_BUFFER_LENGTH];\n vsnprintf(buffer, sizeof(buffer), format, args);\n os_log_with_type(g_logger, log_type, \"%{public}s\", buffer);\n}\n}\n\nDNBCallbackLog OsLogger::GetLogFunction() {\n return _os_log_impl ? DarwinLogCallback : nullptr;\n}\n\n#else\n\nDNBCallbackLog OsLogger::GetLogFunction() { return nullptr; }\n\n#endif\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelsoundsettingsapplet.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"soundsettingsapplet.h\"\n\n#include \n#include \n#include \n\n#include \"alerttone.h\"\n#include \"alerttonetoplevel.h\"\n#include \"alerttonebrowser.h\"\n#include \"alerttoneappletwidget.h\"\n\n#define DEBUG\n#define WARNING\n#include \"..\/debug.h\"\n\n#ifndef UNIT_TEST\n#include \nM_LIBRARY\n#endif\n\nQ_EXPORT_PLUGIN2(soundsettingsapplet, SoundSettingsApplet)\n\nint gst_argc = 1;\nchar** gst_argv = NULL;\n\nSoundSettingsApplet::SoundSettingsApplet()\n{\n}\n\nSoundSettingsApplet::~SoundSettingsApplet()\n{\n\tgst_deinit ();\n\n if ((gst_argv != NULL) && (gst_argv[0] != NULL))\n {\n delete[] gst_argv[0];\n delete[] gst_argv;\n }\n}\n\nvoid\nSoundSettingsApplet::init()\n{\n gst_argv = new char*[2];\n gst_argv[0] = qstrdup (\"app\");\n gst_argv[1] = NULL;\n\n gst_init (&gst_argc, &gst_argv);\n\n m_alertTones = AlertTone::alertTones ();\n}\n\n\/* widgetId: 0xaaaabbbb where \n 0xaaaa is the widget ID and \n 0xbbbb is the alert tone index *\/\nDcpWidget *\nSoundSettingsApplet::constructWidget(int widgetId)\n{\n SYS_DEBUG (\"%s: widgetId = %d\", SYS_TIME_STR, widgetId);\n\tAlertToneToplevel *newWidget = NULL;\n\tint realWidgetId = widgetId \/ 65536;\n\tint alertToneIdx = widgetId - realWidgetId * 65536;\n\n\tif (m_stack.size() > 0)\n\t\tif (((m_stack.top()->getWidgetId() \/ 65536) == AlertToneBrowser_id && realWidgetId == AlertToneBrowser_id) ||\n\t\t ((m_stack.top()->getWidgetId() \/ 65536) == AlertToneAppletWidget_id && realWidgetId != AlertToneBrowser_id))\n\t\t\treturn NULL;\n\n\tif (AlertToneAppletWidget_id == realWidgetId)\n\t\tnewWidget = new AlertToneAppletWidget(m_alertTones);\n\telse\n\tif (AlertToneBrowser_id == realWidgetId && alertToneIdx >= 0 && alertToneIdx < m_alertTones.size())\n\t\tnewWidget = new AlertToneBrowser(m_alertTones[alertToneIdx]);\n\telse\n\t\tSYS_WARNING (\"Invalid widgetId = %d\", widgetId);\n\n\tif (newWidget)\n {\n\t\tm_stack.push(newWidget);\n\t\tconnect (newWidget, SIGNAL (destroyed (QObject *)),\n SLOT (toplevelDestroyed (QObject *)));\n\t}\n\n SYS_DEBUG (\"%s: done\", SYS_TIME_STR);\n\treturn newWidget;\n}\n\nvoid\nSoundSettingsApplet::toplevelDestroyed(QObject *goner)\n{\n\tif (m_stack.size() > 0)\n\t\tif (goner == qobject_cast(m_stack.top()))\n\t\t\tm_stack.pop();\n}\n\nQString\nSoundSettingsApplet::title() const\n{\n QString title = qtTrId(\"qtn_sond_sounds\");\n\n\tif (m_stack.size() > 0)\n \tif (m_stack.top())\n\t\t\ttitle = qobject_cast(m_stack.top())->title();\n\n\treturn title;\n}\n\nQVector \nSoundSettingsApplet::viewMenuItems()\n{\n\tQVector vector;\n\n\tif (m_stack.size() > 0)\n\t\tif (m_stack.top())\n\t\t\tvector = qobject_cast(m_stack.top())->viewMenuItems();\n\n\treturn vector;\n}\n\nDcpBrief *\nSoundSettingsApplet::constructBrief (\n int partId)\n{\n Q_UNUSED (partId);\n return NULL;\n}\n\nChanges: disable debug\/****************************************************************************\n**\n** Copyright (C) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of meegotouch-controlpanelsoundsettingsapplet.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n#include \"soundsettingsapplet.h\"\n\n#include \n#include \n#include \n\n#include \"alerttone.h\"\n#include \"alerttonetoplevel.h\"\n#include \"alerttonebrowser.h\"\n#include \"alerttoneappletwidget.h\"\n\n#undef DEBUG\n#define WARNING\n#include \"..\/debug.h\"\n\n#ifndef UNIT_TEST\n#include \nM_LIBRARY\n#endif\n\nQ_EXPORT_PLUGIN2(soundsettingsapplet, SoundSettingsApplet)\n\nint gst_argc = 1;\nchar** gst_argv = NULL;\n\nSoundSettingsApplet::SoundSettingsApplet()\n{\n}\n\nSoundSettingsApplet::~SoundSettingsApplet()\n{\n\tgst_deinit ();\n\n if ((gst_argv != NULL) && (gst_argv[0] != NULL))\n {\n delete[] gst_argv[0];\n delete[] gst_argv;\n }\n}\n\nvoid\nSoundSettingsApplet::init()\n{\n gst_argv = new char*[2];\n gst_argv[0] = qstrdup (\"app\");\n gst_argv[1] = NULL;\n\n gst_init (&gst_argc, &gst_argv);\n\n m_alertTones = AlertTone::alertTones ();\n}\n\n\/* widgetId: 0xaaaabbbb where \n 0xaaaa is the widget ID and \n 0xbbbb is the alert tone index *\/\nDcpWidget *\nSoundSettingsApplet::constructWidget(int widgetId)\n{\n SYS_DEBUG (\"%s: widgetId = %d\", SYS_TIME_STR, widgetId);\n\tAlertToneToplevel *newWidget = NULL;\n\tint realWidgetId = widgetId \/ 65536;\n\tint alertToneIdx = widgetId - realWidgetId * 65536;\n\n\tif (m_stack.size() > 0)\n\t\tif (((m_stack.top()->getWidgetId() \/ 65536) == AlertToneBrowser_id && realWidgetId == AlertToneBrowser_id) ||\n\t\t ((m_stack.top()->getWidgetId() \/ 65536) == AlertToneAppletWidget_id && realWidgetId != AlertToneBrowser_id))\n\t\t\treturn NULL;\n\n\tif (AlertToneAppletWidget_id == realWidgetId)\n\t\tnewWidget = new AlertToneAppletWidget(m_alertTones);\n\telse\n\tif (AlertToneBrowser_id == realWidgetId && alertToneIdx >= 0 && alertToneIdx < m_alertTones.size())\n\t\tnewWidget = new AlertToneBrowser(m_alertTones[alertToneIdx]);\n\telse\n\t\tSYS_WARNING (\"Invalid widgetId = %d\", widgetId);\n\n\tif (newWidget)\n {\n\t\tm_stack.push(newWidget);\n\t\tconnect (newWidget, SIGNAL (destroyed (QObject *)),\n SLOT (toplevelDestroyed (QObject *)));\n\t}\n\n SYS_DEBUG (\"%s: done\", SYS_TIME_STR);\n\treturn newWidget;\n}\n\nvoid\nSoundSettingsApplet::toplevelDestroyed(QObject *goner)\n{\n\tif (m_stack.size() > 0)\n\t\tif (goner == qobject_cast(m_stack.top()))\n\t\t\tm_stack.pop();\n}\n\nQString\nSoundSettingsApplet::title() const\n{\n QString title = qtTrId(\"qtn_sond_sounds\");\n\n\tif (m_stack.size() > 0)\n \tif (m_stack.top())\n\t\t\ttitle = qobject_cast(m_stack.top())->title();\n\n\treturn title;\n}\n\nQVector \nSoundSettingsApplet::viewMenuItems()\n{\n\tQVector vector;\n\n\tif (m_stack.size() > 0)\n\t\tif (m_stack.top())\n\t\t\tvector = qobject_cast(m_stack.top())->viewMenuItems();\n\n\treturn vector;\n}\n\nDcpBrief *\nSoundSettingsApplet::constructBrief (\n int partId)\n{\n Q_UNUSED (partId);\n return NULL;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include \"intro.h\"\n#include \"ui_intro.h\"\n\n#include \"guiutil.h\"\n\n#include \"util.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nstatic const uint64_t GB_BYTES = 1000000000LL;\n\/* Minimum free space (in GB) needed for data directory *\/\nstatic const uint64_t BLOCK_CHAIN_SIZE = 50;\n\/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target *\/\nstatic const uint64_t CHAIN_STATE_SIZE = 2;\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \"intro.moc\"\n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n namespace fs = boost::filesystem;\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(0),\n signalled(false)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));\n ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));\n uint64_t pruneTarget = std::max(0, GetArg(\"-prune\", 0));\n requiredSpace = BLOCK_CHAIN_SIZE;\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n }\n }\n requiredSpace += CHAIN_STATE_SIZE;\n ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(tr(PACKAGE_NAME)).arg(requiredSpace));\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n Q_EMIT stopThread();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nbool Intro::pickDataDirectory()\n{\n namespace fs = boost::filesystem;\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || GetBoolArg(\"-resetguisettings\", false))\n {\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro;\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(0, tr(PACKAGE_NAME),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory())\n SoftSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));\n connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));\n \/* make sure executor object is deleted in its own thread *\/\n connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));\n connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\nUpdate src\/qt\/intro.cpp\/\/ Copyright (c) 2011-2016 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \"config\/bitcoin-config.h\"\n#endif\n\n#include \"intro.h\"\n#include \"ui_intro.h\"\n\n#include \"guiutil.h\"\n\n#include \"util.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n\nstatic const uint64_t GB_BYTES = 1000000000LL;\n\/* Minimum free space (in GB) needed for data directory *\/\nstatic const uint64_t BLOCK_CHAIN_SIZE = 55;\n\/* Minimum free space (in GB) needed for data directory when pruned; Does not include prune target *\/\nstatic const uint64_t CHAIN_STATE_SIZE = 2;\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \"intro.moc\"\n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n namespace fs = boost::filesystem;\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(0),\n signalled(false)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));\n ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));\n uint64_t pruneTarget = std::max(0, GetArg(\"-prune\", 0));\n requiredSpace = BLOCK_CHAIN_SIZE;\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n }\n }\n requiredSpace += CHAIN_STATE_SIZE;\n ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(tr(PACKAGE_NAME)).arg(requiredSpace));\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n Q_EMIT stopThread();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nbool Intro::pickDataDirectory()\n{\n namespace fs = boost::filesystem;\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || GetBoolArg(\"-resetguisettings\", false))\n {\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro;\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(0, tr(PACKAGE_NAME),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory())\n SoftSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));\n connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));\n \/* make sure executor object is deleted in its own thread *\/\n connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));\n connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\n<|endoftext|>"} {"text":"#include \"Shader.h\"\n#include \"renderers\/utils\/GLResourceManager.h\"\n#include \"utils\/Log.h\"\n\n#include \n\nnamespace carto {\n\n Shader::~Shader() {\n }\n\n GLuint Shader::getProgId() const {\n create();\n return _progId;\n }\n \n GLuint Shader::getUniformLoc(const std::string& uniformName) const {\n auto it = _uniformMap.find(uniformName);\n if (it == _uniformMap.end()) {\n Log::Errorf(\"Shader::getUniformLoc: Uniform '%s' not found in shader '%s'\", uniformName.c_str(), _name.c_str());\n return 0;\n }\n return it->second;\n }\n \n GLuint Shader::getAttribLoc(const std::string& attribName) const {\n auto it = _attribMap.find(attribName);\n if (it == _attribMap.end()) {\n Log::Errorf(\"Shader::getAttribLoc: Attribute '%s' not found in shader '%s'\", attribName.c_str(), _name.c_str());\n return 0;\n }\n return it->second;\n }\n \n Shader::Shader(const std::weak_ptr& manager, const std::string& name, const std::string& vertSource, const std::string& fragSource) :\n GLResource(manager),\n _name(name),\n _vertSource(vertSource),\n _fragSource(fragSource),\n _progId(0),\n _vertShaderId(0),\n _fragShaderId(0),\n _uniformMap(),\n _attribMap()\n {\n }\n\n void Shader::create() const {\n if (_progId == 0) {\n _vertShaderId = LoadShader(_name, _vertSource, GL_VERTEX_SHADER);\n _fragShaderId = LoadShader(_name, _fragSource, GL_FRAGMENT_SHADER);\n _progId = LoadProg(_name, _vertShaderId, _fragShaderId);\n\n registerVars(_progId);\n }\n }\n\n void Shader::destroy() const {\n if (_vertShaderId) {\n glDeleteShader(_vertShaderId);\n _vertShaderId = 0;\n }\n \n if (_fragShaderId) {\n glDeleteShader(_fragShaderId);\n _fragShaderId = 0;\n }\n \n if (_progId) {\n glDeleteProgram(_progId);\n _progId = 0;\n }\n \n _uniformMap.clear();\n _attribMap.clear();\n \n GLContext::CheckGLError(\"Shader::destroy\");\n }\n \n void Shader::registerVars(GLuint progId) const {\n enum { VAR_NAME_BUF_SIZE = 256 };\n char varNameBuf[VAR_NAME_BUF_SIZE];\n GLint count = 0;\n \n \/\/ Assign a location for every uniform variable, save them to map\n glGetProgramiv(progId, GL_ACTIVE_UNIFORMS, &count);\n for (GLuint tsj = 0; tsj < (GLuint) count; tsj++) {\n GLsizei actualLength = 0;\n GLint size = 0;\n GLenum type = 0;\n glGetActiveUniform(progId, tsj, VAR_NAME_BUF_SIZE, &actualLength, &size, &type, varNameBuf);\n std::string varName(varNameBuf, actualLength);\n GLuint loc = glGetUniformLocation(progId, varName.c_str());\n _uniformMap[varName] = loc;\n }\n \n \/\/ Assign a location for every attribute variable, save them to map\n glGetProgramiv(progId, GL_ACTIVE_ATTRIBUTES, &count);\n for (GLuint tsj = 0; tsj < (GLuint) count; tsj++) {\n GLsizei actualLength = 0;\n GLint size = 0;\n GLenum type = 0;\n glGetActiveAttrib(progId, tsj, VAR_NAME_BUF_SIZE, &actualLength, &size, &type, varNameBuf);\n std::string varName(varNameBuf, actualLength);\n GLuint loc = glGetAttribLocation(progId, varName.c_str());\n _attribMap[varName] = loc;\n }\n \n GLContext::CheckGLError(\"Shader::registerVars\");\n }\n\n GLuint Shader::LoadProg(const std::string& name, GLuint vertShaderId, GLuint fragShaderId) {\n GLuint progId = glCreateProgram();\n if (progId == 0) {\n Log::Errorf(\"Shader::LoadProg: Failed to create shader program in '%s' shader\", name.c_str());\n return 0;\n }\n\n glAttachShader(progId, vertShaderId);\n glAttachShader(progId, fragShaderId);\n glLinkProgram(progId);\n GLint linked = GL_FALSE;\n glGetProgramiv(progId, GL_LINK_STATUS, &linked);\n if (linked == GL_FALSE) {\n GLint infoLen = 0;\n glGetShaderiv(progId, GL_INFO_LOG_LENGTH, &infoLen);\n if (infoLen > 0) {\n std::vector infoBuf(infoLen);\n glGetProgramInfoLog(progId, infoLen, NULL, infoBuf.data());\n Log::Errorf(\"Shader::LoadProg: Failed to link shader program in '%s' shader \\n Error: %s \", name.c_str(), infoBuf.data());\n }\n glDeleteProgram(progId);\n progId = 0;\n }\n\n GLContext::CheckGLError(\"Shader::LoadProg\");\n\n return progId;\n }\n\n GLuint Shader::LoadShader(const std::string& name, const std::string& source, GLenum shaderType) {\n GLuint shaderId = glCreateShader(shaderType);\n if (shaderId == 0) {\n Log::Errorf(\"Shader::LoadShader: Failed to create shader type %i in '%s' shader\", shaderType, name.c_str());\n return 0;\n }\n\n const char* sourceBuf = source.data();\n glShaderSource(shaderId, 1, &sourceBuf, NULL);\n\n glCompileShader(shaderId);\n GLint compiled = GL_FALSE;\n glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compiled);\n if (compiled == GL_FALSE) {\n GLint infoLen = 0;\n glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLen);\n if (infoLen > 0) {\n std::vector infoBuf(infoLen);\n glGetShaderInfoLog(shaderId, infoLen, NULL, infoBuf.data());\n Log::Errorf(\"Shader::LoadShader: Failed to compile shader type %i in '%s' shader \\n Error: %s \", shaderType, name.c_str(), infoBuf.data());\n }\n glDeleteShader(shaderId);\n shaderId = 0;\n }\n\n GLContext::CheckGLError(\"Shader::LoadShader\");\n\n return shaderId;\n }\n\n}\nMinor cleanup of the Shader wrapper#include \"Shader.h\"\n#include \"renderers\/utils\/GLResourceManager.h\"\n#include \"utils\/Log.h\"\n\n#include \n\nnamespace carto {\n\n Shader::~Shader() {\n }\n\n GLuint Shader::getProgId() const {\n create();\n return _progId;\n }\n \n GLuint Shader::getUniformLoc(const std::string& uniformName) const {\n create();\n auto it = _uniformMap.find(uniformName);\n if (it == _uniformMap.end()) {\n Log::Errorf(\"Shader::getUniformLoc: Uniform '%s' not found in shader '%s'\", uniformName.c_str(), _name.c_str());\n return 0;\n }\n return it->second;\n }\n \n GLuint Shader::getAttribLoc(const std::string& attribName) const {\n create();\n auto it = _attribMap.find(attribName);\n if (it == _attribMap.end()) {\n Log::Errorf(\"Shader::getAttribLoc: Attribute '%s' not found in shader '%s'\", attribName.c_str(), _name.c_str());\n return 0;\n }\n return it->second;\n }\n \n Shader::Shader(const std::weak_ptr& manager, const std::string& name, const std::string& vertSource, const std::string& fragSource) :\n GLResource(manager),\n _name(name),\n _vertSource(vertSource),\n _fragSource(fragSource),\n _progId(0),\n _vertShaderId(0),\n _fragShaderId(0),\n _uniformMap(),\n _attribMap()\n {\n }\n\n void Shader::create() const {\n enum { VAR_NAME_BUF_SIZE = 256 };\n\n if (_vertShaderId == 0) {\n _vertShaderId = LoadShader(_name, _vertSource, GL_VERTEX_SHADER);\n }\n\n if (_fragShaderId == 0) {\n _fragShaderId = LoadShader(_name, _fragSource, GL_FRAGMENT_SHADER);\n }\n\n if (_progId == 0) {\n _progId = LoadProg(_name, _vertShaderId, _fragShaderId);\n\n \/\/ Assign a location for every uniform variable, save them to map\n GLint uniformCount = 0;\n glGetProgramiv(_progId, GL_ACTIVE_UNIFORMS, &uniformCount);\n for (GLuint tsj = 0; tsj < (GLuint) uniformCount; tsj++) {\n char varNameBuf[VAR_NAME_BUF_SIZE];\n GLsizei actualLength = 0;\n GLint size = 0;\n GLenum type = 0;\n glGetActiveUniform(_progId, tsj, VAR_NAME_BUF_SIZE, &actualLength, &size, &type, varNameBuf);\n std::string varName(varNameBuf, actualLength);\n GLuint loc = glGetUniformLocation(_progId, varName.c_str());\n _uniformMap[varName] = loc;\n }\n \n \/\/ Assign a location for every attribute variable, save them to map\n GLint attribCount = 0;\n glGetProgramiv(_progId, GL_ACTIVE_ATTRIBUTES, &attribCount);\n for (GLuint tsj = 0; tsj < (GLuint) attribCount; tsj++) {\n char varNameBuf[VAR_NAME_BUF_SIZE];\n GLsizei actualLength = 0;\n GLint size = 0;\n GLenum type = 0;\n glGetActiveAttrib(_progId, tsj, VAR_NAME_BUF_SIZE, &actualLength, &size, &type, varNameBuf);\n std::string varName(varNameBuf, actualLength);\n GLuint loc = glGetAttribLocation(_progId, varName.c_str());\n _attribMap[varName] = loc;\n }\n\n GLContext::CheckGLError(\"Shader::create\");\n }\n }\n\n void Shader::destroy() const {\n if (_vertShaderId != 0) {\n glDeleteShader(_vertShaderId);\n _vertShaderId = 0;\n }\n \n if (_fragShaderId != 0) {\n glDeleteShader(_fragShaderId);\n _fragShaderId = 0;\n }\n \n if (_progId != 0) {\n glDeleteProgram(_progId);\n _progId = 0;\n\n _uniformMap.clear();\n _attribMap.clear();\n\n GLContext::CheckGLError(\"Shader::destroy\");\n }\n }\n \n GLuint Shader::LoadProg(const std::string& name, GLuint vertShaderId, GLuint fragShaderId) {\n GLuint progId = glCreateProgram();\n if (progId == 0) {\n Log::Errorf(\"Shader::LoadProg: Failed to create shader program in '%s' shader\", name.c_str());\n return 0;\n }\n\n glAttachShader(progId, vertShaderId);\n glAttachShader(progId, fragShaderId);\n glLinkProgram(progId);\n GLint linked = GL_FALSE;\n glGetProgramiv(progId, GL_LINK_STATUS, &linked);\n if (linked == GL_FALSE) {\n GLint infoLen = 0;\n glGetShaderiv(progId, GL_INFO_LOG_LENGTH, &infoLen);\n if (infoLen > 0) {\n std::vector infoBuf(infoLen);\n glGetProgramInfoLog(progId, infoLen, NULL, infoBuf.data());\n Log::Errorf(\"Shader::LoadProg: Failed to link shader program in '%s' shader \\n Error: %s \", name.c_str(), infoBuf.data());\n }\n glDeleteProgram(progId);\n progId = 0;\n }\n\n GLContext::CheckGLError(\"Shader::LoadProg\");\n\n return progId;\n }\n\n GLuint Shader::LoadShader(const std::string& name, const std::string& source, GLenum shaderType) {\n GLuint shaderId = glCreateShader(shaderType);\n if (shaderId == 0) {\n Log::Errorf(\"Shader::LoadShader: Failed to create shader type %i in '%s' shader\", shaderType, name.c_str());\n return 0;\n }\n\n const char* sourceBuf = source.data();\n glShaderSource(shaderId, 1, &sourceBuf, NULL);\n\n glCompileShader(shaderId);\n GLint compiled = GL_FALSE;\n glGetShaderiv(shaderId, GL_COMPILE_STATUS, &compiled);\n if (compiled == GL_FALSE) {\n GLint infoLen = 0;\n glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &infoLen);\n if (infoLen > 0) {\n std::vector infoBuf(infoLen);\n glGetShaderInfoLog(shaderId, infoLen, NULL, infoBuf.data());\n Log::Errorf(\"Shader::LoadShader: Failed to compile shader type %i in '%s' shader \\n Error: %s \", shaderType, name.c_str(), infoBuf.data());\n }\n glDeleteShader(shaderId);\n shaderId = 0;\n }\n\n GLContext::CheckGLError(\"Shader::LoadShader\");\n\n return shaderId;\n }\n\n}\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nnamespace animation {\nKeyframeEditorWidget::KeyframeEditorWidget(Keyframe &keyframe, SequenceEditorWidget *parent)\n : QWidget(parent), keyframe_(keyframe), sequenceEditorWidget_(parent) {\n\n setObjectName(\"KeyframeEditorWidget\");\n\n keyframe.addObserver(this);\n\n layout_ = new QHBoxLayout();\n \n\n timeSpinner_ = new QDoubleSpinBox();\n timeSpinner_->setValue(keyframe.getTime().count());\n timeSpinner_->setSuffix(\"s\");\n timeSpinner_->setSingleStep(0.1);\n timeSpinner_->setDecimals(5);\n \n\n void (QDoubleSpinBox::*signal)(double) = &QDoubleSpinBox::valueChanged;\n connect(timeSpinner_, signal, this, [this](double t){\n keyframe_.setTime(Seconds(t));\n });\n\n layout_->addWidget(timeSpinner_);\n\n if (auto propTrack = dynamic_cast(&parent->getTrack())) {\n auto baseProperty = propTrack->getProperty();\n property_.reset(baseProperty->clone());\n\t\tpropTrack->setOtherProperty(property_.get(),&keyframe);\n property_->onChange([b = baseProperty, p = property_.get(),t= propTrack,k=&keyframe_]() {\n b->set(p); \n t->updateKeyframeFromProperty(p,k);\n });\n property_->setOwner(nullptr);\n \n auto propWidget =\n util::getInviwoApplication()->getPropertyWidgetFactory()->create(property_.get());\n propertyWidget_ = static_cast(propWidget.release());\n\n if (auto label = propertyWidget_->findChild()) {\n label->setVisible(false);\n }\n\n layout_->addWidget(propertyWidget_);\n\t}\n\telse if (auto ctrlTrack = dynamic_cast(&parent->getTrack())) {\n\t\t\/\/ Assume that we only have ControlKeyframes within ControlTracks\n\t\tauto& ctrlKey = *static_cast(&keyframe);\n\n\t\tactionWidget_ = new QComboBox();\n\t\tactionWidget_->addItems({ \"Pause\", \"Jump To\", \"Script\" });\n\t\tactionWidget_->setCurrentIndex(static_cast(ctrlKey.getAction()));\n\n\t\tjumpToWidget_ = new QDoubleSpinBox();\n\t\tjumpToWidget_->setValue(ctrlKey.getPayload().jumpToTime.count());\n\t\tjumpToWidget_->setSuffix(\"s\");\n\t\tjumpToWidget_->setSingleStep(0.1);\n\t\tjumpToWidget_->setDecimals(5);\n\t\tjumpToWidget_->setVisible(ctrlKey.getAction() == ControlAction::JumpTo);\n\n\t\tconnect(actionWidget_, static_cast(&QComboBox::activated),\n\t\t\t[this, &ctrlKey](int idx) {\n\t\t\tctrlKey.setAction(static_cast(idx));\n\t\t\tjumpToWidget_->setVisible(ctrlKey.getAction() == ControlAction::JumpTo);\n\t\t});\n\n\t\tconnect(timeSpinner_, static_cast(&QDoubleSpinBox::valueChanged),\n\t\t\tthis, [this, &ctrlKey](double t) {\n\t\t\tControlPayload payload;\n\t\t\tpayload.jumpToTime = Seconds{ t };\n\t\t\tctrlKey.setPayload(payload);\n\t\t});\n\n\t\tlayout_->addWidget(actionWidget_);\n\t\tlayout_->addWidget(jumpToWidget_);\n\t}\n\n setLayout(layout_);\n}\n\nKeyframeEditorWidget::~KeyframeEditorWidget() {\n if(propertyWidget_){\n layout_->removeWidget(propertyWidget_);\n delete propertyWidget_;\n }\n}\n\nvoid KeyframeEditorWidget::onKeyframeTimeChanged(Keyframe* key, Seconds oldTime) {\n timeSpinner_->setValue(key->getTime().count());\n sequenceEditorWidget_->setReorderNeeded();\n}\n\nvoid KeyframeEditorWidget::onKeyframeSelectionChanged(Keyframe *key) {\n sequenceEditorWidget_->updateVisibility();\n}\n\n} \/\/ namespace animation\n\n} \/\/ namespace inviwo\nAnimationQT: Added comment on why we need to manually remove and delete the propertyWidget_\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2017 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\nnamespace animation {\nKeyframeEditorWidget::KeyframeEditorWidget(Keyframe &keyframe, SequenceEditorWidget *parent)\n : QWidget(parent), keyframe_(keyframe), sequenceEditorWidget_(parent) {\n\n setObjectName(\"KeyframeEditorWidget\");\n\n keyframe.addObserver(this);\n\n layout_ = new QHBoxLayout();\n\n timeSpinner_ = new QDoubleSpinBox();\n timeSpinner_->setValue(keyframe.getTime().count());\n timeSpinner_->setSuffix(\"s\");\n timeSpinner_->setSingleStep(0.1);\n timeSpinner_->setDecimals(5);\n\n void (QDoubleSpinBox::*signal)(double) = &QDoubleSpinBox::valueChanged;\n connect(timeSpinner_, signal, this, [this](double t) { keyframe_.setTime(Seconds(t)); });\n\n layout_->addWidget(timeSpinner_);\n\n if (auto propTrack = dynamic_cast(&parent->getTrack())) {\n auto baseProperty = propTrack->getProperty();\n property_.reset(baseProperty->clone());\n propTrack->setOtherProperty(property_.get(), &keyframe);\n property_->onChange(\n [ b = baseProperty, p = property_.get(), t = propTrack, k = &keyframe_ ]() {\n b->set(p);\n t->updateKeyframeFromProperty(p, k);\n });\n property_->setOwner(nullptr);\n\n auto propWidget =\n util::getInviwoApplication()->getPropertyWidgetFactory()->create(property_.get());\n propertyWidget_ = static_cast(propWidget.release());\n\n if (auto label = propertyWidget_->findChild()) {\n label->setVisible(false);\n }\n\n layout_->addWidget(propertyWidget_);\n } else if (auto ctrlTrack = dynamic_cast(&parent->getTrack())) {\n \/\/ Assume that we only have ControlKeyframes within ControlTracks\n auto &ctrlKey = *static_cast(&keyframe);\n\n actionWidget_ = new QComboBox();\n actionWidget_->addItems({\"Pause\", \"Jump To\", \"Script\"});\n actionWidget_->setCurrentIndex(static_cast(ctrlKey.getAction()));\n\n jumpToWidget_ = new QDoubleSpinBox();\n jumpToWidget_->setValue(ctrlKey.getPayload().jumpToTime.count());\n jumpToWidget_->setSuffix(\"s\");\n jumpToWidget_->setSingleStep(0.1);\n jumpToWidget_->setDecimals(5);\n jumpToWidget_->setVisible(ctrlKey.getAction() == ControlAction::JumpTo);\n\n connect(actionWidget_, static_cast(&QComboBox::activated),\n [this, &ctrlKey](int idx) {\n ctrlKey.setAction(static_cast(idx));\n jumpToWidget_->setVisible(ctrlKey.getAction() == ControlAction::JumpTo);\n });\n\n connect(timeSpinner_,\n static_cast(&QDoubleSpinBox::valueChanged), this,\n [this, &ctrlKey](double t) {\n ControlPayload payload;\n payload.jumpToTime = Seconds{t};\n ctrlKey.setPayload(payload);\n });\n\n layout_->addWidget(actionWidget_);\n layout_->addWidget(jumpToWidget_);\n }\n\n setLayout(layout_);\n}\n\nKeyframeEditorWidget::~KeyframeEditorWidget() {\n if (propertyWidget_) {\n \/\/ We need to manually remove and delete the propertyWidget_ since the destructor of\n \/\/ propertyWidget_ tries to use the property. If we do not remove it it will be destroyed in\n \/\/ QWidgets destructor which is called after this destructor, hence, the property has been\n \/\/ destroyed.\n layout_->removeWidget(propertyWidget_);\n delete propertyWidget_;\n }\n}\n\nvoid KeyframeEditorWidget::onKeyframeTimeChanged(Keyframe *key, Seconds oldTime) {\n timeSpinner_->setValue(key->getTime().count());\n sequenceEditorWidget_->setReorderNeeded();\n}\n\nvoid KeyframeEditorWidget::onKeyframeSelectionChanged(Keyframe *key) {\n sequenceEditorWidget_->updateVisibility();\n}\n\n} \/\/ namespace animation\n\n} \/\/ namespace inviwo\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * customwidgets.cpp: Custom widgets\n ****************************************************************************\n * Copyright (C) 2006 the VideoLAN team\n * Copyright (C) 2004 Daniel Molkentin \n * $Id: qvlcframe.hpp 16283 2006-08-17 18:16:09Z zorglub $\n *\n * Authors: Clément Stenac \n * The \"ClickLineEdit\" control is based on code by Daniel Molkentin\n * for libkdepim\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************\/\n\n#include \"customwidgets.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nClickLineEdit::ClickLineEdit( const QString &msg, QWidget *parent) : QLineEdit( parent )\n{\n mDrawClickMsg = true;\n setClickMessage( msg );\n}\n\nvoid ClickLineEdit::setClickMessage( const QString &msg )\n{\n mClickMessage = msg;\n repaint();\n}\n\n\nvoid ClickLineEdit::setText( const QString &txt )\n{\n mDrawClickMsg = txt.isEmpty();\n repaint();\n QLineEdit::setText( txt );\n}\n\nvoid ClickLineEdit::paintEvent( QPaintEvent *pe )\n{\n QPainter p( this );\n QLineEdit::paintEvent( pe );\n if ( mDrawClickMsg == true && !hasFocus() ) {\n QPen tmp = p.pen();\n p.setPen( palette().color( QPalette::Disabled, QPalette::Text ) );\n QRect cr = contentsRect();\n \/\/ Add two pixel margin on the left side\n cr.setLeft( cr.left() + 3 );\n p.drawText( cr, Qt::AlignLeft | Qt::AlignVCenter, mClickMessage );\n p.setPen( tmp );\n }\n}\n\nvoid ClickLineEdit::dropEvent( QDropEvent *ev )\n{\n mDrawClickMsg = false;\n QLineEdit::dropEvent( ev );\n}\n\n\nvoid ClickLineEdit::focusInEvent( QFocusEvent *ev )\n{\n if ( mDrawClickMsg == true ) {\n mDrawClickMsg = false;\n repaint();\n }\n QLineEdit::focusInEvent( ev );\n}\n\n\nvoid ClickLineEdit::focusOutEvent( QFocusEvent *ev )\n{\n if ( text().isEmpty() ) {\n mDrawClickMsg = true;\n repaint();\n }\n QLineEdit::focusOutEvent( ev );\n}\n\n\/***************************************************************************\n * Hotkeys converters\n ***************************************************************************\/\nint qtKeyModifiersToVLC( QInputEvent* e )\n{\n int i_keyModifiers = 0;\n if( e->modifiers() & Qt::ShiftModifier ) i_keyModifiers |= KEY_MODIFIER_SHIFT;\n if( e->modifiers() & Qt::AltModifier ) i_keyModifiers |= KEY_MODIFIER_ALT;\n if( e->modifiers() & Qt::ControlModifier ) i_keyModifiers |= KEY_MODIFIER_CTRL;\n if( e->modifiers() & Qt::MetaModifier ) i_keyModifiers |= KEY_MODIFIER_META;\n return i_keyModifiers;\n}\n\nint qtEventToVLCKey( QKeyEvent *e )\n{\n int i_vlck = 0;\n \/* Handle modifiers *\/\n i_vlck |= qtKeyModifiersToVLC( e );\n\n bool found = false;\n \/* Look for some special keys *\/\n#define HANDLE( qt, vk ) case Qt::qt : i_vlck |= vk; found = true;break\n switch( e->key() )\n {\n HANDLE( Key_Left, KEY_LEFT );\n HANDLE( Key_Right, KEY_RIGHT );\n HANDLE( Key_Up, KEY_UP );\n HANDLE( Key_Down, KEY_DOWN );\n HANDLE( Key_Space, KEY_SPACE );\n HANDLE( Key_Escape, KEY_ESC );\n HANDLE( Key_Enter, KEY_ENTER );\n HANDLE( Key_F1, KEY_F1 );\n HANDLE( Key_F2, KEY_F2 );\n HANDLE( Key_F3, KEY_F3 );\n HANDLE( Key_F4, KEY_F4 );\n HANDLE( Key_F5, KEY_F5 );\n HANDLE( Key_F6, KEY_F6 );\n HANDLE( Key_F7, KEY_F7 );\n HANDLE( Key_F8, KEY_F8 );\n HANDLE( Key_F9, KEY_F9 );\n HANDLE( Key_F10, KEY_F10 );\n HANDLE( Key_F11, KEY_F11 );\n HANDLE( Key_F12, KEY_F12 );\n HANDLE( Key_PageUp, KEY_PAGEUP );\n HANDLE( Key_PageDown, KEY_PAGEDOWN );\n HANDLE( Key_Home, KEY_HOME );\n HANDLE( Key_End, KEY_END );\n HANDLE( Key_Insert, KEY_INSERT );\n HANDLE( Key_Delete, KEY_DELETE );\n\n }\n if( !found )\n {\n \/* Force lowercase *\/\n if( e->key() >= Qt::Key_A && e->key() <= Qt::Key_Z )\n i_vlck += e->key() + 32;\n \/* Rest of the ascii range *\/\n else if( e->key() >= Qt::Key_Space && e->key() <= Qt::Key_AsciiTilde )\n i_vlck += e->key();\n }\n return i_vlck;\n}\n\nint qtWheelEventToVLCKey( QWheelEvent *e )\n{\n int i_vlck = 0;\n \/* Handle modifiers *\/\n i_vlck |= qtKeyModifiersToVLC( e );\n if ( e->delta() > 0 )\n i_vlck |= KEY_MOUSEWHEELUP;\n else\n i_vlck |= KEY_MOUSEWHEELDOWN;\n return i_vlck;\n}\n\nQString VLCKeyToString( int val )\n{\n QString r = \"\";\n if( val & KEY_MODIFIER_CTRL )\n r+= \"Ctrl+\";\n if( val & KEY_MODIFIER_ALT )\n r+= \"Alt+\";\n if( val & KEY_MODIFIER_SHIFT )\n r+= \"Shift+\";\n\n unsigned int i_keys = sizeof(vlc_keys)\/sizeof(key_descriptor_t);\n for( unsigned int i = 0; i< i_keys; i++ )\n {\n if( vlc_keys[i].i_key_code == (val& ~KEY_MODIFIER) )\n {\n r+= vlc_keys[i].psz_key_string;\n }\n }\n return r;\n}\nQt4 - MediaKeys support, patch by Ilkka Ollakka\/*****************************************************************************\n * customwidgets.cpp: Custom widgets\n ****************************************************************************\n * Copyright (C) 2006 the VideoLAN team\n * Copyright (C) 2004 Daniel Molkentin \n * $Id: qvlcframe.hpp 16283 2006-08-17 18:16:09Z zorglub $\n *\n * Authors: Clément Stenac \n * The \"ClickLineEdit\" control is based on code by Daniel Molkentin\n * for libkdepim\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************\/\n\n#include \"customwidgets.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nClickLineEdit::ClickLineEdit( const QString &msg, QWidget *parent) : QLineEdit( parent )\n{\n mDrawClickMsg = true;\n setClickMessage( msg );\n}\n\nvoid ClickLineEdit::setClickMessage( const QString &msg )\n{\n mClickMessage = msg;\n repaint();\n}\n\n\nvoid ClickLineEdit::setText( const QString &txt )\n{\n mDrawClickMsg = txt.isEmpty();\n repaint();\n QLineEdit::setText( txt );\n}\n\nvoid ClickLineEdit::paintEvent( QPaintEvent *pe )\n{\n QPainter p( this );\n QLineEdit::paintEvent( pe );\n if ( mDrawClickMsg == true && !hasFocus() ) {\n QPen tmp = p.pen();\n p.setPen( palette().color( QPalette::Disabled, QPalette::Text ) );\n QRect cr = contentsRect();\n \/\/ Add two pixel margin on the left side\n cr.setLeft( cr.left() + 3 );\n p.drawText( cr, Qt::AlignLeft | Qt::AlignVCenter, mClickMessage );\n p.setPen( tmp );\n }\n}\n\nvoid ClickLineEdit::dropEvent( QDropEvent *ev )\n{\n mDrawClickMsg = false;\n QLineEdit::dropEvent( ev );\n}\n\n\nvoid ClickLineEdit::focusInEvent( QFocusEvent *ev )\n{\n if ( mDrawClickMsg == true ) {\n mDrawClickMsg = false;\n repaint();\n }\n QLineEdit::focusInEvent( ev );\n}\n\n\nvoid ClickLineEdit::focusOutEvent( QFocusEvent *ev )\n{\n if ( text().isEmpty() ) {\n mDrawClickMsg = true;\n repaint();\n }\n QLineEdit::focusOutEvent( ev );\n}\n\n\/***************************************************************************\n * Hotkeys converters\n ***************************************************************************\/\nint qtKeyModifiersToVLC( QInputEvent* e )\n{\n int i_keyModifiers = 0;\n if( e->modifiers() & Qt::ShiftModifier ) i_keyModifiers |= KEY_MODIFIER_SHIFT;\n if( e->modifiers() & Qt::AltModifier ) i_keyModifiers |= KEY_MODIFIER_ALT;\n if( e->modifiers() & Qt::ControlModifier ) i_keyModifiers |= KEY_MODIFIER_CTRL;\n if( e->modifiers() & Qt::MetaModifier ) i_keyModifiers |= KEY_MODIFIER_META;\n return i_keyModifiers;\n}\n\nint qtEventToVLCKey( QKeyEvent *e )\n{\n int i_vlck = 0;\n \/* Handle modifiers *\/\n i_vlck |= qtKeyModifiersToVLC( e );\n\n bool found = false;\n \/* Look for some special keys *\/\n#define HANDLE( qt, vk ) case Qt::qt : i_vlck |= vk; found = true;break\n switch( e->key() )\n {\n HANDLE( Key_Left, KEY_LEFT );\n HANDLE( Key_Right, KEY_RIGHT );\n HANDLE( Key_Up, KEY_UP );\n HANDLE( Key_Down, KEY_DOWN );\n HANDLE( Key_Space, KEY_SPACE );\n HANDLE( Key_Escape, KEY_ESC );\n HANDLE( Key_Enter, KEY_ENTER );\n HANDLE( Key_F1, KEY_F1 );\n HANDLE( Key_F2, KEY_F2 );\n HANDLE( Key_F3, KEY_F3 );\n HANDLE( Key_F4, KEY_F4 );\n HANDLE( Key_F5, KEY_F5 );\n HANDLE( Key_F6, KEY_F6 );\n HANDLE( Key_F7, KEY_F7 );\n HANDLE( Key_F8, KEY_F8 );\n HANDLE( Key_F9, KEY_F9 );\n HANDLE( Key_F10, KEY_F10 );\n HANDLE( Key_F11, KEY_F11 );\n HANDLE( Key_F12, KEY_F12 );\n HANDLE( Key_PageUp, KEY_PAGEUP );\n HANDLE( Key_PageDown, KEY_PAGEDOWN );\n HANDLE( Key_Home, KEY_HOME );\n HANDLE( Key_End, KEY_END );\n HANDLE( Key_Insert, KEY_INSERT );\n HANDLE( Key_Delete, KEY_DELETE );\n HANDLE( Key_VolumeDown, KEY_VOLUME_DOWN);\n HANDLE( Key_VolumeUp, KEY_VOLUME_UP );\n HANDLE( Key_MediaPlay, KEY_MEDIA_PLAY_PAUSE );\n HANDLE( Key_MediaStop, KEY_MEDIA_STOP );\n HANDLE( Key_MediaPrevious, KEY_MEDIA_PREV_TRACK );\n HANDLE( Key_MediaNext, KEY_MEDIA_NEXT_TRACK );\n\n }\n if( !found )\n {\n \/* Force lowercase *\/\n if( e->key() >= Qt::Key_A && e->key() <= Qt::Key_Z )\n i_vlck += e->key() + 32;\n \/* Rest of the ascii range *\/\n else if( e->key() >= Qt::Key_Space && e->key() <= Qt::Key_AsciiTilde )\n i_vlck += e->key();\n }\n return i_vlck;\n}\n\nint qtWheelEventToVLCKey( QWheelEvent *e )\n{\n int i_vlck = 0;\n \/* Handle modifiers *\/\n i_vlck |= qtKeyModifiersToVLC( e );\n if ( e->delta() > 0 )\n i_vlck |= KEY_MOUSEWHEELUP;\n else\n i_vlck |= KEY_MOUSEWHEELDOWN;\n return i_vlck;\n}\n\nQString VLCKeyToString( int val )\n{\n QString r = \"\";\n if( val & KEY_MODIFIER_CTRL )\n r+= \"Ctrl+\";\n if( val & KEY_MODIFIER_ALT )\n r+= \"Alt+\";\n if( val & KEY_MODIFIER_SHIFT )\n r+= \"Shift+\";\n\n unsigned int i_keys = sizeof(vlc_keys)\/sizeof(key_descriptor_t);\n for( unsigned int i = 0; i< i_keys; i++ )\n {\n if( vlc_keys[i].i_key_code == (val& ~KEY_MODIFIER) )\n {\n r+= vlc_keys[i].psz_key_string;\n }\n }\n return r;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef rtkRegularizedConjugateGradientConeBeamReconstructionFilter_hxx\n#define rtkRegularizedConjugateGradientConeBeamReconstructionFilter_hxx\n\n#include \"rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h\"\n\nnamespace rtk\n{\n\ntemplate< typename TImage >\nRegularizedConjugateGradientConeBeamReconstructionFilter::RegularizedConjugateGradientConeBeamReconstructionFilter()\n{\n \/\/ Set the default values of member parameters\n m_GammaTV = 0.00005;\n m_Gamma = 0; \/\/ Laplacian regularization\n m_Tikhonov = 0; \/\/ Tikhonov regularization\n m_SoftThresholdWavelets = 0.001;\n m_SoftThresholdOnImage = 0.001;\n m_Preconditioned = false;\n m_RegularizedCG = false;\n\n m_TV_iterations=10;\n m_MainLoop_iterations=10;\n m_CG_iterations=4;\n\n \/\/ Default pipeline: CG, positivity, spatial TV\n m_PerformPositivity = true;\n m_PerformTVSpatialDenoising = true;\n m_PerformWaveletsSpatialDenoising = false;\n m_PerformSoftThresholdOnImage= false;\n\n \/\/ Dimensions processed for TV, default is all\n for (unsigned int i=0; i\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputVolume(const TImage* Volume)\n{\n this->SetPrimaryInput(const_cast(Volume));\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputProjectionStack(const TImage* Projection)\n{\n this->SetInput(\"ProjectionStack\", const_cast(Projection));\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputWeights(const TImage* Weights)\n{\n this->SetInput(\"Weights\", const_cast(Weights));\n}\n\ntemplate< typename TOutputImage>\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter::\nSetSupportMask(const TOutputImage *SupportMask)\n{\n this->SetInput(\"SupportMask\", const_cast(SupportMask));\n}\n\ntemplate< typename TImage >\ntypename TImage::ConstPointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputVolume()\n{\n return static_cast< const TImage * >\n ( this->itk::ProcessObject::GetInput(\"Primary\") );\n}\n\ntemplate< typename TImage >\ntypename TImage::Pointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputProjectionStack()\n{\n return static_cast< TImage * >\n ( this->itk::ProcessObject::GetInput(\"ProjectionStack\") );\n}\n\ntemplate< typename TImage >\ntypename TImage::Pointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputWeights()\n{\n return static_cast< TImage * >\n ( this->itk::ProcessObject::GetInput(\"Weights\") );\n}\n\ntemplate< typename TOutputImage>\ntypename TOutputImage::ConstPointer\nRegularizedConjugateGradientConeBeamReconstructionFilter::\nGetSupportMask()\n{\n return static_cast< const TOutputImage * >\n ( this->itk::ProcessObject::GetInput(\"SupportMask\") );\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetForwardProjectionFilter(ForwardProjectionType _arg)\n{\n if( _arg != this->GetForwardProjectionFilter() )\n {\n Superclass::SetForwardProjectionFilter( _arg );\n m_CGFilter->SetForwardProjectionFilter( _arg );\n }\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetBackProjectionFilter(BackProjectionType _arg)\n{\n if( _arg != this->GetBackProjectionFilter() )\n {\n Superclass::SetBackProjectionFilter( _arg );\n m_CGFilter->SetBackProjectionFilter( _arg );\n }\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateInputRequestedRegion()\n{\n \/\/Call the superclass' implementation of this method\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ Let the CG subfilters compute the requested regions for the projections\n \/\/ stack and the input volume\n m_CGFilter->PropagateRequestedRegion(m_CGFilter->GetOutput());\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateOutputInformation()\n{\n \/\/ Construct the pipeline, adding regularization filters if the user wants them\n \/\/ Connect the last filter's output to the next filter's input using the currentDownstreamFilter pointer\n typename itk::ImageToImageFilter::Pointer currentDownstreamFilter;\n\n \/\/ The conjugate gradient filter is the only part that must be in the pipeline\n \/\/ whatever was the user wants\n m_CGFilter->SetInput(0, this->GetInputVolume());\n m_CGFilter->SetInput(1, this->GetInputProjectionStack());\n m_CGFilter->SetInput(2, this->GetInputWeights());\n m_CGFilter->SetSupportMask(this->GetSupportMask());\n m_CGFilter->SetGeometry(this->m_Geometry);\n m_CGFilter->SetNumberOfIterations(this->m_CG_iterations);\n m_CGFilter->SetCudaConjugateGradient(this->GetCudaConjugateGradient());\n m_CGFilter->SetGamma(this->m_Gamma);\n m_CGFilter->SetTikhonov(this->m_Tikhonov);\n\/\/ m_CGFilter->SetIterationCosts(m_IterationCosts);\n m_CGFilter->SetDisableDisplacedDetectorFilter(m_DisableDisplacedDetectorFilter);\n\n currentDownstreamFilter = m_CGFilter;\n\n \/\/ Plug the positivity filter if requested\n if (m_PerformPositivity)\n {\n m_PositivityFilter->SetInPlace(true);\n\n m_PositivityFilter->SetOutsideValue(0.0);\n m_PositivityFilter->ThresholdBelow(0.0);\n m_PositivityFilter->SetInput(currentDownstreamFilter->GetOutput());\n\n currentDownstreamFilter = m_PositivityFilter;\n }\n\n if (m_PerformTVSpatialDenoising)\n {\n currentDownstreamFilter->ReleaseDataFlagOn();\n\n m_TVDenoising->SetInput(currentDownstreamFilter->GetOutput());\n m_TVDenoising->SetNumberOfIterations(this->m_TV_iterations);\n m_TVDenoising->SetGamma(this->m_GammaTV);\n m_TVDenoising->SetDimensionsProcessed(this->m_DimensionsProcessedForTV);\n\n currentDownstreamFilter = m_TVDenoising;\n }\n\n if (m_PerformWaveletsSpatialDenoising)\n {\n currentDownstreamFilter->ReleaseDataFlagOn();\n\n m_WaveletsDenoising->SetInput(currentDownstreamFilter->GetOutput());\n m_WaveletsDenoising->SetOrder(m_Order);\n m_WaveletsDenoising->SetThreshold(m_SoftThresholdWavelets);\n m_WaveletsDenoising->SetNumberOfLevels(m_NumberOfLevels);\n\n currentDownstreamFilter = m_WaveletsDenoising;\n }\n\n if (m_PerformSoftThresholdOnImage)\n {\n currentDownstreamFilter->ReleaseDataFlagOn();\n\n m_SoftThresholdFilter->SetInput(currentDownstreamFilter->GetOutput());\n m_SoftThresholdFilter->SetThreshold(m_SoftThresholdOnImage);\n\n currentDownstreamFilter = m_SoftThresholdFilter;\n }\n\n \/\/ Have the last filter calculate its output information\n currentDownstreamFilter->ReleaseDataFlagOff();\n currentDownstreamFilter->UpdateOutputInformation();\n\n \/\/ Copy it as the output information of the composite filter\n this->GetOutput()->CopyInformation( currentDownstreamFilter->GetOutput() );\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateData()\n{\n \/\/ Declare the pointer that will be used to plug the output back as input\n typename itk::ImageToImageFilter::Pointer currentDownstreamFilter;\n typename TImage::Pointer pimg;\n\n for (int i=0; i0)\n {\n pimg = currentDownstreamFilter->GetOutput();\n\n pimg->DisconnectPipeline();\n m_CGFilter->SetInput(0, pimg);\n\n \/\/ The input volume is no longer needed on the GPU, so we transfer it back to the CPU\n this->GetInputVolume()->GetBufferPointer();\n }\n\n currentDownstreamFilter = m_CGFilter;\n if (m_PerformPositivity)\n {\n currentDownstreamFilter = m_PositivityFilter;\n }\n if (m_PerformTVSpatialDenoising)\n {\n currentDownstreamFilter = m_TVDenoising;\n }\n if (m_PerformWaveletsSpatialDenoising)\n {\n currentDownstreamFilter = m_WaveletsDenoising;\n }\n if (m_PerformSoftThresholdOnImage)\n {\n currentDownstreamFilter = m_SoftThresholdFilter;\n }\n\n currentDownstreamFilter->Update();\n }\n\n this->GraftOutput( currentDownstreamFilter->GetOutput() );\n}\n\n}\/\/ end namespace\n\n\n#endif\nRemoved some releaseDataFlag which caused RegularizedConjugateGradientConeBeamReconstructionFilter to update the rtkConjugateGradientImageFilter twice\/*=========================================================================\n *\n * Copyright RTK Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n#ifndef rtkRegularizedConjugateGradientConeBeamReconstructionFilter_hxx\n#define rtkRegularizedConjugateGradientConeBeamReconstructionFilter_hxx\n\n#include \"rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h\"\n\nnamespace rtk\n{\n\ntemplate< typename TImage >\nRegularizedConjugateGradientConeBeamReconstructionFilter::RegularizedConjugateGradientConeBeamReconstructionFilter()\n{\n \/\/ Set the default values of member parameters\n m_GammaTV = 0.00005;\n m_Gamma = 0; \/\/ Laplacian regularization\n m_Tikhonov = 0; \/\/ Tikhonov regularization\n m_SoftThresholdWavelets = 0.001;\n m_SoftThresholdOnImage = 0.001;\n m_Preconditioned = false;\n m_RegularizedCG = false;\n\n m_TV_iterations=10;\n m_MainLoop_iterations=10;\n m_CG_iterations=4;\n\n \/\/ Default pipeline: CG, positivity, spatial TV\n m_PerformPositivity = true;\n m_PerformTVSpatialDenoising = true;\n m_PerformWaveletsSpatialDenoising = false;\n m_PerformSoftThresholdOnImage= false;\n\n \/\/ Dimensions processed for TV, default is all\n for (unsigned int i=0; i\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputVolume(const TImage* Volume)\n{\n this->SetPrimaryInput(const_cast(Volume));\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputProjectionStack(const TImage* Projection)\n{\n this->SetInput(\"ProjectionStack\", const_cast(Projection));\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetInputWeights(const TImage* Weights)\n{\n this->SetInput(\"Weights\", const_cast(Weights));\n}\n\ntemplate< typename TOutputImage>\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter::\nSetSupportMask(const TOutputImage *SupportMask)\n{\n this->SetInput(\"SupportMask\", const_cast(SupportMask));\n}\n\ntemplate< typename TImage >\ntypename TImage::ConstPointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputVolume()\n{\n return static_cast< const TImage * >\n ( this->itk::ProcessObject::GetInput(\"Primary\") );\n}\n\ntemplate< typename TImage >\ntypename TImage::Pointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputProjectionStack()\n{\n return static_cast< TImage * >\n ( this->itk::ProcessObject::GetInput(\"ProjectionStack\") );\n}\n\ntemplate< typename TImage >\ntypename TImage::Pointer\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GetInputWeights()\n{\n return static_cast< TImage * >\n ( this->itk::ProcessObject::GetInput(\"Weights\") );\n}\n\ntemplate< typename TOutputImage>\ntypename TOutputImage::ConstPointer\nRegularizedConjugateGradientConeBeamReconstructionFilter::\nGetSupportMask()\n{\n return static_cast< const TOutputImage * >\n ( this->itk::ProcessObject::GetInput(\"SupportMask\") );\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetForwardProjectionFilter(ForwardProjectionType _arg)\n{\n if( _arg != this->GetForwardProjectionFilter() )\n {\n Superclass::SetForwardProjectionFilter( _arg );\n m_CGFilter->SetForwardProjectionFilter( _arg );\n }\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::SetBackProjectionFilter(BackProjectionType _arg)\n{\n if( _arg != this->GetBackProjectionFilter() )\n {\n Superclass::SetBackProjectionFilter( _arg );\n m_CGFilter->SetBackProjectionFilter( _arg );\n }\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateInputRequestedRegion()\n{\n \/\/Call the superclass' implementation of this method\n Superclass::GenerateInputRequestedRegion();\n\n \/\/ Let the CG subfilters compute the requested regions for the projections\n \/\/ stack and the input volume\n m_CGFilter->PropagateRequestedRegion(m_CGFilter->GetOutput());\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateOutputInformation()\n{\n \/\/ Construct the pipeline, adding regularization filters if the user wants them\n \/\/ Connect the last filter's output to the next filter's input using the currentDownstreamFilter pointer\n typename itk::ImageToImageFilter::Pointer currentDownstreamFilter;\n\n \/\/ The conjugate gradient filter is the only part that must be in the pipeline\n \/\/ whatever was the user wants\n m_CGFilter->SetInput(0, this->GetInputVolume());\n m_CGFilter->SetInput(1, this->GetInputProjectionStack());\n m_CGFilter->SetInput(2, this->GetInputWeights());\n m_CGFilter->SetSupportMask(this->GetSupportMask());\n m_CGFilter->SetGeometry(this->m_Geometry);\n m_CGFilter->SetNumberOfIterations(this->m_CG_iterations);\n m_CGFilter->SetCudaConjugateGradient(this->GetCudaConjugateGradient());\n m_CGFilter->SetGamma(this->m_Gamma);\n m_CGFilter->SetTikhonov(this->m_Tikhonov);\n\/\/ m_CGFilter->SetIterationCosts(m_IterationCosts);\n m_CGFilter->SetDisableDisplacedDetectorFilter(m_DisableDisplacedDetectorFilter);\n\n currentDownstreamFilter = m_CGFilter;\n\n \/\/ Plug the positivity filter if requested\n if (m_PerformPositivity)\n {\n m_PositivityFilter->SetInPlace(false);\n\n m_PositivityFilter->SetOutsideValue(0.0);\n m_PositivityFilter->ThresholdBelow(0.0);\n m_PositivityFilter->SetInput(currentDownstreamFilter->GetOutput());\n\n currentDownstreamFilter = m_PositivityFilter;\n }\n\n if (m_PerformTVSpatialDenoising)\n {\n currentDownstreamFilter->ReleaseDataFlagOn();\n\n m_TVDenoising->SetInput(currentDownstreamFilter->GetOutput());\n m_TVDenoising->SetNumberOfIterations(this->m_TV_iterations);\n m_TVDenoising->SetGamma(this->m_GammaTV);\n m_TVDenoising->SetDimensionsProcessed(this->m_DimensionsProcessedForTV);\n\n currentDownstreamFilter = m_TVDenoising;\n }\n\n if (m_PerformWaveletsSpatialDenoising)\n {\n m_WaveletsDenoising->SetInput(currentDownstreamFilter->GetOutput());\n m_WaveletsDenoising->SetOrder(m_Order);\n m_WaveletsDenoising->SetThreshold(m_SoftThresholdWavelets);\n m_WaveletsDenoising->SetNumberOfLevels(m_NumberOfLevels);\n\n currentDownstreamFilter = m_WaveletsDenoising;\n }\n\n if (m_PerformSoftThresholdOnImage)\n {\n currentDownstreamFilter->ReleaseDataFlagOn();\n\n m_SoftThresholdFilter->SetInput(currentDownstreamFilter->GetOutput());\n m_SoftThresholdFilter->SetThreshold(m_SoftThresholdOnImage);\n\n currentDownstreamFilter = m_SoftThresholdFilter;\n }\n\n \/\/ Have the last filter calculate its output information\n currentDownstreamFilter->ReleaseDataFlagOff();\n currentDownstreamFilter->UpdateOutputInformation();\n\n \/\/ Copy it as the output information of the composite filter\n this->GetOutput()->CopyInformation( currentDownstreamFilter->GetOutput() );\n}\n\ntemplate< typename TImage >\nvoid\nRegularizedConjugateGradientConeBeamReconstructionFilter\n::GenerateData()\n{\n \/\/ Declare the pointer that will be used to plug the output back as input\n typename itk::ImageToImageFilter::Pointer currentDownstreamFilter;\n typename TImage::Pointer pimg;\n\n for (int i=0; i0)\n {\n pimg = currentDownstreamFilter->GetOutput();\n\n pimg->DisconnectPipeline();\n m_CGFilter->SetInput(0, pimg);\n\n \/\/ The input volume is no longer needed on the GPU, so we transfer it back to the CPU\n this->GetInputVolume()->GetBufferPointer();\n }\n\n currentDownstreamFilter = m_CGFilter;\n if (m_PerformPositivity)\n {\n currentDownstreamFilter = m_PositivityFilter;\n }\n if (m_PerformTVSpatialDenoising)\n {\n currentDownstreamFilter = m_TVDenoising;\n }\n if (m_PerformWaveletsSpatialDenoising)\n {\n currentDownstreamFilter = m_WaveletsDenoising;\n }\n if (m_PerformSoftThresholdOnImage)\n {\n currentDownstreamFilter = m_SoftThresholdFilter;\n }\n\n currentDownstreamFilter->Update();\n }\n\n this->GraftOutput( currentDownstreamFilter->GetOutput() );\n}\n\n}\/\/ end namespace\n\n\n#endif\n<|endoftext|>"} {"text":"\/**********************************************************************\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.osgeo.org\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n * Copyright (C) 2005 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation.\n * See the COPYING file for more information.\n *\n **********************************************************************\n *\n * Last port: geomgraph\/TopologyLocation.java r428 (JTS-1.12+)\n *\n **********************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#ifndef GEOS_INLINE\n# include \n#endif\n\nusing namespace geos::geom;\n\nnamespace geos {\nnamespace geomgraph { \/\/ geos.geomgraph\n\n\/*public*\/\nvoid\nTopologyLocation::merge(const TopologyLocation& gl)\n{\n \/\/ if the src is an Area label & and the dest is not, increase the dest to be an Area\n std::size_t sz = locationSize;\n std::size_t glsz = gl.locationSize;\n if(glsz > sz) {\n locationSize = 3;\n location[Position::LEFT] = Location::NONE;\n location[Position::RIGHT] = Location::NONE;\n }\n for(std::size_t i = 0; i < locationSize; ++i) {\n if(location[i] == Location::NONE && i < glsz) {\n location[i] = gl.location[i];\n }\n }\n}\n\nstd::string\nTopologyLocation::toString() const\n{\n std::stringstream ss;\n ss << *this;\n return ss.str();\n}\n\nstd::ostream&\noperator<< (std::ostream& os, const TopologyLocation& tl)\n{\n if(tl.locationSize > 1) {\n os << tl.location[Position::LEFT];\n }\n os << tl.location[Position::ON];\n if(tl.locationSize > 1) {\n os << tl.location[Position::RIGHT];\n }\n return os;\n}\n\n} \/\/ namespace geos.geomgraph\n} \/\/ namespace geos\n\n\nAvoid useless comparison against glsz inside loop\/**********************************************************************\n *\n * GEOS - Geometry Engine Open Source\n * http:\/\/geos.osgeo.org\n *\n * Copyright (C) 2001-2002 Vivid Solutions Inc.\n * Copyright (C) 2005 Refractions Research Inc.\n *\n * This is free software; you can redistribute and\/or modify it under\n * the terms of the GNU Lesser General Public Licence as published\n * by the Free Software Foundation.\n * See the COPYING file for more information.\n *\n **********************************************************************\n *\n * Last port: geomgraph\/TopologyLocation.java r428 (JTS-1.12+)\n *\n **********************************************************************\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifndef GEOS_INLINE\n# include \n#endif\n\nusing namespace geos::geom;\n\nnamespace geos {\nnamespace geomgraph { \/\/ geos.geomgraph\n\n\/*public*\/\nvoid\nTopologyLocation::merge(const TopologyLocation& gl)\n{\n \/\/ if the src is an Area label & and the dest is not, increase the dest to be an Area\n std::size_t sz = locationSize;\n std::size_t glsz = gl.locationSize;\n if(glsz > sz) {\n locationSize = 3;\n location[Position::LEFT] = Location::NONE;\n location[Position::RIGHT] = Location::NONE;\n }\n const std::size_t maxIndex = std::min(static_cast(locationSize), glsz);\n for(std::size_t i = 0; i < maxIndex; ++i) {\n if(location[i] == Location::NONE) {\n location[i] = gl.location[i];\n }\n }\n}\n\nstd::string\nTopologyLocation::toString() const\n{\n std::stringstream ss;\n ss << *this;\n return ss.str();\n}\n\nstd::ostream&\noperator<< (std::ostream& os, const TopologyLocation& tl)\n{\n if(tl.locationSize > 1) {\n os << tl.location[Position::LEFT];\n }\n os << tl.location[Position::ON];\n if(tl.locationSize > 1) {\n os << tl.location[Position::RIGHT];\n }\n return os;\n}\n\n} \/\/ namespace geos.geomgraph\n} \/\/ namespace geos\n\n\n<|endoftext|>"} {"text":"\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"include\/librados.h\"\n#include \"config.h\"\n#include \"common\/common_init.h\"\n\n#include \n\n#include \n#include \n\nvoid usage() \n{\n cerr << \"usage: radostool [options] [commands]\" << std::endl;\n \/* cerr << \"If no commands are specified, enter interactive mode.\\n\";\n cerr << \"Commands:\" << std::endl;\n cerr << \" stop -- cleanly shut down file system\" << std::endl\n << \" (osd|pg|mds) stat -- get monitor subsystem status\" << std::endl\n << \" ...\" << std::endl;\n *\/\n cerr << \"Options:\" << std::endl;\n cerr << \" -i infile\\n\";\n cerr << \" -o outfile\\n\";\n cerr << \" specify input or output file (for certain commands)\\n\";\n generic_client_usage();\n}\n\nint main(int argc, const char **argv) \n{\n DEFINE_CONF_VARS(usage);\n vector args;\n argv_to_vec(argc, argv, args);\n env_to_vec(args);\n common_init(args, \"rados\", false);\n\n vector nargs;\n bufferlist indata, outdata;\n const char *outfile = 0;\n \n const char *pool = 0;\n\n FOR_EACH_ARG(args) {\n if (CONF_ARG_EQ(\"out_file\", 'o')) {\n CONF_SAFE_SET_ARG_VAL(&outfile, OPT_STR);\n } else if (CONF_ARG_EQ(\"in_data\", 'i')) {\n const char *fname;\n CONF_SAFE_SET_ARG_VAL(&fname, OPT_STR);\n int r = indata.read_file(fname);\n if (r < 0) {\n\tcerr << \"error reading \" << fname << \": \" << strerror(-r) << std::endl;\n\texit(0);\n } else {\n\tcout << \"read \" << indata.length() << \" bytes from \" << fname << std::endl;\n }\n } else if (CONF_ARG_EQ(\"pool\", 'p')) {\n CONF_SAFE_SET_ARG_VAL(&pool, OPT_STR);\n } else if (CONF_ARG_EQ(\"help\", 'h')) {\n usage();\n } else if (args[i][0] == '-' && nargs.empty()) {\n cerr << \"unrecognized option \" << args[i] << std::endl;\n usage();\n } else\n nargs.push_back(args[i]);\n }\n\n if (nargs.empty())\n usage();\n\n \/\/ open rados\n Rados rados;\n if (rados.initialize(0, NULL) < 0) {\n cerr << \"couldn't initialize rados!\" << std::endl;\n exit(1);\n }\n\n \/\/ open pool?\n rados_pool_t p;\n if (pool) {\n int r = rados.open_pool(pool, &p);\n if (r < 0) {\n cerr << \"error opening pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n }\n\n \/\/ list pools?\n if (strcmp(nargs[0], \"lspools\") == 0) {\n vector vec;\n rados.list_pools(vec);\n for (vector::iterator i = vec.begin(); i != vec.end(); ++i)\n cout << *i << std::endl;\n\n } else if (strcmp(nargs[0], \"ls\") == 0) {\n if (!pool)\n usage();\n\n Rados::ListCtx ctx;\n while (1) {\n list vec;\n int r = rados.list(p, 1 << 10, vec, ctx);\n cout << \"list result=\" << r << \" entries=\" << vec.size() << std::endl;\n if (r < 0) {\n\tcerr << \"got error: \" << strerror(-r) << std::endl;\n\tbreak;\n }\n if (vec.empty())\n\tbreak;\n for (list::iterator iter = vec.begin(); iter != vec.end(); ++iter)\n\tcout << *iter << std::endl;\n }\n\n\n } else if (strcmp(nargs[0], \"get\") == 0) {\n if (!pool || nargs.size() < 2)\n usage();\n object_t oid(nargs[1]);\n int r = rados.read(p, oid, 0, outdata, 0);\n if (r < 0) {\n cerr << \"error reading \" << oid << \" from pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n\n } else if (strcmp(nargs[0], \"put\") == 0) {\n if (!pool || nargs.size() < 2)\n usage();\n if (!indata.length()) {\n cerr << \"must specify input file\" << std::endl;\n usage();\n }\n object_t oid(nargs[1]);\n int r = rados.write(p, oid, 0, indata, indata.length());\n if (r < 0) {\n cerr << \"error writing \" << oid << \" to pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n\n } else {\n cerr << \"unrecognized command \" << nargs[0] << std::endl;\n usage();\n }\n\n \/\/ write data?\n int len = outdata.length();\n if (len) {\n if (outfile) {\n if (strcmp(outfile, \"-\") == 0) {\n\t::write(1, outdata.c_str(), len);\n } else {\n\toutdata.write_file(outfile);\n }\n generic_dout(0) << \"wrote \" << len << \" byte payload to \" << outfile << dendl;\n } else {\n generic_dout(0) << \"got \" << len << \" byte payload, discarding (specify -o radostool now includes benchmarking functionality from testradosciopp.cc\/\/ -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- \n\/\/ vim: ts=8 sw=2 smarttab\n\/*\n * Ceph - scalable distributed file system\n *\n * Copyright (C) 2004-2006 Sage Weil \n *\n * This is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software \n * Foundation. See file COPYING.\n * \n *\/\n\n#include \"include\/librados.h\"\n#include \"config.h\"\n#include \"common\/common_init.h\"\n\n#include \n\n#include \n#include \n#include \n\n\nint aio_bench(Rados& rados, rados_pool_t pool, int concurrentios, int secondsToRun,\n\t int writeSize, int readOffResults);\n\nvoid usage() \n{\n cerr << \"usage: radostool [options] [commands]\" << std::endl;\n \/* cerr << \"If no commands are specified, enter interactive mode.\\n\";\n cerr << \"Commands:\" << std::endl;\n cerr << \" stop -- cleanly shut down file system\" << std::endl\n << \" (osd|pg|mds) stat -- get monitor subsystem status\" << std::endl\n << \" ...\" << std::endl;\n *\/\n cerr << \"Options:\" << std::endl;\n cerr << \" -i infile\\n\";\n cerr << \" -o outfile\\n\";\n cerr << \" specify input or output file (for certain commands)\\n\";\n generic_client_usage();\n}\n\nint main(int argc, const char **argv) \n{\n DEFINE_CONF_VARS(usage);\n vector args;\n argv_to_vec(argc, argv, args);\n env_to_vec(args);\n common_init(args, \"rados\", false);\n\n vector nargs;\n bufferlist indata, outdata;\n const char *outfile = 0;\n \n const char *pool = 0;\n\n FOR_EACH_ARG(args) {\n if (CONF_ARG_EQ(\"out_file\", 'o')) {\n CONF_SAFE_SET_ARG_VAL(&outfile, OPT_STR);\n } else if (CONF_ARG_EQ(\"in_data\", 'i')) {\n const char *fname;\n CONF_SAFE_SET_ARG_VAL(&fname, OPT_STR);\n int r = indata.read_file(fname);\n if (r < 0) {\n\tcerr << \"error reading \" << fname << \": \" << strerror(-r) << std::endl;\n\texit(0);\n } else {\n\tcout << \"read \" << indata.length() << \" bytes from \" << fname << std::endl;\n }\n } else if (CONF_ARG_EQ(\"pool\", 'p')) {\n CONF_SAFE_SET_ARG_VAL(&pool, OPT_STR);\n } else if (CONF_ARG_EQ(\"help\", 'h')) {\n usage();\n } else if (args[i][0] == '-' && nargs.empty()) {\n cerr << \"unrecognized option \" << args[i] << std::endl;\n usage();\n } else\n nargs.push_back(args[i]);\n }\n\n if (nargs.empty())\n usage();\n\n \/\/ open rados\n Rados rados;\n if (rados.initialize(0, NULL) < 0) {\n cerr << \"couldn't initialize rados!\" << std::endl;\n exit(1);\n }\n\n \/\/ open pool?\n rados_pool_t p;\n if (pool) {\n int r = rados.open_pool(pool, &p);\n if (r < 0) {\n cerr << \"error opening pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n }\n\n \/\/ list pools?\n if (strcmp(nargs[0], \"lspools\") == 0) {\n vector vec;\n rados.list_pools(vec);\n for (vector::iterator i = vec.begin(); i != vec.end(); ++i)\n cout << *i << std::endl;\n\n } else if (strcmp(nargs[0], \"ls\") == 0) {\n if (!pool)\n usage();\n\n Rados::ListCtx ctx;\n while (1) {\n list vec;\n int r = rados.list(p, 1 << 10, vec, ctx);\n cout << \"list result=\" << r << \" entries=\" << vec.size() << std::endl;\n if (r < 0) {\n\tcerr << \"got error: \" << strerror(-r) << std::endl;\n\tbreak;\n }\n if (vec.empty())\n\tbreak;\n for (list::iterator iter = vec.begin(); iter != vec.end(); ++iter)\n\tcout << *iter << std::endl;\n }\n\n\n } else if (strcmp(nargs[0], \"get\") == 0) {\n if (!pool || nargs.size() < 2)\n usage();\n object_t oid(nargs[1]);\n int r = rados.read(p, oid, 0, outdata, 0);\n if (r < 0) {\n cerr << \"error reading \" << oid << \" from pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n\n } else if (strcmp(nargs[0], \"put\") == 0) {\n if (!pool || nargs.size() < 2)\n usage();\n if (!indata.length()) {\n cerr << \"must specify input file\" << std::endl;\n usage();\n }\n object_t oid(nargs[1]);\n int r = rados.write(p, oid, 0, indata, indata.length());\n if (r < 0) {\n cerr << \"error writing \" << oid << \" to pool \" << pool << \": \" << strerror(-r) << std::endl;\n exit(0);\n }\n\n } else if (strcmp(nargs[0], \"bench\") == 0) {\n if ( nargs.size() < 5) {\n cerr << \"bench requires 4 arguments: Concurrent writes,\" << std::endl\n\t << \"minimum seconds to run, write size, and consistency checking\" << std::endl\n\t << \"(1 for yes, 0 for no).\" << std::endl;\n }\n else {\n aio_bench(rados, p, atoi(nargs[1]), atoi(nargs[2]), atoi(nargs[3]), atoi(nargs[4]));\n }\n }\n else {\n cerr << \"unrecognized command \" << nargs[0] << std::endl;\n usage();\n }\n\n \/\/ write data?\n int len = outdata.length();\n if (len) {\n if (outfile) {\n if (strcmp(outfile, \"-\") == 0) {\n\t::write(1, outdata.c_str(), len);\n } else {\n\toutdata.write_file(outfile);\n }\n generic_dout(0) << \"wrote \" << len << \" byte payload to \" << outfile << dendl;\n } else {\n generic_dout(0) << \"got \" << len << \" byte payload, discarding (specify -o append(contentsChars, writeSize);\n }\n\n \/\/set up the pool, get start time, and go!\n cout << \"open pool result = \" << rados.open_pool(\"data\",&pool) << \" pool = \" << pool << std::endl;\n\n startTime = g_clock.now();\n\n for (int i = 0; iappend(contentsChars, writeSize);\n completions[slot]->wait_for_complete();\n currentLatency = g_clock.now() - startTimes[slot];\n totalLatency += currentLatency;\n if( currentLatency > maxLatency) maxLatency = currentLatency;\n ++writesCompleted;\n completions[slot]->release();\n \/\/write new stuff to rados, then delete old stuff\n \/\/and save locations of new stuff for later deletion\n startTimes[slot] = g_clock.now();\n rados.aio_write(pool, newName, 0, *newContents, writeSize, &completions[slot]);\n ++writesMade;\n delete name[slot];\n delete contents[slot];\n name[slot] = newName;\n contents[slot] = newContents;\n }\n \n cerr << \"Waiting for last writes to finish\\n\";\n while (writesCompleted < writesMade) {\n slot = writesCompleted % concurrentios;\n completions[slot]->wait_for_complete();\n currentLatency = g_clock.now() - startTimes[slot];\n totalLatency += currentLatency;\n if (currentLatency > maxLatency) maxLatency = currentLatency;\n completions[slot]-> release();\n ++writesCompleted;\n delete name[slot];\n delete contents[slot];\n }\n\n utime_t timePassed = g_clock.now() - startTime;\n\n \/\/check objects for consistency if requested\n int errors = 0;\n if (readOffResults) {\n char matchName[128];\n object_t oid;\n bufferlist actualContents;\n for (int i = 0; i < writesCompleted; ++i ) {\n snprintf(matchName, 128, \"Object %s:%d\", iTime, i);\n oid = object_t(matchName);\n snprintf(contentsChars, writeSize, \"I'm the %dth object!\", i);\n rados.read(pool, oid, 0, actualContents, writeSize);\n if (strcmp(contentsChars, actualContents.c_str()) != 0 ) {\n\tcerr << \"Object \" << matchName << \" is not correct!\";\n\t++errors;\n }\n actualContents.clear();\n }\n }\n\n char bw[20];\n double bandwidth = ((double)writesCompleted)*((double)writeSize)\/(double)timePassed;\n bandwidth = bandwidth\/(1024*1024); \/\/ we want it in MB\/sec\n sprintf(bw, \"%.3lf \\n\", bandwidth);\n\n double averageLatency = totalLatency \/ writesCompleted;\n\n cout << \"Total time run: \" << timePassed << std::endl\n << \"Total writes made: \" << writesCompleted << std::endl\n << \"Write size: \" << writeSize << std::endl\n << \"Bandwidth (MB\/sec): \" << bw << std::endl\n << \"Average Latency: \" << averageLatency << std::endl\n << \"Max latency: \" << maxLatency << std::endl\n << \"Time waiting for Rados:\" << totalLatency\/concurrentios << std::endl;\n\n if (readOffResults) {\n if (errors) cout << \"WARNING: There were \" << errors << \" total errors in copying!\\n\";\n else cout << \"No errors in copying!\\n\";\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/traffic_light\/preprocessor\/tl_preprocessor.h\"\n\n#include \"modules\/perception\/lib\/base\/time_util.h\"\n#include \"modules\/perception\/onboard\/transform_input.h\"\n#include \"modules\/perception\/traffic_light\/base\/tl_shared_data.h\"\n#include \"modules\/perception\/traffic_light\/base\/utils.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace traffic_light {\n\nbool TLPreprocessor::Init() {\n ConfigManager *config_manager = ConfigManager::instance();\n const ModelConfig *model_config = NULL;\n if (!config_manager->GetModelConfig(name(), &model_config)) {\n AERROR << \"not found model: \" << name();\n return false;\n }\n\n \/\/ Read parameters from config file\n if (!model_config->GetValue(\"max_cached_lights_size\",\n &max_cached_lights_size_)) {\n AERROR << \"max_cached_image_lights_array_size not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"projection_image_cols\",\n &projection_image_cols_)) {\n AERROR << \"projection_image_cols not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"projection_image_rows\",\n &projection_image_rows_)) {\n AERROR << \"projection_image_rows not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"sync_interval_seconds\",\n &sync_interval_seconds_)) {\n AERROR << \"sync_interval_seconds not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"no_signals_interval_seconds\",\n &no_signals_interval_seconds_)) {\n AERROR << \"no_signals_interval_seconds not found.\" << name();\n return false;\n }\n\n \/\/ init projection\n if (!projection_.Init()) {\n AERROR << \"TLPreprocessor init projection failed.\";\n return false;\n }\n AINFO << kCountCameraId;\n return true;\n}\n\nbool TLPreprocessor::CacheLightsProjections(const CarPose &pose,\n const std::vector &signals,\n const double timestamp) {\n MutexLock lock(&mutex_);\n PERF_FUNCTION();\n\n AINFO << \"TLPreprocessor has \" << cached_lights_.size()\n << \" lights projections cached.\";\n\n \/\/ pop front if cached array'size > FLAGS_max_cached_image_lights_array_size\n while (cached_lights_.size() > static_cast(max_cached_lights_size_)) {\n cached_lights_.erase(cached_lights_.begin());\n }\n\n \/\/ lights projection info. to be added in cached array\n std::shared_ptr image_lights(new ImageLights);\n \/\/ default select long focus camera\n image_lights->camera_id = LONG_FOCUS;\n image_lights->timestamp = timestamp;\n image_lights->pose = pose;\n image_lights->is_pose_valid = true;\n\n AINFO << \"TLPreprocessor Got signal number:\" << signals.size()\n << \", ts: \" << GLOG_TIMESTAMP(timestamp);\n for (const auto &signal : signals) {\n AINFO << \"signal info:\" << signal.ShortDebugString();\n }\n \/\/ lights projections info.\n\n std::vector> lights_on_image(kCountCameraId);\n std::vector> lights_outside_image(kCountCameraId);\n for (auto &light_ptrs : lights_on_image) {\n light_ptrs.reset(new LightPtrs);\n }\n for (auto &light_ptrs : lights_outside_image) {\n light_ptrs.reset(new LightPtrs);\n }\n if (signals.size() > 0) {\n \/\/ project light region on each camera's image plane\n for (int cam_id = 0; cam_id < kCountCameraId; ++cam_id) {\n if (!ProjectLights(pose, signals, static_cast(cam_id),\n lights_on_image[cam_id].get(),\n lights_outside_image[cam_id].get())) {\n AERROR << \"add_cached_lights_projections project lights on \"\n << kCameraIdToStr.at(static_cast(cam_id))\n << \" image failed, \"\n << \"ts: \" << GLOG_TIMESTAMP(timestamp) << \", camera_id: \"\n << kCameraIdToStr.at(static_cast(cam_id));\n return false;\n }\n }\n\n \/\/ select which image to be used\n SelectImage(pose, lights_on_image, lights_outside_image,\n &(image_lights->camera_id));\n AINFO << \"select camera: \" << kCameraIdToStr.at(image_lights->camera_id);\n\n } else {\n last_no_signals_ts_ = timestamp;\n }\n image_lights->num_signals = signals.size();\n AINFO << \"cached info with \" << image_lights->num_signals << \" signals\";\n cached_lights_.push_back(image_lights);\n\n return true;\n}\n\nbool TLPreprocessor::SyncImage(const ImageSharedPtr &image,\n ImageLightsPtr *image_lights, bool *should_pub) {\n MutexLock lock(&mutex_);\n PERF_FUNCTION();\n CameraId camera_id = image->camera_id();\n double image_ts = image->ts();\n bool sync_ok = false;\n\n PERF_FUNCTION();\n if (cached_lights_.size() == 0) {\n AINFO << \"No cached light\";\n return false;\n }\n const int cam_id = static_cast(camera_id);\n if (cam_id < 0 || cam_id >= kCountCameraId) {\n AERROR << \"SyncImage failed, \"\n << \"get unknown CameraId: \" << camera_id;\n return false;\n }\n\n \/\/ find close enough(by timestamp difference)\n \/\/ lights projection from back to front\n\n bool find_loc = false; \/\/ if pose is found\n auto cached_lights_ptr = cached_lights_.rbegin();\n for (; cached_lights_ptr != cached_lights_.rend(); ++cached_lights_ptr) {\n double light_ts = (*cached_lights_ptr)->timestamp;\n if (fabs(light_ts - image_ts) < sync_interval_seconds_) {\n find_loc = true;\n auto proj_cam_id = static_cast((*cached_lights_ptr)->camera_id);\n auto image_cam_id = static_cast(camera_id);\n auto proj_cam_id_str =\n (kCameraIdToStr.find(proj_cam_id) != kCameraIdToStr.end()\n ? kCameraIdToStr.at(proj_cam_id)\n : std::to_string(proj_cam_id));\n \/\/ found related pose but if camear ID doesn't match\n if (proj_cam_id != image_cam_id) {\n AWARN << \"find appropriate localization, but camera_id not match\"\n << \", cached projection's camera_id: \" << proj_cam_id_str\n << \" , image's camera_id: \" << kCameraIdToStr.at(image_cam_id);\n continue;\n }\n if (image_ts < last_output_ts_) {\n AWARN << \"TLPreprocessor reject the image pub ts:\"\n << GLOG_TIMESTAMP(image_ts)\n << \" which is earlier than last output ts:\"\n << GLOG_TIMESTAMP(last_output_ts_)\n << \", image camera_id: \" << kCameraIdToStr.at(image_cam_id);\n return false;\n }\n sync_ok = true;\n break;\n }\n }\n\n if (sync_ok) {\n *image_lights = *cached_lights_ptr;\n (*image_lights)->diff_image_pose_ts =\n image_ts - (*cached_lights_ptr)->timestamp;\n (*image_lights)->diff_image_sys_ts = image_ts - TimeUtil::GetCurrentTime();\n\n (*image_lights)->image = image;\n (*image_lights)->timestamp = image_ts;\n AINFO << \"TLPreprocessor sync ok ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n last_output_ts_ = image_ts;\n last_pub_camera_id_ = camera_id;\n *should_pub = true;\n } else {\n AINFO << \"sync image with cached lights projection failed, \"\n << \"no valid pose, ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n std::string cached_array_str = \"cached lights\";\n double diff_image_pose_ts = 0.0;\n double diff_image_sys_ts = 0.0;\n bool no_signal = false;\n if (fabs(image_ts - last_no_signals_ts_) < no_signals_interval_seconds_) {\n AINFO << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" last_no_signals_ts: \" << GLOG_TIMESTAMP(last_no_signals_ts_)\n << \" (sync_time - last_no_signals_ts): \"\n << GLOG_TIMESTAMP(image_ts - last_no_signals_ts_)\n << \" query \/tf in low frequence because no signals forward \"\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n no_signal = true;\n } else if (image_ts < cached_lights_.front()->timestamp) {\n double pose_ts = cached_lights_.front()->timestamp;\n double system_ts = TimeUtil::GetCurrentTime();\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", which is earlier than \" << cached_array_str\n << \".front() ts: \" << GLOG_TIMESTAMP(pose_ts)\n << \", diff between image and pose ts: \"\n << GLOG_TIMESTAMP(image_ts - pose_ts)\n << \"; system ts: \" << GLOG_TIMESTAMP(system_ts)\n << \", diff between image and system ts: \"\n << GLOG_TIMESTAMP(image_ts - system_ts)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n \/\/ difference between image and pose timestamps\n diff_image_pose_ts = image_ts - pose_ts;\n diff_image_sys_ts = image_ts - system_ts;\n } else if (image_ts > cached_lights_.back()->timestamp) {\n double pose_ts = cached_lights_.back()->timestamp;\n double system_ts = TimeUtil::GetCurrentTime();\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", which is older than \" << cached_array_str\n << \".back() ts: \" << GLOG_TIMESTAMP(pose_ts)\n << \", diff between image and pose ts: \"\n << GLOG_TIMESTAMP(image_ts - pose_ts)\n << \"; system ts: \" << GLOG_TIMESTAMP(system_ts)\n << \", diff between image and system ts: \"\n << GLOG_TIMESTAMP(image_ts - system_ts)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n diff_image_pose_ts = image_ts - pose_ts;\n diff_image_sys_ts = image_ts - system_ts;\n } else if (!find_loc) {\n \/\/ if no pose found, log warning msg\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", cannot find close enough timestamp, \" << cached_array_str\n << \".front() ts: \"\n << GLOG_TIMESTAMP(cached_lights_.front()->timestamp) << \", \"\n << cached_array_str << \".back() ts: \"\n << GLOG_TIMESTAMP(cached_lights_.back()->timestamp)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n }\n if (image->camera_id() == LONG_FOCUS &&\n (no_signal || last_pub_camera_id_ == LONG_FOCUS)) {\n *should_pub = true;\n (*image_lights).reset(new ImageLights);\n (*image_lights)->image = image;\n (*image_lights)->timestamp = image_ts;\n (*image_lights)->diff_image_sys_ts = diff_image_sys_ts;\n (*image_lights)->diff_image_pose_ts = diff_image_pose_ts;\n (*image_lights)->is_pose_valid = no_signal;\n (*image_lights)->num_signals = 0;\n }\n }\n \/\/ sync fail may because:\n \/\/ 1. image is not selected\n \/\/ 2. timestamp drift\n \/\/ 3. [there is no tf]\n return sync_ok;\n}\n\nvoid TLPreprocessor::set_last_pub_camera_id(CameraId camera_id) {\n last_pub_camera_id_ = camera_id;\n}\n\nCameraId TLPreprocessor::last_pub_camera_id() const {\n return last_pub_camera_id_;\n}\n\nint TLPreprocessor::max_cached_lights_size() const {\n return max_cached_lights_size_;\n}\n\nvoid TLPreprocessor::SelectImage(const CarPose &pose,\n const LightsArray &lights_on_image_array,\n const LightsArray &lights_outside_image_array,\n CameraId *selection) {\n *selection = static_cast(kShortFocusIdx);\n\n \/\/ check from long focus to short focus\n for (int cam_id = 0; cam_id < kCountCameraId; ++cam_id) {\n if (!lights_outside_image_array[cam_id]->empty()) {\n continue;\n }\n bool ok = true;\n \/\/ find the short focus camera without range check\n if (cam_id != kShortFocusIdx) {\n for (const LightPtr &light : *(lights_on_image_array[cam_id])) {\n if (IsOnBorder(cv::Size(projection_image_cols_, projection_image_rows_),\n light->region.projection_roi,\n image_border_size[cam_id])) {\n ok = false;\n AINFO << \"light project on image border region, \"\n << \"CameraId: \" << kCameraIdToStr.at(cam_id);\n break;\n }\n }\n }\n if (ok) {\n *selection = static_cast(cam_id);\n break;\n }\n }\n\n AINFO << \"select_image selection: \" << *selection;\n}\n\nbool TLPreprocessor::ProjectLights(const CarPose &pose,\n const std::vector &signals,\n const CameraId &camera_id,\n LightPtrs *lights_on_image,\n LightPtrs *lights_outside_image) {\n if (signals.empty()) {\n ADEBUG << \"project_lights get empty signals.\";\n return true;\n }\n\n const int cam_id = static_cast(camera_id);\n if (cam_id < 0 || cam_id >= kCountCameraId) {\n AERROR << \"project_lights get invalid CameraId: \" << camera_id;\n return false;\n }\n\n for (size_t i = 0; i < signals.size(); ++i) {\n LightPtr light(new Light);\n light->info = signals[i];\n if (!projection_.Project(pose, ProjectOption(camera_id), light.get())) {\n lights_outside_image->push_back(light);\n } else {\n lights_on_image->push_back(light);\n }\n }\n\n return true;\n}\n\nbool TLPreprocessor::IsOnBorder(const cv::Size size, const cv::Rect &roi,\n const int border_size) const {\n if (roi.x < border_size || roi.y < border_size) {\n return true;\n }\n if (roi.x + roi.width + border_size >= size.width ||\n roi.y + roi.height + border_size >= size.height) {\n return true;\n }\n return false;\n}\n\nint TLPreprocessor::GetMinFocalLenCameraId() { return kShortFocusIdx; }\n\nint TLPreprocessor::GetMaxFocalLenCameraId() { return kLongFocusIdx; }\n\nREGISTER_PREPROCESSOR(TLPreprocessor);\n\n} \/\/ namespace traffic_light\n} \/\/ namespace perception\n} \/\/ namespace apollo\nfix when there is no signal, traffic light give error info (#2304)\/******************************************************************************\n * Copyright 2017 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"modules\/perception\/traffic_light\/preprocessor\/tl_preprocessor.h\"\n\n#include \"modules\/perception\/lib\/base\/time_util.h\"\n#include \"modules\/perception\/onboard\/transform_input.h\"\n#include \"modules\/perception\/traffic_light\/base\/tl_shared_data.h\"\n#include \"modules\/perception\/traffic_light\/base\/utils.h\"\n\nnamespace apollo {\nnamespace perception {\nnamespace traffic_light {\n\nbool TLPreprocessor::Init() {\n ConfigManager *config_manager = ConfigManager::instance();\n const ModelConfig *model_config = NULL;\n if (!config_manager->GetModelConfig(name(), &model_config)) {\n AERROR << \"not found model: \" << name();\n return false;\n }\n\n \/\/ Read parameters from config file\n if (!model_config->GetValue(\"max_cached_lights_size\",\n &max_cached_lights_size_)) {\n AERROR << \"max_cached_image_lights_array_size not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"projection_image_cols\",\n &projection_image_cols_)) {\n AERROR << \"projection_image_cols not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"projection_image_rows\",\n &projection_image_rows_)) {\n AERROR << \"projection_image_rows not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"sync_interval_seconds\",\n &sync_interval_seconds_)) {\n AERROR << \"sync_interval_seconds not found.\" << name();\n return false;\n }\n if (!model_config->GetValue(\"no_signals_interval_seconds\",\n &no_signals_interval_seconds_)) {\n AERROR << \"no_signals_interval_seconds not found.\" << name();\n return false;\n }\n\n \/\/ init projection\n if (!projection_.Init()) {\n AERROR << \"TLPreprocessor init projection failed.\";\n return false;\n }\n AINFO << kCountCameraId;\n return true;\n}\n\nbool TLPreprocessor::CacheLightsProjections(const CarPose &pose,\n const std::vector &signals,\n const double timestamp) {\n MutexLock lock(&mutex_);\n PERF_FUNCTION();\n\n AINFO << \"TLPreprocessor has \" << cached_lights_.size()\n << \" lights projections cached.\";\n\n \/\/ pop front if cached array'size > FLAGS_max_cached_image_lights_array_size\n while (cached_lights_.size() > static_cast(max_cached_lights_size_)) {\n cached_lights_.erase(cached_lights_.begin());\n }\n\n \/\/ lights projection info. to be added in cached array\n std::shared_ptr image_lights(new ImageLights);\n \/\/ default select long focus camera\n image_lights->camera_id = LONG_FOCUS;\n image_lights->timestamp = timestamp;\n image_lights->pose = pose;\n image_lights->is_pose_valid = true;\n\n AINFO << \"TLPreprocessor Got signal number:\" << signals.size()\n << \", ts: \" << GLOG_TIMESTAMP(timestamp);\n for (const auto &signal : signals) {\n AINFO << \"signal info:\" << signal.ShortDebugString();\n }\n \/\/ lights projections info.\n\n std::vector> lights_on_image(kCountCameraId);\n std::vector> lights_outside_image(kCountCameraId);\n for (auto &light_ptrs : lights_on_image) {\n light_ptrs.reset(new LightPtrs);\n }\n for (auto &light_ptrs : lights_outside_image) {\n light_ptrs.reset(new LightPtrs);\n }\n if (signals.size() > 0) {\n \/\/ project light region on each camera's image plane\n for (int cam_id = 0; cam_id < kCountCameraId; ++cam_id) {\n if (!ProjectLights(pose, signals, static_cast(cam_id),\n lights_on_image[cam_id].get(),\n lights_outside_image[cam_id].get())) {\n AERROR << \"add_cached_lights_projections project lights on \"\n << kCameraIdToStr.at(static_cast(cam_id))\n << \" image failed, \"\n << \"ts: \" << GLOG_TIMESTAMP(timestamp) << \", camera_id: \"\n << kCameraIdToStr.at(static_cast(cam_id));\n return false;\n }\n }\n\n \/\/ select which image to be used\n SelectImage(pose, lights_on_image, lights_outside_image,\n &(image_lights->camera_id));\n AINFO << \"select camera: \" << kCameraIdToStr.at(image_lights->camera_id);\n\n } else {\n last_no_signals_ts_ = timestamp;\n }\n image_lights->num_signals = signals.size();\n AINFO << \"cached info with \" << image_lights->num_signals << \" signals\";\n cached_lights_.push_back(image_lights);\n\n return true;\n}\n\nbool TLPreprocessor::SyncImage(const ImageSharedPtr &image,\n ImageLightsPtr *image_lights, bool *should_pub) {\n MutexLock lock(&mutex_);\n PERF_FUNCTION();\n CameraId camera_id = image->camera_id();\n double image_ts = image->ts();\n bool sync_ok = false;\n\n PERF_FUNCTION();\n if (cached_lights_.size() == 0) {\n AINFO << \"No cached light\";\n return false;\n }\n const int cam_id = static_cast(camera_id);\n if (cam_id < 0 || cam_id >= kCountCameraId) {\n AERROR << \"SyncImage failed, \"\n << \"get unknown CameraId: \" << camera_id;\n return false;\n }\n\n \/\/ find close enough(by timestamp difference)\n \/\/ lights projection from back to front\n\n bool find_loc = false; \/\/ if pose is found\n auto cached_lights_ptr = cached_lights_.rbegin();\n for (; cached_lights_ptr != cached_lights_.rend(); ++cached_lights_ptr) {\n double light_ts = (*cached_lights_ptr)->timestamp;\n if (fabs(light_ts - image_ts) < sync_interval_seconds_) {\n find_loc = true;\n auto proj_cam_id = static_cast((*cached_lights_ptr)->camera_id);\n auto image_cam_id = static_cast(camera_id);\n auto proj_cam_id_str =\n (kCameraIdToStr.find(proj_cam_id) != kCameraIdToStr.end()\n ? kCameraIdToStr.at(proj_cam_id)\n : std::to_string(proj_cam_id));\n \/\/ found related pose but if camear ID doesn't match\n if (proj_cam_id != image_cam_id) {\n AWARN << \"find appropriate localization, but camera_id not match\"\n << \", cached projection's camera_id: \" << proj_cam_id_str\n << \" , image's camera_id: \" << kCameraIdToStr.at(image_cam_id);\n continue;\n }\n if (image_ts < last_output_ts_) {\n AWARN << \"TLPreprocessor reject the image pub ts:\"\n << GLOG_TIMESTAMP(image_ts)\n << \" which is earlier than last output ts:\"\n << GLOG_TIMESTAMP(last_output_ts_)\n << \", image camera_id: \" << kCameraIdToStr.at(image_cam_id);\n return false;\n }\n sync_ok = true;\n break;\n }\n }\n\n if (sync_ok) {\n *image_lights = *cached_lights_ptr;\n (*image_lights)->diff_image_pose_ts =\n image_ts - (*cached_lights_ptr)->timestamp;\n (*image_lights)->diff_image_sys_ts = image_ts - TimeUtil::GetCurrentTime();\n\n (*image_lights)->image = image;\n (*image_lights)->timestamp = image_ts;\n AINFO << \"TLPreprocessor sync ok ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n last_output_ts_ = image_ts;\n last_pub_camera_id_ = camera_id;\n *should_pub = true;\n } else {\n AINFO << \"sync image with cached lights projection failed, \"\n << \"no valid pose, ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n std::string cached_array_str = \"cached lights\";\n double diff_image_pose_ts = 0.0;\n double diff_image_sys_ts = 0.0;\n bool no_signal = false;\n if (fabs(image_ts - last_no_signals_ts_) < no_signals_interval_seconds_) {\n AINFO << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \" last_no_signals_ts: \" << GLOG_TIMESTAMP(last_no_signals_ts_)\n << \" (sync_time - last_no_signals_ts): \"\n << GLOG_TIMESTAMP(image_ts - last_no_signals_ts_)\n << \" query \/tf in low frequence because no signals forward \"\n << \" camera_id: \" << kCameraIdToStr.at(camera_id);\n no_signal = true;\n } else if (image_ts < cached_lights_.front()->timestamp) {\n double pose_ts = cached_lights_.front()->timestamp;\n double system_ts = TimeUtil::GetCurrentTime();\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", which is earlier than \" << cached_array_str\n << \".front() ts: \" << GLOG_TIMESTAMP(pose_ts)\n << \", diff between image and pose ts: \"\n << GLOG_TIMESTAMP(image_ts - pose_ts)\n << \"; system ts: \" << GLOG_TIMESTAMP(system_ts)\n << \", diff between image and system ts: \"\n << GLOG_TIMESTAMP(image_ts - system_ts)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n \/\/ difference between image and pose timestamps\n diff_image_pose_ts = image_ts - pose_ts;\n diff_image_sys_ts = image_ts - system_ts;\n } else if (image_ts > cached_lights_.back()->timestamp) {\n double pose_ts = cached_lights_.back()->timestamp;\n double system_ts = TimeUtil::GetCurrentTime();\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", which is older than \" << cached_array_str\n << \".back() ts: \" << GLOG_TIMESTAMP(pose_ts)\n << \", diff between image and pose ts: \"\n << GLOG_TIMESTAMP(image_ts - pose_ts)\n << \"; system ts: \" << GLOG_TIMESTAMP(system_ts)\n << \", diff between image and system ts: \"\n << GLOG_TIMESTAMP(image_ts - system_ts)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n diff_image_pose_ts = image_ts - pose_ts;\n diff_image_sys_ts = image_ts - system_ts;\n } else if (!find_loc) {\n \/\/ if no pose found, log warning msg\n AWARN << \"TLPreprocessor \" << cached_array_str\n << \" sync failed, image ts: \" << GLOG_TIMESTAMP(image_ts)\n << \", cannot find close enough timestamp, \" << cached_array_str\n << \".front() ts: \"\n << GLOG_TIMESTAMP(cached_lights_.front()->timestamp) << \", \"\n << cached_array_str << \".back() ts: \"\n << GLOG_TIMESTAMP(cached_lights_.back()->timestamp)\n << \", camera_id: \" << kCameraIdToStr.at(camera_id);\n }\n if (image->camera_id() == LONG_FOCUS &&\n (no_signal || last_pub_camera_id_ == LONG_FOCUS)) {\n *should_pub = true;\n (*image_lights).reset(new ImageLights);\n (*image_lights)->image = image;\n (*image_lights)->camera_id = image->camera_id();\n (*image_lights)->timestamp = image_ts;\n (*image_lights)->diff_image_sys_ts = diff_image_sys_ts;\n (*image_lights)->diff_image_pose_ts = diff_image_pose_ts;\n (*image_lights)->is_pose_valid = no_signal;\n (*image_lights)->num_signals = 0;\n }\n }\n \/\/ sync fail may because:\n \/\/ 1. image is not selected\n \/\/ 2. timestamp drift\n \/\/ 3. [there is no tf]\n return sync_ok;\n}\n\nvoid TLPreprocessor::set_last_pub_camera_id(CameraId camera_id) {\n last_pub_camera_id_ = camera_id;\n}\n\nCameraId TLPreprocessor::last_pub_camera_id() const {\n return last_pub_camera_id_;\n}\n\nint TLPreprocessor::max_cached_lights_size() const {\n return max_cached_lights_size_;\n}\n\nvoid TLPreprocessor::SelectImage(const CarPose &pose,\n const LightsArray &lights_on_image_array,\n const LightsArray &lights_outside_image_array,\n CameraId *selection) {\n *selection = static_cast(kShortFocusIdx);\n\n \/\/ check from long focus to short focus\n for (int cam_id = 0; cam_id < kCountCameraId; ++cam_id) {\n if (!lights_outside_image_array[cam_id]->empty()) {\n continue;\n }\n bool ok = true;\n \/\/ find the short focus camera without range check\n if (cam_id != kShortFocusIdx) {\n for (const LightPtr &light : *(lights_on_image_array[cam_id])) {\n if (IsOnBorder(cv::Size(projection_image_cols_, projection_image_rows_),\n light->region.projection_roi,\n image_border_size[cam_id])) {\n ok = false;\n AINFO << \"light project on image border region, \"\n << \"CameraId: \" << kCameraIdToStr.at(cam_id);\n break;\n }\n }\n }\n if (ok) {\n *selection = static_cast(cam_id);\n break;\n }\n }\n\n AINFO << \"select_image selection: \" << *selection;\n}\n\nbool TLPreprocessor::ProjectLights(const CarPose &pose,\n const std::vector &signals,\n const CameraId &camera_id,\n LightPtrs *lights_on_image,\n LightPtrs *lights_outside_image) {\n if (signals.empty()) {\n ADEBUG << \"project_lights get empty signals.\";\n return true;\n }\n\n const int cam_id = static_cast(camera_id);\n if (cam_id < 0 || cam_id >= kCountCameraId) {\n AERROR << \"project_lights get invalid CameraId: \" << camera_id;\n return false;\n }\n\n for (size_t i = 0; i < signals.size(); ++i) {\n LightPtr light(new Light);\n light->info = signals[i];\n if (!projection_.Project(pose, ProjectOption(camera_id), light.get())) {\n lights_outside_image->push_back(light);\n } else {\n lights_on_image->push_back(light);\n }\n }\n\n return true;\n}\n\nbool TLPreprocessor::IsOnBorder(const cv::Size size, const cv::Rect &roi,\n const int border_size) const {\n if (roi.x < border_size || roi.y < border_size) {\n return true;\n }\n if (roi.x + roi.width + border_size >= size.width ||\n roi.y + roi.height + border_size >= size.height) {\n return true;\n }\n return false;\n}\n\nint TLPreprocessor::GetMinFocalLenCameraId() { return kShortFocusIdx; }\n\nint TLPreprocessor::GetMaxFocalLenCameraId() { return kLongFocusIdx; }\n\nREGISTER_PREPROCESSOR(TLPreprocessor);\n\n} \/\/ namespace traffic_light\n} \/\/ namespace perception\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008-2015 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \n\n\/\/ QUESO\n#include \n#include \n\n\/\/ C++\n#include \n\nnamespace QUESO\n{\n template\n InterpolationSurrogateData::InterpolationSurrogateData(const BoxSubset & domain,\n const std::vector& n_points )\n : m_domain(domain),\n m_n_points(n_points)\n {\n \/\/ This checks that the dimension of n_points and the domain are consistent\n this->check_dim_consistency();\n\n \/\/ Size m_values\n this->init_values(this->m_n_points);\n }\n\n template\n void InterpolationSurrogateData::check_dim_consistency() const\n {\n if( this->dim() != this->m_n_points.size() )\n {\n std::stringstream vspace_dim;\n vspace_dim << this->m_domain.vectorSpace().dimGlobal();\n\n std::stringstream n_points_dim;\n n_points_dim << this->m_n_points.size();\n\n std::string error = \"ERROR: Mismatch between dimension of parameter space and number of points\\n.\";\n error += \" domain dimension = \" + vspace_dim.str() + \"\\n\";\n error += \" points dimension = \" + n_points_dim.str() + \"\\n\";\n\n queso_error_msg(error);\n }\n }\n\n template\n void InterpolationSurrogateData::init_values( const std::vector& n_points )\n {\n unsigned int n_total_points = 0;\n for( std::vector::const_iterator it = n_points.begin();\n it != n_points.end(); ++it )\n {\n n_total_points += *it;\n }\n\n this->m_values.resize(n_total_points);\n }\n\n template\n void InterpolationSurrogateData::set_values( std::vector& values )\n {\n queso_assert_equal_to( values.size(), m_values.size() );\n\n this->m_values = values;\n }\n\n template\n void InterpolationSurrogateData::set_value( unsigned int n, double value )\n {\n queso_assert_less( n, m_values.size() );\n\n this->m_values[n] = value;\n }\n\n template\n double InterpolationSurrogateData::spacing( unsigned int dim ) const\n {\n unsigned int n_intervals = this->m_n_points[dim]-1;\n double x_min = this->x_min(dim);\n double x_max = this->x_max(dim);\n\n return (x_max-x_min)\/n_intervals;\n }\n\n} \/\/ end namespace QUESO\n\n\/\/ Instantiate\ntemplate class QUESO::InterpolationSurrogateData;\nFixed bug in InterpolationSurrogateData::init_values\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ QUESO - a library to support the Quantification of Uncertainty\n\/\/ for Estimation, Simulation and Optimization\n\/\/\n\/\/ Copyright (C) 2008-2015 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\/\/ This class\n#include \n\n\/\/ QUESO\n#include \n#include \n\n\/\/ C++\n#include \n\nnamespace QUESO\n{\n template\n InterpolationSurrogateData::InterpolationSurrogateData(const BoxSubset & domain,\n const std::vector& n_points )\n : m_domain(domain),\n m_n_points(n_points)\n {\n \/\/ This checks that the dimension of n_points and the domain are consistent\n this->check_dim_consistency();\n\n \/\/ Size m_values\n this->init_values(this->m_n_points);\n }\n\n template\n void InterpolationSurrogateData::check_dim_consistency() const\n {\n if( this->dim() != this->m_n_points.size() )\n {\n std::stringstream vspace_dim;\n vspace_dim << this->m_domain.vectorSpace().dimGlobal();\n\n std::stringstream n_points_dim;\n n_points_dim << this->m_n_points.size();\n\n std::string error = \"ERROR: Mismatch between dimension of parameter space and number of points\\n.\";\n error += \" domain dimension = \" + vspace_dim.str() + \"\\n\";\n error += \" points dimension = \" + n_points_dim.str() + \"\\n\";\n\n queso_error_msg(error);\n }\n }\n\n template\n void InterpolationSurrogateData::init_values( const std::vector& n_points )\n {\n unsigned int n_total_points = 1.0;\n for( std::vector::const_iterator it = n_points.begin();\n it != n_points.end(); ++it )\n {\n n_total_points *= *it;\n }\n\n this->m_values.resize(n_total_points);\n }\n\n template\n void InterpolationSurrogateData::set_values( std::vector& values )\n {\n queso_assert_equal_to( values.size(), m_values.size() );\n\n this->m_values = values;\n }\n\n template\n void InterpolationSurrogateData::set_value( unsigned int n, double value )\n {\n queso_assert_less( n, m_values.size() );\n\n this->m_values[n] = value;\n }\n\n template\n double InterpolationSurrogateData::spacing( unsigned int dim ) const\n {\n unsigned int n_intervals = this->m_n_points[dim]-1;\n double x_min = this->x_min(dim);\n double x_max = this->x_max(dim);\n\n return (x_max-x_min)\/n_intervals;\n }\n\n} \/\/ end namespace QUESO\n\n\/\/ Instantiate\ntemplate class QUESO::InterpolationSurrogateData;\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \"renderer.h\"\r\n\r\n#define PI 3.141592653589793826433\r\n\r\nvoid Camera::init(Vec3 from, Vec3 lookat, Vec3 up, double fov, double aspect, double aperture, double focus_dist)\r\n{\r\n\tlens_radius_ = aperture \/ 2;\r\n\tdouble theta = fov * PI \/ 180;\r\n\tdouble half_height = tan(theta \/ 2);\r\n\tdouble half_width = aspect * half_height;\r\n\torigin_ = from;\r\n\tVec3 d = from - lookat;\r\n\tw_ = d.normalize();\r\n\tu_ = cross(up, w_).normalize();\r\n\tv_ = cross(w_, u_);\r\n\tlower_left_corner_ = origin_ - u_ * (half_width * focus_dist) - v_ * (half_height * focus_dist) - w_ * focus_dist;\r\n\thorizontal_ = u_ * (2.0 * half_width * focus_dist);\r\n\tvertical_ = v_ * (2.0 * half_height * focus_dist);\r\n}\r\n\r\n\r\nrenderer::renderer(int w, int h)\r\n\t:steps_(0)\r\n{\r\n\tWIDTH = w;\r\n\tHEIGHT = h;\r\n\r\n\t\/\/ camera\r\n\tVec3 from(13, 3, 3);\r\n\tVec3 lookat(0, 0.5, 0);\r\n\tVec3 up(0, 1, 0);\r\n\tdouble fov = 20.0;\r\n\tdouble aspect = (double)WIDTH \/ (double)HEIGHT;\r\n\tdouble dist_to_focus = 10.0;\r\n\tdouble aperture = 0.1;\r\n\r\n\tcam_.init(from, lookat, up, fov, aspect, aperture, dist_to_focus);\r\n\r\n\t\/\/ scene\r\n\tdouble R = cos(PI \/ 4);\r\n\tscene_.Append(new Sphere(Vec3(0, -1000, 0), 1000, new Lambertian(Vec3(0.5, 0.5, 0.5))));\r\n\tscene_.Append(new Sphere(Vec3(0, 1, 0), 1.0, new Dielectric(1.5)));\r\n\tscene_.Append(new Sphere(Vec3(-4, 1, 0), 1.0, new Lambertian(Vec3(0.4, 0.2, 0.1))));\r\n\tscene_.Append(new Sphere(Vec3(4, 1, 0), 1.0, new Metal(Vec3(0.7, 0.6, 0.5), 0.0)));\r\n}\r\n\r\nrenderer::~renderer()\r\n{\r\n}\r\n\r\nVec3 renderer::raytrace(Ray r, int depth, my_rand &rnd)const\r\n{\r\n\t\/\/ noise for debug\r\n\treturn Vec3(rand_.get(), rand_.get(), rand_.get());\r\n\r\n\tHitRecord rec;\r\n\tif (scene_.hit(r, 0.001, DBL_MAX, rec)) {\r\n\t\tRay scattered;\r\n\t\tVec3 attenuation;\r\n\t\tif (depth < 50 && rec.mat_ptr->scatter(r, rec, attenuation, scattered, rnd)) {\r\n\t\t\treturn attenuation * raytrace(scattered, depth + 1, rnd);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn Vec3(0, 0, 0);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tVec3 unit_direction = r.direction().normalize();\r\n\t\tdouble t = 0.5*(unit_direction.y + 1.0);\r\n\t\treturn (1.0 - t)*Vec3(1.0, 1.0, 1.0) + t * Vec3(0.5, 0.7, 1.0);\r\n\t}\r\n}\r\n\r\nVec3 renderer::color(double u, double v, my_rand &rnd)const\r\n{\r\n\tRay r = cam_.get_ray(u, v, rnd);\r\n\treturn raytrace(r, 0, rnd);\r\n}\r\n\r\nvoid renderer::update(const double *src, double *dest, my_rand *a_rand)const\r\n{\r\n\tconst double INV_WIDTH = 1.0 \/ (double)WIDTH;\r\n\tconst double INV_HEIGHT = 1.0 \/ (double)HEIGHT;\r\n\r\n\t#pragma omp parallel for\r\n\tfor (int y = 0; y < HEIGHT; y++) {\r\n\t\tmy_rand &rnd = a_rand[omp_get_thread_num()];\r\n\t\tfor (int x = 0; x < WIDTH; x++) {\r\n\t\t\tint index = 3 * (y * WIDTH + x);\r\n\r\n\t\t\tdouble u = ((double)x + rnd.get()) * INV_WIDTH;\r\n\t\t\tdouble v = 1.0 - ((double)y + rnd.get()) * INV_HEIGHT;\r\n\r\n\t\t\tVec3 color = this->color(u, v, rnd);\r\n\t\t\tdest[index + 0] = src[index + 0] + color.x;\r\n\t\t\tdest[index + 1] = src[index + 1] + color.y;\r\n\t\t\tdest[index + 2] = src[index + 2] + color.z;\r\n\t\t}\r\n\t}\r\n}\r\nUpdate renderer.cpp#include \r\n#include \r\n#include \"renderer.h\"\r\n\r\n#define PI 3.141592653589793826433\r\n\r\nvoid Camera::init(Vec3 from, Vec3 lookat, Vec3 up, double fov, double aspect, double aperture, double focus_dist)\r\n{\r\n\tlens_radius_ = aperture \/ 2;\r\n\tdouble theta = fov * PI \/ 180;\r\n\tdouble half_height = tan(theta \/ 2);\r\n\tdouble half_width = aspect * half_height;\r\n\torigin_ = from;\r\n\tVec3 d = from - lookat;\r\n\tw_ = d.normalize();\r\n\tu_ = cross(up, w_).normalize();\r\n\tv_ = cross(w_, u_);\r\n\tlower_left_corner_ = origin_ - u_ * (half_width * focus_dist) - v_ * (half_height * focus_dist) - w_ * focus_dist;\r\n\thorizontal_ = u_ * (2.0 * half_width * focus_dist);\r\n\tvertical_ = v_ * (2.0 * half_height * focus_dist);\r\n}\r\n\r\n\r\nrenderer::renderer(int w, int h)\r\n\t:steps_(0)\r\n{\r\n\tWIDTH = w;\r\n\tHEIGHT = h;\r\n\r\n\t\/\/ camera\r\n\tVec3 from(13, 3, 3);\r\n\tVec3 lookat(0, 0.5, 0);\r\n\tVec3 up(0, 1, 0);\r\n\tdouble fov = 20.0;\r\n\tdouble aspect = (double)WIDTH \/ (double)HEIGHT;\r\n\tdouble dist_to_focus = 10.0;\r\n\tdouble aperture = 0.1;\r\n\r\n\tcam_.init(from, lookat, up, fov, aspect, aperture, dist_to_focus);\r\n\r\n\t\/\/ scene\r\n\tdouble R = cos(PI \/ 4);\r\n\tscene_.Append(new Sphere(Vec3(0, -1000, 0), 1000, new Lambertian(Vec3(0.5, 0.5, 0.5))));\r\n\tscene_.Append(new Sphere(Vec3(0, 1, 0), 1.0, new Dielectric(1.5)));\r\n\tscene_.Append(new Sphere(Vec3(-4, 1, 0), 1.0, new Lambertian(Vec3(0.4, 0.2, 0.1))));\r\n\tscene_.Append(new Sphere(Vec3(4, 1, 0), 1.0, new Metal(Vec3(0.7, 0.6, 0.5), 0.0)));\r\n}\r\n\r\nrenderer::~renderer()\r\n{\r\n}\r\n\r\nVec3 renderer::raytrace(Ray r, int depth, my_rand &rnd)const\r\n{\r\n\t\/\/ noise for debug\r\n\treturn Vec3(0,0,0);\r\n\/\/\treturn Vec3(rand_.get(), rand_.get(), rand_.get());\r\n\r\n\tHitRecord rec;\r\n\tif (scene_.hit(r, 0.001, DBL_MAX, rec)) {\r\n\t\tRay scattered;\r\n\t\tVec3 attenuation;\r\n\t\tif (depth < 50 && rec.mat_ptr->scatter(r, rec, attenuation, scattered, rnd)) {\r\n\t\t\treturn attenuation * raytrace(scattered, depth + 1, rnd);\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn Vec3(0, 0, 0);\r\n\t\t}\r\n\t}\r\n\telse {\r\n\t\tVec3 unit_direction = r.direction().normalize();\r\n\t\tdouble t = 0.5*(unit_direction.y + 1.0);\r\n\t\treturn (1.0 - t)*Vec3(1.0, 1.0, 1.0) + t * Vec3(0.5, 0.7, 1.0);\r\n\t}\r\n}\r\n\r\nVec3 renderer::color(double u, double v, my_rand &rnd)const\r\n{\r\n\tRay r = cam_.get_ray(u, v, rnd);\r\n\treturn raytrace(r, 0, rnd);\r\n}\r\n\r\nvoid renderer::update(const double *src, double *dest, my_rand *a_rand)const\r\n{\r\n\tconst double INV_WIDTH = 1.0 \/ (double)WIDTH;\r\n\tconst double INV_HEIGHT = 1.0 \/ (double)HEIGHT;\r\n\r\n\t#pragma omp parallel for\r\n\tfor (int y = 0; y < HEIGHT; y++) {\r\n\t\tmy_rand &rnd = a_rand[omp_get_thread_num()];\r\n\t\tfor (int x = 0; x < WIDTH; x++) {\r\n\t\t\tint index = 3 * (y * WIDTH + x);\r\n\r\n\t\t\tdouble u = ((double)x + rnd.get()) * INV_WIDTH;\r\n\t\t\tdouble v = 1.0 - ((double)y + rnd.get()) * INV_HEIGHT;\r\n\r\n\t\t\tVec3 color = this->color(u, v, rnd);\r\n\t\t\tdest[index + 0] = src[index + 0] + color.x;\r\n\t\t\tdest[index + 1] = src[index + 1] + color.y;\r\n\t\t\tdest[index + 2] = src[index + 2] + color.z;\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_http_protocol_handler.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/listen_socket.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nconst int kBufferSize = 16 * 1024;\n\nnamespace {\n\n\/\/ An internal implementation of DevToolsClientHost that delegates\n\/\/ messages sent for DevToolsClient to a DebuggerShell instance.\nclass DevToolsClientHostImpl : public DevToolsClientHost {\n public:\n explicit DevToolsClientHostImpl(HttpListenSocket* socket)\n : socket_(socket) {}\n ~DevToolsClientHostImpl() {}\n\n \/\/ DevToolsClientHost interface\n virtual void InspectedTabClosing() {\n ChromeThread::PostTask(\n ChromeThread::IO,\n FROM_HERE,\n NewRunnableMethod(socket_,\n &HttpListenSocket::Close));\n }\n\n virtual void SendMessageToClient(const IPC::Message& msg) {\n IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)\n IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);\n IPC_MESSAGE_UNHANDLED_ERROR()\n IPC_END_MESSAGE_MAP()\n }\n\n void NotifyCloseListener() {\n DevToolsClientHost::NotifyCloseListener();\n }\n private:\n \/\/ Message handling routines\n void OnRpcMessage(const DevToolsMessageData& data) {\n std::string message;\n message += \"devtools$$dispatch(\\\"\" + data.class_name + \"\\\", \\\"\" +\n data.method_name + \"\\\"\";\n for (std::vector::const_iterator it = data.arguments.begin();\n it != data.arguments.end(); ++it) {\n std::string param = *it;\n if (!param.empty())\n message += \", \" + param;\n }\n message += \")\";\n socket_->SendOverWebSocket(message);\n }\n HttpListenSocket* socket_;\n};\n\n}\n\nDevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {\n \/\/ Stop() must be called prior to this being called\n DCHECK(server_.get() == NULL);\n}\n\nvoid DevToolsHttpProtocolHandler::Start() {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));\n}\n\nvoid DevToolsHttpProtocolHandler::Stop() {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n if (info.path == \"\" || info.path == \"\/\") {\n \/\/ Pages discovery request.\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(this,\n &DevToolsHttpProtocolHandler::OnHttpRequestUI,\n socket,\n info));\n return;\n }\n\n size_t pos = info.path.find(\"\/devtools\/\");\n if (pos != 0) {\n socket->Send404();\n return;\n }\n\n \/\/ Proxy static files from chrome:\/\/devtools\/*.\n URLRequest* request = new URLRequest(GURL(\"chrome:\/\" + info.path), this);\n Bind(request, socket);\n request->set_context(\n Profile::GetDefaultRequestContext()->GetURLRequestContext());\n request->Start();\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketRequestUI,\n socket,\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,\n const std::string& data) {\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketMessageUI,\n socket,\n data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it != socket_to_requests_io_.end()) {\n \/\/ Dispose delegating socket.\n for (std::set::iterator it2 = it->second.begin();\n it2 != it->second.end(); ++it2) {\n URLRequest* request = *it2;\n request->Cancel();\n request_to_socket_io_.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n }\n socket_to_requests_io_.erase(socket);\n }\n\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnCloseUI,\n socket));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n std::string response = \"\";\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n TabContents* tab_contents = model->GetTabContentsAt(i);\n NavigationController& controller = tab_contents->controller();\n NavigationEntry* entry = controller.GetActiveEntry();\n if (entry == NULL)\n continue;\n\n if (!entry->url().is_valid())\n continue;\n\n DevToolsClientHost* client_host = DevToolsManager::GetInstance()->\n GetDevToolsClientHostFor(tab_contents->render_view_host());\n if (!client_host) {\n response += StringPrintf(\n \"%s (%s)<\/a>
\",\n controller.session_id().id(),\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n } else {\n response += StringPrintf(\n \"%s (%s)
\",\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n }\n }\n }\n response += \"<\/body><\/html>\";\n Send200(socket, response, \"text\/html\");\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n std::string prefix = \"\/devtools\/page\/\";\n size_t pos = request.path.find(prefix);\n if (pos != 0) {\n Send404(socket);\n return;\n }\n std::string page_id = request.path.substr(prefix.length());\n int id = 0;\n if (!StringToInt(page_id, &id)) {\n Send500(socket, \"Invalid page id: \" + page_id);\n return;\n }\n\n TabContents* tab_contents = GetTabContents(id);\n if (tab_contents == NULL) {\n Send500(socket, \"No such page id: \" + page_id);\n return;\n }\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {\n Send500(socket, \"Page with given id is being inspected: \" + page_id);\n return;\n }\n\n DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);\n socket_to_client_host_ui_[socket] = client_host;\n\n manager->RegisterDevToolsClientHostFor(\n tab_contents->render_view_host(),\n client_host);\n AcceptWebSocket(socket, request);\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessageUI(\n HttpListenSocket* socket,\n const std::string& d) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n\n std::string data = d;\n \/\/ TODO(pfeldman): Replace with proper parsing \/ dispatching.\n DevToolsMessageData message_data;\n message_data.class_name = \"ToolsAgent\";\n message_data.method_name = \"dispatchOnInspectorController\";\n\n size_t pos = data.find(\" \");\n message_data.arguments.push_back(data.substr(0, pos));\n data = data.substr(pos + 1);\n\n message_data.arguments.push_back(data);\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n manager->ForwardToDevToolsAgent(it->second,\n DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n DevToolsClientHostImpl* client_host =\n static_cast(it->second);\n client_host->NotifyCloseListener();\n delete client_host;\n socket_to_client_host_ui_.erase(socket);\n}\n\nvoid DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n int expected_size = static_cast(request->GetExpectedContentSize());\n\n std::string content_type;\n request->GetMimeType(&content_type);\n\n if (request->status().is_success()) {\n socket->Send(StringPrintf(\"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type:%s\\r\\n\"\n \"Content-Length:%d\\r\\n\"\n \"\\r\\n\",\n content_type.c_str(),\n expected_size));\n } else {\n socket->Send404();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n if (request->status().is_success())\n request->Read(buffer, kBufferSize, &bytes_read);\n OnReadCompleted(request, bytes_read);\n}\n\nvoid DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,\n int bytes_read) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n do {\n if (!request->status().is_success() || bytes_read <= 0)\n break;\n socket->Send(buffer->data(), bytes_read);\n } while (request->Read(buffer, kBufferSize, &bytes_read));\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request->status().is_io_pending())\n RequestCompleted(request);\n}\n\nDevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)\n : port_(port),\n server_(NULL) {\n}\n\nvoid DevToolsHttpProtocolHandler::Init() {\n server_ = HttpListenSocket::Listen(\"127.0.0.1\", port_, this);\n}\n\n\/\/ Run on I\/O thread\nvoid DevToolsHttpProtocolHandler::Teardown() {\n server_ = NULL;\n}\n\nvoid DevToolsHttpProtocolHandler::Bind(URLRequest* request,\n HttpListenSocket* socket) {\n request_to_socket_io_[request] = socket;\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it == socket_to_requests_io_.end()) {\n std::pair > value(\n socket,\n std::set());\n it = socket_to_requests_io_.insert(value).first;\n }\n it->second.insert(request);\n request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);\n}\n\nvoid DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n request_to_socket_io_.erase(request);\n SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);\n it2->second.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n}\n\nvoid DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,\n const std::string& data,\n const std::string& mime_type) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send200,\n data,\n mime_type));\n}\n\nvoid DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send404));\n}\n\nvoid DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,\n const std::string& message) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send500,\n message));\n}\n\nvoid DevToolsHttpProtocolHandler::AcceptWebSocket(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::AcceptWebSocket,\n request));\n}\n\nTabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n NavigationController& controller =\n model->GetTabContentsAt(i)->controller();\n if (controller.session_id().id() == session_id)\n return controller.tab_contents();\n }\n }\n return NULL;\n}\nDevTools: restore remote rebugging after upstream breakage.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/debugger\/devtools_http_protocol_handler.h\"\n\n#include \"base\/compiler_specific.h\"\n#include \"base\/logging.h\"\n#include \"base\/message_loop_proxy.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/debugger\/devtools_client_host.h\"\n#include \"chrome\/browser\/debugger\/devtools_manager.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/devtools_messages.h\"\n#include \"chrome\/common\/net\/url_request_context_getter.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"net\/base\/io_buffer.h\"\n#include \"net\/base\/listen_socket.h\"\n#include \"net\/server\/http_server_request_info.h\"\n#include \"net\/url_request\/url_request_context.h\"\n\nconst int kBufferSize = 16 * 1024;\n\nnamespace {\n\n\/\/ An internal implementation of DevToolsClientHost that delegates\n\/\/ messages sent for DevToolsClient to a DebuggerShell instance.\nclass DevToolsClientHostImpl : public DevToolsClientHost {\n public:\n explicit DevToolsClientHostImpl(HttpListenSocket* socket)\n : socket_(socket) {}\n ~DevToolsClientHostImpl() {}\n\n \/\/ DevToolsClientHost interface\n virtual void InspectedTabClosing() {\n ChromeThread::PostTask(\n ChromeThread::IO,\n FROM_HERE,\n NewRunnableMethod(socket_,\n &HttpListenSocket::Close));\n }\n\n virtual void SendMessageToClient(const IPC::Message& msg) {\n IPC_BEGIN_MESSAGE_MAP(DevToolsClientHostImpl, msg)\n IPC_MESSAGE_HANDLER(DevToolsClientMsg_RpcMessage, OnRpcMessage);\n IPC_MESSAGE_UNHANDLED_ERROR()\n IPC_END_MESSAGE_MAP()\n }\n\n void NotifyCloseListener() {\n DevToolsClientHost::NotifyCloseListener();\n }\n private:\n \/\/ Message handling routines\n void OnRpcMessage(const DevToolsMessageData& data) {\n std::string message;\n message += \"devtools$$dispatch(\\\"\" + data.class_name + \"\\\", \\\"\" +\n data.method_name + \"\\\"\";\n for (std::vector::const_iterator it = data.arguments.begin();\n it != data.arguments.end(); ++it) {\n std::string param = *it;\n if (!param.empty())\n message += \", \" + param;\n }\n message += \")\";\n socket_->SendOverWebSocket(message);\n }\n HttpListenSocket* socket_;\n};\n\n}\n\nDevToolsHttpProtocolHandler::~DevToolsHttpProtocolHandler() {\n \/\/ Stop() must be called prior to this being called\n DCHECK(server_.get() == NULL);\n}\n\nvoid DevToolsHttpProtocolHandler::Start() {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Init));\n}\n\nvoid DevToolsHttpProtocolHandler::Stop() {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(this, &DevToolsHttpProtocolHandler::Teardown));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n if (info.path == \"\" || info.path == \"\/\") {\n \/\/ Pages discovery request.\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(this,\n &DevToolsHttpProtocolHandler::OnHttpRequestUI,\n socket,\n info));\n return;\n }\n\n size_t pos = info.path.find(\"\/devtools\/\");\n if (pos != 0) {\n socket->Send404();\n return;\n }\n\n \/\/ Proxy static files from chrome:\/\/devtools\/*.\n URLRequest* request = new URLRequest(GURL(\"chrome:\/\" + info.path), this);\n Bind(request, socket);\n request->set_context(\n Profile::GetDefaultRequestContext()->GetURLRequestContext());\n request->Start();\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequest(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketRequestUI,\n socket,\n request));\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessage(HttpListenSocket* socket,\n const std::string& data) {\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnWebSocketMessageUI,\n socket,\n data));\n}\n\nvoid DevToolsHttpProtocolHandler::OnClose(HttpListenSocket* socket) {\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it != socket_to_requests_io_.end()) {\n \/\/ Dispose delegating socket.\n for (std::set::iterator it2 = it->second.begin();\n it2 != it->second.end(); ++it2) {\n URLRequest* request = *it2;\n request->Cancel();\n request_to_socket_io_.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n }\n socket_to_requests_io_.erase(socket);\n }\n\n ChromeThread::PostTask(\n ChromeThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &DevToolsHttpProtocolHandler::OnCloseUI,\n socket));\n}\n\nvoid DevToolsHttpProtocolHandler::OnHttpRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& info) {\n std::string response = \"\";\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n TabContents* tab_contents = model->GetTabContentsAt(i);\n NavigationController& controller = tab_contents->controller();\n NavigationEntry* entry = controller.GetActiveEntry();\n if (entry == NULL)\n continue;\n\n if (!entry->url().is_valid())\n continue;\n\n DevToolsClientHost* client_host = DevToolsManager::GetInstance()->\n GetDevToolsClientHostFor(tab_contents->render_view_host());\n if (!client_host) {\n response += StringPrintf(\n \"
%s (%s)<\/a>
\",\n controller.session_id().id(),\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n } else {\n response += StringPrintf(\n \"%s (%s)
\",\n UTF16ToUTF8(entry->title()).c_str(),\n entry->url().spec().c_str());\n }\n }\n }\n response += \"<\/body><\/html>\";\n Send200(socket, response, \"text\/html\");\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketRequestUI(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n std::string prefix = \"\/devtools\/page\/\";\n size_t pos = request.path.find(prefix);\n if (pos != 0) {\n Send404(socket);\n return;\n }\n std::string page_id = request.path.substr(prefix.length());\n int id = 0;\n if (!StringToInt(page_id, &id)) {\n Send500(socket, \"Invalid page id: \" + page_id);\n return;\n }\n\n TabContents* tab_contents = GetTabContents(id);\n if (tab_contents == NULL) {\n Send500(socket, \"No such page id: \" + page_id);\n return;\n }\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n if (manager->GetDevToolsClientHostFor(tab_contents->render_view_host())) {\n Send500(socket, \"Page with given id is being inspected: \" + page_id);\n return;\n }\n\n DevToolsClientHostImpl* client_host = new DevToolsClientHostImpl(socket);\n socket_to_client_host_ui_[socket] = client_host;\n\n manager->RegisterDevToolsClientHostFor(\n tab_contents->render_view_host(),\n client_host);\n AcceptWebSocket(socket, request);\n}\n\nvoid DevToolsHttpProtocolHandler::OnWebSocketMessageUI(\n HttpListenSocket* socket,\n const std::string& data) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n\n \/\/ TODO(pfeldman): Replace with proper parsing \/ dispatching.\n DevToolsMessageData message_data;\n message_data.class_name = \"ToolsAgent\";\n message_data.method_name = \"dispatchOnInspectorController\";\n message_data.arguments.push_back(data);\n\n DevToolsManager* manager = DevToolsManager::GetInstance();\n manager->ForwardToDevToolsAgent(it->second,\n DevToolsAgentMsg_RpcMessage(DevToolsMessageData(message_data)));\n}\n\nvoid DevToolsHttpProtocolHandler::OnCloseUI(HttpListenSocket* socket) {\n SocketToClientHostMap::iterator it = socket_to_client_host_ui_.find(socket);\n if (it == socket_to_client_host_ui_.end())\n return;\n DevToolsClientHostImpl* client_host =\n static_cast(it->second);\n client_host->NotifyCloseListener();\n delete client_host;\n socket_to_client_host_ui_.erase(socket);\n}\n\nvoid DevToolsHttpProtocolHandler::OnResponseStarted(URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n int expected_size = static_cast(request->GetExpectedContentSize());\n\n std::string content_type;\n request->GetMimeType(&content_type);\n\n if (request->status().is_success()) {\n socket->Send(StringPrintf(\"HTTP\/1.1 200 OK\\r\\n\"\n \"Content-Type:%s\\r\\n\"\n \"Content-Length:%d\\r\\n\"\n \"\\r\\n\",\n content_type.c_str(),\n expected_size));\n } else {\n socket->Send404();\n }\n\n int bytes_read = 0;\n \/\/ Some servers may treat HEAD requests as GET requests. To free up the\n \/\/ network connection as soon as possible, signal that the request has\n \/\/ completed immediately, without trying to read any data back (all we care\n \/\/ about is the response code and headers, which we already have).\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n if (request->status().is_success())\n request->Read(buffer, kBufferSize, &bytes_read);\n OnReadCompleted(request, bytes_read);\n}\n\nvoid DevToolsHttpProtocolHandler::OnReadCompleted(URLRequest* request,\n int bytes_read) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n\n net::IOBuffer* buffer = request_to_buffer_io_[request].get();\n do {\n if (!request->status().is_success() || bytes_read <= 0)\n break;\n socket->Send(buffer->data(), bytes_read);\n } while (request->Read(buffer, kBufferSize, &bytes_read));\n\n \/\/ See comments re: HEAD requests in OnResponseStarted().\n if (!request->status().is_io_pending())\n RequestCompleted(request);\n}\n\nDevToolsHttpProtocolHandler::DevToolsHttpProtocolHandler(int port)\n : port_(port),\n server_(NULL) {\n}\n\nvoid DevToolsHttpProtocolHandler::Init() {\n server_ = HttpListenSocket::Listen(\"127.0.0.1\", port_, this);\n}\n\n\/\/ Run on I\/O thread\nvoid DevToolsHttpProtocolHandler::Teardown() {\n server_ = NULL;\n}\n\nvoid DevToolsHttpProtocolHandler::Bind(URLRequest* request,\n HttpListenSocket* socket) {\n request_to_socket_io_[request] = socket;\n SocketToRequestsMap::iterator it = socket_to_requests_io_.find(socket);\n if (it == socket_to_requests_io_.end()) {\n std::pair > value(\n socket,\n std::set());\n it = socket_to_requests_io_.insert(value).first;\n }\n it->second.insert(request);\n request_to_buffer_io_[request] = new net::IOBuffer(kBufferSize);\n}\n\nvoid DevToolsHttpProtocolHandler::RequestCompleted(URLRequest* request) {\n RequestToSocketMap::iterator it = request_to_socket_io_.find(request);\n if (it == request_to_socket_io_.end())\n return;\n\n HttpListenSocket* socket = it->second;\n request_to_socket_io_.erase(request);\n SocketToRequestsMap::iterator it2 = socket_to_requests_io_.find(socket);\n it2->second.erase(request);\n request_to_buffer_io_.erase(request);\n delete request;\n}\n\nvoid DevToolsHttpProtocolHandler::Send200(HttpListenSocket* socket,\n const std::string& data,\n const std::string& mime_type) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send200,\n data,\n mime_type));\n}\n\nvoid DevToolsHttpProtocolHandler::Send404(HttpListenSocket* socket) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send404));\n}\n\nvoid DevToolsHttpProtocolHandler::Send500(HttpListenSocket* socket,\n const std::string& message) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::Send500,\n message));\n}\n\nvoid DevToolsHttpProtocolHandler::AcceptWebSocket(\n HttpListenSocket* socket,\n const HttpServerRequestInfo& request) {\n ChromeThread::PostTask(\n ChromeThread::IO, FROM_HERE,\n NewRunnableMethod(socket,\n &HttpListenSocket::AcceptWebSocket,\n request));\n}\n\nTabContents* DevToolsHttpProtocolHandler::GetTabContents(int session_id) {\n for (BrowserList::const_iterator it = BrowserList::begin(),\n end = BrowserList::end(); it != end; ++it) {\n TabStripModel* model = (*it)->tabstrip_model();\n for (int i = 0, size = model->count(); i < size; ++i) {\n NavigationController& controller =\n model->GetTabContentsAt(i)->controller();\n if (controller.session_id().id() == session_id)\n return controller.tab_contents();\n }\n }\n return NULL;\n}\n<|endoftext|>"} {"text":"\/\/ library.C\n\/\/ \n\/\/ Copyright 1996-2001 Per Abrahamsen and Sren Hansen\n\/\/ Copyright 2000-2001 KVL.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#define BUILD_DLL\n\n#include \"library.h\"\n#include \"block.h\"\n#include \"alist.h\"\n#include \"syntax.h\"\n#include \"treelog.h\"\n#include \n#include \"assertion.h\"\n#include \"symbol.h\"\n#include \"memutils.h\"\n#include \n#include \n#include \n\nstruct Library::Implementation\n{\n \/\/ Id.\n const symbol name;\n const char * description;\n\n \/\/ Types.\n typedef std::map bmap_type;\n typedef std::map alist_map;\n typedef std::map syntax_map;\n\n \/\/ Data (remember to update Library::clone if you change this).\n bmap_type builders;\n alist_map alists;\n syntax_map syntaxen;\n std::vector doc_funs;\n\n \/\/ Accessors.\n AttributeList& lookup (symbol) const;\n bool check (symbol) const;\n void add_base (AttributeList&, const Syntax&);\n void add (symbol, AttributeList&, const Syntax&, builder);\n const Syntax& syntax (symbol) const;\n void entries (std::vector&) const;\n void remove (symbol);\n void clear_parsed ();\n void refile_parsed (const std::string& from, const std::string& to);\n static void load_syntax (Syntax&, AttributeList&);\n Implementation (const char* n);\n ~Implementation ();\n};\n\nAttributeList&\nLibrary::Implementation::lookup (const symbol key) const\n{ \n alist_map::const_iterator i = alists.find (key);\n\n if (i == alists.end ())\n daisy_notreached ();\n\n return *(*i).second;\n}\n\nbool\nLibrary::Implementation::check (const symbol key) const\n{ \n alist_map::const_iterator i = alists.find (key);\n\n if (i == alists.end ())\n return false;\n\n return true;\n}\n\nvoid\nLibrary::Implementation::add_base (AttributeList& value,\n\t\t\t const Syntax& syntax)\n{\n daisy_assert (value.check (\"base_model\"));\n const symbol key = value.identifier (\"base_model\");\n alists[key] = &value;\n syntaxen[key] = &syntax;\n}\n\nvoid\nLibrary::Implementation::add (const symbol key, AttributeList& value,\n\t\t\t const Syntax& syntax, builder build)\n{\n alists[key] = &value;\n syntaxen[key] = &syntax;\n \/\/ builders.insert (std::make_pair (key, build));\n builders[key] = build;\n}\n\nconst Syntax& \nLibrary::Implementation::syntax (const symbol key) const\n{ \n syntax_map::const_iterator i = syntaxen.find (key);\n\n if (i == syntaxen.end ())\n daisy_panic (\"'\" + key + \"' not found\");\n\n return *(*i).second;\n}\n\nvoid\nLibrary::Implementation::entries (std::vector& result) const\n{\n for (syntax_map::const_iterator i = syntaxen.begin ();\n i != syntaxen.end ();\n i++)\n {\n result.push_back ((*i).first);\n }\n}\n\nvoid\nLibrary::Implementation::remove (const symbol key)\n{\n alists.erase (alists.find (key));\n syntaxen.erase (syntaxen.find (key));\n}\n\nvoid\nLibrary::Implementation::clear_parsed ()\n{\n retry:\n for (alist_map::iterator i = alists.begin (); i != alists.end (); i++)\n {\n AttributeList& alist = *((*i).second);\n if (alist.check (\"parsed_from_file\"))\n\t{\n\t const symbol key = (*i).first;\n\t syntax_map::iterator j = syntaxen.find (key);\n\t daisy_assert (j != syntaxen.end ());\n\t syntaxen.erase (j);\n\t alists.erase (i);\n\t delete &alist;\n\t goto retry;\n\t}\n }\n}\n\nvoid\nLibrary::Implementation::refile_parsed (const std::string& from, const std::string& to)\n{\n daisy_assert (from != to);\n for (alist_map::iterator i = alists.begin (); i != alists.end (); i++)\n {\n AttributeList& alist = *((*i).second);\n if (alist.check (\"parsed_from_file\")\n\t && alist.name (\"parsed_from_file\") == from)\n\t{\n\t alist.add (\"parsed_from_file\", to);\n\t}\n }\n}\n\nLibrary::Implementation::Implementation (const char* n) \n : name (symbol (n)),\n description (NULL)\n{ }\n\nLibrary::Implementation::~Implementation ()\n{ \n \/\/ Delete alists.\n map_delete (alists.begin (), alists.end ());\n\n \/\/ Delete unique syntaxen.\n std::set unique;\n for (syntax_map::iterator i = syntaxen.begin ();\n i != syntaxen.end ();\n i++)\n {\n daisy_assert ((*i).second);\n unique.insert ((*i).second);\n (*i).second = NULL;\n }\n sequence_delete (unique.begin (), unique.end ());\n}\n\nvoid \nLibrary::clear_parsed ()\n{ impl->clear_parsed (); }\n\nvoid \nLibrary::refile_parsed (const std::string& from, const std::string& to)\n{ impl->refile_parsed (from, to); }\n\nsymbol\nLibrary::name () const\n{ return impl->name; }\n\nconst char*\nLibrary::description () const\n{ return impl->description; }\n\nAttributeList&\nLibrary::lookup (const symbol key) const\n{ return impl->lookup (key); }\n\nbool\nLibrary::check (const symbol key) const\n{ return impl->check (key); }\n\nbool\nLibrary::complete (const Metalib& metalib, const symbol key) const\n{ \n if (!check (key))\n return false;\n\n if (!syntax (key).check (metalib, lookup (key), Treelog::null ()))\n return false;\n\n return true;\n}\n\nvoid\nLibrary::add_base (AttributeList& value, const Syntax& syntax)\n{ impl->add_base (value, syntax); }\n\nvoid\nLibrary::add (const symbol key, AttributeList& value, const Syntax& syntax,\n builder build)\n{ impl->add (key, value, syntax, build); }\n\nvoid \nLibrary::add_derived (const symbol name, AttributeList& al,\n\t\t const symbol super)\n{ \n add_derived (name, syntax (super), al, super); \n}\n\nvoid\nLibrary::add_derived (const symbol name, const Syntax& syn, AttributeList& al,\n\t\t const symbol super)\n{ \n al.add (\"type\", super);\n add (name, al, syn, impl->builders[super]); \n}\n\nconst Syntax& \nLibrary::syntax (const symbol key) const\n{ return impl->syntax (key); }\n\nvoid\nLibrary::entries (std::vector& result) const\n{ impl->entries (result); }\n\nbool \nLibrary::is_derived_from (const symbol a, const symbol b) const\n{\n if (a == b)\n return true;\n\n const AttributeList& al = lookup (a);\n\n if (!al.check (\"type\") && !al.check (\"base_model\"))\n return false;\n\n const symbol type = al.check (\"type\") \n ? al.identifier (\"type\") \n : al.identifier (\"base_model\");\n\n if (type == b)\n return true;\n\n daisy_assert (check (type));\n\n if (type == a)\n return false;\n\n return is_derived_from (type, b);\n}\n \nconst symbol\nLibrary::base_model (const symbol parameterization) const\n{\n const AttributeList& al = lookup (parameterization);\n\n if (al.check (\"type\"))\n return base_model (al.identifier (\"type\"));\n if (al.check (\"base_model\")\n && al.identifier (\"base_model\") != parameterization)\n return base_model (al.identifier (\"base_model\"));\n\n return parameterization;\n}\n\nbool \nLibrary::has_interesting_description (const AttributeList& alist) const\n{\n \/\/ A missing description is boring.\n if (!alist.check (\"description\"))\n return false;\n \n \/\/ The description of models are always interesting.\n if (!alist.check (\"type\"))\n return true;\n \n \/\/ If the model has no description, this one is interesting.\n const symbol type = alist.identifier (\"type\");\n if (!check (type))\n {\n daisy_bug (name () + \" does not have \" + type.name ());\n return false;\n }\n daisy_assert (check (type));\n const AttributeList& super = lookup (type);\n if (!super.check (\"description\"))\n return true;\n \n \/\/ If the model description is different, this one is interesting.\n return alist.name (\"description\") != super.name (\"description\");\n}\n\nvoid\nLibrary::add_doc_fun (doc_fun fun) \n{ impl->doc_funs.push_back (fun); }\n\nstd::vector& \nLibrary::doc_funs () const\n{ return impl->doc_funs; }\n\nvoid\nLibrary::remove (const symbol key)\n{ impl->remove (key); }\n\nModel* \nLibrary::build_raw (const symbol type, Block& block) const\n{ \n const Implementation::bmap_type::const_iterator i \n = impl->builders.find (type);\n if (i == impl->builders.end ())\n {\n std::ostringstream tmp;\n tmp << \"No '\" << type.name () << \"' found in '\" << impl->name.name()\n << \"' library\";\n daisy_panic (tmp.str ());\n }\n return &(*i).second (block);\n}\n\nvoid \nLibrary::set_description (const char *const description)\n{\n daisy_assert (!impl->description);\n impl->description = description;\n}\n\nLibrary* \nLibrary::clone () const\n{ \n Library *const lib = new Library (impl->name.name ().c_str ());\n lib->set_description (impl->description);\n lib->impl->builders = impl->builders;\n for (Implementation::alist_map::const_iterator i = impl->alists.begin ();\n i != impl->alists.end ();\n i++)\n lib->impl->alists[(*i).first] = new AttributeList (*(*i).second);\n for (Implementation::syntax_map::const_iterator i = impl->syntaxen.begin ();\n i != impl->syntaxen.end ();\n i++)\n lib->impl->syntaxen[(*i).first] = new Syntax (*(*i).second);\n lib->impl->doc_funs = impl->doc_funs;\n\n return lib;\n}\n\nLibrary::Library (const char* name) \n : impl (new Implementation (name))\n{ }\n\nLibrary::~Library ()\n{ }\n\n\/\/ library.C ends here\nVersion 4.16\/\/ library.C\n\/\/ \n\/\/ Copyright 1996-2001 Per Abrahamsen and Sren Hansen\n\/\/ Copyright 2000-2001 KVL.\n\/\/\n\/\/ This file is part of Daisy.\n\/\/ \n\/\/ Daisy is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser Public License as published by\n\/\/ the Free Software Foundation; either version 2.1 of the License, or\n\/\/ (at your option) any later version.\n\/\/ \n\/\/ Daisy is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU Lesser Public License\n\/\/ along with Daisy; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n#define BUILD_DLL\n\n#include \"library.h\"\n#include \"block.h\"\n#include \"alist.h\"\n#include \"syntax.h\"\n#include \"treelog.h\"\n#include \n#include \"assertion.h\"\n#include \"symbol.h\"\n#include \"memutils.h\"\n#include \n#include \n#include \n\nstruct Library::Implementation\n{\n \/\/ Id.\n const symbol name;\n const char * description;\n\n \/\/ Types.\n typedef std::map bmap_type;\n typedef std::map alist_map;\n typedef std::map syntax_map;\n\n \/\/ Data (remember to update Library::clone if you change this).\n bmap_type builders;\n alist_map alists;\n syntax_map syntaxen;\n std::vector doc_funs;\n\n \/\/ Accessors.\n AttributeList& lookup (symbol) const;\n bool check (symbol) const;\n void add_base (AttributeList&, const Syntax&);\n void add (symbol, AttributeList&, const Syntax&, builder);\n const Syntax& syntax (symbol) const;\n void entries (std::vector&) const;\n void remove (symbol);\n void clear_parsed ();\n void refile_parsed (const std::string& from, const std::string& to);\n static void load_syntax (Syntax&, AttributeList&);\n Implementation (const char* n);\n ~Implementation ();\n};\n\nAttributeList&\nLibrary::Implementation::lookup (const symbol key) const\n{ \n alist_map::const_iterator i = alists.find (key);\n\n if (i == alists.end ())\n daisy_panic (\"Model '\" + key.name ()\n + \"' not in library '\" + name.name () + \"'\");\n return *(*i).second;\n}\n\nbool\nLibrary::Implementation::check (const symbol key) const\n{ \n alist_map::const_iterator i = alists.find (key);\n\n if (i == alists.end ())\n return false;\n\n return true;\n}\n\nvoid\nLibrary::Implementation::add_base (AttributeList& value,\n\t\t\t const Syntax& syntax)\n{\n daisy_assert (value.check (\"base_model\"));\n const symbol key = value.identifier (\"base_model\");\n alists[key] = &value;\n syntaxen[key] = &syntax;\n}\n\nvoid\nLibrary::Implementation::add (const symbol key, AttributeList& value,\n\t\t\t const Syntax& syntax, builder build)\n{\n alists[key] = &value;\n syntaxen[key] = &syntax;\n \/\/ builders.insert (std::make_pair (key, build));\n builders[key] = build;\n}\n\nconst Syntax& \nLibrary::Implementation::syntax (const symbol key) const\n{ \n syntax_map::const_iterator i = syntaxen.find (key);\n\n if (i == syntaxen.end ())\n daisy_panic (\"'\" + key + \"' not found\");\n\n return *(*i).second;\n}\n\nvoid\nLibrary::Implementation::entries (std::vector& result) const\n{\n for (syntax_map::const_iterator i = syntaxen.begin ();\n i != syntaxen.end ();\n i++)\n {\n result.push_back ((*i).first);\n }\n}\n\nvoid\nLibrary::Implementation::remove (const symbol key)\n{\n alists.erase (alists.find (key));\n syntaxen.erase (syntaxen.find (key));\n}\n\nvoid\nLibrary::Implementation::clear_parsed ()\n{\n retry:\n for (alist_map::iterator i = alists.begin (); i != alists.end (); i++)\n {\n AttributeList& alist = *((*i).second);\n if (alist.check (\"parsed_from_file\"))\n\t{\n\t const symbol key = (*i).first;\n\t syntax_map::iterator j = syntaxen.find (key);\n\t daisy_assert (j != syntaxen.end ());\n\t syntaxen.erase (j);\n\t alists.erase (i);\n\t delete &alist;\n\t goto retry;\n\t}\n }\n}\n\nvoid\nLibrary::Implementation::refile_parsed (const std::string& from, const std::string& to)\n{\n daisy_assert (from != to);\n for (alist_map::iterator i = alists.begin (); i != alists.end (); i++)\n {\n AttributeList& alist = *((*i).second);\n if (alist.check (\"parsed_from_file\")\n\t && alist.name (\"parsed_from_file\") == from)\n\t{\n\t alist.add (\"parsed_from_file\", to);\n\t}\n }\n}\n\nLibrary::Implementation::Implementation (const char* n) \n : name (symbol (n)),\n description (NULL)\n{ }\n\nLibrary::Implementation::~Implementation ()\n{ \n \/\/ Delete alists.\n map_delete (alists.begin (), alists.end ());\n\n \/\/ Delete unique syntaxen.\n std::set unique;\n for (syntax_map::iterator i = syntaxen.begin ();\n i != syntaxen.end ();\n i++)\n {\n daisy_assert ((*i).second);\n unique.insert ((*i).second);\n (*i).second = NULL;\n }\n sequence_delete (unique.begin (), unique.end ());\n}\n\nvoid \nLibrary::clear_parsed ()\n{ impl->clear_parsed (); }\n\nvoid \nLibrary::refile_parsed (const std::string& from, const std::string& to)\n{ impl->refile_parsed (from, to); }\n\nsymbol\nLibrary::name () const\n{ return impl->name; }\n\nconst char*\nLibrary::description () const\n{ return impl->description; }\n\nAttributeList&\nLibrary::lookup (const symbol key) const\n{ return impl->lookup (key); }\n\nbool\nLibrary::check (const symbol key) const\n{ return impl->check (key); }\n\nbool\nLibrary::complete (const Metalib& metalib, const symbol key) const\n{ \n if (!check (key))\n return false;\n\n if (!syntax (key).check (metalib, lookup (key), Treelog::null ()))\n return false;\n\n return true;\n}\n\nvoid\nLibrary::add_base (AttributeList& value, const Syntax& syntax)\n{ impl->add_base (value, syntax); }\n\nvoid\nLibrary::add (const symbol key, AttributeList& value, const Syntax& syntax,\n builder build)\n{ impl->add (key, value, syntax, build); }\n\nvoid \nLibrary::add_derived (const symbol name, AttributeList& al,\n\t\t const symbol super)\n{ \n add_derived (name, syntax (super), al, super); \n}\n\nvoid\nLibrary::add_derived (const symbol name, const Syntax& syn, AttributeList& al,\n\t\t const symbol super)\n{ \n al.add (\"type\", super);\n add (name, al, syn, impl->builders[super]); \n}\n\nconst Syntax& \nLibrary::syntax (const symbol key) const\n{ return impl->syntax (key); }\n\nvoid\nLibrary::entries (std::vector& result) const\n{ impl->entries (result); }\n\nbool \nLibrary::is_derived_from (const symbol a, const symbol b) const\n{\n if (a == b)\n return true;\n\n const AttributeList& al = lookup (a);\n\n if (!al.check (\"type\") && !al.check (\"base_model\"))\n return false;\n\n const symbol type = al.check (\"type\") \n ? al.identifier (\"type\") \n : al.identifier (\"base_model\");\n\n if (type == b)\n return true;\n\n daisy_assert (check (type));\n\n if (type == a)\n return false;\n\n return is_derived_from (type, b);\n}\n \nconst symbol\nLibrary::base_model (const symbol parameterization) const\n{\n const AttributeList& al = lookup (parameterization);\n\n if (al.check (\"type\"))\n return base_model (al.identifier (\"type\"));\n if (al.check (\"base_model\")\n && al.identifier (\"base_model\") != parameterization)\n return base_model (al.identifier (\"base_model\"));\n\n return parameterization;\n}\n\nbool \nLibrary::has_interesting_description (const AttributeList& alist) const\n{\n \/\/ A missing description is boring.\n if (!alist.check (\"description\"))\n return false;\n \n \/\/ The description of models are always interesting.\n if (!alist.check (\"type\"))\n return true;\n \n \/\/ If the model has no description, this one is interesting.\n const symbol type = alist.identifier (\"type\");\n if (!check (type))\n {\n daisy_bug (name () + \" does not have \" + type.name ());\n return false;\n }\n daisy_assert (check (type));\n const AttributeList& super = lookup (type);\n if (!super.check (\"description\"))\n return true;\n \n \/\/ If the model description is different, this one is interesting.\n return alist.name (\"description\") != super.name (\"description\");\n}\n\nvoid\nLibrary::add_doc_fun (doc_fun fun) \n{ impl->doc_funs.push_back (fun); }\n\nstd::vector& \nLibrary::doc_funs () const\n{ return impl->doc_funs; }\n\nvoid\nLibrary::remove (const symbol key)\n{ impl->remove (key); }\n\nModel* \nLibrary::build_raw (const symbol type, Block& block) const\n{ \n const Implementation::bmap_type::const_iterator i \n = impl->builders.find (type);\n if (i == impl->builders.end ())\n {\n std::ostringstream tmp;\n tmp << \"No '\" << type.name () << \"' found in '\" << impl->name.name()\n << \"' library\";\n daisy_panic (tmp.str ());\n }\n return &(*i).second (block);\n}\n\nvoid \nLibrary::set_description (const char *const description)\n{\n daisy_assert (!impl->description);\n impl->description = description;\n}\n\nLibrary* \nLibrary::clone () const\n{ \n Library *const lib = new Library (impl->name.name ().c_str ());\n lib->set_description (impl->description);\n lib->impl->builders = impl->builders;\n for (Implementation::alist_map::const_iterator i = impl->alists.begin ();\n i != impl->alists.end ();\n i++)\n lib->impl->alists[(*i).first] = new AttributeList (*(*i).second);\n for (Implementation::syntax_map::const_iterator i = impl->syntaxen.begin ();\n i != impl->syntaxen.end ();\n i++)\n lib->impl->syntaxen[(*i).first] = new Syntax (*(*i).second);\n lib->impl->doc_funs = impl->doc_funs;\n\n return lib;\n}\n\nLibrary::Library (const char* name) \n : impl (new Implementation (name))\n{ }\n\nLibrary::~Library ()\n{ }\n\n\/\/ library.C ends here\n<|endoftext|>"} {"text":"\/* For copyright information please refer to files in the COPYRIGHT directory\n *\/\n#include \"debug.hpp\"\n#include \"locks.hpp\"\n#include \"filesystem.hpp\"\n#include \"utils.hpp\"\n#include \"irods_log.hpp\"\n#include \"initServer.hpp\"\n#include \"irods_server_properties.hpp\"\n\nint lockMutex( mutex_type **mutex ) {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"lockMutex: call to getMutexName failed\" );\n return -1;\n }\n\n try {\n *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() );\n }\n catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n try {\n ( *mutex )->lock();\n }\n catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"lock threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n return 0;\n}\n\nvoid unlockMutex( mutex_type **mutex ) {\n ( *mutex )->unlock();\n delete *mutex;\n}\n\n\/* This function can be used during initialization to remove a previously held mutex that has not been released.\n * This should only be used when there is no other process using the mutex *\/\nvoid resetMutex() {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"resetMutex: call to getMutexName failed\" );\n }\n\n boost::interprocess::named_mutex::remove( mutex_name.c_str() );\n}\n\nirods::error getMutexName( std::string &mutex_name ) {\n std::string mutex_name_salt;\n irods::error ret = irods::server_properties::getInstance().get_property( RE_CACHE_SALT_KW, mutex_name_salt );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"getMutexName: failed to retrieve re cache salt from server_properties\\n%s\", ret.result().c_str() );\n return PASS( ret );\n }\n\n getResourceName( mutex_name, mutex_name_salt.c_str() );\n mutex_name = \"re_cache_mutex_\" + mutex_name;\n\n return SUCCESS();\n}\n[#2212] CID26297:\/* For copyright information please refer to files in the COPYRIGHT directory\n *\/\n#include \"debug.hpp\"\n#include \"locks.hpp\"\n#include \"filesystem.hpp\"\n#include \"utils.hpp\"\n#include \"irods_log.hpp\"\n#include \"initServer.hpp\"\n#include \"irods_server_properties.hpp\"\n\nint lockMutex( mutex_type **mutex ) {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"lockMutex: call to getMutexName failed\" );\n return -1;\n }\n\n try {\n *mutex = new boost::interprocess::named_mutex( boost::interprocess::open_or_create, mutex_name.c_str() );\n }\n catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"boost::interprocess::named_mutex threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n try {\n ( *mutex )->lock();\n }\n catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"lock threw a boost::interprocess::interprocess_exception.\" );\n return -1;\n }\n return 0;\n}\n\nvoid unlockMutex( mutex_type **mutex ) {\n try {\n ( *mutex )->unlock();\n }\n catch ( const boost::interprocess::interprocess_exception& ) {\n rodsLog( LOG_ERROR, \"unlock threw a boost::interprocess::interprocess_exception.\" );\n }\n delete *mutex;\n}\n\n\/* This function can be used during initialization to remove a previously held mutex that has not been released.\n * This should only be used when there is no other process using the mutex *\/\nvoid resetMutex() {\n std::string mutex_name;\n irods::error ret = getMutexName( mutex_name );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"resetMutex: call to getMutexName failed\" );\n }\n\n boost::interprocess::named_mutex::remove( mutex_name.c_str() );\n}\n\nirods::error getMutexName( std::string &mutex_name ) {\n std::string mutex_name_salt;\n irods::error ret = irods::server_properties::getInstance().get_property( RE_CACHE_SALT_KW, mutex_name_salt );\n if ( !ret.ok() ) {\n rodsLog( LOG_ERROR, \"getMutexName: failed to retrieve re cache salt from server_properties\\n%s\", ret.result().c_str() );\n return PASS( ret );\n }\n\n getResourceName( mutex_name, mutex_name_salt.c_str() );\n mutex_name = \"re_cache_mutex_\" + mutex_name;\n\n return SUCCESS();\n}\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2017 Asylo authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"asylo\/platform\/core\/trusted_application.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/synchronization\/mutex.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"asylo\/identity\/init.h\"\n#include \"asylo\/platform\/arch\/include\/trusted\/host_calls.h\"\n#include \"asylo\/platform\/arch\/include\/trusted\/time.h\"\n#include \"asylo\/platform\/common\/bridge_types.h\"\n#include \"asylo\/platform\/core\/shared_name_kind.h\"\n#include \"asylo\/platform\/core\/trusted_global_state.h\"\n#include \"asylo\/platform\/posix\/io\/io_manager.h\"\n#include \"asylo\/platform\/posix\/io\/native_paths.h\"\n#include \"asylo\/platform\/posix\/io\/random_devices.h\"\n#include \"asylo\/platform\/posix\/signal\/signal_manager.h\"\n#include \"asylo\/platform\/posix\/threading\/thread_manager.h\"\n#include \"asylo\/util\/posix_error_space.h\"\n#include \"asylo\/util\/status.h\"\n\nusing EnclaveState = ::asylo::TrustedApplication::State;\nusing google::protobuf::RepeatedPtrField;\n\nnamespace asylo {\nnamespace {\n\nvoid LogError(const Status &status) {\n EnclaveState state = GetApplicationInstance()->GetState();\n if (state < EnclaveState::kUserInitializing) {\n \/\/ LOG() is unavailable here because the I\/O subsystem has not yet been\n \/\/ initialized.\n enc_untrusted_puts(status.ToString().c_str());\n } else {\n LOG(ERROR) << status;\n }\n}\n\n\/\/ StatusSerializer can be used to serialize a given proto2 message to an\n\/\/ untrusted buffer.\n\/\/\n\/\/ OutputProto must be a proto2 message type.\ntemplate \nclass StatusSerializer {\n public:\n \/\/ Creates a new StatusSerializer that saves Status objects to |status_proto|,\n \/\/ which is a nested message within |output_proto|. StatusSerializer does not\n \/\/ take ownership of any of the input pointers. Input pointers must remain\n \/\/ valid for the lifetime of the StatusSerializer.\n StatusSerializer(const OutputProto *output_proto, StatusProto *status_proto,\n char **output, size_t *output_len)\n : output_proto_{output_proto},\n status_proto_{status_proto},\n output_{output},\n output_len_{output_len} {}\n\n \/\/ Creates a new StatusSerializer that saves Status objects to |status_proto|.\n \/\/ StatusSerializer does not take ownership of any of the input pointers.\n \/\/ Input pointers must remain valid for the lifetime of the StatusSerializer.\n StatusSerializer(char **output, size_t *output_len)\n : output_proto_{&proto},\n status_proto_{&proto},\n output_{output},\n output_len_{output_len} {}\n\n \/\/ Saves the given |status| into the StatusSerializer's status_proto_. Then\n \/\/ serializes its output_proto_ into a buffer. On success 0 is returned, else\n \/\/ 1 is returned and the StatusSerializer logs the error.\n int Serialize(const Status &status) {\n status.SaveTo(status_proto_);\n\n \/\/ Serialize to a trusted buffer instead of an untrusted buffer because the\n \/\/ serialization routine may rely on read backs for correctness.\n *output_len_ = output_proto_->ByteSize();\n std::unique_ptr trusted_output(new char[*output_len_]);\n if (!output_proto_->SerializeToArray(trusted_output.get(), *output_len_)) {\n *output_ = nullptr;\n *output_len_ = 0;\n LogError(status);\n return 1;\n }\n *output_ = reinterpret_cast(enc_untrusted_malloc(*output_len_));\n memcpy(*output_, trusted_output.get(), *output_len_);\n return 0;\n }\n\n private:\n OutputProto proto;\n const OutputProto *output_proto_;\n StatusProto *status_proto_;\n char **output_;\n size_t *output_len_;\n};\n\n} \/\/ namespace\n\nStatus TrustedApplication::VerifyAndSetState(const EnclaveState &expected_state,\n const EnclaveState &new_state) {\n absl::MutexLock lock(&mutex_);\n if (enclave_state_ != expected_state) {\n return Status(error::GoogleError::FAILED_PRECONDITION,\n ::absl::StrCat(\"Enclave is in state: \", enclave_state_,\n \" expected state: \", expected_state));\n }\n enclave_state_ = new_state;\n return Status::OkStatus();\n}\n\nEnclaveState TrustedApplication::GetState() {\n absl::MutexLock lock(&mutex_);\n return enclave_state_;\n}\n\nvoid TrustedApplication::SetState(const EnclaveState &state) {\n absl::MutexLock lock(&mutex_);\n enclave_state_ = state;\n}\n\nStatus VerifyOutputArguments(char **output, size_t *output_len) {\n if (!output || !output_len) {\n Status status =\n Status(error::GoogleError::INVALID_ARGUMENT,\n \"Invalid input parameter passed to __asylo_user...()\");\n LogError(status);\n return status;\n }\n return Status::OkStatus();\n}\n\n\/\/ Application instance returned by BuildTrustedApplication.\nstatic TrustedApplication *global_trusted_application = nullptr;\n\n\/\/ A mutex that avoids race condition when getting |global_trusted_application|.\nstatic absl::Mutex get_application_lock;\n\n\/\/ Initialize IO subsystem.\nstatic void InitializeIO(const EnclaveConfig &config);\n\nTrustedApplication *GetApplicationInstance() {\n absl::MutexLock lock(&get_application_lock);\n if (!global_trusted_application) {\n global_trusted_application = BuildTrustedApplication();\n }\n return global_trusted_application;\n}\n\nStatus InitializeEnvironmentVariables(\n const RepeatedPtrField &variables) {\n for (const auto &variable : variables) {\n if (!variable.has_name() || !variable.has_value()) {\n return Status(error::GoogleError::INVALID_ARGUMENT,\n \"Environment variables should set both name and value \"\n \"fields\");\n }\n setenv(variable.name().c_str(), variable.value().c_str(), \/*overwrite=*\/0);\n }\n return Status::OkStatus();\n}\n\nStatus TrustedApplication::InitializeInternal(const EnclaveConfig &config) {\n InitializeIO(config);\n Status status =\n InitializeEnvironmentVariables(config.environment_variables());\n const char *log_directory = config.logging_config().log_directory().c_str();\n int vlog_level = config.logging_config().vlog_level();\n if(!InitLogging(log_directory, GetEnclaveName().c_str(), vlog_level)) {\n fprintf(stderr, \"Initialization of enclave logging failed\\n\");\n }\n if (!status.ok()) {\n LOG(WARNING) << \"Initialization of enclave environment variables failed: \"\n << status;\n }\n SetEnclaveConfig(config);\n \/\/ This call can fail, but it should not stop the enclave from running.\n status = InitializeEnclaveAssertionAuthorities(\n config.enclave_assertion_authority_configs().begin(),\n config.enclave_assertion_authority_configs().end());\n if (!status.ok()) {\n LOG(WARNING) << \"Initialization of enclave assertion authorities failed: \"\n << status;\n }\n\n status = VerifyAndSetState(EnclaveState::kInternalInitializing,\n EnclaveState::kUserInitializing);\n if (!status.ok()) {\n return status;\n }\n\n return Initialize(config);\n}\n\nvoid InitializeIO(const EnclaveConfig &config) {\n auto &io_manager = io::IOManager::GetInstance();\n\n \/\/ Register host file descriptors as stdin, stdout, and stderr. The order of\n \/\/ initialization is significant since we need to match the convention that\n \/\/ these refer to descriptors 0, 1, and 2 respectively.\n if (config.stdin_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stdin_fd());\n }\n if (config.stdout_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stdout_fd());\n }\n if (config.stderr_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stderr_fd());\n }\n\n \/\/ Register handler for \/ so paths without other handlers are forwarded on to\n \/\/ the host system. Paths are registered without the trailing slash, so an\n \/\/ empty string is used.\n io_manager.RegisterVirtualPathHandler(\n \"\", ::absl::make_unique());\n\n \/\/ Register handlers for \/dev\/random and \/dev\/urandom so they can be opened\n \/\/ and read like regular files without exiting the enclave.\n io_manager.RegisterVirtualPathHandler(\n RandomPathHandler::kRandomPath, ::absl::make_unique());\n io_manager.RegisterVirtualPathHandler(\n RandomPathHandler::kURandomPath,\n ::absl::make_unique());\n\n \/\/ Set the current working directory so that relative paths can be handled.\n io_manager.SetCurrentWorkingDirectory(config.current_working_directory());\n}\n\n\/\/ Asylo enclave entry points.\n\/\/\n\/\/ See asylo\/platform\/arch\/include\/trusted\/entry_points.h for detailed\n\/\/ documentation for each function.\nextern \"C\" {\n\nint __asylo_user_init(const char *name, const char *config, size_t config_len,\n char **output, size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n StatusSerializer status_serializer(output, output_len);\n\n EnclaveConfig enclave_config;\n if (!enclave_config.ParseFromArray(config, config_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveConfig\");\n return status_serializer.Serialize(status);\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n status = trusted_application->VerifyAndSetState(\n EnclaveState::kUninitialized, EnclaveState::kInternalInitializing);\n if (!status.ok()) {\n return status_serializer.Serialize(status);\n }\n\n SetEnclaveName(name);\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->InitializeInternal(enclave_config);\n if (!status.ok()) {\n trusted_application->SetState(EnclaveState::kUninitialized);\n return status_serializer.Serialize(status);\n }\n\n trusted_application->SetState(EnclaveState::kRunning);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_user_run(const char *input, size_t input_len, char **output,\n size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n EnclaveOutput enclave_output;\n StatusSerializer status_serializer(\n &enclave_output, enclave_output.mutable_status(), output, output_len);\n\n EnclaveInput enclave_input;\n if (!enclave_input.ParseFromArray(input, input_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveInput\");\n return status_serializer.Serialize(status);\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n if (trusted_application->GetState() != EnclaveState::kRunning) {\n status = Status(error::GoogleError::FAILED_PRECONDITION,\n \"Enclave not in state RUNNING\");\n return status_serializer.Serialize(status);\n }\n\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->Run(enclave_input, &enclave_output);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_user_fini(const char *input, size_t input_len, char **output,\n size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n StatusSerializer status_serializer(output, output_len);\n\n asylo::EnclaveFinal enclave_final;\n if (!enclave_final.ParseFromArray(input, input_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveFinal\");\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n status = trusted_application->VerifyAndSetState(EnclaveState::kRunning,\n EnclaveState::kFinalizing);\n if (!status.ok()) {\n return status_serializer.Serialize(status);\n }\n\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->Finalize(enclave_final);\n if (!status.ok()) {\n trusted_application->SetState(EnclaveState::kRunning);\n return status_serializer.Serialize(status);\n }\n\n trusted_application->SetState(EnclaveState::kFinalized);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_threading_donate() {\n TrustedApplication *trusted_application = GetApplicationInstance();\n EnclaveState current_state = trusted_application->GetState();\n if (current_state < EnclaveState::kUserInitializing ||\n current_state > EnclaveState::kFinalizing) {\n Status status = Status(error::GoogleError::FAILED_PRECONDITION,\n \"Enclave ThreadManager has not been initialized\");\n LOG(ERROR) << status;\n return EPERM;\n }\n\n ThreadManager *thread_manager = ThreadManager::GetInstance();\n return thread_manager->StartThread();\n}\n\nint __asylo_handle_signal(const char *input, size_t input_len) {\n asylo::EnclaveSignal signal;\n if (!signal.ParseFromArray(input, input_len)) {\n return -1;\n }\n TrustedApplication *trusted_application = GetApplicationInstance();\n EnclaveState current_state = trusted_application->GetState();\n if (current_state < EnclaveState::kRunning ||\n current_state > EnclaveState::kFinalizing) {\n enc_untrusted_puts(\"Enclave signal handling internals not available\");\n return EPERM;\n }\n int signum = FromBridgeSignal(signal.signum());\n if (signum < 0) {\n return -1;\n }\n siginfo_t info;\n info.si_signo = signum;\n info.si_code = signal.code();\n ucontext_t ucontext;\n for (int greg_index = 0;\n greg_index < NGREG && greg_index < signal.gregs_size(); ++greg_index) {\n ucontext.uc_mcontext.gregs[greg_index] =\n static_cast(signal.gregs(greg_index));\n }\n SignalManager *signal_manager = SignalManager::GetInstance();\n const sigset_t mask = signal_manager->GetSignalMask();\n\n \/\/ If the signal is blocked and still passed into the enclave. The signal\n \/\/ masks inside the enclave is out of sync with the untrusted signal mask.\n if (sigismember(&mask, signum)) {\n return EPERM;\n }\n if (!signal_manager->HandleSignal(signum, &info, &ucontext).ok()) {\n return -1;\n }\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n} \/\/ namespace asylo\nFix a bug in error propagation from Finalize\/*\n *\n * Copyright 2017 Asylo authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \"asylo\/platform\/core\/trusted_application.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"absl\/memory\/memory.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/synchronization\/mutex.h\"\n#include \"asylo\/util\/logging.h\"\n#include \"asylo\/identity\/init.h\"\n#include \"asylo\/platform\/arch\/include\/trusted\/host_calls.h\"\n#include \"asylo\/platform\/arch\/include\/trusted\/time.h\"\n#include \"asylo\/platform\/common\/bridge_types.h\"\n#include \"asylo\/platform\/core\/shared_name_kind.h\"\n#include \"asylo\/platform\/core\/trusted_global_state.h\"\n#include \"asylo\/platform\/posix\/io\/io_manager.h\"\n#include \"asylo\/platform\/posix\/io\/native_paths.h\"\n#include \"asylo\/platform\/posix\/io\/random_devices.h\"\n#include \"asylo\/platform\/posix\/signal\/signal_manager.h\"\n#include \"asylo\/platform\/posix\/threading\/thread_manager.h\"\n#include \"asylo\/util\/posix_error_space.h\"\n#include \"asylo\/util\/status.h\"\n\nusing EnclaveState = ::asylo::TrustedApplication::State;\nusing google::protobuf::RepeatedPtrField;\n\nnamespace asylo {\nnamespace {\n\nvoid LogError(const Status &status) {\n EnclaveState state = GetApplicationInstance()->GetState();\n if (state < EnclaveState::kUserInitializing) {\n \/\/ LOG() is unavailable here because the I\/O subsystem has not yet been\n \/\/ initialized.\n enc_untrusted_puts(status.ToString().c_str());\n } else {\n LOG(ERROR) << status;\n }\n}\n\n\/\/ StatusSerializer can be used to serialize a given proto2 message to an\n\/\/ untrusted buffer.\n\/\/\n\/\/ OutputProto must be a proto2 message type.\ntemplate \nclass StatusSerializer {\n public:\n \/\/ Creates a new StatusSerializer that saves Status objects to |status_proto|,\n \/\/ which is a nested message within |output_proto|. StatusSerializer does not\n \/\/ take ownership of any of the input pointers. Input pointers must remain\n \/\/ valid for the lifetime of the StatusSerializer.\n StatusSerializer(const OutputProto *output_proto, StatusProto *status_proto,\n char **output, size_t *output_len)\n : output_proto_{output_proto},\n status_proto_{status_proto},\n output_{output},\n output_len_{output_len} {}\n\n \/\/ Creates a new StatusSerializer that saves Status objects to |status_proto|.\n \/\/ StatusSerializer does not take ownership of any of the input pointers.\n \/\/ Input pointers must remain valid for the lifetime of the StatusSerializer.\n StatusSerializer(char **output, size_t *output_len)\n : output_proto_{&proto},\n status_proto_{&proto},\n output_{output},\n output_len_{output_len} {}\n\n \/\/ Saves the given |status| into the StatusSerializer's status_proto_. Then\n \/\/ serializes its output_proto_ into a buffer. On success 0 is returned, else\n \/\/ 1 is returned and the StatusSerializer logs the error.\n int Serialize(const Status &status) {\n status.SaveTo(status_proto_);\n\n \/\/ Serialize to a trusted buffer instead of an untrusted buffer because the\n \/\/ serialization routine may rely on read backs for correctness.\n *output_len_ = output_proto_->ByteSize();\n std::unique_ptr trusted_output(new char[*output_len_]);\n if (!output_proto_->SerializeToArray(trusted_output.get(), *output_len_)) {\n *output_ = nullptr;\n *output_len_ = 0;\n LogError(status);\n return 1;\n }\n *output_ = reinterpret_cast(enc_untrusted_malloc(*output_len_));\n memcpy(*output_, trusted_output.get(), *output_len_);\n return 0;\n }\n\n private:\n OutputProto proto;\n const OutputProto *output_proto_;\n StatusProto *status_proto_;\n char **output_;\n size_t *output_len_;\n};\n\n} \/\/ namespace\n\nStatus TrustedApplication::VerifyAndSetState(const EnclaveState &expected_state,\n const EnclaveState &new_state) {\n absl::MutexLock lock(&mutex_);\n if (enclave_state_ != expected_state) {\n return Status(error::GoogleError::FAILED_PRECONDITION,\n ::absl::StrCat(\"Enclave is in state: \", enclave_state_,\n \" expected state: \", expected_state));\n }\n enclave_state_ = new_state;\n return Status::OkStatus();\n}\n\nEnclaveState TrustedApplication::GetState() {\n absl::MutexLock lock(&mutex_);\n return enclave_state_;\n}\n\nvoid TrustedApplication::SetState(const EnclaveState &state) {\n absl::MutexLock lock(&mutex_);\n enclave_state_ = state;\n}\n\nStatus VerifyOutputArguments(char **output, size_t *output_len) {\n if (!output || !output_len) {\n Status status =\n Status(error::GoogleError::INVALID_ARGUMENT,\n \"Invalid input parameter passed to __asylo_user...()\");\n LogError(status);\n return status;\n }\n return Status::OkStatus();\n}\n\n\/\/ Application instance returned by BuildTrustedApplication.\nstatic TrustedApplication *global_trusted_application = nullptr;\n\n\/\/ A mutex that avoids race condition when getting |global_trusted_application|.\nstatic absl::Mutex get_application_lock;\n\n\/\/ Initialize IO subsystem.\nstatic void InitializeIO(const EnclaveConfig &config);\n\nTrustedApplication *GetApplicationInstance() {\n absl::MutexLock lock(&get_application_lock);\n if (!global_trusted_application) {\n global_trusted_application = BuildTrustedApplication();\n }\n return global_trusted_application;\n}\n\nStatus InitializeEnvironmentVariables(\n const RepeatedPtrField &variables) {\n for (const auto &variable : variables) {\n if (!variable.has_name() || !variable.has_value()) {\n return Status(error::GoogleError::INVALID_ARGUMENT,\n \"Environment variables should set both name and value \"\n \"fields\");\n }\n setenv(variable.name().c_str(), variable.value().c_str(), \/*overwrite=*\/0);\n }\n return Status::OkStatus();\n}\n\nStatus TrustedApplication::InitializeInternal(const EnclaveConfig &config) {\n InitializeIO(config);\n Status status =\n InitializeEnvironmentVariables(config.environment_variables());\n const char *log_directory = config.logging_config().log_directory().c_str();\n int vlog_level = config.logging_config().vlog_level();\n if(!InitLogging(log_directory, GetEnclaveName().c_str(), vlog_level)) {\n fprintf(stderr, \"Initialization of enclave logging failed\\n\");\n }\n if (!status.ok()) {\n LOG(WARNING) << \"Initialization of enclave environment variables failed: \"\n << status;\n }\n SetEnclaveConfig(config);\n \/\/ This call can fail, but it should not stop the enclave from running.\n status = InitializeEnclaveAssertionAuthorities(\n config.enclave_assertion_authority_configs().begin(),\n config.enclave_assertion_authority_configs().end());\n if (!status.ok()) {\n LOG(WARNING) << \"Initialization of enclave assertion authorities failed: \"\n << status;\n }\n\n status = VerifyAndSetState(EnclaveState::kInternalInitializing,\n EnclaveState::kUserInitializing);\n if (!status.ok()) {\n return status;\n }\n\n return Initialize(config);\n}\n\nvoid InitializeIO(const EnclaveConfig &config) {\n auto &io_manager = io::IOManager::GetInstance();\n\n \/\/ Register host file descriptors as stdin, stdout, and stderr. The order of\n \/\/ initialization is significant since we need to match the convention that\n \/\/ these refer to descriptors 0, 1, and 2 respectively.\n if (config.stdin_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stdin_fd());\n }\n if (config.stdout_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stdout_fd());\n }\n if (config.stderr_fd() >= 0) {\n io_manager.RegisterHostFileDescriptor(config.stderr_fd());\n }\n\n \/\/ Register handler for \/ so paths without other handlers are forwarded on to\n \/\/ the host system. Paths are registered without the trailing slash, so an\n \/\/ empty string is used.\n io_manager.RegisterVirtualPathHandler(\n \"\", ::absl::make_unique());\n\n \/\/ Register handlers for \/dev\/random and \/dev\/urandom so they can be opened\n \/\/ and read like regular files without exiting the enclave.\n io_manager.RegisterVirtualPathHandler(\n RandomPathHandler::kRandomPath, ::absl::make_unique());\n io_manager.RegisterVirtualPathHandler(\n RandomPathHandler::kURandomPath,\n ::absl::make_unique());\n\n \/\/ Set the current working directory so that relative paths can be handled.\n io_manager.SetCurrentWorkingDirectory(config.current_working_directory());\n}\n\n\/\/ Asylo enclave entry points.\n\/\/\n\/\/ See asylo\/platform\/arch\/include\/trusted\/entry_points.h for detailed\n\/\/ documentation for each function.\nextern \"C\" {\n\nint __asylo_user_init(const char *name, const char *config, size_t config_len,\n char **output, size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n StatusSerializer status_serializer(output, output_len);\n\n EnclaveConfig enclave_config;\n if (!enclave_config.ParseFromArray(config, config_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveConfig\");\n return status_serializer.Serialize(status);\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n status = trusted_application->VerifyAndSetState(\n EnclaveState::kUninitialized, EnclaveState::kInternalInitializing);\n if (!status.ok()) {\n return status_serializer.Serialize(status);\n }\n\n SetEnclaveName(name);\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->InitializeInternal(enclave_config);\n if (!status.ok()) {\n trusted_application->SetState(EnclaveState::kUninitialized);\n return status_serializer.Serialize(status);\n }\n\n trusted_application->SetState(EnclaveState::kRunning);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_user_run(const char *input, size_t input_len, char **output,\n size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n EnclaveOutput enclave_output;\n StatusSerializer status_serializer(\n &enclave_output, enclave_output.mutable_status(), output, output_len);\n\n EnclaveInput enclave_input;\n if (!enclave_input.ParseFromArray(input, input_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveInput\");\n return status_serializer.Serialize(status);\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n if (trusted_application->GetState() != EnclaveState::kRunning) {\n status = Status(error::GoogleError::FAILED_PRECONDITION,\n \"Enclave not in state RUNNING\");\n return status_serializer.Serialize(status);\n }\n\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->Run(enclave_input, &enclave_output);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_user_fini(const char *input, size_t input_len, char **output,\n size_t *output_len) {\n Status status = VerifyOutputArguments(output, output_len);\n if (!status.ok()) {\n return 1;\n }\n\n StatusSerializer status_serializer(output, output_len);\n\n asylo::EnclaveFinal enclave_final;\n if (!enclave_final.ParseFromArray(input, input_len)) {\n status = Status(error::GoogleError::INVALID_ARGUMENT,\n \"Failed to parse EnclaveFinal\");\n return status_serializer.Serialize(status);\n }\n\n TrustedApplication *trusted_application = GetApplicationInstance();\n status = trusted_application->VerifyAndSetState(EnclaveState::kRunning,\n EnclaveState::kFinalizing);\n if (!status.ok()) {\n return status_serializer.Serialize(status);\n }\n\n \/\/ Invoke the enclave entry-point.\n status = trusted_application->Finalize(enclave_final);\n if (!status.ok()) {\n trusted_application->SetState(EnclaveState::kRunning);\n return status_serializer.Serialize(status);\n }\n\n trusted_application->SetState(EnclaveState::kFinalized);\n return status_serializer.Serialize(status);\n}\n\nint __asylo_threading_donate() {\n TrustedApplication *trusted_application = GetApplicationInstance();\n EnclaveState current_state = trusted_application->GetState();\n if (current_state < EnclaveState::kUserInitializing ||\n current_state > EnclaveState::kFinalizing) {\n Status status = Status(error::GoogleError::FAILED_PRECONDITION,\n \"Enclave ThreadManager has not been initialized\");\n LOG(ERROR) << status;\n return EPERM;\n }\n\n ThreadManager *thread_manager = ThreadManager::GetInstance();\n return thread_manager->StartThread();\n}\n\nint __asylo_handle_signal(const char *input, size_t input_len) {\n asylo::EnclaveSignal signal;\n if (!signal.ParseFromArray(input, input_len)) {\n return -1;\n }\n TrustedApplication *trusted_application = GetApplicationInstance();\n EnclaveState current_state = trusted_application->GetState();\n if (current_state < EnclaveState::kRunning ||\n current_state > EnclaveState::kFinalizing) {\n enc_untrusted_puts(\"Enclave signal handling internals not available\");\n return EPERM;\n }\n int signum = FromBridgeSignal(signal.signum());\n if (signum < 0) {\n return -1;\n }\n siginfo_t info;\n info.si_signo = signum;\n info.si_code = signal.code();\n ucontext_t ucontext;\n for (int greg_index = 0;\n greg_index < NGREG && greg_index < signal.gregs_size(); ++greg_index) {\n ucontext.uc_mcontext.gregs[greg_index] =\n static_cast(signal.gregs(greg_index));\n }\n SignalManager *signal_manager = SignalManager::GetInstance();\n const sigset_t mask = signal_manager->GetSignalMask();\n\n \/\/ If the signal is blocked and still passed into the enclave. The signal\n \/\/ masks inside the enclave is out of sync with the untrusted signal mask.\n if (sigismember(&mask, signum)) {\n return EPERM;\n }\n if (!signal_manager->HandleSignal(signum, &info, &ucontext).ok()) {\n return -1;\n }\n return 0;\n}\n\n} \/\/ extern \"C\"\n\n} \/\/ namespace asylo\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"messages.h\"\n#include \"util.h\"\n\n\nextern secp256k1_context* secp256k1ctx;\n\nNAN_METHOD(secretKeyVerify) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n const unsigned char* seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer);\n\n if (node::Buffer::Length(seckey_buffer) != 32) {\n return info.GetReturnValue().Set(Nan::New(false));\n }\n\n int result = secp256k1_ec_seckey_verify(secp256k1ctx, seckey);\n\n info.GetReturnValue().Set(Nan::New(result));\n}\n\nNAN_METHOD(secretKeyExport) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n const unsigned char* seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer);\n\n int compressed = 1;\n v8::Local compressed_value = info[1];\n if (!compressed_value->IsUndefined()) {\n CHECK_TYPE_BOOLEAN(compressed_value, COMPRESSED_TYPE_INVALID);\n if (!compressed_value->BooleanValue()) {\n compressed = 0;\n }\n }\n\n unsigned char privkey[279];\n size_t privkeylen;\n if (ec_privkey_export_der(secp256k1ctx, &privkey[0], &privkeylen, seckey, compressed) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_EXPORT_DER_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(privkey, privkeylen));\n}\n\nNAN_METHOD(secretKeyImport) {\n Nan::HandleScope scope;\n\n v8::Local privkey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(privkey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH_GT_ZERO(privkey_buffer, EC_PRIVKEY_LENGTH_INVALID);\n const unsigned char* privkey = (const unsigned char*) node::Buffer::Data(privkey_buffer);\n size_t privkeylen = node::Buffer::Length(privkey_buffer);\n\n unsigned char seckey[32];\n if (ec_privkey_import_der(secp256k1ctx, &seckey[0], privkey, privkeylen) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_IMPORT_DER_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(seckey, 32));\n}\n\nNAN_METHOD(secretKeyTweakAdd) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n unsigned char* seckey = (unsigned char *) node::Buffer::Data(seckey_buffer);\n\n v8::Local tweak_buffer = info[1].As();\n CHECK_TYPE_BUFFER(tweak_buffer, TWEAK_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(tweak_buffer, 32, TWEAK_LENGTH_INVALID);\n const unsigned char* tweak = (unsigned char *) node::Buffer::Data(tweak_buffer);\n\n if (secp256k1_ec_privkey_tweak_add(secp256k1ctx, seckey, tweak) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_TWEAK_ADD_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(seckey, 32));\n}\n\nNAN_METHOD(secretKeyTweakMul) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n unsigned char* seckey = (unsigned char *) node::Buffer::Data(seckey_buffer);\n\n v8::Local tweak_buffer = info[1].As();\n CHECK_TYPE_BUFFER(tweak_buffer, TWEAK_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(tweak_buffer, 32, TWEAK_LENGTH_INVALID);\n const unsigned char* tweak = (unsigned char *) node::Buffer::Data(tweak_buffer);\n\n if (secp256k1_ec_privkey_tweak_mul(secp256k1ctx, seckey, tweak) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_TWEAK_MUL_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(seckey, 32));\n}\nFix bug with rewriting secret key#include \n#include \n#include \n#include \n\n#include \"messages.h\"\n#include \"util.h\"\n\n\nextern secp256k1_context* secp256k1ctx;\n\nNAN_METHOD(secretKeyVerify) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n const unsigned char* seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer);\n\n if (node::Buffer::Length(seckey_buffer) != 32) {\n return info.GetReturnValue().Set(Nan::New(false));\n }\n\n int result = secp256k1_ec_seckey_verify(secp256k1ctx, seckey);\n\n info.GetReturnValue().Set(Nan::New(result));\n}\n\nNAN_METHOD(secretKeyExport) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n const unsigned char* seckey = (const unsigned char*) node::Buffer::Data(seckey_buffer);\n\n int compressed = 1;\n v8::Local compressed_value = info[1];\n if (!compressed_value->IsUndefined()) {\n CHECK_TYPE_BOOLEAN(compressed_value, COMPRESSED_TYPE_INVALID);\n if (!compressed_value->BooleanValue()) {\n compressed = 0;\n }\n }\n\n unsigned char privkey[279];\n size_t privkeylen;\n if (ec_privkey_export_der(secp256k1ctx, &privkey[0], &privkeylen, seckey, compressed) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_EXPORT_DER_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(privkey, privkeylen));\n}\n\nNAN_METHOD(secretKeyImport) {\n Nan::HandleScope scope;\n\n v8::Local privkey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(privkey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH_GT_ZERO(privkey_buffer, EC_PRIVKEY_LENGTH_INVALID);\n const unsigned char* privkey = (const unsigned char*) node::Buffer::Data(privkey_buffer);\n size_t privkeylen = node::Buffer::Length(privkey_buffer);\n\n unsigned char seckey[32];\n if (ec_privkey_import_der(secp256k1ctx, &seckey[0], privkey, privkeylen) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_IMPORT_DER_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(seckey, 32));\n}\n\nNAN_METHOD(secretKeyTweakAdd) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n unsigned char seckey[32];\n memcpy(&seckey[0], node::Buffer::Data(seckey_buffer), 32);\n\n v8::Local tweak_buffer = info[1].As();\n CHECK_TYPE_BUFFER(tweak_buffer, TWEAK_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(tweak_buffer, 32, TWEAK_LENGTH_INVALID);\n const unsigned char* tweak = (unsigned char *) node::Buffer::Data(tweak_buffer);\n\n if (secp256k1_ec_privkey_tweak_add(secp256k1ctx, &seckey[0], tweak) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_TWEAK_ADD_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(&seckey[0], 32));\n}\n\nNAN_METHOD(secretKeyTweakMul) {\n Nan::HandleScope scope;\n\n v8::Local seckey_buffer = info[0].As();\n CHECK_TYPE_BUFFER(seckey_buffer, EC_PRIVKEY_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(seckey_buffer, 32, EC_PRIVKEY_LENGTH_INVALID);\n unsigned char seckey[32];\n memcpy(&seckey[0], node::Buffer::Data(seckey_buffer), 32);\n\n v8::Local tweak_buffer = info[1].As();\n CHECK_TYPE_BUFFER(tweak_buffer, TWEAK_TYPE_INVALID);\n CHECK_BUFFER_LENGTH(tweak_buffer, 32, TWEAK_LENGTH_INVALID);\n const unsigned char* tweak = (unsigned char *) node::Buffer::Data(tweak_buffer);\n\n if (secp256k1_ec_privkey_tweak_mul(secp256k1ctx, &seckey[0], tweak) == 0) {\n return Nan::ThrowError(EC_PRIVKEY_TWEAK_MUL_FAIL);\n }\n\n info.GetReturnValue().Set(COPY_BUFFER(&seckey[0], 32));\n}\n<|endoftext|>"} {"text":"\/*\n * This is an example client for relation-finder-client, demonstrating its\n * protocol using Boost.Asio for network communication.\n *\n * The protocol is pretty simple, the only data send is a couple of\n * 32 bit unsigned integers. It basically works like this:\n * 1. Connect to relation-finder via TCP.\n * 2. Send the user ID of the first person (user A).\n * 3. Send the user ID of the second person (user B).\n * 4. Read the length of path.\n * If that number is 0, no path could be found.\n * 5. Read as many user IDs as the path was long.\n * This is the result, the path from user A to user B.\n *\/\n\n#include \n#include \n#include \n#include \n\nusing asio::ip::tcp;\n\nuint32_t read_uint(tcp::socket& socket)\n{\n asio::error_code error;\n uint32_t uint;\n socket.read_some(asio::buffer((void*) &uint, sizeof(uint)), error);\n if (error)\n throw asio::system_error(error);\n return uint;\n}\n\nvoid write_uint(tcp::socket& socket, uint32_t uint)\n{\n asio::error_code error;\n socket.write_some(asio::buffer((void*) &uint, sizeof(uint)), error);\n if (error)\n throw asio::system_error(error);\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ Read address and request parameters from the commandline\n if (argc < 5) {\n std::cerr << \"relation-finder-client - asks relation-finder for a \"\n << \"connection between two people\" << std::endl\n << \"Usage: relation-finder-client HOST PORT PERSON1 PERSON2\"\n << std::endl;\n return 1;\n }\n\n std::string host = argv[1];\n std::string port = argv[2];\n unsigned int pid1 = atoi(argv[3]);\n unsigned int pid2 = atoi(argv[4]);\n\n try {\n \/\/ Resolve the host\n asio::io_service io_service;\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(host, port);\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n tcp::resolver::iterator end;\n\n \/\/ Connect to the server\n tcp::socket socket(io_service);\n asio::error_code error = asio::error::host_not_found;\n while (error && endpoint_iterator != end) {\n socket.close();\n socket.connect(*endpoint_iterator++, error);\n }\n if (error)\n throw asio::system_error(error);\n\n \/\/ Write the person's id\n write_uint(socket, pid1);\n\n \/\/ Write the other person's id\n write_uint(socket, pid2);\n\n \/\/ Read the length of the path\n int path_length = read_uint(socket);\n if (path_length == 0) {\n std::cout << \"No path was found.\" << std::endl;\n } else {\n std::cout << \"Found a path: \";\n\n \/\/ Read the path\n for (int i = 0; i < path_length; i++) {\n unsigned int node = read_uint(socket);\n std::cout << node;\n if (i != path_length - 1)\n std::cout << \" -> \";\n }\n std::cout << std::endl;\n }\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\nImproved comment.\/*\n * This is an example client for relation-finder, demonstrating its protocol\n * using Boost.Asio for network communication.\n *\n * The protocol is pretty simple, the only data send is a couple of unsigned\n * 32-bit integers. It basically works like this:\n * 1. Connect to relation-finder via TCP.\n * 2. Send the user ID of the first person (user A).\n * 3. Send the user ID of the second person (user B).\n * 4. Read the length of path. If that number is 0, no path could be found.\n * 5. Read as many user IDs as the path was long.\n * This is the result, the path from user A to user B.\n *\/\n\n#include \n#include \n#include \n#include \n\nusing asio::ip::tcp;\n\nuint32_t read_uint(tcp::socket& socket)\n{\n asio::error_code error;\n uint32_t uint;\n socket.read_some(asio::buffer((void*) &uint, sizeof(uint)), error);\n if (error)\n throw asio::system_error(error);\n return uint;\n}\n\nvoid write_uint(tcp::socket& socket, uint32_t uint)\n{\n asio::error_code error;\n socket.write_some(asio::buffer((void*) &uint, sizeof(uint)), error);\n if (error)\n throw asio::system_error(error);\n}\n\nint main(int argc, char* argv[])\n{\n \/\/ Read address and request parameters from the commandline\n if (argc < 5) {\n std::cerr << \"relation-finder-client - asks relation-finder for a \"\n << \"connection between two people\" << std::endl\n << \"Usage: relation-finder-client HOST PORT PERSON1 PERSON2\"\n << std::endl;\n return 1;\n }\n\n std::string host = argv[1];\n std::string port = argv[2];\n unsigned int pid1 = atoi(argv[3]);\n unsigned int pid2 = atoi(argv[4]);\n\n try {\n \/\/ Resolve the host\n asio::io_service io_service;\n tcp::resolver resolver(io_service);\n tcp::resolver::query query(host, port);\n tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n tcp::resolver::iterator end;\n\n \/\/ Connect to the server\n tcp::socket socket(io_service);\n asio::error_code error = asio::error::host_not_found;\n while (error && endpoint_iterator != end) {\n socket.close();\n socket.connect(*endpoint_iterator++, error);\n }\n if (error)\n throw asio::system_error(error);\n\n \/\/ Write the person's id\n write_uint(socket, pid1);\n\n \/\/ Write the other person's id\n write_uint(socket, pid2);\n\n \/\/ Read the length of the path\n int path_length = read_uint(socket);\n if (path_length == 0) {\n std::cout << \"No path was found.\" << std::endl;\n } else {\n std::cout << \"Found a path: \";\n\n \/\/ Read the path\n for (int i = 0; i < path_length; i++) {\n unsigned int node = read_uint(socket);\n std::cout << node;\n if (i != path_length - 1)\n std::cout << \" -> \";\n }\n std::cout << std::endl;\n }\n } catch (std::exception& e) {\n std::cerr << e.what() << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"pch.h\"\n#include \"json_rpc_debug_logger.h\"\n\n#include \n\nnamespace jcon {\n\nvoid JsonRpcDebugLogger::logInfo(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\nvoid JsonRpcDebugLogger::logWarning(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\nvoid JsonRpcDebugLogger::logError(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\n}\nRemove inclusion of non-existing precompiled header#include \"json_rpc_debug_logger.h\"\n\n#include \n\nnamespace jcon {\n\nvoid JsonRpcDebugLogger::logInfo(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\nvoid JsonRpcDebugLogger::logWarning(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\nvoid JsonRpcDebugLogger::logError(const QString& message)\n{\n qDebug().noquote() << message;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef COMPILER_EXCEPTION_H\n#define COMPILER_EXCEPTION_H\n\n#include \n\n#include \"Token.hpp\"\n\nnamespace eddic {\n\nclass CompilerException: public std::exception {\n protected:\n std::string m_message;\n Token* m_token;\n\n public:\n CompilerException(const std::string& message) : m_message(message) {};\n CompilerException(const std::string& message, Token* token) : m_message(message), m_token(token) {};\n ~CompilerException() throw() {};\n\n virtual const char* what() const throw();\n};\n\nclass TokenException: public CompilerException {\n private:\n Token* m_token;\n\n public:\n TokenException(const std::string& message, Token* token) : CompilerException(message), m_token(token) {}\n ~TokenException() throw() {};\n\n const char* what() const throw();\n};\n\n} \/\/end of eddic\n\n#endif\nPut the Token* as const\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#ifndef COMPILER_EXCEPTION_H\n#define COMPILER_EXCEPTION_H\n\n#include \n\n#include \"Token.hpp\"\n\nnamespace eddic {\n\nclass CompilerException: public std::exception {\n protected:\n std::string m_message;\n const Token* m_token;\n\n public:\n CompilerException(const std::string& message) : m_message(message) {};\n CompilerException(const std::string& message, const Token* token) : m_message(message), m_token(token) {};\n ~CompilerException() throw() {};\n\n virtual const char* what() const throw();\n};\n\nclass TokenException: public CompilerException {\n private:\n Token* m_token;\n\n public:\n TokenException(const std::string& message, Token* token) : CompilerException(message), m_token(token) {}\n ~TokenException() throw() {};\n\n const char* what() const throw();\n};\n\n} \/\/end of eddic\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016, Egor Pugin\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of\n * its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"access_table.h\"\n#include \"config.h\"\n#include \"database.h\"\n#include \"directories.h\"\n#include \"hash.h\"\n#include \"hasher.h\"\n#include \"log.h\"\n#include \"templates.h\"\n#include \"stamp.h\"\n\n#include \n\n#include \"logger.h\"\nDECLARE_STATIC_LOGGER(logger, \"settings\");\n\nconst Remotes default_remotes{\n {\n DEFAULT_REMOTE_NAME,\n \"https:\/\/cppan.org\/\",\n \"data\"\n },\n};\n\nSettings::Settings()\n{\n build_dir = temp_directory_path() \/ \"build\";\n storage_dir = get_root_directory() \/ STORAGE_DIR;\n}\n\nvoid Settings::load(const path &p, const ConfigType type)\n{\n auto root = YAML::LoadFile(p.string());\n load(root, type);\n}\n\nvoid Settings::load(const yaml &root, const ConfigType type)\n{\n load_main(root, type);\n\n auto get_storage_dir = [this](ConfigType type)\n {\n switch (type)\n {\n case ConfigType::Local:\n return cppan_dir \/ STORAGE_DIR;\n case ConfigType::User:\n return Config::get_user_config().settings.storage_dir;\n case ConfigType::System:\n return Config::get_system_config().settings.storage_dir;\n default:\n return storage_dir;\n }\n };\n\n auto get_build_dir = [this](const path &p, ConfigType type)\n {\n switch (type)\n {\n case ConfigType::Local:\n return fs::current_path();\n case ConfigType::User:\n return directories.storage_dir_tmp;\n case ConfigType::System:\n return temp_directory_path() \/ \"build\";\n default:\n return p;\n }\n };\n\n Directories dirs;\n dirs.storage_dir_type = storage_dir_type;\n dirs.set_storage_dir(get_storage_dir(storage_dir_type));\n dirs.build_dir_type = build_dir_type;\n dirs.set_build_dir(get_build_dir(build_dir, build_dir_type));\n directories.update(dirs, type);\n}\n\nvoid Settings::load_main(const yaml &root, const ConfigType type)\n{\n auto packages_dir_type_from_string = [](const String &s, const String &key)\n {\n if (s == \"local\")\n return ConfigType::Local;\n if (s == \"user\")\n return ConfigType::User;\n if (s == \"system\")\n return ConfigType::System;\n throw std::runtime_error(\"Unknown '\" + key + \"'. Should be one of [local, user, system]\");\n };\n\n get_map_and_iterate(root, \"remotes\", [this](auto &kv)\n {\n auto n = kv.first.template as();\n bool o = n == DEFAULT_REMOTE_NAME; \/\/ origin\n Remote rm;\n Remote *prm = o ? &remotes[0] : &rm;\n prm->name = n;\n EXTRACT_VAR(kv.second, prm->url, \"url\", String);\n EXTRACT_VAR(kv.second, prm->data_dir, \"data_dir\", String);\n EXTRACT_VAR(kv.second, prm->user, \"user\", String);\n EXTRACT_VAR(kv.second, prm->token, \"token\", String);\n if (!o)\n remotes.push_back(*prm);\n });\n\n EXTRACT_AUTO(disable_update_checks);\n EXTRACT(storage_dir, String);\n EXTRACT(build_dir, String);\n EXTRACT(cppan_dir, String);\n\n auto &p = root[\"proxy\"];\n if (p.IsDefined())\n {\n if (!p.IsMap())\n throw std::runtime_error(\"'proxy' should be a map\");\n EXTRACT_VAR(p, proxy.host, \"host\", String);\n EXTRACT_VAR(p, proxy.user, \"user\", String);\n }\n\n storage_dir_type = packages_dir_type_from_string(get_scalar(root, \"storage_dir_type\", \"user\"), \"storage_dir_type\");\n if (root[\"storage_dir\"].IsDefined())\n storage_dir_type = ConfigType::None;\n build_dir_type = packages_dir_type_from_string(get_scalar(root, \"build_dir_type\", \"system\"), \"build_dir_type\");\n if (root[\"build_dir\"].IsDefined())\n build_dir_type = ConfigType::None;\n\n \/\/ read these first from local settings\n \/\/ and they'll be overriden in bs (if they exist there)\n EXTRACT_AUTO(use_cache);\n EXTRACT_AUTO(show_ide_projects);\n EXTRACT_AUTO(add_run_cppan_target);\n EXTRACT_AUTO(cmake_verbose);\n\n \/\/ read build settings\n if (type == ConfigType::Local)\n {\n \/\/ at first, we load bs from current root\n load_build(root);\n\n \/\/ then override settings with specific (or default) config\n yaml current_build;\n if (root[\"builds\"].IsDefined())\n {\n \/\/ yaml will not keep sorting of keys in map\n \/\/ so we can take 'first' build in document\n if (root[\"current_build\"].IsDefined())\n current_build = root[\"builds\"][root[\"current_build\"].template as()];\n }\n else if (root[\"build\"].IsDefined())\n current_build = root[\"build\"];\n\n load_build(current_build);\n }\n}\n\nvoid Settings::load_build(const yaml &root)\n{\n if (root.IsNull())\n return;\n\n \/\/ extract\n EXTRACT_AUTO(c_compiler);\n EXTRACT_AUTO(cxx_compiler);\n EXTRACT_AUTO(compiler);\n EXTRACT_AUTO(c_compiler_flags);\n if (c_compiler_flags.empty())\n EXTRACT_VAR(root, c_compiler_flags, \"c_flags\", String);\n EXTRACT_AUTO(cxx_compiler_flags);\n if (cxx_compiler_flags.empty())\n EXTRACT_VAR(root, cxx_compiler_flags, \"cxx_flags\", String);\n EXTRACT_AUTO(compiler_flags);\n EXTRACT_AUTO(link_flags);\n EXTRACT_AUTO(link_libraries);\n EXTRACT_AUTO(configuration);\n EXTRACT_AUTO(generator);\n EXTRACT_AUTO(toolset);\n EXTRACT_AUTO(use_shared_libs);\n EXTRACT_AUTO(silent);\n EXTRACT_AUTO(use_cache);\n EXTRACT_AUTO(show_ide_projects);\n EXTRACT_AUTO(add_run_cppan_target);\n EXTRACT_AUTO(cmake_verbose);\n\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n {\n auto t = configuration_types[i];\n boost::to_lower(t);\n EXTRACT_VAR(root, c_compiler_flags_conf[i], \"c_compiler_flags_\" + t, String);\n EXTRACT_VAR(root, cxx_compiler_flags_conf[i], \"cxx_compiler_flags_\" + t, String);\n EXTRACT_VAR(root, compiler_flags_conf[i], \"compiler_flags_\" + t, String);\n EXTRACT_VAR(root, link_flags_conf[i], \"link_flags_\" + t, String);\n }\n\n cmake_options = get_sequence(root[\"cmake_options\"]);\n get_string_map(root, \"env\", env);\n\n \/\/ process\n if (c_compiler.empty())\n c_compiler = cxx_compiler;\n if (c_compiler.empty())\n c_compiler = compiler;\n if (cxx_compiler.empty())\n cxx_compiler = compiler;\n\n c_compiler_flags += \" \" + compiler_flags;\n cxx_compiler_flags += \" \" + compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n {\n c_compiler_flags_conf[i] += \" \" + compiler_flags_conf[i];\n cxx_compiler_flags_conf[i] += \" \" + compiler_flags_conf[i];\n }\n}\n\nbool Settings::is_custom_build_dir() const\n{\n return build_dir_type == ConfigType::Local || build_dir_type == ConfigType::None;\n}\n\nvoid Settings::set_build_dirs(const String &name)\n{\n filename = name;\n filename_without_ext = name;\n\n source_directory = directories.build_dir;\n if (directories.build_dir_type == ConfigType::Local ||\n directories.build_dir_type == ConfigType::None)\n {\n source_directory \/= (CPPAN_LOCAL_BUILD_PREFIX + filename);\n }\n else\n {\n source_directory_hash = sha256_short(name);\n source_directory \/= source_directory_hash;\n }\n binary_directory = source_directory \/ \"build\";\n}\n\nvoid Settings::append_build_dirs(const path &p)\n{\n source_directory \/= p;\n binary_directory = source_directory \/ \"build\";\n}\n\nString Settings::get_hash() const\n{\n Hasher h;\n h |= c_compiler;\n h |= cxx_compiler;\n h |= compiler;\n h |= c_compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= c_compiler_flags_conf[i];\n h |= cxx_compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= cxx_compiler_flags_conf[i];\n h |= compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= compiler_flags_conf[i];\n h |= link_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= link_flags_conf[i];\n h |= link_libraries;\n h |= generator;\n h |= toolset;\n h |= use_shared_libs;\n return h.hash;\n}\n\nString Settings::get_fs_generator() const\n{\n String g = generator;\n boost::to_lower(g);\n boost::replace_all(g, \" \", \"-\");\n return g;\n}\n\nString get_config(const Settings &settings)\n{\n \/\/ add original config to db\n \/\/ but return hashed\n\n auto &db = getServiceDatabase();\n auto h = settings.get_hash();\n auto c = db.getConfigByHash(h);\n\n if (!c.empty())\n return hash_config(c);\n\n c = test_run(settings);\n auto ch = hash_config(c);\n db.addConfigHash(h, c, ch);\n\n return ch;\n}\n\nString test_run(const Settings &settings)\n{\n \/\/ do a test build to extract config string\n auto src_dir = temp_directory_path() \/ \"temp\" \/ fs::unique_path();\n auto bin_dir = src_dir \/ \"build\";\n\n fs::create_directories(src_dir);\n write_file(src_dir \/ CPPAN_FILENAME, \"\");\n SCOPE_EXIT\n {\n \/\/ remove test dir\n boost::system::error_code ec;\n fs::remove_all(src_dir, ec);\n };\n\n \/\/ invoke cppan\n Config conf(src_dir);\n conf.process(src_dir);\n conf.settings = settings;\n conf.settings.allow_links = false;\n conf.settings.disable_checks = true;\n conf.settings.source_directory = src_dir;\n conf.settings.binary_directory = bin_dir;\n\n auto printer = Printer::create(settings.printerType);\n printer->rc = &conf;\n printer->prepare_build();\n\n LOG(\"--\");\n LOG(\"-- Performing test run\");\n LOG(\"--\");\n\n auto ret = printer->generate();\n\n if (ret)\n throw std::runtime_error(\"There are errors during test run\");\n\n \/\/ read cfg\n auto c = read_file(bin_dir \/ CPPAN_CONFIG_FILENAME);\n auto cmake_version = get_cmake_version();\n\n \/\/ move this to printer some time\n \/\/ copy cached cmake config to storage\n copy_dir(\n bin_dir \/ \"CMakeFiles\" \/ cmake_version,\n directories.storage_dir_cfg \/ hash_config(c) \/ \"CMakeFiles\" \/ cmake_version);\n\n return c;\n}\n\nint Settings::build_packages(Config &c, const String &name)\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n\n config = get_config(*this);\n\n set_build_dirs(name);\n append_build_dirs(config);\n\n auto cmake_version = get_cmake_version();\n auto src = directories.storage_dir_cfg \/ config \/ \"CMakeFiles\" \/ cmake_version;\n\n \/\/ if dir does not exist it means probably we have new cmake version\n \/\/ we have config value but there was not a test run with copying cmake prepared files\n \/\/ so start unconditional test run\n if (!fs::exists(src))\n test_run(*this);\n\n \/\/ move this to printer some time\n \/\/ copy cached cmake config to bin dir\n copy_dir(src, binary_directory \/ \"CMakeFiles\" \/ cmake_version);\n\n \/\/ setup printer config\n c.process(source_directory);\n printer->prepare_build();\n\n auto ret = generate(c);\n if (ret)\n return ret;\n return build(c);\n}\n\nint Settings::generate(Config &c) const\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n return printer->generate();\n}\n\nint Settings::build(Config &c) const\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n return printer->build();\n}\n\nbool Settings::checkForUpdates() const\n{\n if (disable_update_checks)\n return false;\n\n#ifdef _WIN32\n String stamp_file = \"\/client\/.service\/win32.stamp\";\n#elif __APPLE__\n String stamp_file = \"\/client\/.service\/macos.stamp\";\n#else\n String stamp_file = \"\/client\/.service\/linux.stamp\";\n#endif\n\n DownloadData dd;\n dd.url = remotes[0].url + stamp_file;\n dd.fn = fs::temp_directory_path() \/ fs::unique_path();\n download_file(dd);\n auto stamp_remote = boost::trim_copy(read_file(dd.fn));\n boost::replace_all(stamp_remote, \"\\\"\", \"\");\n uint64_t s1 = std::stoull(cppan_stamp);\n uint64_t s2 = std::stoull(stamp_remote);\n if (!(s1 != 0 && s2 != 0 && s2 > s1))\n return false;\n\n std::cout << \"New version of the CPPAN client is available!\" << \"\\n\";\n std::cout << \"Feel free to upgrade it from website or simply run:\" << \"\\n\";\n std::cout << \"cppan --self-upgrade\" << \"\\n\";\n#ifdef _WIN32\n std::cout << \"(or the same command but from administrator)\" << \"\\n\";\n#else\n std::cout << \"or\" << \"\\n\";\n std::cout << \"sudo cppan --self-upgrade\" << \"\\n\";\n#endif\n std::cout << \"\\n\";\n return true;\n}\nRemove unnecessary copying.\/*\n * Copyright (c) 2016, Egor Pugin\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of\n * its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n\n#include \"access_table.h\"\n#include \"config.h\"\n#include \"database.h\"\n#include \"directories.h\"\n#include \"hash.h\"\n#include \"hasher.h\"\n#include \"log.h\"\n#include \"templates.h\"\n#include \"stamp.h\"\n\n#include \n\n#include \"logger.h\"\nDECLARE_STATIC_LOGGER(logger, \"settings\");\n\nconst Remotes default_remotes{\n {\n DEFAULT_REMOTE_NAME,\n \"https:\/\/cppan.org\/\",\n \"data\"\n },\n};\n\nSettings::Settings()\n{\n build_dir = temp_directory_path() \/ \"build\";\n storage_dir = get_root_directory() \/ STORAGE_DIR;\n}\n\nvoid Settings::load(const path &p, const ConfigType type)\n{\n auto root = YAML::LoadFile(p.string());\n load(root, type);\n}\n\nvoid Settings::load(const yaml &root, const ConfigType type)\n{\n load_main(root, type);\n\n auto get_storage_dir = [this](ConfigType type)\n {\n switch (type)\n {\n case ConfigType::Local:\n return cppan_dir \/ STORAGE_DIR;\n case ConfigType::User:\n return Config::get_user_config().settings.storage_dir;\n case ConfigType::System:\n return Config::get_system_config().settings.storage_dir;\n default:\n return storage_dir;\n }\n };\n\n auto get_build_dir = [this](const path &p, ConfigType type)\n {\n switch (type)\n {\n case ConfigType::Local:\n return fs::current_path();\n case ConfigType::User:\n return directories.storage_dir_tmp;\n case ConfigType::System:\n return temp_directory_path() \/ \"build\";\n default:\n return p;\n }\n };\n\n Directories dirs;\n dirs.storage_dir_type = storage_dir_type;\n dirs.set_storage_dir(get_storage_dir(storage_dir_type));\n dirs.build_dir_type = build_dir_type;\n dirs.set_build_dir(get_build_dir(build_dir, build_dir_type));\n directories.update(dirs, type);\n}\n\nvoid Settings::load_main(const yaml &root, const ConfigType type)\n{\n auto packages_dir_type_from_string = [](const String &s, const String &key)\n {\n if (s == \"local\")\n return ConfigType::Local;\n if (s == \"user\")\n return ConfigType::User;\n if (s == \"system\")\n return ConfigType::System;\n throw std::runtime_error(\"Unknown '\" + key + \"'. Should be one of [local, user, system]\");\n };\n\n get_map_and_iterate(root, \"remotes\", [this](auto &kv)\n {\n auto n = kv.first.template as();\n bool o = n == DEFAULT_REMOTE_NAME; \/\/ origin\n Remote rm;\n Remote *prm = o ? &remotes[0] : &rm;\n prm->name = n;\n EXTRACT_VAR(kv.second, prm->url, \"url\", String);\n EXTRACT_VAR(kv.second, prm->data_dir, \"data_dir\", String);\n EXTRACT_VAR(kv.second, prm->user, \"user\", String);\n EXTRACT_VAR(kv.second, prm->token, \"token\", String);\n if (!o)\n remotes.push_back(*prm);\n });\n\n EXTRACT_AUTO(disable_update_checks);\n EXTRACT(storage_dir, String);\n EXTRACT(build_dir, String);\n EXTRACT(cppan_dir, String);\n\n auto &p = root[\"proxy\"];\n if (p.IsDefined())\n {\n if (!p.IsMap())\n throw std::runtime_error(\"'proxy' should be a map\");\n EXTRACT_VAR(p, proxy.host, \"host\", String);\n EXTRACT_VAR(p, proxy.user, \"user\", String);\n }\n\n storage_dir_type = packages_dir_type_from_string(get_scalar(root, \"storage_dir_type\", \"user\"), \"storage_dir_type\");\n if (root[\"storage_dir\"].IsDefined())\n storage_dir_type = ConfigType::None;\n build_dir_type = packages_dir_type_from_string(get_scalar(root, \"build_dir_type\", \"system\"), \"build_dir_type\");\n if (root[\"build_dir\"].IsDefined())\n build_dir_type = ConfigType::None;\n\n \/\/ read these first from local settings\n \/\/ and they'll be overriden in bs (if they exist there)\n EXTRACT_AUTO(use_cache);\n EXTRACT_AUTO(show_ide_projects);\n EXTRACT_AUTO(add_run_cppan_target);\n EXTRACT_AUTO(cmake_verbose);\n\n \/\/ read build settings\n if (type == ConfigType::Local)\n {\n \/\/ at first, we load bs from current root\n load_build(root);\n\n \/\/ then override settings with specific (or default) config\n yaml current_build;\n if (root[\"builds\"].IsDefined())\n {\n \/\/ yaml will not keep sorting of keys in map\n \/\/ so we can take 'first' build in document\n if (root[\"current_build\"].IsDefined())\n current_build = root[\"builds\"][root[\"current_build\"].template as()];\n }\n else if (root[\"build\"].IsDefined())\n current_build = root[\"build\"];\n\n load_build(current_build);\n }\n}\n\nvoid Settings::load_build(const yaml &root)\n{\n if (root.IsNull())\n return;\n\n \/\/ extract\n EXTRACT_AUTO(c_compiler);\n EXTRACT_AUTO(cxx_compiler);\n EXTRACT_AUTO(compiler);\n EXTRACT_AUTO(c_compiler_flags);\n if (c_compiler_flags.empty())\n EXTRACT_VAR(root, c_compiler_flags, \"c_flags\", String);\n EXTRACT_AUTO(cxx_compiler_flags);\n if (cxx_compiler_flags.empty())\n EXTRACT_VAR(root, cxx_compiler_flags, \"cxx_flags\", String);\n EXTRACT_AUTO(compiler_flags);\n EXTRACT_AUTO(link_flags);\n EXTRACT_AUTO(link_libraries);\n EXTRACT_AUTO(configuration);\n EXTRACT_AUTO(generator);\n EXTRACT_AUTO(toolset);\n EXTRACT_AUTO(use_shared_libs);\n EXTRACT_AUTO(silent);\n EXTRACT_AUTO(use_cache);\n EXTRACT_AUTO(show_ide_projects);\n EXTRACT_AUTO(add_run_cppan_target);\n EXTRACT_AUTO(cmake_verbose);\n\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n {\n auto t = configuration_types[i];\n boost::to_lower(t);\n EXTRACT_VAR(root, c_compiler_flags_conf[i], \"c_compiler_flags_\" + t, String);\n EXTRACT_VAR(root, cxx_compiler_flags_conf[i], \"cxx_compiler_flags_\" + t, String);\n EXTRACT_VAR(root, compiler_flags_conf[i], \"compiler_flags_\" + t, String);\n EXTRACT_VAR(root, link_flags_conf[i], \"link_flags_\" + t, String);\n }\n\n cmake_options = get_sequence(root[\"cmake_options\"]);\n get_string_map(root, \"env\", env);\n\n \/\/ process\n if (c_compiler.empty())\n c_compiler = cxx_compiler;\n if (c_compiler.empty())\n c_compiler = compiler;\n if (cxx_compiler.empty())\n cxx_compiler = compiler;\n\n c_compiler_flags += \" \" + compiler_flags;\n cxx_compiler_flags += \" \" + compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n {\n c_compiler_flags_conf[i] += \" \" + compiler_flags_conf[i];\n cxx_compiler_flags_conf[i] += \" \" + compiler_flags_conf[i];\n }\n}\n\nbool Settings::is_custom_build_dir() const\n{\n return build_dir_type == ConfigType::Local || build_dir_type == ConfigType::None;\n}\n\nvoid Settings::set_build_dirs(const String &name)\n{\n filename = name;\n filename_without_ext = name;\n\n source_directory = directories.build_dir;\n if (directories.build_dir_type == ConfigType::Local ||\n directories.build_dir_type == ConfigType::None)\n {\n source_directory \/= (CPPAN_LOCAL_BUILD_PREFIX + filename);\n }\n else\n {\n source_directory_hash = sha256_short(name);\n source_directory \/= source_directory_hash;\n }\n binary_directory = source_directory \/ \"build\";\n}\n\nvoid Settings::append_build_dirs(const path &p)\n{\n source_directory \/= p;\n binary_directory = source_directory \/ \"build\";\n}\n\nString Settings::get_hash() const\n{\n Hasher h;\n h |= c_compiler;\n h |= cxx_compiler;\n h |= compiler;\n h |= c_compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= c_compiler_flags_conf[i];\n h |= cxx_compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= cxx_compiler_flags_conf[i];\n h |= compiler_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= compiler_flags_conf[i];\n h |= link_flags;\n for (int i = 0; i < CMakeConfigurationType::Max; i++)\n h |= link_flags_conf[i];\n h |= link_libraries;\n h |= generator;\n h |= toolset;\n h |= use_shared_libs;\n return h.hash;\n}\n\nString Settings::get_fs_generator() const\n{\n String g = generator;\n boost::to_lower(g);\n boost::replace_all(g, \" \", \"-\");\n return g;\n}\n\nString get_config(const Settings &settings)\n{\n \/\/ add original config to db\n \/\/ but return hashed\n\n auto &db = getServiceDatabase();\n auto h = settings.get_hash();\n auto c = db.getConfigByHash(h);\n\n if (!c.empty())\n return hash_config(c);\n\n c = test_run(settings);\n auto ch = hash_config(c);\n db.addConfigHash(h, c, ch);\n\n return ch;\n}\n\nString test_run(const Settings &settings)\n{\n \/\/ do a test build to extract config string\n auto src_dir = temp_directory_path() \/ \"temp\" \/ fs::unique_path();\n auto bin_dir = src_dir \/ \"build\";\n\n fs::create_directories(src_dir);\n write_file(src_dir \/ CPPAN_FILENAME, \"\");\n SCOPE_EXIT\n {\n \/\/ remove test dir\n boost::system::error_code ec;\n fs::remove_all(src_dir, ec);\n };\n\n \/\/ invoke cppan\n Config conf(src_dir);\n conf.process(src_dir);\n conf.settings = settings;\n conf.settings.allow_links = false;\n conf.settings.disable_checks = true;\n conf.settings.source_directory = src_dir;\n conf.settings.binary_directory = bin_dir;\n\n auto printer = Printer::create(settings.printerType);\n printer->rc = &conf;\n printer->prepare_build();\n\n LOG(\"--\");\n LOG(\"-- Performing test run\");\n LOG(\"--\");\n\n auto ret = printer->generate();\n\n if (ret)\n throw std::runtime_error(\"There are errors during test run\");\n\n \/\/ read cfg\n auto c = read_file(bin_dir \/ CPPAN_CONFIG_FILENAME);\n auto cmake_version = get_cmake_version();\n\n \/\/ move this to printer some time\n \/\/ copy cached cmake config to storage\n copy_dir(\n bin_dir \/ \"CMakeFiles\" \/ cmake_version,\n directories.storage_dir_cfg \/ hash_config(c) \/ \"CMakeFiles\" \/ cmake_version);\n\n return c;\n}\n\nint Settings::build_packages(Config &c, const String &name)\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n\n config = get_config(*this);\n\n set_build_dirs(name);\n append_build_dirs(config);\n\n auto cmake_version = get_cmake_version();\n auto src = directories.storage_dir_cfg \/ config \/ \"CMakeFiles\" \/ cmake_version;\n\n \/\/ if dir does not exist it means probably we have new cmake version\n \/\/ we have config value but there was not a test run with copying cmake prepared files\n \/\/ so start unconditional test run\n if (!fs::exists(src))\n test_run(*this);\n\n \/\/ move this to printer some time\n \/\/ copy cached cmake config to bin dir\n auto dst = binary_directory \/ \"CMakeFiles\" \/ cmake_version;\n if (!fs::exists(dst))\n copy_dir(src, dst);\n\n \/\/ setup printer config\n c.process(source_directory);\n printer->prepare_build();\n\n auto ret = generate(c);\n if (ret)\n return ret;\n return build(c);\n}\n\nint Settings::generate(Config &c) const\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n return printer->generate();\n}\n\nint Settings::build(Config &c) const\n{\n auto printer = Printer::create(printerType);\n printer->rc = &c;\n return printer->build();\n}\n\nbool Settings::checkForUpdates() const\n{\n if (disable_update_checks)\n return false;\n\n#ifdef _WIN32\n String stamp_file = \"\/client\/.service\/win32.stamp\";\n#elif __APPLE__\n String stamp_file = \"\/client\/.service\/macos.stamp\";\n#else\n String stamp_file = \"\/client\/.service\/linux.stamp\";\n#endif\n\n DownloadData dd;\n dd.url = remotes[0].url + stamp_file;\n dd.fn = fs::temp_directory_path() \/ fs::unique_path();\n download_file(dd);\n auto stamp_remote = boost::trim_copy(read_file(dd.fn));\n boost::replace_all(stamp_remote, \"\\\"\", \"\");\n uint64_t s1 = std::stoull(cppan_stamp);\n uint64_t s2 = std::stoull(stamp_remote);\n if (!(s1 != 0 && s2 != 0 && s2 > s1))\n return false;\n\n std::cout << \"New version of the CPPAN client is available!\" << \"\\n\";\n std::cout << \"Feel free to upgrade it from website or simply run:\" << \"\\n\";\n std::cout << \"cppan --self-upgrade\" << \"\\n\";\n#ifdef _WIN32\n std::cout << \"(or the same command but from administrator)\" << \"\\n\";\n#else\n std::cout << \"or\" << \"\\n\";\n std::cout << \"sudo cppan --self-upgrade\" << \"\\n\";\n#endif\n std::cout << \"\\n\";\n return true;\n}\n<|endoftext|>"} {"text":"Bugfix: add missing `#include` line.<|endoftext|>"} {"text":"\/\/ This file manages project configuration & persisting it to EEPROM.\n#include \"settings.h\"\n#include \"primitives\/string_utils.h\"\n#include \"vive_sensors_pipeline.h\"\n#include \"led_state.h\"\n#include \"print_helpers.h\"\n\nconstexpr uint32_t current_settings_version = 0xbabe0000 + sizeof(PersistentSettings);\nconstexpr uint32_t initial_eeprom_addr = 0;\n\nstatic_assert(sizeof(PersistentSettings) < 1500, \"PersistentSettings must fit into EEPROM with some leeway\");\nstatic_assert(std::is_trivially_copyable(), \"All definitions must be trivially copyable to be bitwise-stored\");\n\n\/* Example settings\n# Comments are prepended by '#'\nreset # Reset all settings to clean state\nsensor0 pin 12 positive\nbase0 origin -1.528180 2.433750 -1.969390 matrix -0.841840 0.332160 -0.425400 -0.046900 0.740190 0.670760 0.537680 0.584630 -0.607540\nbase1 origin 1.718700 2.543170 0.725060 matrix 0.458350 -0.649590 0.606590 0.028970 0.693060 0.720300 -0.888300 -0.312580 0.336480\nobject0 sensor0\nstream0 position object0 > usb_serial\nstream1 angles > usb_serial\nserial1 57600\nstream2 mavlink object0 ned 110 > serial1\n*\/\n\nPersistentSettings settings;\n\nPersistentSettings::PersistentSettings() {\n reset();\n read_from_eeprom();\n}\n\nbool PersistentSettings::read_from_eeprom() {\n uint32_t eeprom_addr = initial_eeprom_addr, version;\n eeprom_read(eeprom_addr, &version, sizeof(version)); eeprom_addr += sizeof(version);\n if (version == current_settings_version) {\n \/\/ Normal initialization: Just copy block of data.\n eeprom_read(eeprom_addr, this, sizeof(*this));\n return true;\n } \n \/\/ Unknown version.\n return false;\n}\n\nvoid PersistentSettings::write_to_eeprom() {\n uint32_t version = current_settings_version;\n uint32_t eeprom_addr = initial_eeprom_addr;\n eeprom_write(eeprom_addr, &version, sizeof(version)); eeprom_addr += sizeof(version);\n eeprom_write(eeprom_addr, this, sizeof(*this));\n}\n\nvoid PersistentSettings::restart_in_configuration_mode() {\n is_configured_ = false;\n write_to_eeprom();\n restart_system();\n}\n\n\/\/ Initialize settings.\nvoid PersistentSettings::reset() {\n memset(this, 0, sizeof(*this));\n\n \/\/ Defaults.\n outputs_.set_size(num_outputs);\n outputs_[0].active = true;\n}\n\nbool PersistentSettings::validate_setup(PrintStream &error_stream) {\n try {\n \/\/ Try to create the pipeline and then delete it.\n std::unique_ptr pipeline = create_vive_sensor_pipeline(*this);\n return true;\n }\n catch (const std::exception& e) { \/\/ This included bad_alloc, runtime_exception etc.\n error_stream.printf(\"Validation error: %s\\n\", e.what());\n }\n catch (...) {\n error_stream.printf(\"Unknown validation error.\\n\");\n }\n return false;\n}\n\ntemplate\nvoid PersistentSettings::set_value(Vector &arr, uint32_t idx, HashedWord *input_words, PrintStream &stream) {\n if (idx <= arr.size() && idx < arr_len) {\n T def;\n if (def.parse_def(idx, input_words, stream)) {\n bool push_new = idx == arr.size();\n if (push_new)\n arr.push(def); \n else\n std::swap(arr[idx], def);\n\n if (validate_setup(stream)) {\n \/\/ Success.\n def.print_def(idx, stream); \n } else {\n \/\/ Validation failed. Undo.\n if (push_new)\n arr.pop(); \n else\n std::swap(arr[idx], def);\n }\n }\n } else\n stream.printf(\"Index too large. Next available index: %d.\\n\", arr.size());\n}\n\nbool PersistentSettings::process_command(char *input_cmd, PrintStream &stream) {\n HashedWord *input_words = hash_words(input_cmd);\n if (*input_words && input_words->word[0] != '#') { \/\/ Do nothing on comments and empty lines.\n uint32_t idx = input_words->idx;\n switch (*input_words++) {\n case \"view\"_hash:\n \/\/ Print all current settings.\n stream.printf(\"# Current configuration. Copy\/paste to save\/restore.\\n\", \n inputs_.size(), base_stations_.size());\n stream.printf(\"reset\\n\");\n for (uint32_t i = 0; i < inputs_.size(); i++)\n inputs_[i].print_def(i, stream);\n for (uint32_t i = 0; i < base_stations_.size(); i++)\n base_stations_[i].print_def(i, stream);\n for (uint32_t i = 0; i < geo_builders_.size(); i++)\n geo_builders_[i].print_def(i, stream);\n for (uint32_t i = 0; i < outputs_.size(); i++)\n outputs_[i].print_def(i, stream);\n for (uint32_t i = 0; i < formatters_.size(); i++)\n formatters_[i].print_def(i, stream);\n break;\n \n case \"sensor#\"_hash:\n set_value(inputs_, idx, input_words, stream);\n break;\n \n case \"base#\"_hash:\n set_value(base_stations_, idx, input_words, stream);\n break;\n\n case \"object#\"_hash:\n set_value(geo_builders_, idx, input_words, stream);\n break;\n \n case \"stream#\"_hash:\n set_value(formatters_, idx, input_words, stream);\n break;\n\n case \"usb_serial\"_hash:\n case \"serial#\"_hash:\n if (idx == (uint32_t)-1) idx = 0;\n set_value(outputs_, idx, input_words, stream);\n break;\n \n case \"reset\"_hash:\n reset();\n stream.printf(\"Reset successful.\\n\");\n break;\n\n case \"reload\"_hash:\n if (read_from_eeprom())\n stream.printf(\"Loaded previous configuration from EEPROM.\\n\");\n else\n stream.printf(\"No valid configuration found in EEPROM.\\n\");\n break;\n\n case \"write\"_hash:\n if (!validate_setup(stream)) break;\n is_configured_ = true;\n write_to_eeprom();\n stream.printf(\"Write to EEPROM successful. Type 'continue' to start using it.\\n\");\n break;\n\n case \"validate\"_hash:\n if (validate_setup(stream))\n stream.printf(\"Validation successful.\\n\");\n break;\n\n case \"continue\"_hash:\n if (!validate_setup(stream)) break;\n is_configured_ = true;\n return false;\n\n default:\n stream.printf(\"Unknown command '%s'. Valid commands: view, , reset, reload, write, validate, continue.\\n\", (input_words-1)->word);\n }\n }\n\n \/\/ Print prompt for the next command.\n stream.printf(\"config> \");\n return true;\n}\n\n\n\/\/ == Configuration pipeline ==================================================\n\nclass SettingsReaderWriterNode \n : public WorkerNode\n , public DataChunkLineSplitter\n , public Producer {\npublic:\n SettingsReaderWriterNode(PersistentSettings *settings, Pipeline *pipeline)\n : settings_(settings)\n , pipeline_(pipeline) {\n set_led_state(LedState::kConfigMode);\n }\n\nprivate:\n virtual void consume_line(char *line, Timestamp time) {\n DataChunkPrintStream stream(this, time);\n if (!settings_->process_command(line, stream))\n pipeline_->stop();\n }\n\n virtual void do_work(Timestamp cur_time) {\n update_led_pattern(cur_time);\n }\n\n PersistentSettings *settings_;\n Pipeline *pipeline_;\n};\n\nstd::unique_ptr PersistentSettings::create_configuration_pipeline(uint32_t stream_idx) {\n auto pipeline = std::make_unique();\n\n auto reader = pipeline->add_back(std::make_unique(this, pipeline.get()));\n auto output_node = pipeline->add_back(OutputNode::create(stream_idx, OutputDef{}));\n reader->pipe(output_node);\n output_node->pipe(reader);\n\n return pipeline;\n}\nMinor fix: print new value when changing config\/\/ This file manages project configuration & persisting it to EEPROM.\n#include \"settings.h\"\n#include \"primitives\/string_utils.h\"\n#include \"vive_sensors_pipeline.h\"\n#include \"led_state.h\"\n#include \"print_helpers.h\"\n\nconstexpr uint32_t current_settings_version = 0xbabe0000 + sizeof(PersistentSettings);\nconstexpr uint32_t initial_eeprom_addr = 0;\n\nstatic_assert(sizeof(PersistentSettings) < 1500, \"PersistentSettings must fit into EEPROM with some leeway\");\nstatic_assert(std::is_trivially_copyable(), \"All definitions must be trivially copyable to be bitwise-stored\");\n\n\/* Example settings\n# Comments are prepended by '#'\nreset # Reset all settings to clean state\nsensor0 pin 12 positive\nbase0 origin -1.528180 2.433750 -1.969390 matrix -0.841840 0.332160 -0.425400 -0.046900 0.740190 0.670760 0.537680 0.584630 -0.607540\nbase1 origin 1.718700 2.543170 0.725060 matrix 0.458350 -0.649590 0.606590 0.028970 0.693060 0.720300 -0.888300 -0.312580 0.336480\nobject0 sensor0\nstream0 position object0 > usb_serial\nstream1 angles > usb_serial\nserial1 57600\nstream2 mavlink object0 ned 110 > serial1\n*\/\n\nPersistentSettings settings;\n\nPersistentSettings::PersistentSettings() {\n reset();\n read_from_eeprom();\n}\n\nbool PersistentSettings::read_from_eeprom() {\n uint32_t eeprom_addr = initial_eeprom_addr, version;\n eeprom_read(eeprom_addr, &version, sizeof(version)); eeprom_addr += sizeof(version);\n if (version == current_settings_version) {\n \/\/ Normal initialization: Just copy block of data.\n eeprom_read(eeprom_addr, this, sizeof(*this));\n return true;\n } \n \/\/ Unknown version.\n return false;\n}\n\nvoid PersistentSettings::write_to_eeprom() {\n uint32_t version = current_settings_version;\n uint32_t eeprom_addr = initial_eeprom_addr;\n eeprom_write(eeprom_addr, &version, sizeof(version)); eeprom_addr += sizeof(version);\n eeprom_write(eeprom_addr, this, sizeof(*this));\n}\n\nvoid PersistentSettings::restart_in_configuration_mode() {\n is_configured_ = false;\n write_to_eeprom();\n restart_system();\n}\n\n\/\/ Initialize settings.\nvoid PersistentSettings::reset() {\n memset(this, 0, sizeof(*this));\n\n \/\/ Defaults.\n outputs_.set_size(num_outputs);\n outputs_[0].active = true;\n}\n\nbool PersistentSettings::validate_setup(PrintStream &error_stream) {\n try {\n \/\/ Try to create the pipeline and then delete it.\n std::unique_ptr pipeline = create_vive_sensor_pipeline(*this);\n return true;\n }\n catch (const std::exception& e) { \/\/ This included bad_alloc, runtime_exception etc.\n error_stream.printf(\"Validation error: %s\\n\", e.what());\n }\n catch (...) {\n error_stream.printf(\"Unknown validation error.\\n\");\n }\n return false;\n}\n\ntemplate\nvoid PersistentSettings::set_value(Vector &arr, uint32_t idx, HashedWord *input_words, PrintStream &stream) {\n if (idx <= arr.size() && idx < arr_len) {\n T def;\n if (def.parse_def(idx, input_words, stream)) {\n bool push_new = idx == arr.size();\n if (push_new)\n arr.push(def); \n else\n std::swap(arr[idx], def);\n\n if (validate_setup(stream)) {\n \/\/ Success.\n stream.printf(\"Updated: \");\n arr[idx].print_def(idx, stream);\n } else {\n \/\/ Validation failed. Undo.\n if (push_new)\n arr.pop(); \n else\n std::swap(arr[idx], def);\n }\n }\n } else\n stream.printf(\"Index too large. Next available index: %d.\\n\", arr.size());\n}\n\nbool PersistentSettings::process_command(char *input_cmd, PrintStream &stream) {\n HashedWord *input_words = hash_words(input_cmd);\n if (*input_words && input_words->word[0] != '#') { \/\/ Do nothing on comments and empty lines.\n uint32_t idx = input_words->idx;\n switch (*input_words++) {\n case \"view\"_hash:\n \/\/ Print all current settings.\n stream.printf(\"# Current configuration. Copy\/paste to save\/restore.\\n\", \n inputs_.size(), base_stations_.size());\n stream.printf(\"reset\\n\");\n for (uint32_t i = 0; i < inputs_.size(); i++)\n inputs_[i].print_def(i, stream);\n for (uint32_t i = 0; i < base_stations_.size(); i++)\n base_stations_[i].print_def(i, stream);\n for (uint32_t i = 0; i < geo_builders_.size(); i++)\n geo_builders_[i].print_def(i, stream);\n for (uint32_t i = 0; i < outputs_.size(); i++)\n outputs_[i].print_def(i, stream);\n for (uint32_t i = 0; i < formatters_.size(); i++)\n formatters_[i].print_def(i, stream);\n break;\n \n case \"sensor#\"_hash:\n set_value(inputs_, idx, input_words, stream);\n break;\n \n case \"base#\"_hash:\n set_value(base_stations_, idx, input_words, stream);\n break;\n\n case \"object#\"_hash:\n set_value(geo_builders_, idx, input_words, stream);\n break;\n \n case \"stream#\"_hash:\n set_value(formatters_, idx, input_words, stream);\n break;\n\n case \"usb_serial\"_hash:\n case \"serial#\"_hash:\n if (idx == (uint32_t)-1) idx = 0;\n set_value(outputs_, idx, input_words, stream);\n break;\n \n case \"reset\"_hash:\n reset();\n stream.printf(\"Reset successful.\\n\");\n break;\n\n case \"reload\"_hash:\n if (read_from_eeprom())\n stream.printf(\"Loaded previous configuration from EEPROM.\\n\");\n else\n stream.printf(\"No valid configuration found in EEPROM.\\n\");\n break;\n\n case \"write\"_hash:\n if (!validate_setup(stream)) break;\n is_configured_ = true;\n write_to_eeprom();\n stream.printf(\"Write to EEPROM successful. Type 'continue' to start using it.\\n\");\n break;\n\n case \"validate\"_hash:\n if (validate_setup(stream))\n stream.printf(\"Validation successful.\\n\");\n break;\n\n case \"continue\"_hash:\n if (!validate_setup(stream)) break;\n is_configured_ = true;\n return false;\n\n default:\n stream.printf(\"Unknown command '%s'. Valid commands: view, , reset, reload, write, validate, continue.\\n\", (input_words-1)->word);\n }\n }\n\n \/\/ Print prompt for the next command.\n stream.printf(\"config> \");\n return true;\n}\n\n\n\/\/ == Configuration pipeline ==================================================\n\nclass SettingsReaderWriterNode \n : public WorkerNode\n , public DataChunkLineSplitter\n , public Producer {\npublic:\n SettingsReaderWriterNode(PersistentSettings *settings, Pipeline *pipeline)\n : settings_(settings)\n , pipeline_(pipeline) {\n set_led_state(LedState::kConfigMode);\n }\n\nprivate:\n virtual void consume_line(char *line, Timestamp time) {\n DataChunkPrintStream stream(this, time);\n if (!settings_->process_command(line, stream))\n pipeline_->stop();\n }\n\n virtual void do_work(Timestamp cur_time) {\n update_led_pattern(cur_time);\n }\n\n PersistentSettings *settings_;\n Pipeline *pipeline_;\n};\n\nstd::unique_ptr PersistentSettings::create_configuration_pipeline(uint32_t stream_idx) {\n auto pipeline = std::make_unique();\n\n auto reader = pipeline->add_back(std::make_unique(this, pipeline.get()));\n auto output_node = pipeline->add_back(OutputNode::create(stream_idx, OutputDef{}));\n reader->pipe(output_node);\n output_node->pipe(reader);\n\n return pipeline;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_ENUMS_MATH_HPP\n#define NAZARA_ENUMS_MATH_HPP\n\nenum nzCorner\n{\n\tnzCorner_FarLeftBottom,\n\tnzCorner_FarLeftTop,\n\tnzCorner_FarRightBottom,\n\tnzCorner_FarRightTop,\n\tnzCorner_NearLeftBottom,\n\tnzCorner_NearLeftTop,\n\tnzCorner_NearRightBottom,\n\tnzCorner_NearRightTop,\n\n\tnzCorner_Max = nzCorner_FarRightTop\n};\n\n#endif \/\/ NAZARA_ENUMS_MATH_HPP\nFixed Corner_Max\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Mathematics module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#pragma once\n\n#ifndef NAZARA_ENUMS_MATH_HPP\n#define NAZARA_ENUMS_MATH_HPP\n\nenum nzCorner\n{\n\tnzCorner_FarLeftBottom,\n\tnzCorner_FarLeftTop,\n\tnzCorner_FarRightBottom,\n\tnzCorner_FarRightTop,\n\tnzCorner_NearLeftBottom,\n\tnzCorner_NearLeftTop,\n\tnzCorner_NearRightBottom,\n\tnzCorner_NearRightTop,\n\n\tnzCorner_Max = nzCorner_NearRightTop\n};\n\n#endif \/\/ NAZARA_ENUMS_MATH_HPP\n<|endoftext|>"} {"text":"#pragma once\n\n\/\/ std\n#include \n\n\/\/ project\n#include \"Section.hpp\"\n#include \"Type.hpp\"\n\nnamespace dai\n{\nnamespace bootloader\n{\n\n\/\/ Memory section structure\nstruct Structure {\n Structure() = default;\n std::map offset, size;\nprotected:\n Structure(decltype(offset) a, decltype(size) b) : offset(a), size(b) {}\n};\n\n\/\/ Structure\nstruct NetworkBootloaderStructure : Structure {\n\n constexpr static long HEADER_OFFSET = 0;\n constexpr static long HEADER_SIZE = 512;\n constexpr static long CONFIG_SIZE = 16 * 1024;\n constexpr static long BOOTLOADER_OFFSET = HEADER_OFFSET + HEADER_SIZE;\n constexpr static long BOOTLOADER_SIZE = 8 * 1024 * 1024 - CONFIG_SIZE - HEADER_SIZE;\n constexpr static long CONFIG_OFFSET = BOOTLOADER_OFFSET + BOOTLOADER_SIZE;\n constexpr static long APPLICATION_OFFSET = CONFIG_OFFSET + CONFIG_SIZE;\n\n NetworkBootloaderStructure() : Structure({\n {Section::HEADER, HEADER_OFFSET},\n {Section::BOOTLOADER_CONFIG, CONFIG_OFFSET},\n {Section::BOOTLOADER, BOOTLOADER_OFFSET},\n {Section::APPLICATION, APPLICATION_OFFSET},\n }, {\n {Section::HEADER, HEADER_SIZE},\n {Section::BOOTLOADER_CONFIG, CONFIG_SIZE},\n {Section::BOOTLOADER, BOOTLOADER_SIZE},\n {Section::APPLICATION, 0},\n }) {}\n\n};\n\n\/\/ Structure\nstruct UsbBootloaderStructure : Structure {\n\n constexpr static long HEADER_OFFSET = 0;\n constexpr static long HEADER_SIZE = 512;\n constexpr static long CONFIG_SIZE = 16 * 1024;\n constexpr static long BOOTLOADER_OFFSET = HEADER_OFFSET + HEADER_SIZE;\n constexpr static long BOOTLOADER_SIZE = 1 * 1024 * 1024 - CONFIG_SIZE - HEADER_SIZE;\n constexpr static long CONFIG_OFFSET = BOOTLOADER_OFFSET + BOOTLOADER_SIZE;\n constexpr static long APPLICATION_OFFSET = CONFIG_OFFSET + CONFIG_SIZE;\n\n UsbBootloaderStructure() : Structure({\n {Section::HEADER, HEADER_OFFSET},\n {Section::BOOTLOADER_CONFIG, CONFIG_OFFSET},\n {Section::BOOTLOADER, BOOTLOADER_OFFSET},\n {Section::APPLICATION, APPLICATION_OFFSET},\n }, {\n {Section::HEADER, HEADER_SIZE},\n {Section::BOOTLOADER_CONFIG, CONFIG_SIZE},\n {Section::BOOTLOADER, BOOTLOADER_SIZE},\n {Section::APPLICATION, 0},\n }) {}\n\n};\n\ninline const Structure getStructure(Type type){\n switch(type){\n case Type::AUTO: throw std::invalid_argument(\"Invalid argument to getStructure function\");\n case Type::USB: return UsbBootloaderStructure();\n case Type::NETWORK: return NetworkBootloaderStructure();\n }\n \/\/ Default\n return UsbBootloaderStructure();\n}\n\n} \/\/ namespace bootloader\n} \/\/ namespace dai\n\nAdded missing header to Structure#pragma once\n\n\/\/ std\n#include \n#include \n\n\/\/ project\n#include \"Section.hpp\"\n#include \"Type.hpp\"\n\nnamespace dai\n{\nnamespace bootloader\n{\n\n\/\/ Memory section structure\nstruct Structure {\n Structure() = default;\n std::map offset, size;\nprotected:\n Structure(decltype(offset) a, decltype(size) b) : offset(a), size(b) {}\n};\n\n\/\/ Structure\nstruct NetworkBootloaderStructure : Structure {\n\n constexpr static long HEADER_OFFSET = 0;\n constexpr static long HEADER_SIZE = 512;\n constexpr static long CONFIG_SIZE = 16 * 1024;\n constexpr static long BOOTLOADER_OFFSET = HEADER_OFFSET + HEADER_SIZE;\n constexpr static long BOOTLOADER_SIZE = 8 * 1024 * 1024 - CONFIG_SIZE - HEADER_SIZE;\n constexpr static long CONFIG_OFFSET = BOOTLOADER_OFFSET + BOOTLOADER_SIZE;\n constexpr static long APPLICATION_OFFSET = CONFIG_OFFSET + CONFIG_SIZE;\n\n NetworkBootloaderStructure() : Structure({\n {Section::HEADER, HEADER_OFFSET},\n {Section::BOOTLOADER_CONFIG, CONFIG_OFFSET},\n {Section::BOOTLOADER, BOOTLOADER_OFFSET},\n {Section::APPLICATION, APPLICATION_OFFSET},\n }, {\n {Section::HEADER, HEADER_SIZE},\n {Section::BOOTLOADER_CONFIG, CONFIG_SIZE},\n {Section::BOOTLOADER, BOOTLOADER_SIZE},\n {Section::APPLICATION, 0},\n }) {}\n\n};\n\n\/\/ Structure\nstruct UsbBootloaderStructure : Structure {\n\n constexpr static long HEADER_OFFSET = 0;\n constexpr static long HEADER_SIZE = 512;\n constexpr static long CONFIG_SIZE = 16 * 1024;\n constexpr static long BOOTLOADER_OFFSET = HEADER_OFFSET + HEADER_SIZE;\n constexpr static long BOOTLOADER_SIZE = 1 * 1024 * 1024 - CONFIG_SIZE - HEADER_SIZE;\n constexpr static long CONFIG_OFFSET = BOOTLOADER_OFFSET + BOOTLOADER_SIZE;\n constexpr static long APPLICATION_OFFSET = CONFIG_OFFSET + CONFIG_SIZE;\n\n UsbBootloaderStructure() : Structure({\n {Section::HEADER, HEADER_OFFSET},\n {Section::BOOTLOADER_CONFIG, CONFIG_OFFSET},\n {Section::BOOTLOADER, BOOTLOADER_OFFSET},\n {Section::APPLICATION, APPLICATION_OFFSET},\n }, {\n {Section::HEADER, HEADER_SIZE},\n {Section::BOOTLOADER_CONFIG, CONFIG_SIZE},\n {Section::BOOTLOADER, BOOTLOADER_SIZE},\n {Section::APPLICATION, 0},\n }) {}\n\n};\n\ninline const Structure getStructure(Type type){\n switch(type){\n case Type::AUTO: throw std::invalid_argument(\"Invalid argument to getStructure function\");\n case Type::USB: return UsbBootloaderStructure();\n case Type::NETWORK: return NetworkBootloaderStructure();\n }\n \/\/ Default\n return UsbBootloaderStructure();\n}\n\n} \/\/ namespace bootloader\n} \/\/ namespace dai\n\n<|endoftext|>"} {"text":"#include \/\/ for imshow\n#include \/\/ for blur, dilation, erosion\n#include \/\/ for backgroundsubtractor\n#include \/\/ for videocapture\n\n#include \n\nvoid show(std::string title, const cv::Mat& image) {\n cv::imshow(title.c_str(), image);\n char c = static_cast(cv::waitKey(1));\n if (c == 27) exit(0);\n}\n\nconst auto learning_rate_divider = 10000;\n\nvoid subtract(cv::Ptr pMOG2, cv::Mat* image,\n cv::Mat* background, int learning_rate) {\n auto rate = learning_rate \/ static_cast(learning_rate_divider);\n if (learning_rate <= 0) {\n rate = -1.0;\n }\n pMOG2->apply(*image, *background, rate);\n}\n\nvoid blur(cv::Mat* input_output, int blur_size) {\n if (blur_size <= 0) {\n return;\n }\n cv::blur(*input_output, *input_output, cv::Size(blur_size, blur_size));\n}\n\nvoid erode(cv::Mat* input_output, int erosion_size) {\n if (erosion_size <= 0) {\n return;\n }\n int erosion_type = cv::MORPH_RECT;\n cv::Mat element = cv::getStructuringElement(\n erosion_type, cv::Size(2 * erosion_size, 2 * erosion_size),\n cv::Point(erosion_size, erosion_size));\n cv::erode(*input_output, *input_output, element);\n}\n\nvoid dilate(cv::Mat* input_output, int dilation_size) {\n if (dilation_size <= 0) {\n return;\n }\n int dilation_type = cv::MORPH_RECT;\n cv::Mat element = cv::getStructuringElement(\n dilation_type, cv::Size(2 * dilation_size, 2 * dilation_size),\n cv::Point(dilation_size, dilation_size));\n cv::dilate(*input_output, *input_output, element);\n}\n\ncv::Point2f findContourMiddle(const std::vector& contour) {\n \/\/\/ Get the moments\n cv::Moments moments = cv::moments(contour, false);\n if (moments.m00 == 0) {\n return cv::Point2f(-1, -1);\n }\n\n \/\/\/ Get the mass centers:\n cv::Point2f mc =\n cv::Point2f(moments.m10 \/ moments.m00, moments.m01 \/ moments.m00);\n return mc;\n}\n\nvoid findContours(const cv::Mat& image, int camera_number) {\n cv::Mat canny_output;\n std::vector > contours;\n std::vector hierarchy;\n\n \/\/\/ Find contours\n cv::findContours(image, contours, hierarchy, cv::RETR_TREE,\n cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n\n if (contours.size() < 1) {\n return;\n }\n\n cv::Mat drawing = cv::Mat::zeros(image.size(), CV_8UC3);\n\n int index = 0;\n double biggest_area = 0.0;\n for (size_t i = 0; i < contours.size(); i++) {\n auto area = cv::contourArea(contours[i]);\n if (area > biggest_area) {\n index = i;\n biggest_area = area;\n }\n }\n\n auto middle = findContourMiddle(contours[index]);\n std::cout << camera_number << \":\" << static_cast(middle.x) << \",\"\n << static_cast(middle.y) << std::endl;\n\n cv::Scalar color = cv::Scalar(255, 255, 255);\n cv::drawContours(drawing, contours, index, color, 2, 8, hierarchy, 0,\n cv::Point());\n show(\"contours\", drawing);\n}\n\nint thread(int camera_number) {\n cv::Mat background; \/\/ background image\n cv::Ptr pMOG2; \/\/ MOG2 Background subtractor\n int blur_size = 10;\n int erosion_size = 10;\n int dilation_size = 10;\n int learning_rate = 0;\n\n const int bg_history = 500;\n const int threshold = 16; \/\/ default value\n const bool detectShadows = false; \/\/ non-default\n\n pMOG2 =\n cv::createBackgroundSubtractorMOG2(bg_history, threshold, detectShadows);\n\n auto capture = cv::VideoCapture(camera_number);\n std::string control_window_name = \"control\" + std::to_string(camera_number);\n cv::namedWindow(control_window_name);\n cv::createTrackbar(\"blur\", control_window_name, &blur_size, 20);\n cv::createTrackbar(\"erosion\", control_window_name, &erosion_size, 20);\n cv::createTrackbar(\"dilation\", control_window_name, &dilation_size, 20);\n cv::createTrackbar(\"learning rate\", control_window_name, &learning_rate,\n learning_rate_divider);\n\n std::cerr << camera_number << \" started\\n\";\n while (1) {\n cv::Mat image;\n if (!capture.read(image) || image.empty()) {\n continue;\n }\n blur(&image, blur_size);\n erode(&image, erosion_size);\n dilate(&image, dilation_size);\n subtract(pMOG2, &image, &background, learning_rate);\n findContours(background, camera_number);\n show(\"transformed\" + std::to_string(camera_number), background);\n }\n}\n\nint main(void) { thread(0); }\nDefault learning rate of 5#include \n#include \/\/ for imshow\n#include \/\/ for blur, dilation, erosion\n#include \/\/ for backgroundsubtractor\n#include \/\/ for videocapture\n\nvoid show(std::string title, const cv::Mat& image) {\n cv::imshow(title.c_str(), image);\n char c = static_cast(cv::waitKey(1));\n if (c == 27) exit(0);\n}\n\nconst auto learning_rate_divider = 10000;\n\nvoid subtract(cv::Ptr pMOG2, cv::Mat* image,\n cv::Mat* background, int learning_rate) {\n auto rate = learning_rate \/ static_cast(learning_rate_divider);\n if (learning_rate <= 0) {\n rate = -1.0;\n }\n pMOG2->apply(*image, *background, rate);\n}\n\nvoid blur(cv::Mat* input_output, int blur_size) {\n if (blur_size <= 0) {\n return;\n }\n cv::blur(*input_output, *input_output, cv::Size(blur_size, blur_size));\n}\n\nvoid erode(cv::Mat* input_output, int erosion_size) {\n if (erosion_size <= 0) {\n return;\n }\n int erosion_type = cv::MORPH_RECT;\n cv::Mat element = cv::getStructuringElement(\n erosion_type, cv::Size(2 * erosion_size, 2 * erosion_size),\n cv::Point(erosion_size, erosion_size));\n cv::erode(*input_output, *input_output, element);\n}\n\nvoid dilate(cv::Mat* input_output, int dilation_size) {\n if (dilation_size <= 0) {\n return;\n }\n int dilation_type = cv::MORPH_RECT;\n cv::Mat element = cv::getStructuringElement(\n dilation_type, cv::Size(2 * dilation_size, 2 * dilation_size),\n cv::Point(dilation_size, dilation_size));\n cv::dilate(*input_output, *input_output, element);\n}\n\ncv::Point2f findContourMiddle(const std::vector& contour) {\n \/\/\/ Get the moments\n cv::Moments moments = cv::moments(contour, false);\n if (moments.m00 == 0) {\n return cv::Point2f(-1, -1);\n }\n\n \/\/\/ Get the mass centers:\n cv::Point2f mc =\n cv::Point2f(moments.m10 \/ moments.m00, moments.m01 \/ moments.m00);\n return mc;\n}\n\nvoid findContours(const cv::Mat& image, int camera_number) {\n cv::Mat canny_output;\n std::vector > contours;\n std::vector hierarchy;\n\n \/\/\/ Find contours\n cv::findContours(image, contours, hierarchy, cv::RETR_TREE,\n cv::CHAIN_APPROX_SIMPLE, cv::Point(0, 0));\n\n if (contours.size() < 1) {\n return;\n }\n\n cv::Mat drawing = cv::Mat::zeros(image.size(), CV_8UC3);\n\n int index = 0;\n double biggest_area = 0.0;\n for (size_t i = 0; i < contours.size(); i++) {\n auto area = cv::contourArea(contours[i]);\n if (area > biggest_area) {\n index = i;\n biggest_area = area;\n }\n }\n\n auto middle = findContourMiddle(contours[index]);\n std::cout << camera_number << \":\" << static_cast(middle.x) << \",\"\n << static_cast(middle.y) << std::endl;\n\n cv::Scalar color = cv::Scalar(255, 255, 255);\n cv::drawContours(drawing, contours, index, color, 2, 8, hierarchy, 0,\n cv::Point());\n show(\"contours\", drawing);\n}\n\nint thread(int camera_number) {\n cv::Mat background; \/\/ background image\n cv::Ptr pMOG2; \/\/ MOG2 Background subtractor\n int blur_size = 10;\n int erosion_size = 10;\n int dilation_size = 10;\n int learning_rate = 50;\n\n const int bg_history = 500;\n const int threshold = 16; \/\/ default value\n const bool detectShadows = false; \/\/ non-default\n\n pMOG2 =\n cv::createBackgroundSubtractorMOG2(bg_history, threshold, detectShadows);\n\n auto capture = cv::VideoCapture(camera_number);\n std::string control_window_name = \"control\" + std::to_string(camera_number);\n cv::namedWindow(control_window_name);\n cv::createTrackbar(\"blur\", control_window_name, &blur_size, 20);\n cv::createTrackbar(\"erosion\", control_window_name, &erosion_size, 20);\n cv::createTrackbar(\"dilation\", control_window_name, &dilation_size, 20);\n cv::createTrackbar(\"learning rate\", control_window_name, &learning_rate,\n learning_rate_divider);\n\n std::cerr << camera_number << \" started\\n\";\n while (1) {\n cv::Mat image;\n if (!capture.read(image) || image.empty()) {\n continue;\n }\n blur(&image, blur_size);\n erode(&image, erosion_size);\n dilate(&image, dilation_size);\n subtract(pMOG2, &image, &background, learning_rate);\n findContours(background, camera_number);\n show(\"transformed\" + std::to_string(camera_number), background);\n }\n}\n\nint main(void) { thread(0); }\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#ifndef LOG_HPP\n#define LOG_HPP\n\n#define LOG( log, message ) \\\n (log).logMessage( \\\n static_cast( \\\n std::ostringstream().flush() << (message) \\\n ).str() \\\n )\n\n#define LOG_COND( log, cond, message ) \\\n if ( cond ) LOG( log, message )\n\nnamespace Log\n{\n class Log\n {\n public:\n Log( const std::string& filename )\n : filename_( filename )\n , out_file_( filename, std::ios_base::out | std::ios_base::trunc )\n {\n time_t rawtime;\n tm * timeinfo;\n char buffer[80];\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n\n strftime( buffer, 80, \"%Y-%m-%d %H:%M:%S\", timeinfo );\n\n out_file_ << buffer << std::endl;\n }\n\n \/** Copy constructor *\/\n Log( const Log& other )\n : filename_( other.filename_ )\n , out_file_( filename_, std::ios_base::out | std::ios_base::app )\n {\n }\n\n \/** Move constructor *\/\n Log( Log&& other )\n : filename_( other.filename_ )\n , out_file_( filename_, std::ios_base::out | std::ios_base::app )\n {\n other.out_file_.close();\n }\n\n \/** Destructor *\/\n ~Log()\n {\n if ( out_file_.is_open() )\n {\n out_file_.close();\n }\n }\n\n \/** Copy assignment operator *\/\n Log& operator= ( const Log& other )\n {\n Log tmp( other ); \/\/ re-use copy-constructor\n *this = std::move( tmp ); \/\/ re-use move-assignment\n return *this;\n }\n\n \/** Move assignment operator *\/\n Log& operator= ( Log&& other)\n {\n std::swap( filename_, other.filename_ );\n other.out_file_.close();\n\n if ( out_file_.is_open() )\n {\n out_file_.close();\n }\n\n out_file_.open( filename_, std::ios_base::out | std::ios_base::app );\n\n return *this;\n }\n\n void logMessage( const std::string& message )\n {\n out_file_ << message << std::endl;\n }\n\n private:\n std::string filename_;\n std::ofstream out_file_;\n };\n}\n\n#endif \/\/ LOG_HPP\nAdded a TODO in recognition of the fact that this file is both poorly commented, and has not been reviewed.#include \n#include \n#include \n\n#ifndef LOG_HPP\n#define LOG_HPP\n\n#define LOG( log, message ) \\\n (log).logMessage( \\\n static_cast( \\\n std::ostringstream().flush() << (message) \\\n ).str() \\\n )\n\n#define LOG_COND( log, cond, message ) \\\n if ( cond ) LOG( log, message )\n\n\n\/\/ TODO: confirm that I havn't made any mistakes in this file\nnamespace Log\n{\n class Log\n {\n public:\n Log( const std::string& filename )\n : filename_( filename )\n , out_file_( filename, std::ios_base::out | std::ios_base::trunc )\n {\n time_t rawtime;\n tm * timeinfo;\n char buffer[80];\n\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n\n strftime( buffer, 80, \"%Y-%m-%d %H:%M:%S\", timeinfo );\n\n out_file_ << buffer << std::endl;\n }\n\n \/** Copy constructor *\/\n Log( const Log& other )\n : filename_( other.filename_ )\n , out_file_( filename_, std::ios_base::out | std::ios_base::app )\n {\n }\n\n \/** Move constructor *\/\n Log( Log&& other )\n : filename_( other.filename_ )\n , out_file_( filename_, std::ios_base::out | std::ios_base::app )\n {\n other.out_file_.close();\n }\n\n \/** Destructor *\/\n ~Log()\n {\n if ( out_file_.is_open() )\n {\n out_file_.close();\n }\n }\n\n \/** Copy assignment operator *\/\n Log& operator= ( const Log& other )\n {\n Log tmp( other ); \/\/ re-use copy-constructor\n *this = std::move( tmp ); \/\/ re-use move-assignment\n return *this;\n }\n\n \/** Move assignment operator *\/\n Log& operator= ( Log&& other)\n {\n std::swap( filename_, other.filename_ );\n other.out_file_.close();\n\n if ( out_file_.is_open() )\n {\n out_file_.close();\n }\n\n out_file_.open( filename_, std::ios_base::out | std::ios_base::app );\n\n return *this;\n }\n\n void logMessage( const std::string& message )\n {\n out_file_ << message << std::endl;\n }\n\n private:\n std::string filename_;\n std::ofstream out_file_;\n };\n}\n\n#endif \/\/ LOG_HPP\n<|endoftext|>"} {"text":"#ifndef CENTRALIZEDSIMULATIONMANAGER_HPP_\n#define CENTRALIZEDSIMULATIONMANAGER_HPP_\n\n#include \"simulation_manager_impl.h\"\n#include \"application.h\"\n\n#include \"simulation_stats.h\"\n#include \n#include \n\nusing std::deque;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::swap;\n\ntemplate < class ES >\nclass CentralizedSimulationManager : public SimulationManager< ES > {\npublic:\n typedef pair< event::vtime_t, size_t > pair_time_offset;\n typedef pair< object *, pair_time_offset > pair_object_timestamp;\n typedef deque< pair_object_timestamp > object_handle_map_t;\n typedef deque< object * > object_group_t;\n typedef pair< event::vtime_t, object_group_t * > concurrent_group_t;\n typedef map< event::vtime_t, object_group_t * > ordered_object_exe_t;\n typedef typename ordered_object_exe_t::iterator _iterator;\n\n CentralizedSimulationManager( shared_ptr< application >, system_id::manager_id_t id = 0 );\n CentralizedSimulationManager( shared_ptr< application >, shared_ptr< SimulationStats >, system_id::manager_id_t id = 0 );\n\n virtual const event::vtime_t & getSimulationTime() const;\n virtual bool isSimulationComplete() const;\n\n virtual const system_id getNextObjectID();\n\n virtual void registerObject( object * obj );\n virtual void unregisterObject( object * obj );\n\n virtual size_t getObjectCount() const;\n virtual object * getObject( const system_id & id ) const;\n\n virtual void initialize();\n virtual void simulate( const event::vtime_t & until );\n virtual void finalize();\n\n virtual void routeEvent( const event * evt );\n virtual void notifyNextEvent( const system_id & obj, const event::vtime_t & t );\n\n virtual ~CentralizedSimulationManager();\nprotected:\n\n virtual concurrent_group_t getNextObjectGroup();\n\n virtual bool setSimulationTime( const event::vtime_t & t );\n virtual void setSimulateUntil( const event::vtime_t & t );\n\n void moveObject( object * obj, event::vtime_t t );\n\n shared_ptr< application > m_app;\n\n event::vtime_t m_sim_time;\n event::vtime_t m_sim_until;\n bool m_sim_complete;\n\n object_handle_map_t m_objects;\n ordered_object_exe_t m_ordered_objs;\n\n unsigned int m_nPendingEvents, m_nProcessedEvents;\n unsigned int m_nRegisteredObjs;\n unsigned int m_nUnregisterCalls;\n\n shared_ptr< SimulationStats > m_stats;\n};\n\n\/\/\n\/\/ Implementation\n\/\/\n\ntemplate < class ES >\nCentralizedSimulationManager::CentralizedSimulationManager( shared_ptr< application > app, system_id::manager_id_t id ) :\n SimulationManager(id),\n m_app( app ),\n m_sim_time( SystemClock::ZERO ),\n m_sim_until( SystemClock::POSITIVE_INFINITY ),\n m_sim_complete(false),\n m_nPendingEvents(0),\n m_nProcessedEvents(0),\n m_nRegisteredObjs(0),\n m_nUnregisterCalls(0),\n m_stats( new SimulationStats() )\n{}\n\ntemplate < class ES >\nCentralizedSimulationManager::CentralizedSimulationManager( shared_ptr< application > app, shared_ptr< SimulationStats > stats, system_id::manager_id_t id ) :\n SimulationManager(id),\n m_app( app ),\n m_sim_time( SystemClock::ZERO ),\n m_sim_until( SystemClock::POSITIVE_INFINITY ),\n m_sim_complete(false),\n m_nPendingEvents(0),\n m_nProcessedEvents(0),\n m_nRegisteredObjs(0),\n m_nUnregisterCalls(0),\n m_stats( stats )\n{}\n\ntemplate < class ES >\nCentralizedSimulationManager::~CentralizedSimulationManager() {\n cout << m_nUnregisterCalls << \" objects unregistered BEFORE destruction\" << endl;\n unsigned int nUnfinalized = 0;\n while( !m_objects.empty() ) {\n object * tmp = m_objects.back().first;\n m_objects.pop_back();\n if( tmp ) {\n ++nUnfinalized;\n tmp->finalize();\n delete tmp;\n }\n }\n cout << nUnfinalized << \" objects were finalized AFTER simulation finalization.\" << endl;\n m_ordered_objs.clear();\n}\n\ntemplate < class ES >\nconst system_id CentralizedSimulationManager::getNextObjectID() {\n system_id nid( this->getManagerID(), m_objects.size() );\n m_objects.push_back( make_pair( (object *)NULL, make_pair(SystemClock::POSITIVE_INFINITY, 0 ) ) );\n return nid;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::registerObject( object * obj ) {\n if( obj == NULL ) return;\n\n assert( obj->getSystemID() != this->m_id );\n\n if( m_objects[ obj->getObjectID() ].first == NULL ) {\n m_objects[ obj->getObjectID() ].first = obj;\n ++m_nRegisteredObjs;\n } else {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::unregisterObject( object * obj ) {\n ++m_nUnregisterCalls;\n if( obj == NULL ) return;\n\n if( m_objects[ obj->getObjectID() ].first != NULL ) {\n m_nPendingEvents += obj->pendingEventCount(obj->getSystemID());\n m_nProcessedEvents += obj->processedEventCount(obj->getSystemID());\n\n if( m_objects[ obj->getObjectID() ].second.first != SystemClock::POSITIVE_INFINITY ) {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n\n m_objects[ obj->getObjectID() ].first = NULL;\n --m_nRegisteredObjs;\n }\n}\n\ntemplate < class ES >\nvoid CentralizedSimulationManager::moveObject( object * obj, event::vtime_t newT ) {\n pair_time_offset pto = m_objects[ obj->getObjectID() ].second;\n\n if( pto.first != SystemClock::POSITIVE_INFINITY ) {\n \/\/ objects with time set to POSITIVE_INFINITY are not \"queued\"\n _iterator it = m_ordered_objs.find( pto.first );\n\n if( it != m_ordered_objs.end() ) {\n object_group_t * g = it->second;\n\n assert( pto.second < g->size() && g->at( pto.second ) == obj );\n\n if( g->back() != obj ) {\n \/\/ object is not at the end of vector\n \/\/ swap with object at the end of the vector\n \/\/ and update that objects offset value to\n \/\/ be that of the current obj \n system_id other = g->back()->getSystemID();\n\n (*g)[ pto.second ] = g->back();\n g->back() = obj;\n\n assert( g->back() == obj );\n\n m_objects[ other.getObjectID() ].second.second = pto.second;\n }\n g->pop_back();\n }\n }\n\n m_objects[ obj->getObjectID() ].second.first = newT;\n if( newT != SystemClock::POSITIVE_INFINITY ) {\n _iterator it = m_ordered_objs.find( newT );\n if( it == m_ordered_objs.end() ) {\n \/\/ no other objects have events scheduled at newT\n pair< _iterator, bool > res = m_ordered_objs.insert( make_pair(newT, new object_group_t() ) );\n assert( res.second );\n it = res.first;\n }\n\n m_objects[ obj->getObjectID() ].second.second = it->second->size();\n it->second->push_back( obj );\n }\n}\n\ntemplate< class ES >\nsize_t CentralizedSimulationManager::getObjectCount() const {\n return m_nRegisteredObjs;\n}\n\n\ntemplate< class ES >\nobject * CentralizedSimulationManager::getObject( const system_id & id ) const {\n return m_objects[ id.getObjectID() ].first;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::routeEvent( const event * evt ) {\n assert( m_objects.size() > evt->getReceiver().getObjectID() );\n m_objects[ evt->getReceiver().getObjectID() ].first->receiveEvent( evt );\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::notifyNextEvent( const system_id & obj, const event::vtime_t & t ) {\n moveObject( m_objects[ obj.getObjectID() ].first, t );\n}\n\ntemplate< class ES >\ntypename CentralizedSimulationManager::concurrent_group_t CentralizedSimulationManager::getNextObjectGroup() {\n concurrent_group_t ot = *m_ordered_objs.begin();\n m_ordered_objs.erase( m_ordered_objs.begin() );\n\n return ot;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::initialize() {\n m_stats->startPhase( INIT_PHASE_K );\n m_app->initialize();\n m_stats->stopPhase( INIT_PHASE_K );\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::simulate( const event::vtime_t & until ) {\n setSimulateUntil( until );\n\n m_stats->startPhase( SIMULATE_PHASE_K );\n while(! m_ordered_objs.empty() ) {\n concurrent_group_t ot = getNextObjectGroup();\n\n if( ot.first == SystemClock::POSITIVE_INFINITY || setSimulationTime( ot.first ) ) {\n break;\n }\n\n\/\/ for( object_group_t::iterator it = ot.second->begin(); it != ot.second->end(); it++ ) {\n while( !ot.second->empty() ) {\n object * obj = ot.second->back();\n ot.second->pop_back();\n\n m_objects[ obj->getObjectID() ].second.first = SystemClock::POSITIVE_INFINITY;\n obj->updateLocalTime(ot.first);\n obj->process();\n\n const event * e = obj->peekEvent( obj->getSystemID() );\n if( e != NULL ) {\n moveObject( obj, e->getReceived() );\n } else {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n }\n\n delete ot.second;\n }\n\n m_stats->stopPhase( SIMULATE_PHASE_K );\n\n cout << \"End simulation time: \" << getSimulationTime() << endl;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::finalize() {\n m_stats->startPhase( FINALIZE_PHASE_K );\n\n m_app->finalize();\n\n m_stats->stopPhase( FINALIZE_PHASE_K );\n\n m_stats->setProcessedEvents( m_nProcessedEvents );\n m_stats->setPendingEvents( m_nPendingEvents );\n\n}\n\ntemplate< class ES >\nbool CentralizedSimulationManager::isSimulationComplete() const {\n return m_sim_complete;\n}\n\ntemplate< class ES >\nbool CentralizedSimulationManager::setSimulationTime( const event::vtime_t & t ) {\n assert( m_sim_time <= t );\n if( m_sim_time != t ) {\n m_sim_time = t;\n m_sim_complete = (m_sim_time >= m_sim_until);\n }\n\n return m_sim_complete;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::setSimulateUntil( const event::vtime_t & t ) {\n m_sim_until = t;\n}\n\ntemplate< class ES >\nconst event::vtime_t & CentralizedSimulationManager::getSimulationTime() const {\n return m_sim_time;\n}\n#endif \/\/ CENTRALIZEDSIMULATIONMANAGER_HPP_\nWent back to vector container for object_group_t, instead of deque. The vector seems to offer slightly better performance#ifndef CENTRALIZEDSIMULATIONMANAGER_HPP_\n#define CENTRALIZEDSIMULATIONMANAGER_HPP_\n\n#include \"simulation_manager_impl.h\"\n#include \"application.h\"\n\n#include \"simulation_stats.h\"\n#include \n#include \n\nusing std::deque;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::swap;\n\ntemplate < class ES >\nclass CentralizedSimulationManager : public SimulationManager< ES > {\npublic:\n typedef pair< event::vtime_t, size_t > pair_time_offset;\n typedef pair< object *, pair_time_offset > pair_object_timestamp;\n typedef deque< pair_object_timestamp > object_handle_map_t;\n typedef vector< object * > object_group_t;\n typedef pair< event::vtime_t, object_group_t * > concurrent_group_t;\n typedef map< event::vtime_t, object_group_t * > ordered_object_exe_t;\n typedef typename ordered_object_exe_t::iterator _iterator;\n\n CentralizedSimulationManager( shared_ptr< application >, system_id::manager_id_t id = 0 );\n CentralizedSimulationManager( shared_ptr< application >, shared_ptr< SimulationStats >, system_id::manager_id_t id = 0 );\n\n virtual const event::vtime_t & getSimulationTime() const;\n virtual bool isSimulationComplete() const;\n\n virtual const system_id getNextObjectID();\n\n virtual void registerObject( object * obj );\n virtual void unregisterObject( object * obj );\n\n virtual size_t getObjectCount() const;\n virtual object * getObject( const system_id & id ) const;\n\n virtual void initialize();\n virtual void simulate( const event::vtime_t & until );\n virtual void finalize();\n\n virtual void routeEvent( const event * evt );\n virtual void notifyNextEvent( const system_id & obj, const event::vtime_t & t );\n\n virtual ~CentralizedSimulationManager();\nprotected:\n\n virtual concurrent_group_t getNextObjectGroup();\n\n virtual bool setSimulationTime( const event::vtime_t & t );\n virtual void setSimulateUntil( const event::vtime_t & t );\n\n void moveObject( object * obj, event::vtime_t t );\n\n shared_ptr< application > m_app;\n\n event::vtime_t m_sim_time;\n event::vtime_t m_sim_until;\n bool m_sim_complete;\n\n object_handle_map_t m_objects;\n ordered_object_exe_t m_ordered_objs;\n\n unsigned int m_nPendingEvents, m_nProcessedEvents;\n unsigned int m_nRegisteredObjs;\n unsigned int m_nUnregisterCalls;\n\n shared_ptr< SimulationStats > m_stats;\n};\n\n\/\/\n\/\/ Implementation\n\/\/\n\ntemplate < class ES >\nCentralizedSimulationManager::CentralizedSimulationManager( shared_ptr< application > app, system_id::manager_id_t id ) :\n SimulationManager(id),\n m_app( app ),\n m_sim_time( SystemClock::ZERO ),\n m_sim_until( SystemClock::POSITIVE_INFINITY ),\n m_sim_complete(false),\n m_nPendingEvents(0),\n m_nProcessedEvents(0),\n m_nRegisteredObjs(0),\n m_nUnregisterCalls(0),\n m_stats( new SimulationStats() )\n{}\n\ntemplate < class ES >\nCentralizedSimulationManager::CentralizedSimulationManager( shared_ptr< application > app, shared_ptr< SimulationStats > stats, system_id::manager_id_t id ) :\n SimulationManager(id),\n m_app( app ),\n m_sim_time( SystemClock::ZERO ),\n m_sim_until( SystemClock::POSITIVE_INFINITY ),\n m_sim_complete(false),\n m_nPendingEvents(0),\n m_nProcessedEvents(0),\n m_nRegisteredObjs(0),\n m_nUnregisterCalls(0),\n m_stats( stats )\n{}\n\ntemplate < class ES >\nCentralizedSimulationManager::~CentralizedSimulationManager() {\n cout << m_nUnregisterCalls << \" objects unregistered BEFORE destruction\" << endl;\n unsigned int nUnfinalized = 0;\n while( !m_objects.empty() ) {\n object * tmp = m_objects.back().first;\n m_objects.pop_back();\n if( tmp ) {\n ++nUnfinalized;\n tmp->finalize();\n delete tmp;\n }\n }\n cout << nUnfinalized << \" objects were finalized AFTER simulation finalization.\" << endl;\n m_ordered_objs.clear();\n}\n\ntemplate < class ES >\nconst system_id CentralizedSimulationManager::getNextObjectID() {\n system_id nid( this->getManagerID(), m_objects.size() );\n m_objects.push_back( make_pair( (object *)NULL, make_pair(SystemClock::POSITIVE_INFINITY, 0 ) ) );\n return nid;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::registerObject( object * obj ) {\n if( obj == NULL ) return;\n\n assert( obj->getSystemID() != this->m_id );\n\n if( m_objects[ obj->getObjectID() ].first == NULL ) {\n m_objects[ obj->getObjectID() ].first = obj;\n ++m_nRegisteredObjs;\n } else {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::unregisterObject( object * obj ) {\n ++m_nUnregisterCalls;\n if( obj == NULL ) return;\n\n if( m_objects[ obj->getObjectID() ].first != NULL ) {\n m_nPendingEvents += obj->pendingEventCount(obj->getSystemID());\n m_nProcessedEvents += obj->processedEventCount(obj->getSystemID());\n\n if( m_objects[ obj->getObjectID() ].second.first != SystemClock::POSITIVE_INFINITY ) {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n\n m_objects[ obj->getObjectID() ].first = NULL;\n --m_nRegisteredObjs;\n }\n}\n\ntemplate < class ES >\nvoid CentralizedSimulationManager::moveObject( object * obj, event::vtime_t newT ) {\n pair_time_offset pto = m_objects[ obj->getObjectID() ].second;\n\n if( pto.first != SystemClock::POSITIVE_INFINITY ) {\n \/\/ objects with time set to POSITIVE_INFINITY are not \"queued\"\n _iterator it = m_ordered_objs.find( pto.first );\n\n if( it != m_ordered_objs.end() ) {\n object_group_t * g = it->second;\n\n assert( pto.second < g->size() && g->at( pto.second ) == obj );\n\n if( g->back() != obj ) {\n \/\/ object is not at the end of vector\n \/\/ swap with object at the end of the vector\n \/\/ and update that objects offset value to\n \/\/ be that of the current obj \n system_id other = g->back()->getSystemID();\n\n (*g)[ pto.second ] = g->back();\n g->back() = obj;\n\n assert( g->back() == obj );\n\n m_objects[ other.getObjectID() ].second.second = pto.second;\n }\n g->pop_back();\n }\n }\n\n m_objects[ obj->getObjectID() ].second.first = newT;\n if( newT != SystemClock::POSITIVE_INFINITY ) {\n _iterator it = m_ordered_objs.find( newT );\n if( it == m_ordered_objs.end() ) {\n \/\/ no other objects have events scheduled at newT\n pair< _iterator, bool > res = m_ordered_objs.insert( make_pair(newT, new object_group_t() ) );\n assert( res.second );\n it = res.first;\n\n\/\/ it->second->reserve( m_nRegisteredObjs );\n }\n\n m_objects[ obj->getObjectID() ].second.second = it->second->size();\n it->second->push_back( obj );\n }\n}\n\ntemplate< class ES >\nsize_t CentralizedSimulationManager::getObjectCount() const {\n return m_nRegisteredObjs;\n}\n\n\ntemplate< class ES >\nobject * CentralizedSimulationManager::getObject( const system_id & id ) const {\n return m_objects[ id.getObjectID() ].first;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::routeEvent( const event * evt ) {\n assert( m_objects.size() > evt->getReceiver().getObjectID() );\n m_objects[ evt->getReceiver().getObjectID() ].first->receiveEvent( evt );\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::notifyNextEvent( const system_id & obj, const event::vtime_t & t ) {\n moveObject( m_objects[ obj.getObjectID() ].first, t );\n}\n\ntemplate< class ES >\ntypename CentralizedSimulationManager::concurrent_group_t CentralizedSimulationManager::getNextObjectGroup() {\n concurrent_group_t ot = *m_ordered_objs.begin();\n m_ordered_objs.erase( m_ordered_objs.begin() );\n\n return ot;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::initialize() {\n m_stats->startPhase( INIT_PHASE_K );\n m_app->initialize();\n m_stats->stopPhase( INIT_PHASE_K );\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::simulate( const event::vtime_t & until ) {\n setSimulateUntil( until );\n\n m_stats->startPhase( SIMULATE_PHASE_K );\n while(! m_ordered_objs.empty() ) {\n concurrent_group_t ot = getNextObjectGroup();\n\n if( ot.first == SystemClock::POSITIVE_INFINITY || setSimulationTime( ot.first ) ) {\n break;\n }\n\n\/\/ for( object_group_t::iterator it = ot.second->begin(); it != ot.second->end(); it++ ) {\n while( !ot.second->empty() ) {\n object * obj = ot.second->back();\n ot.second->pop_back();\n\n m_objects[ obj->getObjectID() ].second.first = SystemClock::POSITIVE_INFINITY;\n obj->updateLocalTime(ot.first);\n obj->process();\n\n const event * e = obj->peekEvent( obj->getSystemID() );\n if( e != NULL ) {\n moveObject( obj, e->getReceived() );\n } else {\n moveObject( obj, SystemClock::POSITIVE_INFINITY );\n }\n }\n\n delete ot.second;\n }\n\n m_stats->stopPhase( SIMULATE_PHASE_K );\n\n cout << \"End simulation time: \" << getSimulationTime() << endl;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::finalize() {\n m_stats->startPhase( FINALIZE_PHASE_K );\n\n m_app->finalize();\n\n m_stats->stopPhase( FINALIZE_PHASE_K );\n\n m_stats->setProcessedEvents( m_nProcessedEvents );\n m_stats->setPendingEvents( m_nPendingEvents );\n\n}\n\ntemplate< class ES >\nbool CentralizedSimulationManager::isSimulationComplete() const {\n return m_sim_complete;\n}\n\ntemplate< class ES >\nbool CentralizedSimulationManager::setSimulationTime( const event::vtime_t & t ) {\n assert( m_sim_time <= t );\n if( m_sim_time != t ) {\n m_sim_time = t;\n m_sim_complete = (m_sim_time >= m_sim_until);\n }\n\n return m_sim_complete;\n}\n\ntemplate< class ES >\nvoid CentralizedSimulationManager::setSimulateUntil( const event::vtime_t & t ) {\n m_sim_until = t;\n}\n\ntemplate< class ES >\nconst event::vtime_t & CentralizedSimulationManager::getSimulationTime() const {\n return m_sim_time;\n}\n#endif \/\/ CENTRALIZEDSIMULATIONMANAGER_HPP_\n<|endoftext|>"} {"text":"\/**\n * \\file macros.hpp\n *\n * \\brief TODO: Add description\n *\n * \\author Matthew Rodusek (matthew.rodusek@gmail.com)\n *\/\n#ifndef BIT_MEMORY_MACROS_HPP\n#define BIT_MEMORY_MACROS_HPP\n\n#ifdef BIT_MEMORY_LIKELY\n#error BIT_MEMORY_LIKELY cannot be defined outside of macros.hpp\n#endif\n\n#ifdef BIT_MEMORY_UNLIKELY\n#error BIT_MEMORY_UNLIKELY cannot be defined outside of macros.hpp\n#endif\n\n#ifdef BIT_MEMORY_ASSUME\n#error BIT_MEMORY_ASSUME cannot be defined outside of macros.hpp\n#endif\n\n#ifdef __GNUC__\n#define BIT_MEMORY_LIKELY(x) __builtin_expect(!!(x),1)\n#else\n#define BIT_MEMORY_LIKELY(x) x\n#endif\n\n#ifdef __GNUC__\n#define BIT_MEMORY_UNLIKELY(x) __builtin_expect(!!(x),0)\n#else\n#define BIT_MEMORY_UNLIKELY(x) x\n#endif\n\n#if defined(__clang__)\n#define BIT_MEMORY_ASSUME(x) __builtin_assume(x)\n#elif defined(_MSC_VER)\n#define BIT_MEMORY_ASSUME(x) __assume(x)\n#else\n#define BIT_MEMORY_ASSUME(x) x\n#endif\n\n#endif \/* BIT_MEMORY_MACROS_HPP *\/\nAdded 'BIT_MEMORY_UNUSED' macro\/**\n * \\file macros.hpp\n *\n * \\brief TODO: Add description\n *\n * \\author Matthew Rodusek (matthew.rodusek@gmail.com)\n *\/\n#ifndef BIT_MEMORY_MACROS_HPP\n#define BIT_MEMORY_MACROS_HPP\n\n#ifdef BIT_MEMORY_LIKELY\n#error BIT_MEMORY_LIKELY cannot be defined outside of macros.hpp\n#endif\n\n#ifdef BIT_MEMORY_UNLIKELY\n#error BIT_MEMORY_UNLIKELY cannot be defined outside of macros.hpp\n#endif\n\n#ifdef BIT_MEMORY_ASSUME\n#error BIT_MEMORY_ASSUME cannot be defined outside of macros.hpp\n#endif\n\n#ifdef BIT_MEMORY_UNUSED\n#error BIT_MEMORY_UNUSED cannot be defined outside of macros.hpp\n#endif\n\n\n#ifdef __GNUC__\n#define BIT_MEMORY_LIKELY(x) __builtin_expect(!!(x),1)\n#else\n#define BIT_MEMORY_LIKELY(x) x\n#endif\n\n#ifdef __GNUC__\n#define BIT_MEMORY_UNLIKELY(x) __builtin_expect(!!(x),0)\n#else\n#define BIT_MEMORY_UNLIKELY(x) x\n#endif\n\n#if defined(__clang__)\n#define BIT_MEMORY_ASSUME(x) __builtin_assume(x)\n#elif defined(_MSC_VER)\n#define BIT_MEMORY_ASSUME(x) __assume(x)\n#else\n#define BIT_MEMORY_ASSUME(x) x\n#endif\n\n#define BIT_MEMORY_UNUSED(x) (void) x\n\n#endif \/* BIT_MEMORY_MACROS_HPP *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ Created by marandil on 08.09.15.\n\/\/\n\n#ifndef MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\n#define MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mdl\n{\n \/* Class providing a pool of workers, which can asynchronously perform selected tasks.\n *\n * Currently, there are two strategies at which the tasks can be assigned and two\n * methods of creating tasks.\n *\n * Strategies: (see )\n * Methods: , \n *\/\n class thread_pool : protected mdl::exception_handler, protected mdl::handler\n {\n public:\n \/* Strategies that can be used to assign tasks to workers *\/\n enum class strategy\n {\n \/* In this strategy, each worker performs equal numbers of tasks.\n * Whenever a new task is created, it's posted to the next worker in queue\n * and the worker is requeued.\n * This strategy might cause some workers to be idle for extended periods of time,\n * if their jobs are less time consuming than the others'.\n *\/\n round_robin,\n \/* In this strategy, each worker keeps track of the end of it's message queue.\n * Once it's reached, it asks the for a new task and becomes temporarily\n * idle, if no tasks are queued in . This aims at counteracting the situation\n * in which some tasks have long task queues, while others are idle, as the tasks are\n * assigned one-at-a-time.\n *\/\n dynamic\n };\n\n protected:\n \/* Implementation of that keeps track of it's parent, and registers him as\n * exception and message handler\n *\/\n struct thread_handler : public looper_thread\n {\n thread_pool &parent;\n unsigned id;\n\n thread_handler(unsigned id, thread_pool &parent) :\n id(id),\n parent(parent),\n looper_thread(static_cast(parent),\n static_cast(parent)) { }\n };\n\n \/\/ Implementation of interface. Will enqueue pending exceptions in exception_queue.\n virtual void handle_exception(std::exception_ptr);\n\n \/\/ Implementation of interface. keeps track of empty_queue_guard messages in case of\n \/\/ dynamic task allocation.\n virtual bool handle_message(mdl::message_ptr);\n\n \/\/ Constructor helper, enqueues empty_queue_guard messages for all workers.\n void initialize_queues();\n\n typedef mdl::const_vector pool_type;\n \/\/ Pool of all available s.\n pool_type pool;\n \/\/ Iterator to the next handler in case of round_robin task assignment strategy.\n pool_type::iterator next_robin;\n\n std::mutex exception_queue_lock;\n \/\/ Queue holding exception_ptr to all exceptions thrown in the workers.\n std::queue exception_queue;\n\n std::mutex task_queue_lock;\n \/\/ Queue of messages to be assigned to workers in case of dynamic task assignment.\n std::queue task_queue;\n\n\n void throw_if_nonempty();\n\n void stop_and_join();\n\n void send_message(message_ptr);\n\n unsigned processes;\n strategy task_assigning_strategy;\n\n public:\n \/* Create a with workers and strategy.\n * @processes Number of worker threads to create. Defaults to std::thread::hardware_concurrency() or 1, if undefined.\n * @task_assigning_strategy Strategy of assigning tasks to the workers. Defaults to strategy::round_robin.\n *\/\n thread_pool(unsigned processes = helper::hw_concurrency(),\n strategy task_assigning_strategy = strategy::round_robin) :\n processes(processes),\n task_assigning_strategy(task_assigning_strategy),\n pool(pool_type::make_indexed(processes, *this)),\n next_robin(pool.begin())\n {\n initialize_queues();\n }\n\n \/\/ Destructor. Joins all workers and blocks untill all the tasks are done.\n ~thread_pool(void)\n {\n stop_and_join();\n }\n\n \/\/ The number of workers (threads).\n mdl::const_accessor workers{processes};\n\n \/* Execute the function asynchronously.\n * @fn Function to call.\n * @args... Function arguments.\n *\n * Reassembles the standard function std::async, with few exceptions.\n * First of all, the work will be run on one of the workers in the .\n * Second, the arguments passed to the function have to be packed inside a lambda expression,\n * which might cause problems with some complex or uncopyable types, so it's better to\n * explicitly envelop all references with reference_wrappers, etc.\n *\n * @return std::future, where T is the result type of Fn(Args...), which will hold the\n * result of the fn(args...) once finished.\n *\/\n template::type>\n std::future\n async(Fn &&fn, Args &&... args)\n {\n std::shared_ptr> promise = std::make_shared>();\n auto lambda = [promise, fn, args...](void)\n { promise->set_value(fn(std::move(args)...)); };\n send_message(std::make_shared(lambda));\n return promise->get_future();\n };\n\n \/* Map all values from one range into another asynchronously.\n * @first Random access iterator pointing to the first element of the range (inkl.).\n * @last Random access iterator pointing to the last element of the range (excl.).\n * @output_first Random access iterator pointing to the first element of the output range.\n * @function Function to call on all elements of range [first, last), which results will\n * be stored in [output_first, output_first + (last - first))\n *\n * Each task is created with an call. One additional thread is spawned (using std::async)\n * to keep track of promise of completing the map operation.\n *\n * @return std::future that becomes fulfilled once all elements are mapped.\n *\/\n template\n std::future\n map(RandomAccessIteratorIn first, RandomAccessIteratorIn last, RandomAccessIteratorOut output_first, Fn function)\n {\n typedef typename std::iterator_traits::value_type value_type;\n typedef typename std::iterator_traits::value_type result_type;\n typedef typename std::result_of::type function_result_type;\n\n static_assert(std::is_convertible::value, \"Function return type not convertible to iterator value_type\");\n\n \/\/ Count the distance between last and first:\n ptrdiff_t n = std::distance(first, last);\n if(n < 0) mdl_throw(make_ia_exception, \"Invalid iterator range\", \"first, last\", std::make_pair(first, last));\n \/\/ Create n async tasks for all elements in range:\n auto futures = std::make_shared>>(n);\n for(size_t i = 0; first != last; ++first, ++output_first, ++i)\n {\n futures->at(i) = async([first, output_first, function] ()\n {\n *output_first = function(*first);\n return true;\n });\n }\n return std::async([futures]()\n {\n for(auto& job : (*futures))\n job.get();\n return;\n });\n }\n };\n}\n\n#endif \/\/MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\nFixed `async` function to properly compile under GCC 5.3\/\/\n\/\/ Created by marandil on 08.09.15.\n\/\/\n\n#ifndef MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\n#define MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mdl\n{\n \/* Class providing a pool of workers, which can asynchronously perform selected tasks.\n *\n * Currently, there are two strategies at which the tasks can be assigned and two\n * methods of creating tasks.\n *\n * Strategies: (see )\n * Methods: , \n *\/\n class thread_pool : protected mdl::exception_handler, protected mdl::handler\n {\n public:\n \/* Strategies that can be used to assign tasks to workers *\/\n enum class strategy\n {\n \/* In this strategy, each worker performs equal numbers of tasks.\n * Whenever a new task is created, it's posted to the next worker in queue\n * and the worker is requeued.\n * This strategy might cause some workers to be idle for extended periods of time,\n * if their jobs are less time consuming than the others'.\n *\/\n round_robin,\n \/* In this strategy, each worker keeps track of the end of it's message queue.\n * Once it's reached, it asks the for a new task and becomes temporarily\n * idle, if no tasks are queued in . This aims at counteracting the situation\n * in which some tasks have long task queues, while others are idle, as the tasks are\n * assigned one-at-a-time.\n *\/\n dynamic\n };\n\n protected:\n \/* Implementation of that keeps track of it's parent, and registers him as\n * exception and message handler\n *\/\n struct thread_handler : public looper_thread\n {\n thread_pool &parent;\n unsigned id;\n\n thread_handler(unsigned id, thread_pool &parent) :\n id(id),\n parent(parent),\n looper_thread(static_cast(parent),\n static_cast(parent)) { }\n };\n\n \/\/ Implementation of interface. Will enqueue pending exceptions in exception_queue.\n virtual void handle_exception(std::exception_ptr);\n\n \/\/ Implementation of interface. keeps track of empty_queue_guard messages in case of\n \/\/ dynamic task allocation.\n virtual bool handle_message(mdl::message_ptr);\n\n \/\/ Constructor helper, enqueues empty_queue_guard messages for all workers.\n void initialize_queues();\n\n typedef mdl::const_vector pool_type;\n \/\/ Pool of all available s.\n pool_type pool;\n \/\/ Iterator to the next handler in case of round_robin task assignment strategy.\n pool_type::iterator next_robin;\n\n std::mutex exception_queue_lock;\n \/\/ Queue holding exception_ptr to all exceptions thrown in the workers.\n std::queue exception_queue;\n\n std::mutex task_queue_lock;\n \/\/ Queue of messages to be assigned to workers in case of dynamic task assignment.\n std::queue task_queue;\n\n\n void throw_if_nonempty();\n\n void stop_and_join();\n\n void send_message(message_ptr);\n\n unsigned processes;\n strategy task_assigning_strategy;\n\n public:\n \/* Create a with workers and strategy.\n * @processes Number of worker threads to create. Defaults to std::thread::hardware_concurrency() or 1, if undefined.\n * @task_assigning_strategy Strategy of assigning tasks to the workers. Defaults to strategy::round_robin.\n *\/\n thread_pool(unsigned processes = helper::hw_concurrency(),\n strategy task_assigning_strategy = strategy::round_robin) :\n processes(processes),\n task_assigning_strategy(task_assigning_strategy),\n pool(pool_type::make_indexed(processes, *this)),\n next_robin(pool.begin())\n {\n initialize_queues();\n }\n\n \/\/ Destructor. Joins all workers and blocks untill all the tasks are done.\n ~thread_pool(void)\n {\n stop_and_join();\n }\n\n \/\/ The number of workers (threads).\n mdl::const_accessor workers{processes};\n\n \/* Execute the function asynchronously.\n * @fn Function to call.\n * @args... Function arguments.\n *\n * Reassembles the standard function std::async, with few exceptions.\n * First of all, the work will be run on one of the workers in the .\n * Second, the arguments passed to the function have to be packed inside a lambda expression,\n * which might cause problems with some complex or uncopyable types, so it's better to\n * explicitly envelop all references with reference_wrappers, etc.\n *\n * @return std::future, where T is the result type of Fn(Args...), which will hold the\n * result of the fn(args...) once finished.\n *\/\n template::type>\n std::future\n async(Fn &&fn, Args &&... args)\n {\n std::shared_ptr> promise = std::make_shared>();\n std::function::type...)> floc = fn;\n auto lambda = [promise, floc, args...](void)\n { promise->set_value(floc(std::move(args)...)); };\n send_message(std::make_shared(lambda));\n return promise->get_future();\n };\n\n \/* Map all values from one range into another asynchronously.\n * @first Random access iterator pointing to the first element of the range (inkl.).\n * @last Random access iterator pointing to the last element of the range (excl.).\n * @output_first Random access iterator pointing to the first element of the output range.\n * @function Function to call on all elements of range [first, last), which results will\n * be stored in [output_first, output_first + (last - first))\n *\n * Each task is created with an call. One additional thread is spawned (using std::async)\n * to keep track of promise of completing the map operation.\n *\n * @return std::future that becomes fulfilled once all elements are mapped.\n *\/\n template\n std::future\n map(RandomAccessIteratorIn first, RandomAccessIteratorIn last, RandomAccessIteratorOut output_first, Fn function)\n {\n typedef typename std::iterator_traits::value_type value_type;\n typedef typename std::iterator_traits::value_type result_type;\n typedef typename std::result_of::type function_result_type;\n\n static_assert(std::is_convertible::value, \"Function return type not convertible to iterator value_type\");\n\n \/\/ Count the distance between last and first:\n ptrdiff_t n = std::distance(first, last);\n if(n < 0) mdl_throw(make_ia_exception, \"Invalid iterator range\", \"first, last\", std::make_pair(first, last));\n \/\/ Create n async tasks for all elements in range:\n auto futures = std::make_shared>>(n);\n for(size_t i = 0; first != last; ++first, ++output_first, ++i)\n {\n futures->at(i) = async([first, output_first, function] ()\n {\n *output_first = function(*first);\n return true;\n });\n }\n return std::async([futures]()\n {\n for(auto& job : (*futures))\n job.get();\n return;\n });\n }\n };\n}\n\n#endif \/\/MDLUTILS_MULTITHREADING_THREAD_POOL_HPP\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace hadesmem\r\n{\r\n\r\nnamespace detail\r\n{\r\n\r\n\/\/ TODO: Turn this into a template like the old EnsureCleanup class template?\r\nclass SmartHandle\r\n{\r\npublic:\r\n HADESMEM_CONSTEXPR SmartHandle() HADESMEM_NOEXCEPT\r\n : handle_(nullptr), \r\n invalid_(nullptr)\r\n { }\r\n \r\n explicit HADESMEM_CONSTEXPR SmartHandle(HANDLE handle) HADESMEM_NOEXCEPT\r\n : handle_(handle), \r\n invalid_(nullptr)\r\n { }\r\n\r\n explicit HADESMEM_CONSTEXPR SmartHandle(HANDLE handle, HANDLE invalid) HADESMEM_NOEXCEPT\r\n : handle_(handle), \r\n invalid_(invalid)\r\n { }\r\n\r\n SmartHandle& operator=(HANDLE handle) HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n\r\n handle_ = handle;\r\n\r\n return *this;\r\n }\r\n\r\n SmartHandle(SmartHandle&& other) HADESMEM_NOEXCEPT\r\n : handle_(other.handle_), \r\n invalid_(other.invalid_)\r\n {\r\n other.handle_ = nullptr;\r\n }\r\n\r\n SmartHandle& operator=(SmartHandle&& other) HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n\r\n handle_ = other.handle_;\r\n other.handle_ = other.invalid_;\r\n\r\n invalid_ = other.invalid_;\r\n\r\n return *this;\r\n }\r\n\r\n ~SmartHandle() HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n }\r\n\r\n HANDLE GetHandle() const HADESMEM_NOEXCEPT\r\n {\r\n return handle_;\r\n }\r\n\r\n HANDLE GetInvalid() const HADESMEM_NOEXCEPT\r\n {\r\n return invalid_;\r\n }\r\n\r\n bool IsValid() const HADESMEM_NOEXCEPT\r\n {\r\n return GetHandle() != GetInvalid();\r\n }\r\n\r\n void Cleanup()\r\n {\r\n if (handle_ == invalid_)\r\n {\r\n return;\r\n }\r\n\r\n if (!::CloseHandle(handle_))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n HADESMEM_THROW_EXCEPTION(Error() << \r\n ErrorString(\"CloseHandle failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n\r\n handle_ = invalid_;\r\n }\r\n\r\nprivate:\r\n SmartHandle(SmartHandle const& other) HADESMEM_DELETED_FUNCTION;\r\n SmartHandle& operator=(SmartHandle const& other) HADESMEM_DELETED_FUNCTION;\r\n\r\n void CleanupUnchecked() HADESMEM_NOEXCEPT\r\n {\r\n try\r\n {\r\n Cleanup();\r\n }\r\n catch (std::exception const& e)\r\n {\r\n (void)e;\r\n\r\n \/\/ WARNING: Handle is leaked if 'Cleanup' fails.\r\n HADESMEM_ASSERT(boost::diagnostic_information(e).c_str() && false);\r\n\r\n handle_ = invalid_;\r\n }\r\n }\r\n\r\n HANDLE handle_;\r\n HANDLE invalid_;\r\n};\r\n\r\n}\r\n\r\n}\r\n* Fix SmartHandle move constructor. It was not correctly setting the moved-from object's state.\/\/ Copyright (C) 2010-2013 Joshua Boyce.\r\n\/\/ See the file COPYING for copying permission.\r\n\r\n#pragma once\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace hadesmem\r\n{\r\n\r\nnamespace detail\r\n{\r\n\r\n\/\/ TODO: Turn this into a template like the old EnsureCleanup class template?\r\nclass SmartHandle\r\n{\r\npublic:\r\n HADESMEM_CONSTEXPR SmartHandle() HADESMEM_NOEXCEPT\r\n : handle_(nullptr), \r\n invalid_(nullptr)\r\n { }\r\n \r\n explicit HADESMEM_CONSTEXPR SmartHandle(HANDLE handle) HADESMEM_NOEXCEPT\r\n : handle_(handle), \r\n invalid_(nullptr)\r\n { }\r\n\r\n explicit HADESMEM_CONSTEXPR SmartHandle(HANDLE handle, HANDLE invalid) HADESMEM_NOEXCEPT\r\n : handle_(handle), \r\n invalid_(invalid)\r\n { }\r\n\r\n SmartHandle& operator=(HANDLE handle) HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n\r\n handle_ = handle;\r\n\r\n return *this;\r\n }\r\n\r\n SmartHandle(SmartHandle&& other) HADESMEM_NOEXCEPT\r\n : handle_(other.handle_), \r\n invalid_(other.invalid_)\r\n {\r\n other.handle_ = other.invalid_;\r\n }\r\n\r\n SmartHandle& operator=(SmartHandle&& other) HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n\r\n handle_ = other.handle_;\r\n other.handle_ = other.invalid_;\r\n\r\n invalid_ = other.invalid_;\r\n\r\n return *this;\r\n }\r\n\r\n ~SmartHandle() HADESMEM_NOEXCEPT\r\n {\r\n CleanupUnchecked();\r\n }\r\n\r\n HANDLE GetHandle() const HADESMEM_NOEXCEPT\r\n {\r\n return handle_;\r\n }\r\n\r\n HANDLE GetInvalid() const HADESMEM_NOEXCEPT\r\n {\r\n return invalid_;\r\n }\r\n\r\n bool IsValid() const HADESMEM_NOEXCEPT\r\n {\r\n return GetHandle() != GetInvalid();\r\n }\r\n\r\n void Cleanup()\r\n {\r\n if (handle_ == invalid_)\r\n {\r\n return;\r\n }\r\n\r\n if (!::CloseHandle(handle_))\r\n {\r\n DWORD const last_error = ::GetLastError();\r\n HADESMEM_THROW_EXCEPTION(Error() << \r\n ErrorString(\"CloseHandle failed.\") << \r\n ErrorCodeWinLast(last_error));\r\n }\r\n\r\n handle_ = invalid_;\r\n }\r\n\r\nprivate:\r\n SmartHandle(SmartHandle const& other) HADESMEM_DELETED_FUNCTION;\r\n SmartHandle& operator=(SmartHandle const& other) HADESMEM_DELETED_FUNCTION;\r\n\r\n void CleanupUnchecked() HADESMEM_NOEXCEPT\r\n {\r\n try\r\n {\r\n Cleanup();\r\n }\r\n catch (std::exception const& e)\r\n {\r\n (void)e;\r\n\r\n \/\/ WARNING: Handle is leaked if 'Cleanup' fails.\r\n HADESMEM_ASSERT(boost::diagnostic_information(e).c_str() && false);\r\n\r\n handle_ = invalid_;\r\n }\r\n }\r\n\r\n HANDLE handle_;\r\n HANDLE invalid_;\r\n};\r\n\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/\/ this function is derived from a part of graphics.c\n\/\/ in Xterm pl#310 originally written by Ross Combs.\n\/\/\n\/\/ Copyright 2013,2014 by Ross Combs\n\/\/\n\/\/ All Rights Reserved\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a\n\/\/ copy of this software and associated documentation files (the\n\/\/ \"Software\"), to deal in the Software without restriction, including\n\/\/ without limitation the rights to use, copy, modify, merge, publish,\n\/\/ distribute, sublicense, and\/or sell copies of the Software, and to\n\/\/ permit persons to whom the Software is furnished to do so, subject to\n\/\/ the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included\n\/\/ in all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n\/\/ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n\/\/ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n\/\/ IN NO EVENT SHALL THE ABOVE LISTED COPYRIGHT HOLDER(S) BE LIABLE FOR ANY\n\/\/ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n\/\/ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n\/\/ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\/\/\n\/\/ Except as contained in this notice, the name(s) of the above copyright\n\/\/ holders shall not be used in advertising or otherwise to promote the\n\/\/ sale, use or other dealings in this Software without prior written\n\/\/ authorization.\n\n#include \"sixel_hls.h\"\n\n#define SIXEL_RGB(r, g, b) (((r) << 16) + ((g) << 8) + (b))\n\nint\nhls_to_rgb(int hue, int lum, int sat)\n{\n\tdouble hs = (hue + 240) % 360;\n\tdouble hv = hs \/ 360.0;\n\tdouble lv = lum \/ 100.0;\n\tdouble sv = sat \/ 100.0;\n\tdouble c, x, m, c2;\n\tdouble r1, g1, b1;\n\tint r, g, b;\n\tint hpi;\n\n\tif (sat == 0) {\n\t\tr = g = b = lum * 255 \/ 100;\n\t\treturn SIXEL_RGB(r, g, b);\n\t}\n\n\tif ((c2 = ((2.0 * lv) - 1.0)) < 0.0)\n\t\tc2 = -c2;\n\tc = (1.0 - c2) * sv;\n\thpi = (int) (hv * 6.0);\n\tx = (hpi & 1) ? c : 0.0;\n\tm = lv - 0.5 * c;\n\n\tswitch (hpi) {\n\tcase 0:\n\t\tr1 = c;\n\t\tg1 = x;\n\t\tb1 = 0.0;\n\t\tbreak;\n\tcase 1:\n\t\tr1 = x;\n\t\tg1 = c;\n\t\tb1 = 0.0;\n\t\tbreak;\n\tcase 2:\n\t\tr1 = 0.0;\n\t\tg1 = c;\n\t\tb1 = x;\n\t\tbreak;\n\tcase 3:\n\t\tr1 = 0.0;\n\t\tg1 = x;\n\t\tb1 = c;\n\t\tbreak;\n\tcase 4:\n\t\tr1 = x;\n\t\tg1 = 0.0;\n\t\tb1 = c;\n\t\tbreak;\n\tcase 5:\n\t\tr1 = c;\n\t\tg1 = 0.0;\n\t\tb1 = x;\n\t\tbreak;\n\tdefault:\n\t\treturn SIXEL_RGB(255, 255, 255);\n\t}\n\n\tr = (int) ((r1 + m) * 100.0 + 0.5);\n\tg = (int) ((g1 + m) * 100.0 + 0.5);\n\tb = (int) ((b1 + m) * 100.0 + 0.5);\n\n\tif (r < 0) {\n\t r = 0;\n\t} else if (r > 100) {\n\t r = 100;\n\t}\n\tif (g < 0) {\n\t g = 0;\n\t} else if (g > 100) {\n\t g = 100;\n\t}\n\tif (b < 0) {\n\t b = 0;\n\t} else if (b > 100) {\n\t b = 100;\n\t}\n\treturn SIXEL_RGB(r * 255 \/ 100, g * 255 \/ 100, b * 255 \/ 100);\n}\nRemove unused file src\/sixel_hls.cc because now it's out of build target(with 9100d28).<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"etl\/impl\/egblas\/clip.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief Unary operation that clips all values between two scalars\n * \\tparam T the type of value\n * \\tparam S the type of scalar\n *\/\ntemplate \nstruct clip_scalar_op {\n \/*!\n * The vectorization type for V\n *\/\n template \n using vec_type = typename V::template vec_type;\n\n static constexpr bool linear = true; \/\/\/< Indicates if the operator is linear or not\n static constexpr bool thread_safe = true; \/\/\/< Indicates if the operator is thread safe or not\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template \n static constexpr bool vectorizable = intel_compiler && !is_complex_t;\n\n \/*!\n * \\brief Indicates if the operator can be computed on GPU\n *\/\n template \n static constexpr bool gpu_computable =\n (is_single_precision_t && impl::egblas::has_sclip)\n || (is_double_precision_t && impl::egblas::has_dclip)\n || (is_complex_single_t && impl::egblas::has_cclip)\n || (is_complex_double_t && impl::egblas::has_zclip);\n\n S min; \/\/\/< The minimum for clipping\n S max; \/\/\/< The maximum for clipping\n\n \/*!\n * \\brief Builds a new operator\n * \\param min The minimum for clipping\n * \\param max The maximum for clipping\n *\/\n clip_scalar_op(S min, S max)\n : min(min), max(max) {}\n\n \/*!\n * \\brief Apply the unary operator on x\n * \\param x The value on which to apply the operator\n * \\return The result of applying the unary operator on x\n *\/\n constexpr T apply(const T& x) const noexcept {\n return std::min(std::max(x, min), max);\n }\n\n#ifdef __INTEL_COMPILER\n \/*!\n * \\brief Compute several applications of the operator at a time\n * \\param x The vector on which to operate\n * \\tparam V The vectorization mode\n * \\return a vector containing several results of the operator\n *\/\n template \n vec_type load(const vec_type& lhs) const noexcept {\n return V::min(V::max(lhs, V::set(min)), V::set(max));\n }\n#endif\n\n \/*!\n * \\brief Compute the result of the operation using the GPU\n *\n * \\param x The expression of the unary operation\n *\n * \\return The result of applying the unary operator on x. The result must be a GPU computed expression.\n *\/\n template \n auto gpu_compute_hint(const X& x, Y& y) const noexcept {\n decltype(auto) t1 = smart_gpu_compute_hint(x, y);\n\n auto t2 = force_temporary_gpu(t1);\n\n#ifdef ETL_CUDA\n auto min_gpu = impl::cuda::cuda_allocate_only(1);\n cuda_check(cudaMemcpy(min_gpu.get(), &min, 1 * sizeof(T), cudaMemcpyHostToDevice));\n\n auto max_gpu = impl::cuda::cuda_allocate_only(1);\n cuda_check(cudaMemcpy(max_gpu.get(), &max, 1 * sizeof(T), cudaMemcpyHostToDevice));\n\n T alpha(1.0);\n impl::egblas::clip(etl::size(y), alpha, min_gpu.get(), 0, max_gpu.get(), 0, t2.gpu_memory(), 1);\n#endif\n\n return t2;\n }\n\n \/*!\n * \\brief Compute the result of the operation using the GPU\n *\n * \\param x The expression of the unary operation\n * \\param y The expression into which to store the reuslt\n *\/\n template \n Y& gpu_compute(const X& x, Y& y) const noexcept {\n smart_gpu_compute(x, y);\n\n#ifdef ETL_CUDA\n auto min_gpu = impl::cuda::cuda_allocate_only(1);\n cuda_check(cudaMemcpy(min_gpu.get(), &min, 1 * sizeof(T), cudaMemcpyHostToDevice));\n\n auto max_gpu = impl::cuda::cuda_allocate_only(1);\n cuda_check(cudaMemcpy(max_gpu.get(), &max, 1 * sizeof(T), cudaMemcpyHostToDevice));\n\n T alpha(1.0);\n impl::egblas::clip(etl::size(y), alpha, min_gpu.get(), 0, max_gpu.get(), 0, y.gpu_memory(), 1);\n#else\n cpp_unused(y);\n#endif\n\n y.validate_gpu();\n y.invalidate_cpu();\n\n return y;\n }\n\n \/*!\n * \\brief Returns a textual representation of the operator\n * \\return a string representing the operator\n *\/\n static std::string desc() noexcept {\n return \"clip\";\n }\n};\n\n} \/\/end of namespace etl\nUse the new, more-efficient, clip_value\/\/=======================================================================\n\/\/ Copyright (c) 2014-2017 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#pragma once\n\n#include \"etl\/impl\/egblas\/clip_value.hpp\"\n\nnamespace etl {\n\n\/*!\n * \\brief Unary operation that clips all values between two scalars\n * \\tparam T the type of value\n * \\tparam S the type of scalar\n *\/\ntemplate \nstruct clip_scalar_op {\n \/*!\n * The vectorization type for V\n *\/\n template \n using vec_type = typename V::template vec_type;\n\n static constexpr bool linear = true; \/\/\/< Indicates if the operator is linear or not\n static constexpr bool thread_safe = true; \/\/\/< Indicates if the operator is thread safe or not\n\n \/*!\n * \\brief Indicates if the expression is vectorizable using the\n * given vector mode\n * \\tparam V The vector mode\n *\/\n template \n static constexpr bool vectorizable = intel_compiler && !is_complex_t;\n\n \/*!\n * \\brief Indicates if the operator can be computed on GPU\n *\/\n template \n static constexpr bool gpu_computable =\n (is_single_precision_t && impl::egblas::has_sclip_value)\n || (is_double_precision_t && impl::egblas::has_dclip_value)\n || (is_complex_single_t && impl::egblas::has_cclip_value)\n || (is_complex_double_t && impl::egblas::has_zclip_value);\n\n S min; \/\/\/< The minimum for clipping\n S max; \/\/\/< The maximum for clipping\n\n \/*!\n * \\brief Builds a new operator\n * \\param min The minimum for clipping\n * \\param max The maximum for clipping\n *\/\n clip_scalar_op(S min, S max)\n : min(min), max(max) {}\n\n \/*!\n * \\brief Apply the unary operator on x\n * \\param x The value on which to apply the operator\n * \\return The result of applying the unary operator on x\n *\/\n constexpr T apply(const T& x) const noexcept {\n return std::min(std::max(x, min), max);\n }\n\n#ifdef __INTEL_COMPILER\n \/*!\n * \\brief Compute several applications of the operator at a time\n * \\param x The vector on which to operate\n * \\tparam V The vectorization mode\n * \\return a vector containing several results of the operator\n *\/\n template \n vec_type load(const vec_type& lhs) const noexcept {\n return V::min(V::max(lhs, V::set(min)), V::set(max));\n }\n#endif\n\n \/*!\n * \\brief Compute the result of the operation using the GPU\n *\n * \\param x The expression of the unary operation\n *\n * \\return The result of applying the unary operator on x. The result must be a GPU computed expression.\n *\/\n template \n auto gpu_compute_hint(const X& x, Y& y) const noexcept {\n decltype(auto) t1 = smart_gpu_compute_hint(x, y);\n\n auto t2 = force_temporary_gpu(t1);\n impl::egblas::clip_value(etl::size(y), T(1), min, max, t2.gpu_memory(), 1);\n return t2;\n }\n\n \/*!\n * \\brief Compute the result of the operation using the GPU\n *\n * \\param x The expression of the unary operation\n * \\param y The expression into which to store the reuslt\n *\/\n template \n Y& gpu_compute(const X& x, Y& y) const noexcept {\n smart_gpu_compute(x, y);\n\n impl::egblas::clip_value(etl::size(y), T(1), min, max, y.gpu_memory(), 1);\n\n y.validate_gpu();\n y.invalidate_cpu();\n\n return y;\n }\n\n \/*!\n * \\brief Returns a textual representation of the operator\n * \\return a string representing the operator\n *\/\n static std::string desc() noexcept {\n return \"clip\";\n }\n};\n\n} \/\/end of namespace etl\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include \n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\nInclude limits.h to get NAME_MAX on Unix.\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n#if defined(__GNUC__) && __GNUC__ >= 4\n\n#define TORRENT_DEPRECATED __attribute__ ((deprecated))\n\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# else\n# define TORRENT_EXPORT\n# endif\n\n#elif defined(__GNUC__)\n\n# define TORRENT_EXPORT\n\n#elif defined(BOOST_MSVC)\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# else\n# define TORRENT_EXPORT\n# endif\n\n#else\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n\/\/ set up defines for target environments\n#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n#elif defined __linux__\n#define TORRENT_LINUX\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#else\n#warning unkown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n#define TORRENT_USE_IPV6 1\n#define TORRENT_USE_MLOCK 1\n#define TORRENT_USE_READV 1\n#define TORRENT_USE_WRITEV 1\n#define TORRENT_USE_IOSTREAM 1\n\n\/\/ should wpath or path be used?\n#if defined UNICODE && !defined BOOST_FILESYSTEM_NARROW_ONLY \\\n\t&& BOOST_VERSION >= 103400 && !defined __APPLE__\n#define TORRENT_USE_WPATH 1\n#else\n#define TORRENT_USE_WPATH 0\n#endif\n\n#ifdef TORRENT_WINDOWS\n#include \n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define NAME_MAX 255\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\treturn vsnprintf_s(buf, len, _TRUNCATE, fmt, lp);\n}\n#define strtoll _strtoi64\n#else\n#include \n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) && !defined (TORRENT_UPNP_LOGGING)\n#define TORRENT_UPNP_LOGGING\n#endif\n\n#if !TORRENT_USE_WPATH && defined TORRENT_LINUX\n\/\/ libiconv presnce, not implemented yet\n#define TORRENT_USE_LOCALE_FILENAMES 1\n#else\n#define TORRENT_USE_LOCALE_FILENAMES 0\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n\/\/ determine what timer implementation we can use\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32)\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR\n#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators\n#endif\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\/\/ 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup\n#pragma warning(disable: 4996)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#endif\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 0\n#endif\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_IFADDRS 1\n#define TORRENT_USE_SYSCTL 1\n#define TORRENT_USE_IFCONF 1\n\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n#define TORRENT_USE_IFADDRS 1\n#define TORRENT_USE_NETLINK 1\n#define TORRENT_USE_IFCONF 1\n#define TORRENT_HAS_SALEN 0\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 1\n#endif\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_USE_NETLINK 0\n#define TORRENT_USE_GETADAPTERSADDRESSES 1\n#define TORRENT_HAS_SALEN 0\n#define TORRENT_USE_GETIPFORWARDTABLE 1\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#ifndef TORRENT_USE_GETIPFORWARDTABLE\n#define TORRENT_USE_GETIPFORWARDTABLE 1\n#endif\n#define TORRENT_USE_GETADAPTERSADDRESSES 1\n#define TORRENT_HAS_SALEN 0\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 1\n#endif\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n#define TORRENT_USE_IFCONF 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#endif\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n#include \n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include \n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_HAS_SALEN\n#define TORRENT_HAS_SALEN 1\n#endif\n\n#ifndef TORRENT_USE_GETADAPTERSADDRESSES\n#define TORRENT_USE_GETADAPTERSADDRESSES 0\n#endif\n\n#ifndef TORRENT_USE_NETLINK\n#define TORRENT_USE_NETLINK 0\n#endif\n\n#ifndef TORRENT_USE_SYSCTL\n#define TORRENT_USE_SYSCTL 0\n#endif\n\n#ifndef TORRENT_USE_GETIPFORWARDTABLE\n#define TORRENT_USE_GETIPFORWARDTABLE 0\n#endif\n\n#ifndef TORRENT_USE_LOCALE\n#define TORRENT_USE_LOCALE 0\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IFADDRS\n#define TORRENT_USE_IFADDRS 0\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#ifndef TORRENT_HAS_STRDUP\n#define TORRENT_HAS_STRDUP 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#if !TORRENT_HAS_STRDUP\ninline char* strdup(char const* str)\n{\n\tif (str == 0) return 0;\n\tchar* tmp = (char*)malloc(strlen(str) + 1);\n\tif (tmp == 0) return 0;\n\tstrcpy(tmp, str);\n\treturn tmp;\n}\n#endif\n\n\/\/ for non-exception builds\n#ifdef BOOST_NO_EXCEPTIONS\n#define TORRENT_TRY if (true)\n#define TORRENT_CATCH(x) else if (false)\n#define TORRENT_DECLARE_DUMMY(x, y) x y\n#else\n#define TORRENT_TRY try\n#define TORRENT_CATCH(x) catch(x)\n#define TORRENT_DECLARE_DUMMY(x, y)\n#endif \/\/ BOOST_NO_EXCEPTIONS\n\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\nfix minor mingw issue\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR\n#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators\n#endif\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _MSC_VER\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\/\/ 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup\n#pragma warning(disable: 4996)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#endif\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 0\n#endif\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_IFADDRS 1\n#define TORRENT_USE_SYSCTL 1\n#define TORRENT_USE_IFCONF 1\n\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n#define TORRENT_USE_IFADDRS 1\n#define TORRENT_USE_NETLINK 1\n#define TORRENT_USE_IFCONF 1\n#define TORRENT_HAS_SALEN 0\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 1\n#endif\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_USE_NETLINK 0\n#define TORRENT_USE_GETADAPTERSADDRESSES 1\n#define TORRENT_HAS_SALEN 0\n#define TORRENT_USE_GETIPFORWARDTABLE 1\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n#ifndef TORRENT_USE_GETIPFORWARDTABLE\n#define TORRENT_USE_GETIPFORWARDTABLE 1\n#endif\n#define TORRENT_USE_GETADAPTERSADDRESSES 1\n#define TORRENT_HAS_SALEN 0\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_LOCALE 1\n#endif\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n#define TORRENT_USE_IFCONF 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 0\n#endif\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n#include \n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include \n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_HAS_SALEN\n#define TORRENT_HAS_SALEN 1\n#endif\n\n#ifndef TORRENT_USE_GETADAPTERSADDRESSES\n#define TORRENT_USE_GETADAPTERSADDRESSES 0\n#endif\n\n#ifndef TORRENT_USE_NETLINK\n#define TORRENT_USE_NETLINK 0\n#endif\n\n#ifndef TORRENT_USE_SYSCTL\n#define TORRENT_USE_SYSCTL 0\n#endif\n\n#ifndef TORRENT_USE_GETIPFORWARDTABLE\n#define TORRENT_USE_GETIPFORWARDTABLE 0\n#endif\n\n#ifndef TORRENT_USE_LOCALE\n#define TORRENT_USE_LOCALE 0\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IFADDRS\n#define TORRENT_USE_IFADDRS 0\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#ifndef TORRENT_HAS_STRDUP\n#define TORRENT_HAS_STRDUP 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#if !TORRENT_HAS_STRDUP\ninline char* strdup(char const* str)\n{\n\tif (str == 0) return 0;\n\tchar* tmp = (char*)malloc(strlen(str) + 1);\n\tif (tmp == 0) return 0;\n\tstrcpy(tmp, str);\n\treturn tmp;\n}\n#endif\n\n\/\/ for non-exception builds\n#ifdef BOOST_NO_EXCEPTIONS\n#define TORRENT_TRY if (true)\n#define TORRENT_CATCH(x) else if (false)\n#define TORRENT_DECLARE_DUMMY(x, y) x y\n#else\n#define TORRENT_TRY try\n#define TORRENT_CATCH(x) catch(x)\n#define TORRENT_DECLARE_DUMMY(x, y)\n#endif \/\/ BOOST_NO_EXCEPTIONS\n\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATORS\n#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators\n#endif\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#define TORRENT_USE_ICONV 0\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#define TORRENT_USE_ICONV 0\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_ICONV 0\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\n#include \n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include \n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\nfixed typo in config relating to buffer debug builds\/*\n\nCopyright (c) 2005, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_CONFIG_HPP_INCLUDED\n#define TORRENT_CONFIG_HPP_INCLUDED\n\n#include \n#include \n#include \/\/ for snprintf\n\n#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR\n#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators\n#endif\n\n#ifndef WIN32\n#define __STDC_FORMAT_MACROS\n#include \n#endif\n\n#ifndef PRId64\n#ifdef _WIN32\n#define PRId64 \"I64d\"\n#else\n#define PRId64 \"lld\"\n#endif\n#endif\n\n\n\/\/ ======= GCC =========\n\n#if defined __GNUC__\n\n# if __GNUC__ >= 3\n# define TORRENT_DEPRECATED __attribute__ ((deprecated))\n# endif\n\n\/\/ GCC pre 4.0 did not have support for the visibility attribute\n# if __GNUC__ >= 4\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __attribute__ ((visibility(\"default\")))\n# endif\n# endif\n\n\n\/\/ ======= SUNPRO =========\n\n#elif defined __SUNPRO_CC\n\n# if __SUNPRO_CC >= 0x550\n# if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __global\n# endif\n# endif\n\n\/\/ SunPRO seems to have an overly-strict\n\/\/ definition of POD types and doesn't\n\/\/ seem to allow boost::array in unions\n#define TORRENT_BROKEN_UNIONS 1\n\n\/\/ ======= MSVC =========\n\n#elif defined BOOST_MSVC\n\n#pragma warning(disable: 4258)\n#pragma warning(disable: 4251)\n\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n\n#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)\n\n#endif\n\n\n\/\/ ======= PLATFORMS =========\n\n\n\/\/ set up defines for target environments\n\/\/ ==== AMIGA ===\n#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__\n#define TORRENT_AMIGA\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_WRITEV 0\n#define TORRENT_USE_READV 0\n#define TORRENT_USE_IPV6 0\n#define TORRENT_USE_BOOST_THREAD 0\n#define TORRENT_USE_IOSTREAM 0\n\/\/ set this to 1 to disable all floating point operations\n\/\/ (disables some float-dependent APIs)\n#define TORRENT_NO_FPU 1\n#define TORRENT_USE_I2P 0\n#define TORRENT_USE_ICONV 0\n\n\/\/ ==== Darwin\/BSD ===\n#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \\\n\t|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \\\n\t|| defined __FreeBSD_kernel__\n#define TORRENT_BSD\n\/\/ we don't need iconv on mac, because\n\/\/ the locale is always utf-8\n#if defined __APPLE__\n#define TORRENT_USE_ICONV 0\n#endif\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== LINUX ===\n#elif defined __linux__\n#define TORRENT_LINUX\n\n\/\/ ==== MINGW ===\n#elif defined __MINGW32__\n#define TORRENT_MINGW\n#define TORRENT_WINDOWS\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n\n\/\/ ==== WINDOWS ===\n#elif defined WIN32\n#define TORRENT_WINDOWS\n\/\/ windows has its own functions to convert\n\/\/ apple uses utf-8 as its locale, so no conversion\n\/\/ is necessary\n#define TORRENT_USE_ICONV 0\n#define TORRENT_USE_RLIMIT 0\n#define TORRENT_HAS_FALLOCATE 0\n\n\/\/ ==== SOLARIS ===\n#elif defined sun || defined __sun \n#define TORRENT_SOLARIS\n#define TORRENT_COMPLETE_TYPES_REQUIRED 1\n\n\/\/ ==== BEOS ===\n#elif defined __BEOS__ || defined __HAIKU__\n#define TORRENT_BEOS\n#include \/\/ B_PATH_NAME_LENGTH\n#define TORRENT_HAS_FALLOCATE 0\n#define TORRENT_USE_MLOCK 0\n#define TORRENT_USE_ICONV 0\n#if __GNUCC__ == 2\n# if defined(TORRENT_BUILDING_SHARED)\n# define TORRENT_EXPORT __declspec(dllexport)\n# elif defined(TORRENT_LINKING_SHARED)\n# define TORRENT_EXPORT __declspec(dllimport)\n# endif\n#endif\n#else\n#warning unknown OS, assuming BSD\n#define TORRENT_BSD\n#endif\n\n\/\/ on windows, NAME_MAX refers to Unicode characters\n\/\/ on linux it refers to bytes (utf-8 encoded)\n\/\/ TODO: Make this count Unicode characters instead of bytes on windows\n\n\/\/ windows\n#if defined FILENAME_MAX\n#define TORRENT_MAX_PATH FILENAME_MAX\n\n\/\/ beos\n#elif defined B_PATH_NAME_LENGTH\n#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH\n\n\/\/ solaris\n#elif defined MAXPATH\n#define TORRENT_MAX_PATH MAXPATH\n\n\/\/ posix\n#elif defined NAME_MAX\n#define TORRENT_MAX_PATH NAME_MAX\n\n\/\/ none of the above\n#else\n\/\/ this is the maximum number of characters in a\n\/\/ path element \/ filename on windows\n#define TORRENT_MAX_PATH 255\n#warning unknown platform, assuming the longest path is 255\n\n#endif\n\n#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW\n\n\/\/ class X needs to have dll-interface to be used by clients of class Y\n#pragma warning(disable:4251)\n\/\/ '_vsnprintf': This function or variable may be unsafe\n#pragma warning(disable:4996)\n\n#include \n\ninline int snprintf(char* buf, int len, char const* fmt, ...)\n{\n\tva_list lp;\n\tva_start(lp, fmt);\n\tint ret = _vsnprintf(buf, len, fmt, lp);\n\tva_end(lp);\n\tif (ret < 0) { buf[len-1] = 0; ret = len-1; }\n\treturn ret;\n}\n\n#define strtoll _strtoi64\n#else\n#include \n#endif\n\n#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \\\n\t&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM\n#define TORRENT_UPNP_LOGGING\n#endif\n\n\/\/ libiconv presence, not implemented yet\n#ifndef TORRENT_USE_ICONV\n#define TORRENT_USE_ICONV 1\n#endif\n\n#ifndef TORRENT_BROKEN_UNIONS\n#define TORRENT_BROKEN_UNIONS 0\n#endif\n\n#if defined UNICODE && !defined BOOST_NO_STD_WSTRING\n#define TORRENT_USE_WSTRING 1\n#else\n#define TORRENT_USE_WSTRING 0\n#endif \/\/ UNICODE\n\n#ifndef TORRENT_HAS_FALLOCATE\n#define TORRENT_HAS_FALLOCATE 1\n#endif\n\n#ifndef TORRENT_EXPORT\n# define TORRENT_EXPORT\n#endif\n\n#ifndef TORRENT_DEPRECATED_PREFIX\n#define TORRENT_DEPRECATED_PREFIX\n#endif\n\n#ifndef TORRENT_DEPRECATED\n#define TORRENT_DEPRECATED\n#endif\n\n#ifndef TORRENT_COMPLETE_TYPES_REQUIRED\n#define TORRENT_COMPLETE_TYPES_REQUIRED 0\n#endif\n\n#ifndef TORRENT_USE_RLIMIT\n#define TORRENT_USE_RLIMIT 1\n#endif\n\n#ifndef TORRENT_USE_IPV6\n#define TORRENT_USE_IPV6 1\n#endif\n\n#ifndef TORRENT_USE_MLOCK\n#define TORRENT_USE_MLOCK 1\n#endif\n\n#ifndef TORRENT_USE_WRITEV\n#define TORRENT_USE_WRITEV 1\n#endif\n\n#ifndef TORRENT_USE_READV\n#define TORRENT_USE_READV 1\n#endif\n\n#ifndef TORRENT_NO_FPU\n#define TORRENT_NO_FPU 0\n#endif\n\n#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM\n#define TORRENT_USE_IOSTREAM 1\n#else\n#define TORRENT_USE_IOSTREAM 0\n#endif\n\n#ifndef TORRENT_USE_I2P\n#define TORRENT_USE_I2P 1\n#endif\n\n#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)\n# define TORRENT_READ_HANDLER_MAX_SIZE 256\n#endif\n\n#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)\n# define TORRENT_WRITE_HANDLER_MAX_SIZE 256\n#endif\n\n#if defined _MSC_VER && _MSC_VER <= 1200\n#define for if (false) {} else for\n#endif\n\n#if TORRENT_BROKEN_UNIONS\n#define TORRENT_UNION struct\n#else\n#define TORRENT_UNION union\n#endif\n\n\/\/ determine what timer implementation we can use\n\/\/ if one is already defined, don't pick one\n\/\/ autmatically. This lets the user control this\n\/\/ from the Jamfile\n#if !defined TORRENT_USE_ABSOLUTE_TIME \\\n\t&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \\\n\t&& !defined TORRENT_USE_CLOCK_GETTIME \\\n\t&& !defined TORRENT_USE_BOOST_DATE_TIME \\\n\t&& !defined TORRENT_USE_ECLOCK \\\n\t&& !defined TORRENT_USE_SYSTEM_TIME\n\n#if defined(__MACH__)\n#define TORRENT_USE_ABSOLUTE_TIME 1\n#elif defined(_WIN32) || defined TORRENT_MINGW\n#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1\n#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0\n#define TORRENT_USE_CLOCK_GETTIME 1\n#elif defined(TORRENT_AMIGA)\n#define TORRENT_USE_ECLOCK 1\n#elif defined(TORRENT_BEOS)\n#define TORRENT_USE_SYSTEM_TIME 1\n#else\n#define TORRENT_USE_BOOST_DATE_TIME 1\n#endif\n\n#endif\n\n#endif \/\/ TORRENT_CONFIG_HPP_INCLUDED\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"vfs\/platform.hpp\"\n\n\nnamespace vfs {\n\n \/\/----------------------------------------------------------------------------------------------\n using file_view_impl = class win_file_view;\n \/\/----------------------------------------------------------------------------------------------\n\n\n \/\/----------------------------------------------------------------------------------------------\n class win_file_view\n {\n\tprotected:\n\t\t\/\/------------------------------------------------------------------------------------------\n win_file_view(file_sptr spFile, int64_t viewSize)\n : spFile_(std::move(spFile))\n , name_(spFile_->fileName())\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(viewSize)\n {\n\t\t\tvfs_check(spFile_->isValid());\n map(viewSize, false);\n }\n\n \/\/------------------------------------------------------------------------------------------\n win_file_view(const path &name, int64_t size, bool openExistent)\n : name_(name)\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(size)\n {\n map(size, openExistent);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n ~win_file_view()\n {\n flush();\n unmap();\n\n if (spFile_)\n {\n CloseHandle(fileMappingHandle_);\n }\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool map(int64_t viewSize, bool openExistent)\n {\n const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;\n\n if (spFile_)\n {\n if (!spFile_->createMapping(viewSize))\n {\n return false;\n }\n\n fileMappingHandle_ = spFile_->nativeFileMappingHandle();\n fileTotalSize_ = spFile_->size();\n }\n else\n {\n if (openExistent)\n {\n fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());\n }\n else\n {\n fileMappingHandle_ = CreateFileMapping\n (\n INVALID_HANDLE_VALUE,\n nullptr,\n PAGE_READWRITE,\n DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),\n name_.c_str()\n );\n }\n\n if (fileMappingHandle_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"%sFileMapping(%ws) failed with error: %s\", openExistent ? \"Open\" : \"Create\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n fileTotalSize_ = viewSize;\n }\n\n const auto fileMapAccess = (\n (access == file_access::read_only)\n ? FILE_MAP_READ\n : ((access == file_access::write_only)\n ? FILE_MAP_WRITE\n : FILE_MAP_ALL_ACCESS\n )\n );\n\n pData_ = reinterpret_cast(MapViewOfFile(fileMappingHandle_, fileMapAccess, 0, 0, 0));\n pCursor_ = pData_;\n\n if (pData_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"MapViewOfFile(%ws) failed with error: %s\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n MEMORY_BASIC_INFORMATION memInfo;\n const auto dwInfoBytesCount = VirtualQuery(pData_, &memInfo, sizeof(memInfo));\n if (dwInfoBytesCount != 0)\n {\n mappedTotalSize_ = memInfo.RegionSize;\n }\n\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool unmap()\n {\n if (pData_ && !UnmapViewOfFile(pData_))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool flush()\n {\n if (!FlushViewOfFile(pData_, 0))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t read(uint8_t *dst, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(dst, pCursor_, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t write(const uint8_t *src, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(pCursor_, src, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool isValid() const\n {\n return pData_ != nullptr;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t totalSize() const\n {\n return fileTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool canMoveCursor(int64_t offsetInBytes) const\n {\n return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template\n T* data()\n {\n return reinterpret_cast(pData_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n uint8_t* data()\n {\n return data<>();\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template\n T* cursor()\n {\n return reinterpret_cast(pCursor_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool skip(int64_t offsetInBytes)\n {\n if (canMoveCursor(offsetInBytes))\n {\n pCursor_ += offsetInBytes;\n return true;\n }\n return false;\n }\n\n\tprivate:\n\t\t\/\/------------------------------------------------------------------------------------------\n file_sptr spFile_;\n path name_;\n HANDLE fileMappingHandle_;\n uint8_t *pData_;\n uint8_t *pCursor_;\n int64_t fileTotalSize_;\n int64_t mappedTotalSize_;\n };\n \/\/----------------------------------------------------------------------------------------------\n\n} \/*vfs*\/\nReal fix for double close on file mapping handle#pragma once\n\n#include \"vfs\/platform.hpp\"\n\n\nnamespace vfs {\n\n \/\/----------------------------------------------------------------------------------------------\n using file_view_impl = class win_file_view;\n \/\/----------------------------------------------------------------------------------------------\n\n\n \/\/----------------------------------------------------------------------------------------------\n class win_file_view\n {\n\tprotected:\n\t\t\/\/------------------------------------------------------------------------------------------\n win_file_view(file_sptr spFile, int64_t viewSize)\n : spFile_(std::move(spFile))\n , name_(spFile_->fileName())\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(viewSize)\n {\n\t\t\tvfs_check(spFile_->isValid());\n map(viewSize, false);\n }\n\n \/\/------------------------------------------------------------------------------------------\n win_file_view(const path &name, int64_t size, bool openExistent)\n : name_(name)\n , fileMappingHandle_(nullptr)\n , pData_(nullptr)\n , pCursor_(nullptr)\n , mappedTotalSize_(size)\n {\n map(size, openExistent);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n ~win_file_view()\n {\n flush();\n unmap();\n\n if (spFile_ == nullptr)\n {\n CloseHandle(fileMappingHandle_);\n }\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool map(int64_t viewSize, bool openExistent)\n {\n const auto access = spFile_ ? spFile_->fileAccess() : file_access::read_write;\n\n if (spFile_)\n {\n if (!spFile_->createMapping(viewSize))\n {\n return false;\n }\n\n fileMappingHandle_ = spFile_->nativeFileMappingHandle();\n fileTotalSize_ = spFile_->size();\n }\n else\n {\n if (openExistent)\n {\n fileMappingHandle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name_.c_str());\n }\n else\n {\n fileMappingHandle_ = CreateFileMapping\n (\n INVALID_HANDLE_VALUE,\n nullptr,\n PAGE_READWRITE,\n DWORD(viewSize >> 32), DWORD((viewSize << 32) >> 32),\n name_.c_str()\n );\n }\n\n if (fileMappingHandle_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"%sFileMapping(%ws) failed with error: %s\", openExistent ? \"Open\" : \"Create\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n fileTotalSize_ = viewSize;\n }\n\n const auto fileMapAccess = (\n (access == file_access::read_only)\n ? FILE_MAP_READ\n : ((access == file_access::write_only)\n ? FILE_MAP_WRITE\n : FILE_MAP_ALL_ACCESS\n )\n );\n\n pData_ = reinterpret_cast(MapViewOfFile(fileMappingHandle_, fileMapAccess, 0, 0, 0));\n pCursor_ = pData_;\n\n if (pData_ == nullptr)\n {\n const auto errorCode = GetLastError();\n vfs_errorf(\"MapViewOfFile(%ws) failed with error: %s\", name_.c_str(), get_last_error_as_string(errorCode).c_str());\n return false;\n }\n\n MEMORY_BASIC_INFORMATION memInfo;\n const auto dwInfoBytesCount = VirtualQuery(pData_, &memInfo, sizeof(memInfo));\n if (dwInfoBytesCount != 0)\n {\n mappedTotalSize_ = memInfo.RegionSize;\n }\n\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool unmap()\n {\n if (pData_ && !UnmapViewOfFile(pData_))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool flush()\n {\n if (!FlushViewOfFile(pData_, 0))\n {\n return false;\n }\n return true;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t read(uint8_t *dst, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(dst, pCursor_, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t write(const uint8_t *src, int64_t sizeInBytes)\n {\n if (canMoveCursor(sizeInBytes))\n {\n memcpy(pCursor_, src, sizeInBytes);\n pCursor_ += sizeInBytes;\n return sizeInBytes;\n }\n return 0;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool isValid() const\n {\n return pData_ != nullptr;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n int64_t totalSize() const\n {\n return fileTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool canMoveCursor(int64_t offsetInBytes) const\n {\n return isValid() && (pCursor_ - pData_ + offsetInBytes) <= mappedTotalSize_;\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template\n T* data()\n {\n return reinterpret_cast(pData_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n uint8_t* data()\n {\n return data<>();\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n template\n T* cursor()\n {\n return reinterpret_cast(pCursor_);\n }\n\n\t\t\/\/------------------------------------------------------------------------------------------\n bool skip(int64_t offsetInBytes)\n {\n if (canMoveCursor(offsetInBytes))\n {\n pCursor_ += offsetInBytes;\n return true;\n }\n return false;\n }\n\n\tprivate:\n\t\t\/\/------------------------------------------------------------------------------------------\n file_sptr spFile_;\n path name_;\n HANDLE fileMappingHandle_;\n uint8_t *pData_;\n uint8_t *pCursor_;\n int64_t fileTotalSize_;\n int64_t mappedTotalSize_;\n };\n \/\/----------------------------------------------------------------------------------------------\n\n} \/*vfs*\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace folly;\nusing namespace std;\nusing namespace fizz::client;\n\nnamespace quic {\n\nQuicConnector::QuicConnector(Callback* cb) : cb_(CHECK_NOTNULL(cb)) {}\n\nvoid QuicConnector::onConnectionSetupError(\n std::pair code) noexcept {\n if (cb_) {\n cb_->onConnectError(std::move(code));\n }\n cleanUp();\n}\n\nvoid QuicConnector::onReplaySafe() noexcept {\n if (cb_) {\n cb_->onConnectSuccess();\n }\n cleanUpAndCloseSocket();\n}\n\nvoid QuicConnector::connect(\n folly::EventBase* eventBase,\n folly::Optional localAddr,\n const folly::SocketAddress& connectAddr,\n std::shared_ptr fizzContext,\n std::shared_ptr verifier,\n std::shared_ptr quicPskCache,\n quic::TransportSettings transportSettings,\n const std::vector& supportedQuicVersions,\n std::chrono::milliseconds connectTimeout,\n const folly::SocketOptionMap& socketOptions,\n const folly::Optional& sni,\n std::shared_ptr qLogger,\n std::shared_ptr quicLoopDetectorCallback,\n std::shared_ptr\n quicTransportStatsCallback) {\n if (isBusy()) {\n LOG(ERROR) << \"Already connecting...\";\n return;\n }\n\n auto sock = std::make_unique(eventBase);\n quicClient_ = quic::QuicClientTransport::newClient(\n eventBase,\n std::move(sock),\n quic::FizzClientQuicHandshakeContext::Builder()\n .setFizzClientContext(std::move(fizzContext))\n .setCertificateVerifier(std::move(verifier))\n .setPskCache(std::move(quicPskCache))\n .build(),\n 0, \/* connectionIdSize *\/\n true \/* useSplitConnectionCallbacks *\/);\n quicClient_->setHostname(sni.value_or(connectAddr.getAddressStr()));\n quicClient_->addNewPeerAddress(connectAddr);\n if (localAddr.hasValue()) {\n quicClient_->setLocalAddress(*localAddr);\n }\n quicClient_->setCongestionControllerFactory(\n std::make_shared());\n quicClient_->setTransportStatsCallback(std::move(quicTransportStatsCallback));\n quicClient_->setTransportSettings(std::move(transportSettings));\n quicClient_->setQLogger(std::move(qLogger));\n quicClient_->setLoopDetectorCallback(std::move(quicLoopDetectorCallback));\n quicClient_->setSocketOptions(socketOptions);\n quicClient_->setSupportedVersions(supportedQuicVersions);\n\n VLOG(4) << \"connecting to \" << connectAddr.describe();\n\n doConnect(connectTimeout);\n}\n\nvoid QuicConnector::connect(\n std::shared_ptr quicClient,\n std::chrono::milliseconds connectTimeout) {\n quicClient_ = std::move(quicClient);\n doConnect(connectTimeout);\n}\n\nvoid QuicConnector::doConnect(std::chrono::milliseconds connectTimeout) {\n connectStart_ = std::chrono::steady_clock::now();\n quicClient_->getEventBase()->timer().scheduleTimeout(this, connectTimeout);\n quicClient_->start(this, nullptr);\n}\n\nvoid QuicConnector::reset() {\n cleanUpAndCloseSocket();\n}\n\nvoid QuicConnector::cleanUp() {\n quicClient_.reset();\n connectStart_ = TimePoint{};\n}\n\nvoid QuicConnector::cleanUpAndCloseSocket() {\n if (quicClient_) {\n auto error = std::make_pair(\n quic::QuicErrorCode(quic::LocalErrorCode::SHUTTING_DOWN),\n std::string(\"shutting down\"));\n quicClient_->close(std::move(error));\n }\n cleanUp();\n}\n\nstd::chrono::milliseconds QuicConnector::timeElapsed() {\n return timePointInitialized(connectStart_) ? millisecondsSince(connectStart_)\n : std::chrono::milliseconds(0);\n}\n\nvoid QuicConnector::timeoutExpired() noexcept {\n auto error = std::make_pair(\n quic::QuicErrorCode(quic::LocalErrorCode::CONNECT_FAILED),\n std::string(\"connect operation timed out\"));\n if (quicClient_) {\n quicClient_->close(error);\n }\n onConnectionSetupError(std::move(error));\n}\n\n} \/\/ namespace quic\nRemove dead includes in quic\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nnamespace quic {\n\nQuicConnector::QuicConnector(Callback* cb) : cb_(CHECK_NOTNULL(cb)) {}\n\nvoid QuicConnector::onConnectionSetupError(\n std::pair code) noexcept {\n if (cb_) {\n cb_->onConnectError(std::move(code));\n }\n cleanUp();\n}\n\nvoid QuicConnector::onReplaySafe() noexcept {\n if (cb_) {\n cb_->onConnectSuccess();\n }\n cleanUpAndCloseSocket();\n}\n\nvoid QuicConnector::connect(\n folly::EventBase* eventBase,\n folly::Optional localAddr,\n const folly::SocketAddress& connectAddr,\n std::shared_ptr fizzContext,\n std::shared_ptr verifier,\n std::shared_ptr quicPskCache,\n quic::TransportSettings transportSettings,\n const std::vector& supportedQuicVersions,\n std::chrono::milliseconds connectTimeout,\n const folly::SocketOptionMap& socketOptions,\n const folly::Optional& sni,\n std::shared_ptr qLogger,\n std::shared_ptr quicLoopDetectorCallback,\n std::shared_ptr\n quicTransportStatsCallback) {\n if (isBusy()) {\n LOG(ERROR) << \"Already connecting...\";\n return;\n }\n\n auto sock = std::make_unique(eventBase);\n quicClient_ = quic::QuicClientTransport::newClient(\n eventBase,\n std::move(sock),\n quic::FizzClientQuicHandshakeContext::Builder()\n .setFizzClientContext(std::move(fizzContext))\n .setCertificateVerifier(std::move(verifier))\n .setPskCache(std::move(quicPskCache))\n .build(),\n 0, \/* connectionIdSize *\/\n true \/* useSplitConnectionCallbacks *\/);\n quicClient_->setHostname(sni.value_or(connectAddr.getAddressStr()));\n quicClient_->addNewPeerAddress(connectAddr);\n if (localAddr.hasValue()) {\n quicClient_->setLocalAddress(*localAddr);\n }\n quicClient_->setCongestionControllerFactory(\n std::make_shared());\n quicClient_->setTransportStatsCallback(std::move(quicTransportStatsCallback));\n quicClient_->setTransportSettings(std::move(transportSettings));\n quicClient_->setQLogger(std::move(qLogger));\n quicClient_->setLoopDetectorCallback(std::move(quicLoopDetectorCallback));\n quicClient_->setSocketOptions(socketOptions);\n quicClient_->setSupportedVersions(supportedQuicVersions);\n\n VLOG(4) << \"connecting to \" << connectAddr.describe();\n\n doConnect(connectTimeout);\n}\n\nvoid QuicConnector::connect(\n std::shared_ptr quicClient,\n std::chrono::milliseconds connectTimeout) {\n quicClient_ = std::move(quicClient);\n doConnect(connectTimeout);\n}\n\nvoid QuicConnector::doConnect(std::chrono::milliseconds connectTimeout) {\n connectStart_ = std::chrono::steady_clock::now();\n quicClient_->getEventBase()->timer().scheduleTimeout(this, connectTimeout);\n quicClient_->start(this, nullptr);\n}\n\nvoid QuicConnector::reset() {\n cleanUpAndCloseSocket();\n}\n\nvoid QuicConnector::cleanUp() {\n quicClient_.reset();\n connectStart_ = TimePoint{};\n}\n\nvoid QuicConnector::cleanUpAndCloseSocket() {\n if (quicClient_) {\n auto error = std::make_pair(\n quic::QuicErrorCode(quic::LocalErrorCode::SHUTTING_DOWN),\n std::string(\"shutting down\"));\n quicClient_->close(std::move(error));\n }\n cleanUp();\n}\n\nstd::chrono::milliseconds QuicConnector::timeElapsed() {\n return timePointInitialized(connectStart_) ? millisecondsSince(connectStart_)\n : std::chrono::milliseconds(0);\n}\n\nvoid QuicConnector::timeoutExpired() noexcept {\n auto error = std::make_pair(\n quic::QuicErrorCode(quic::LocalErrorCode::CONNECT_FAILED),\n std::string(\"connect operation timed out\"));\n if (quicClient_) {\n quicClient_->close(error);\n }\n onConnectionSetupError(std::move(error));\n}\n\n} \/\/ namespace quic\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"quic\/test_tools\/simple_data_producer.h\"\n\n#include \n\n#include \"absl\/strings\/string_view.h\"\n#include \"quic\/core\/quic_data_writer.h\"\n#include \"quic\/platform\/api\/quic_bug_tracker.h\"\n#include \"quic\/platform\/api\/quic_flags.h\"\n\nnamespace quic {\n\nnamespace test {\n\nSimpleDataProducer::SimpleDataProducer() {}\n\nSimpleDataProducer::~SimpleDataProducer() {}\n\nvoid SimpleDataProducer::SaveStreamData(QuicStreamId id,\n const struct iovec* iov,\n int iov_count,\n size_t iov_offset,\n QuicByteCount data_length) {\n if (data_length == 0) {\n return;\n }\n if (!send_buffer_map_.contains(id)) {\n send_buffer_map_[id] = std::make_unique(&allocator_);\n }\n send_buffer_map_[id]->SaveStreamData(iov, iov_count, iov_offset, data_length);\n}\n\nvoid SimpleDataProducer::SaveCryptoData(EncryptionLevel level,\n QuicStreamOffset offset,\n absl::string_view data) {\n auto key = std::make_pair(level, offset);\n crypto_buffer_map_[key] = data;\n}\n\nWriteStreamDataResult SimpleDataProducer::WriteStreamData(\n QuicStreamId id,\n QuicStreamOffset offset,\n QuicByteCount data_length,\n QuicDataWriter* writer) {\n auto iter = send_buffer_map_.find(id);\n if (iter == send_buffer_map_.end()) {\n return STREAM_MISSING;\n }\n if (iter->second->WriteStreamData(offset, data_length, writer)) {\n return WRITE_SUCCESS;\n }\n return WRITE_FAILED;\n}\n\nbool SimpleDataProducer::WriteCryptoData(EncryptionLevel level,\n QuicStreamOffset offset,\n QuicByteCount data_length,\n QuicDataWriter* writer) {\n auto it = crypto_buffer_map_.find(std::make_pair(level, offset));\n if (it == crypto_buffer_map_.end() || it->second.length() < data_length) {\n return false;\n }\n return writer->WriteStringPiece(\n absl::string_view(it->second.data(), data_length));\n}\n\n} \/\/ namespace test\n\n} \/\/ namespace quic\nFix implicit conversion from absl::string_view to std::string.\/\/ Copyright (c) 2017 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"quic\/test_tools\/simple_data_producer.h\"\n\n#include \n\n#include \"absl\/strings\/string_view.h\"\n#include \"quic\/core\/quic_data_writer.h\"\n#include \"quic\/platform\/api\/quic_bug_tracker.h\"\n#include \"quic\/platform\/api\/quic_flags.h\"\n\nnamespace quic {\n\nnamespace test {\n\nSimpleDataProducer::SimpleDataProducer() {}\n\nSimpleDataProducer::~SimpleDataProducer() {}\n\nvoid SimpleDataProducer::SaveStreamData(QuicStreamId id,\n const struct iovec* iov,\n int iov_count,\n size_t iov_offset,\n QuicByteCount data_length) {\n if (data_length == 0) {\n return;\n }\n if (!send_buffer_map_.contains(id)) {\n send_buffer_map_[id] = std::make_unique(&allocator_);\n }\n send_buffer_map_[id]->SaveStreamData(iov, iov_count, iov_offset, data_length);\n}\n\nvoid SimpleDataProducer::SaveCryptoData(EncryptionLevel level,\n QuicStreamOffset offset,\n absl::string_view data) {\n auto key = std::make_pair(level, offset);\n crypto_buffer_map_[key] = std::string(data);\n}\n\nWriteStreamDataResult SimpleDataProducer::WriteStreamData(\n QuicStreamId id,\n QuicStreamOffset offset,\n QuicByteCount data_length,\n QuicDataWriter* writer) {\n auto iter = send_buffer_map_.find(id);\n if (iter == send_buffer_map_.end()) {\n return STREAM_MISSING;\n }\n if (iter->second->WriteStreamData(offset, data_length, writer)) {\n return WRITE_SUCCESS;\n }\n return WRITE_FAILED;\n}\n\nbool SimpleDataProducer::WriteCryptoData(EncryptionLevel level,\n QuicStreamOffset offset,\n QuicByteCount data_length,\n QuicDataWriter* writer) {\n auto it = crypto_buffer_map_.find(std::make_pair(level, offset));\n if (it == crypto_buffer_map_.end() || it->second.length() < data_length) {\n return false;\n }\n return writer->WriteStringPiece(\n absl::string_view(it->second.data(), data_length));\n}\n\n} \/\/ namespace test\n\n} \/\/ namespace quic\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: certificateextension_xmlsecimpl.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 17:25:06 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _SAL_CONFIG_H_\n#include \n#endif\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n\n#ifndef _certificateextension_nssimpl_hxx_\n#include \"certificateextension_xmlsecimpl.hxx\"\n#endif\n\nusing namespace ::com::sun::star::uno ;\nusing ::rtl::OUString ;\n\nusing ::com::sun::star::security::XCertificateExtension ;\n\nCertificateExtension_XmlSecImpl :: CertificateExtension_XmlSecImpl() :\n m_critical( sal_False ) ,\n m_xExtnId() ,\n m_xExtnValue()\n{\n}\n\nCertificateExtension_XmlSecImpl :: ~CertificateExtension_XmlSecImpl() {\n}\n\n\n\/\/Methods from XCertificateExtension\nsal_Bool SAL_CALL CertificateExtension_XmlSecImpl :: isCritical() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_critical ;\n}\n\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL CertificateExtension_XmlSecImpl :: getExtensionId() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_xExtnId ;\n}\n\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL CertificateExtension_XmlSecImpl :: getExtensionValue() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_xExtnValue ;\n}\n\n\/\/Helper method\nvoid CertificateExtension_XmlSecImpl :: setCertExtn( ::com::sun::star::uno::Sequence< sal_Int8 > extnId, ::com::sun::star::uno::Sequence< sal_Int8 > extnValue, sal_Bool critical ) {\n m_critical = critical ;\n m_xExtnId = extnId ;\n m_xExtnValue = extnValue ;\n}\n\nvoid CertificateExtension_XmlSecImpl :: setCertExtn( unsigned char* value, unsigned int vlen, unsigned char* id, unsigned int idlen, sal_Bool critical ) {\n unsigned int i ;\n if( value != NULL && vlen != 0 ) {\n Sequence< sal_Int8 > extnv( vlen ) ;\n for( i = 0; i < vlen ; i ++ )\n extnv[i] = *( value + i ) ;\n\n m_xExtnValue = extnv ;\n } else {\n m_xExtnValue = NULL ;\n }\n\n if( id != NULL && idlen != 0 ) {\n Sequence< sal_Int8 > extnId( idlen ) ;\n for( i = 0; i < idlen ; i ++ )\n extnId[i] = *( id + i ) ;\n\n m_xExtnId = extnId ;\n } else {\n m_xExtnId = NULL ;\n }\n\n m_critical = critical ;\n}\n\nINTEGRATION: CWS pchfix02 (1.3.86); FILE MERGED 2006\/09\/01 18:00:53 kaib 1.3.86.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: certificateextension_xmlsecimpl.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 14:42:13 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_xmlsecurity.hxx\"\n\n#ifndef _SAL_CONFIG_H_\n#include \n#endif\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n\n#ifndef _certificateextension_nssimpl_hxx_\n#include \"certificateextension_xmlsecimpl.hxx\"\n#endif\n\nusing namespace ::com::sun::star::uno ;\nusing ::rtl::OUString ;\n\nusing ::com::sun::star::security::XCertificateExtension ;\n\nCertificateExtension_XmlSecImpl :: CertificateExtension_XmlSecImpl() :\n m_critical( sal_False ) ,\n m_xExtnId() ,\n m_xExtnValue()\n{\n}\n\nCertificateExtension_XmlSecImpl :: ~CertificateExtension_XmlSecImpl() {\n}\n\n\n\/\/Methods from XCertificateExtension\nsal_Bool SAL_CALL CertificateExtension_XmlSecImpl :: isCritical() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_critical ;\n}\n\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL CertificateExtension_XmlSecImpl :: getExtensionId() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_xExtnId ;\n}\n\n::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL CertificateExtension_XmlSecImpl :: getExtensionValue() throw( ::com::sun::star::uno::RuntimeException ) {\n return m_xExtnValue ;\n}\n\n\/\/Helper method\nvoid CertificateExtension_XmlSecImpl :: setCertExtn( ::com::sun::star::uno::Sequence< sal_Int8 > extnId, ::com::sun::star::uno::Sequence< sal_Int8 > extnValue, sal_Bool critical ) {\n m_critical = critical ;\n m_xExtnId = extnId ;\n m_xExtnValue = extnValue ;\n}\n\nvoid CertificateExtension_XmlSecImpl :: setCertExtn( unsigned char* value, unsigned int vlen, unsigned char* id, unsigned int idlen, sal_Bool critical ) {\n unsigned int i ;\n if( value != NULL && vlen != 0 ) {\n Sequence< sal_Int8 > extnv( vlen ) ;\n for( i = 0; i < vlen ; i ++ )\n extnv[i] = *( value + i ) ;\n\n m_xExtnValue = extnv ;\n } else {\n m_xExtnValue = NULL ;\n }\n\n if( id != NULL && idlen != 0 ) {\n Sequence< sal_Int8 > extnId( idlen ) ;\n for( i = 0; i < idlen ; i ++ )\n extnId[i] = *( id + i ) ;\n\n m_xExtnId = extnId ;\n } else {\n m_xExtnId = NULL ;\n }\n\n m_critical = critical ;\n}\n\n<|endoftext|>"} {"text":"\/\/===--------------------- R600MergeVectorRegisters.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ This pass merges inputs of swizzeable instructions into vector sharing\n\/\/\/ common data and\/or have enough undef subreg using swizzle abilities.\n\/\/\/\n\/\/\/ For instance let's consider the following pseudo code :\n\/\/\/ vreg5 = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3\n\/\/\/ ...\n\/\/\/ vreg7 = REG_SEQ vreg1, sub0, vreg3, sub1, undef, sub2, vreg4, sub3\n\/\/\/ (swizzable Inst) vreg7, SwizzleMask : sub0, sub1, sub2, sub3\n\/\/\/\n\/\/\/ is turned into :\n\/\/\/ vreg5 = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3\n\/\/\/ ...\n\/\/\/ vreg7 = INSERT_SUBREG vreg4, sub3\n\/\/\/ (swizzable Inst) vreg7, SwizzleMask : sub0, sub2, sub1, sub3\n\/\/\/\n\/\/\/ This allow regalloc to reduce register pressure for vector registers and\n\/\/\/ to reduce MOV count.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"vec-merger\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"AMDGPU.h\"\n#include \"R600InstrInfo.h\"\n#include \"llvm\/CodeGen\/DFAPacketizer.h\"\n#include \"llvm\/CodeGen\/MachineDominators.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nstatic bool\nisImplicitlyDef(MachineRegisterInfo &MRI, unsigned Reg) {\n for (MachineRegisterInfo::def_iterator It = MRI.def_begin(Reg),\n E = MRI.def_end(); It != E; ++It) {\n return (*It).isImplicitDef();\n }\n llvm_unreachable(\"Reg without a def\");\n return false;\n}\n\nclass RegSeqInfo {\npublic:\n MachineInstr *Instr;\n DenseMap RegToChan;\n std::vector UndefReg;\n RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {\n assert (MI->getOpcode() == AMDGPU::REG_SEQUENCE);\n for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {\n MachineOperand &MO = Instr->getOperand(i);\n unsigned Chan = Instr->getOperand(i + 1).getImm();\n if (isImplicitlyDef(MRI, MO.getReg()))\n UndefReg.push_back(Chan);\n else\n RegToChan[MO.getReg()] = Chan;\n }\n }\n RegSeqInfo() {}\n\n bool operator==(const RegSeqInfo &RSI) const {\n return RSI.Instr == Instr;\n }\n};\n\nclass R600VectorRegMerger : public MachineFunctionPass {\nprivate:\n MachineRegisterInfo *MRI;\n const R600InstrInfo *TII;\n bool canSwizzle(const MachineInstr &) const;\n bool areAllUsesSwizzeable(unsigned Reg) const;\n void SwizzleInput(MachineInstr &,\n const std::vector > &) const;\n bool tryMergeVector(const RegSeqInfo *, RegSeqInfo *,\n std::vector > &Remap) const;\n bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan);\n bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan);\n MachineInstr *RebuildVector(RegSeqInfo *MI,\n const RegSeqInfo *BaseVec,\n const std::vector > &RemapChan) const;\n void RemoveMI(MachineInstr *);\n void trackRSI(const RegSeqInfo &RSI);\n\n typedef DenseMap > InstructionSetMap;\n DenseMap PreviousRegSeq;\n InstructionSetMap PreviousRegSeqByReg;\n InstructionSetMap PreviousRegSeqByUndefCount;\npublic:\n static char ID;\n R600VectorRegMerger(TargetMachine &tm) : MachineFunctionPass(ID),\n TII(0) { }\n\n void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired();\n AU.addPreserved();\n AU.addRequired();\n AU.addPreserved();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n const char *getPassName() const {\n return \"R600 Vector Registers Merge Pass\";\n }\n\n bool runOnMachineFunction(MachineFunction &Fn);\n};\n\nchar R600VectorRegMerger::ID = 0;\n\nbool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)\n const {\n if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)\n return true;\n switch (MI.getOpcode()) {\n case AMDGPU::R600_ExportSwz:\n case AMDGPU::EG_ExportSwz:\n return true;\n default:\n return false;\n }\n}\n\nbool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,\n RegSeqInfo *ToMerge, std::vector< std::pair > &Remap)\n const {\n unsigned CurrentUndexIdx = 0;\n for (DenseMap::iterator It = ToMerge->RegToChan.begin(),\n E = ToMerge->RegToChan.end(); It != E; ++It) {\n DenseMap::const_iterator PosInUntouched =\n Untouched->RegToChan.find((*It).first);\n if (PosInUntouched != Untouched->RegToChan.end()) {\n Remap.push_back(std::pair\n ((*It).second, (*PosInUntouched).second));\n continue;\n }\n if (CurrentUndexIdx >= Untouched->UndefReg.size())\n return false;\n Remap.push_back(std::pair\n ((*It).second, Untouched->UndefReg[CurrentUndexIdx++]));\n }\n\n return true;\n}\n\nstatic\nunsigned getReassignedChan(\n const std::vector > &RemapChan,\n unsigned Chan) {\n for (unsigned j = 0, je = RemapChan.size(); j < je; j++) {\n if (RemapChan[j].first == Chan)\n return RemapChan[j].second;\n }\n llvm_unreachable(\"Chan wasn't reassigned\");\n}\n\nMachineInstr *R600VectorRegMerger::RebuildVector(\n RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,\n const std::vector > &RemapChan) const {\n unsigned Reg = RSI->Instr->getOperand(0).getReg();\n MachineBasicBlock::iterator Pos = RSI->Instr;\n MachineBasicBlock &MBB = *Pos->getParent();\n DebugLoc DL = Pos->getDebugLoc();\n\n unsigned SrcVec = BaseRSI->Instr->getOperand(0).getReg();\n DenseMap UpdatedRegToChan = BaseRSI->RegToChan;\n std::vector UpdatedUndef = BaseRSI->UndefReg;\n for (DenseMap::iterator It = RSI->RegToChan.begin(),\n E = RSI->RegToChan.end(); It != E; ++It) {\n unsigned DstReg = MRI->createVirtualRegister(&AMDGPU::R600_Reg128RegClass);\n unsigned SubReg = (*It).first;\n unsigned Swizzle = (*It).second;\n unsigned Chan = getReassignedChan(RemapChan, Swizzle);\n\n MachineInstr *Tmp = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::INSERT_SUBREG),\n DstReg)\n .addReg(SrcVec)\n .addReg(SubReg)\n .addImm(Chan);\n UpdatedRegToChan[SubReg] = Chan;\n std::vector::iterator ChanPos =\n std::find(UpdatedUndef.begin(), UpdatedUndef.end(), Chan);\n if (ChanPos != UpdatedUndef.end())\n UpdatedUndef.erase(ChanPos);\n assert(std::find(UpdatedUndef.begin(), UpdatedUndef.end(), Chan) ==\n UpdatedUndef.end() &&\n \"UpdatedUndef shouldn't contain Chan more than once!\");\n DEBUG(dbgs() << \" ->\"; Tmp->dump(););\n (void)Tmp;\n SrcVec = DstReg;\n }\n Pos = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::COPY), Reg)\n .addReg(SrcVec);\n DEBUG(dbgs() << \" ->\"; Pos->dump(););\n\n DEBUG(dbgs() << \" Updating Swizzle:\\n\");\n for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),\n E = MRI->use_end(); It != E; ++It) {\n DEBUG(dbgs() << \" \";(*It).dump(); dbgs() << \" ->\");\n SwizzleInput(*It, RemapChan);\n DEBUG((*It).dump());\n }\n RSI->Instr->eraseFromParent();\n\n \/\/ Update RSI\n RSI->Instr = Pos;\n RSI->RegToChan = UpdatedRegToChan;\n RSI->UndefReg = UpdatedUndef;\n\n return Pos;\n}\n\nvoid R600VectorRegMerger::RemoveMI(MachineInstr *MI) {\n for (InstructionSetMap::iterator It = PreviousRegSeqByReg.begin(),\n E = PreviousRegSeqByReg.end(); It != E; ++It) {\n std::vector &MIs = (*It).second;\n MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());\n }\n for (InstructionSetMap::iterator It = PreviousRegSeqByUndefCount.begin(),\n E = PreviousRegSeqByUndefCount.end(); It != E; ++It) {\n std::vector &MIs = (*It).second;\n MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());\n }\n}\n\nvoid R600VectorRegMerger::SwizzleInput(MachineInstr &MI,\n const std::vector > &RemapChan) const {\n unsigned Offset;\n if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)\n Offset = 2;\n else\n Offset = 3;\n for (unsigned i = 0; i < 4; i++) {\n unsigned Swizzle = MI.getOperand(i + Offset).getImm() + 1;\n for (unsigned j = 0, e = RemapChan.size(); j < e; j++) {\n if (RemapChan[j].first == Swizzle) {\n MI.getOperand(i + Offset).setImm(RemapChan[j].second - 1);\n break;\n }\n }\n }\n}\n\nbool R600VectorRegMerger::areAllUsesSwizzeable(unsigned Reg) const {\n for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),\n E = MRI->use_end(); It != E; ++It) {\n if (!canSwizzle(*It))\n return false;\n }\n return true;\n}\n\nbool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,\n RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan) {\n for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),\n MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {\n if (!MOp->isReg())\n continue;\n if (PreviousRegSeqByReg[MOp->getReg()].empty())\n continue;\n std::vector MIs = PreviousRegSeqByReg[MOp->getReg()];\n for (unsigned i = 0, e = MIs.size(); i < e; i++) {\n CompatibleRSI = PreviousRegSeq[MIs[i]];\n if (RSI == CompatibleRSI)\n continue;\n if (tryMergeVector(&CompatibleRSI, &RSI, RemapChan))\n return true;\n }\n }\n return false;\n}\n\nbool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,\n RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan) {\n unsigned NeededUndefs = 4 - RSI.UndefReg.size();\n if (PreviousRegSeqByUndefCount[NeededUndefs].empty())\n return false;\n std::vector &MIs =\n PreviousRegSeqByUndefCount[NeededUndefs];\n CompatibleRSI = PreviousRegSeq[MIs.back()];\n tryMergeVector(&CompatibleRSI, &RSI, RemapChan);\n return true;\n}\n\nvoid R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {\n for (DenseMap::const_iterator\n It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {\n PreviousRegSeqByReg[(*It).first].push_back(RSI.Instr);\n }\n PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(RSI.Instr);\n PreviousRegSeq[RSI.Instr] = RSI;\n}\n\nbool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {\n TII = static_cast(Fn.getTarget().getInstrInfo());\n MRI = &(Fn.getRegInfo());\n for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();\n MBB != MBBe; ++MBB) {\n MachineBasicBlock *MB = MBB;\n PreviousRegSeq.clear();\n PreviousRegSeqByReg.clear();\n PreviousRegSeqByUndefCount.clear();\n\n for (MachineBasicBlock::iterator MII = MB->begin(), MIIE = MB->end();\n MII != MIIE; ++MII) {\n MachineInstr *MI = MII;\n if (MI->getOpcode() != AMDGPU::REG_SEQUENCE)\n continue;\n\n RegSeqInfo RSI(*MRI, MI);\n\n \/\/ All uses of MI are swizzeable ?\n unsigned Reg = MI->getOperand(0).getReg();\n if (!areAllUsesSwizzeable(Reg))\n continue;\n\n DEBUG (dbgs() << \"Trying to optimize \";\n MI->dump();\n );\n\n RegSeqInfo CandidateRSI;\n std::vector > RemapChan;\n DEBUG(dbgs() << \"Using common slots...\\n\";);\n if (tryMergeUsingCommonSlot(RSI, CandidateRSI, RemapChan)) {\n \/\/ Remove CandidateRSI mapping\n RemoveMI(CandidateRSI.Instr);\n MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);\n trackRSI(RSI);\n continue;\n }\n DEBUG(dbgs() << \"Using free slots...\\n\";);\n RemapChan.clear();\n if (tryMergeUsingFreeSlot(RSI, CandidateRSI, RemapChan)) {\n RemoveMI(CandidateRSI.Instr);\n MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);\n trackRSI(RSI);\n continue;\n }\n \/\/Failed to merge\n trackRSI(RSI);\n }\n }\n return false;\n}\n\n}\n\nllvm::FunctionPass *llvm::createR600VectorRegMerger(TargetMachine &tm) {\n return new R600VectorRegMerger(tm);\n}\nR600: Do not mergevector after a vector reg is used\/\/===--------------------- R600MergeVectorRegisters.cpp -------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/\/ \\file\n\/\/\/ This pass merges inputs of swizzeable instructions into vector sharing\n\/\/\/ common data and\/or have enough undef subreg using swizzle abilities.\n\/\/\/\n\/\/\/ For instance let's consider the following pseudo code :\n\/\/\/ vreg5 = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3\n\/\/\/ ...\n\/\/\/ vreg7 = REG_SEQ vreg1, sub0, vreg3, sub1, undef, sub2, vreg4, sub3\n\/\/\/ (swizzable Inst) vreg7, SwizzleMask : sub0, sub1, sub2, sub3\n\/\/\/\n\/\/\/ is turned into :\n\/\/\/ vreg5 = REG_SEQ vreg1, sub0, vreg2, sub1, vreg3, sub2, undef, sub3\n\/\/\/ ...\n\/\/\/ vreg7 = INSERT_SUBREG vreg4, sub3\n\/\/\/ (swizzable Inst) vreg7, SwizzleMask : sub0, sub2, sub1, sub3\n\/\/\/\n\/\/\/ This allow regalloc to reduce register pressure for vector registers and\n\/\/\/ to reduce MOV count.\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"vec-merger\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"AMDGPU.h\"\n#include \"R600InstrInfo.h\"\n#include \"llvm\/CodeGen\/DFAPacketizer.h\"\n#include \"llvm\/CodeGen\/MachineDominators.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineLoopInfo.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n\nusing namespace llvm;\n\nnamespace {\n\nstatic bool\nisImplicitlyDef(MachineRegisterInfo &MRI, unsigned Reg) {\n for (MachineRegisterInfo::def_iterator It = MRI.def_begin(Reg),\n E = MRI.def_end(); It != E; ++It) {\n return (*It).isImplicitDef();\n }\n llvm_unreachable(\"Reg without a def\");\n return false;\n}\n\nclass RegSeqInfo {\npublic:\n MachineInstr *Instr;\n DenseMap RegToChan;\n std::vector UndefReg;\n RegSeqInfo(MachineRegisterInfo &MRI, MachineInstr *MI) : Instr(MI) {\n assert (MI->getOpcode() == AMDGPU::REG_SEQUENCE);\n for (unsigned i = 1, e = Instr->getNumOperands(); i < e; i+=2) {\n MachineOperand &MO = Instr->getOperand(i);\n unsigned Chan = Instr->getOperand(i + 1).getImm();\n if (isImplicitlyDef(MRI, MO.getReg()))\n UndefReg.push_back(Chan);\n else\n RegToChan[MO.getReg()] = Chan;\n }\n }\n RegSeqInfo() {}\n\n bool operator==(const RegSeqInfo &RSI) const {\n return RSI.Instr == Instr;\n }\n};\n\nclass R600VectorRegMerger : public MachineFunctionPass {\nprivate:\n MachineRegisterInfo *MRI;\n const R600InstrInfo *TII;\n bool canSwizzle(const MachineInstr &) const;\n bool areAllUsesSwizzeable(unsigned Reg) const;\n void SwizzleInput(MachineInstr &,\n const std::vector > &) const;\n bool tryMergeVector(const RegSeqInfo *, RegSeqInfo *,\n std::vector > &Remap) const;\n bool tryMergeUsingCommonSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan);\n bool tryMergeUsingFreeSlot(RegSeqInfo &RSI, RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan);\n MachineInstr *RebuildVector(RegSeqInfo *MI,\n const RegSeqInfo *BaseVec,\n const std::vector > &RemapChan) const;\n void RemoveMI(MachineInstr *);\n void trackRSI(const RegSeqInfo &RSI);\n\n typedef DenseMap > InstructionSetMap;\n DenseMap PreviousRegSeq;\n InstructionSetMap PreviousRegSeqByReg;\n InstructionSetMap PreviousRegSeqByUndefCount;\npublic:\n static char ID;\n R600VectorRegMerger(TargetMachine &tm) : MachineFunctionPass(ID),\n TII(0) { }\n\n void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n AU.addRequired();\n AU.addPreserved();\n AU.addRequired();\n AU.addPreserved();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n const char *getPassName() const {\n return \"R600 Vector Registers Merge Pass\";\n }\n\n bool runOnMachineFunction(MachineFunction &Fn);\n};\n\nchar R600VectorRegMerger::ID = 0;\n\nbool R600VectorRegMerger::canSwizzle(const MachineInstr &MI)\n const {\n if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)\n return true;\n switch (MI.getOpcode()) {\n case AMDGPU::R600_ExportSwz:\n case AMDGPU::EG_ExportSwz:\n return true;\n default:\n return false;\n }\n}\n\nbool R600VectorRegMerger::tryMergeVector(const RegSeqInfo *Untouched,\n RegSeqInfo *ToMerge, std::vector< std::pair > &Remap)\n const {\n unsigned CurrentUndexIdx = 0;\n for (DenseMap::iterator It = ToMerge->RegToChan.begin(),\n E = ToMerge->RegToChan.end(); It != E; ++It) {\n DenseMap::const_iterator PosInUntouched =\n Untouched->RegToChan.find((*It).first);\n if (PosInUntouched != Untouched->RegToChan.end()) {\n Remap.push_back(std::pair\n ((*It).second, (*PosInUntouched).second));\n continue;\n }\n if (CurrentUndexIdx >= Untouched->UndefReg.size())\n return false;\n Remap.push_back(std::pair\n ((*It).second, Untouched->UndefReg[CurrentUndexIdx++]));\n }\n\n return true;\n}\n\nstatic\nunsigned getReassignedChan(\n const std::vector > &RemapChan,\n unsigned Chan) {\n for (unsigned j = 0, je = RemapChan.size(); j < je; j++) {\n if (RemapChan[j].first == Chan)\n return RemapChan[j].second;\n }\n llvm_unreachable(\"Chan wasn't reassigned\");\n}\n\nMachineInstr *R600VectorRegMerger::RebuildVector(\n RegSeqInfo *RSI, const RegSeqInfo *BaseRSI,\n const std::vector > &RemapChan) const {\n unsigned Reg = RSI->Instr->getOperand(0).getReg();\n MachineBasicBlock::iterator Pos = RSI->Instr;\n MachineBasicBlock &MBB = *Pos->getParent();\n DebugLoc DL = Pos->getDebugLoc();\n\n unsigned SrcVec = BaseRSI->Instr->getOperand(0).getReg();\n DenseMap UpdatedRegToChan = BaseRSI->RegToChan;\n std::vector UpdatedUndef = BaseRSI->UndefReg;\n for (DenseMap::iterator It = RSI->RegToChan.begin(),\n E = RSI->RegToChan.end(); It != E; ++It) {\n unsigned DstReg = MRI->createVirtualRegister(&AMDGPU::R600_Reg128RegClass);\n unsigned SubReg = (*It).first;\n unsigned Swizzle = (*It).second;\n unsigned Chan = getReassignedChan(RemapChan, Swizzle);\n\n MachineInstr *Tmp = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::INSERT_SUBREG),\n DstReg)\n .addReg(SrcVec)\n .addReg(SubReg)\n .addImm(Chan);\n UpdatedRegToChan[SubReg] = Chan;\n std::vector::iterator ChanPos =\n std::find(UpdatedUndef.begin(), UpdatedUndef.end(), Chan);\n if (ChanPos != UpdatedUndef.end())\n UpdatedUndef.erase(ChanPos);\n assert(std::find(UpdatedUndef.begin(), UpdatedUndef.end(), Chan) ==\n UpdatedUndef.end() &&\n \"UpdatedUndef shouldn't contain Chan more than once!\");\n DEBUG(dbgs() << \" ->\"; Tmp->dump(););\n (void)Tmp;\n SrcVec = DstReg;\n }\n Pos = BuildMI(MBB, Pos, DL, TII->get(AMDGPU::COPY), Reg)\n .addReg(SrcVec);\n DEBUG(dbgs() << \" ->\"; Pos->dump(););\n\n DEBUG(dbgs() << \" Updating Swizzle:\\n\");\n for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),\n E = MRI->use_end(); It != E; ++It) {\n DEBUG(dbgs() << \" \";(*It).dump(); dbgs() << \" ->\");\n SwizzleInput(*It, RemapChan);\n DEBUG((*It).dump());\n }\n RSI->Instr->eraseFromParent();\n\n \/\/ Update RSI\n RSI->Instr = Pos;\n RSI->RegToChan = UpdatedRegToChan;\n RSI->UndefReg = UpdatedUndef;\n\n return Pos;\n}\n\nvoid R600VectorRegMerger::RemoveMI(MachineInstr *MI) {\n for (InstructionSetMap::iterator It = PreviousRegSeqByReg.begin(),\n E = PreviousRegSeqByReg.end(); It != E; ++It) {\n std::vector &MIs = (*It).second;\n MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());\n }\n for (InstructionSetMap::iterator It = PreviousRegSeqByUndefCount.begin(),\n E = PreviousRegSeqByUndefCount.end(); It != E; ++It) {\n std::vector &MIs = (*It).second;\n MIs.erase(std::find(MIs.begin(), MIs.end(), MI), MIs.end());\n }\n}\n\nvoid R600VectorRegMerger::SwizzleInput(MachineInstr &MI,\n const std::vector > &RemapChan) const {\n unsigned Offset;\n if (TII->get(MI.getOpcode()).TSFlags & R600_InstFlag::TEX_INST)\n Offset = 2;\n else\n Offset = 3;\n for (unsigned i = 0; i < 4; i++) {\n unsigned Swizzle = MI.getOperand(i + Offset).getImm() + 1;\n for (unsigned j = 0, e = RemapChan.size(); j < e; j++) {\n if (RemapChan[j].first == Swizzle) {\n MI.getOperand(i + Offset).setImm(RemapChan[j].second - 1);\n break;\n }\n }\n }\n}\n\nbool R600VectorRegMerger::areAllUsesSwizzeable(unsigned Reg) const {\n for (MachineRegisterInfo::use_iterator It = MRI->use_begin(Reg),\n E = MRI->use_end(); It != E; ++It) {\n if (!canSwizzle(*It))\n return false;\n }\n return true;\n}\n\nbool R600VectorRegMerger::tryMergeUsingCommonSlot(RegSeqInfo &RSI,\n RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan) {\n for (MachineInstr::mop_iterator MOp = RSI.Instr->operands_begin(),\n MOE = RSI.Instr->operands_end(); MOp != MOE; ++MOp) {\n if (!MOp->isReg())\n continue;\n if (PreviousRegSeqByReg[MOp->getReg()].empty())\n continue;\n std::vector MIs = PreviousRegSeqByReg[MOp->getReg()];\n for (unsigned i = 0, e = MIs.size(); i < e; i++) {\n CompatibleRSI = PreviousRegSeq[MIs[i]];\n if (RSI == CompatibleRSI)\n continue;\n if (tryMergeVector(&CompatibleRSI, &RSI, RemapChan))\n return true;\n }\n }\n return false;\n}\n\nbool R600VectorRegMerger::tryMergeUsingFreeSlot(RegSeqInfo &RSI,\n RegSeqInfo &CompatibleRSI,\n std::vector > &RemapChan) {\n unsigned NeededUndefs = 4 - RSI.UndefReg.size();\n if (PreviousRegSeqByUndefCount[NeededUndefs].empty())\n return false;\n std::vector &MIs =\n PreviousRegSeqByUndefCount[NeededUndefs];\n CompatibleRSI = PreviousRegSeq[MIs.back()];\n tryMergeVector(&CompatibleRSI, &RSI, RemapChan);\n return true;\n}\n\nvoid R600VectorRegMerger::trackRSI(const RegSeqInfo &RSI) {\n for (DenseMap::const_iterator\n It = RSI.RegToChan.begin(), E = RSI.RegToChan.end(); It != E; ++It) {\n PreviousRegSeqByReg[(*It).first].push_back(RSI.Instr);\n }\n PreviousRegSeqByUndefCount[RSI.UndefReg.size()].push_back(RSI.Instr);\n PreviousRegSeq[RSI.Instr] = RSI;\n}\n\nbool R600VectorRegMerger::runOnMachineFunction(MachineFunction &Fn) {\n TII = static_cast(Fn.getTarget().getInstrInfo());\n MRI = &(Fn.getRegInfo());\n for (MachineFunction::iterator MBB = Fn.begin(), MBBe = Fn.end();\n MBB != MBBe; ++MBB) {\n MachineBasicBlock *MB = MBB;\n PreviousRegSeq.clear();\n PreviousRegSeqByReg.clear();\n PreviousRegSeqByUndefCount.clear();\n\n for (MachineBasicBlock::iterator MII = MB->begin(), MIIE = MB->end();\n MII != MIIE; ++MII) {\n MachineInstr *MI = MII;\n if (MI->getOpcode() != AMDGPU::REG_SEQUENCE) {\n if (TII->get(MI->getOpcode()).TSFlags & R600_InstFlag::TEX_INST) {\n unsigned Reg = MI->getOperand(1).getReg();\n for (MachineRegisterInfo::def_iterator It = MRI->def_begin(Reg),\n E = MRI->def_end(); It != E; ++It) {\n RemoveMI(&(*It));\n }\n }\n continue;\n }\n\n\n RegSeqInfo RSI(*MRI, MI);\n\n \/\/ All uses of MI are swizzeable ?\n unsigned Reg = MI->getOperand(0).getReg();\n if (!areAllUsesSwizzeable(Reg))\n continue;\n\n DEBUG (dbgs() << \"Trying to optimize \";\n MI->dump();\n );\n\n RegSeqInfo CandidateRSI;\n std::vector > RemapChan;\n DEBUG(dbgs() << \"Using common slots...\\n\";);\n if (tryMergeUsingCommonSlot(RSI, CandidateRSI, RemapChan)) {\n \/\/ Remove CandidateRSI mapping\n RemoveMI(CandidateRSI.Instr);\n MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);\n trackRSI(RSI);\n continue;\n }\n DEBUG(dbgs() << \"Using free slots...\\n\";);\n RemapChan.clear();\n if (tryMergeUsingFreeSlot(RSI, CandidateRSI, RemapChan)) {\n RemoveMI(CandidateRSI.Instr);\n MII = RebuildVector(&RSI, &CandidateRSI, RemapChan);\n trackRSI(RSI);\n continue;\n }\n \/\/Failed to merge\n trackRSI(RSI);\n }\n }\n return false;\n}\n\n}\n\nllvm::FunctionPass *llvm::createR600VectorRegMerger(TargetMachine &tm) {\n return new R600VectorRegMerger(tm);\n}\n<|endoftext|>"} {"text":"\/\/===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===\/\/\n\/\/\n\/\/ This pass is used to ensure that functions have at most one return\n\/\/ instruction in them. Additionally, it keeps track of which node is the new\n\/\/ exit node of the CFG. If there are no exit nodes in the CFG, the getExitNode\n\/\/ method will return a null pointer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/UnifyFunctionExitNodes.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iPHINode.h\"\n#include \"llvm\/Type.h\"\nusing std::vector;\n\nAnalysisID UnifyFunctionExitNodes::ID(AnalysisID::create());\n\n\n\/\/ UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new\n\/\/ BasicBlock, and converting all returns to unconditional branches to this\n\/\/ new basic block. The singular exit node is returned.\n\/\/\n\/\/ If there are no return stmts in the Function, a null pointer is returned.\n\/\/\nbool UnifyFunctionExitNodes::runOnFunction(Function *M) {\n \/\/ Loop over all of the blocks in a function, tracking all of the blocks that\n \/\/ return.\n \/\/\n vector ReturningBlocks;\n for(Function::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (isa((*I)->getTerminator()))\n ReturningBlocks.push_back(*I);\n\n if (ReturningBlocks.empty()) {\n ExitNode = 0;\n return false; \/\/ No blocks return\n } else if (ReturningBlocks.size() == 1) {\n ExitNode = ReturningBlocks.front(); \/\/ Already has a single return block\n return false;\n }\n\n \/\/ Otherwise, we need to insert a new basic block into the function, add a PHI\n \/\/ node (if the function returns a value), and convert all of the return \n \/\/ instructions into unconditional branches.\n \/\/\n BasicBlock *NewRetBlock = new BasicBlock(\"UnifiedExitNode\", M);\n\n if (M->getReturnType() != Type::VoidTy) {\n \/\/ If the function doesn't return void... add a PHI node to the block...\n PHINode *PN = new PHINode(M->getReturnType());\n NewRetBlock->getInstList().push_back(PN);\n\n \/\/ Add an incoming element to the PHI node for every return instruction that\n \/\/ is merging into this new block...\n for (vector::iterator I = ReturningBlocks.begin(), \n E = ReturningBlocks.end(); I != E; ++I)\n PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);\n\n \/\/ Add a return instruction to return the result of the PHI node...\n NewRetBlock->getInstList().push_back(new ReturnInst(PN));\n } else {\n \/\/ If it returns void, just add a return void instruction to the block\n NewRetBlock->getInstList().push_back(new ReturnInst());\n }\n\n \/\/ Loop over all of the blocks, replacing the return instruction with an\n \/\/ unconditional branch.\n \/\/\n for (vector::iterator I = ReturningBlocks.begin(), \n E = ReturningBlocks.end(); I != E; ++I) {\n delete (*I)->getInstList().pop_back(); \/\/ Remove the return insn\n (*I)->getInstList().push_back(new BranchInst(NewRetBlock));\n }\n ExitNode = NewRetBlock;\n return true;\n}\nGive the unified exit node a name\/\/===- UnifyFunctionExitNodes.cpp - Make all functions have a single exit -===\/\/\n\/\/\n\/\/ This pass is used to ensure that functions have at most one return\n\/\/ instruction in them. Additionally, it keeps track of which node is the new\n\/\/ exit node of the CFG. If there are no exit nodes in the CFG, the getExitNode\n\/\/ method will return a null pointer.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/UnifyFunctionExitNodes.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/Function.h\"\n#include \"llvm\/iTerminators.h\"\n#include \"llvm\/iPHINode.h\"\n#include \"llvm\/Type.h\"\nusing std::vector;\n\nAnalysisID UnifyFunctionExitNodes::ID(AnalysisID::create());\n\n\n\/\/ UnifyAllExitNodes - Unify all exit nodes of the CFG by creating a new\n\/\/ BasicBlock, and converting all returns to unconditional branches to this\n\/\/ new basic block. The singular exit node is returned.\n\/\/\n\/\/ If there are no return stmts in the Function, a null pointer is returned.\n\/\/\nbool UnifyFunctionExitNodes::runOnFunction(Function *M) {\n \/\/ Loop over all of the blocks in a function, tracking all of the blocks that\n \/\/ return.\n \/\/\n vector ReturningBlocks;\n for(Function::iterator I = M->begin(), E = M->end(); I != E; ++I)\n if (isa((*I)->getTerminator()))\n ReturningBlocks.push_back(*I);\n\n if (ReturningBlocks.empty()) {\n ExitNode = 0;\n return false; \/\/ No blocks return\n } else if (ReturningBlocks.size() == 1) {\n ExitNode = ReturningBlocks.front(); \/\/ Already has a single return block\n return false;\n }\n\n \/\/ Otherwise, we need to insert a new basic block into the function, add a PHI\n \/\/ node (if the function returns a value), and convert all of the return \n \/\/ instructions into unconditional branches.\n \/\/\n BasicBlock *NewRetBlock = new BasicBlock(\"UnifiedExitNode\", M);\n\n if (M->getReturnType() != Type::VoidTy) {\n \/\/ If the function doesn't return void... add a PHI node to the block...\n PHINode *PN = new PHINode(M->getReturnType(), \"UnifiedRetVal\");\n NewRetBlock->getInstList().push_back(PN);\n\n \/\/ Add an incoming element to the PHI node for every return instruction that\n \/\/ is merging into this new block...\n for (vector::iterator I = ReturningBlocks.begin(), \n E = ReturningBlocks.end(); I != E; ++I)\n PN->addIncoming((*I)->getTerminator()->getOperand(0), *I);\n\n \/\/ Add a return instruction to return the result of the PHI node...\n NewRetBlock->getInstList().push_back(new ReturnInst(PN));\n } else {\n \/\/ If it returns void, just add a return void instruction to the block\n NewRetBlock->getInstList().push_back(new ReturnInst());\n }\n\n \/\/ Loop over all of the blocks, replacing the return instruction with an\n \/\/ unconditional branch.\n \/\/\n for (vector::iterator I = ReturningBlocks.begin(), \n E = ReturningBlocks.end(); I != E; ++I) {\n delete (*I)->getInstList().pop_back(); \/\/ Remove the return insn\n (*I)->getInstList().push_back(new BranchInst(NewRetBlock));\n }\n ExitNode = NewRetBlock;\n return true;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2018 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"hooks\/hooks.h\"\n\n#include \n#include \n\nvoid LibraryHooks::BeginHookRegistration()\n{\n \/\/ nothing to do\n}\n\nvoid LibraryHooks::RegisterFunctionHook(const char *libraryName, const FunctionHook &hook)\n{\n}\n\nvoid LibraryHooks::RegisterLibraryHook(char const *, FunctionLoadCallback cb)\n{\n if(cb)\n RDCERR(\"Hooking on apple not complete - function load callback not implemented\");\n}\n\nvoid LibraryHooks::IgnoreLibrary(const char *libraryName)\n{\n}\n\nvoid LibraryHooks::EndHookRegistration()\n{\n}\n\nbool LibraryHooks::Detect(const char *identifier)\n{\n return dlsym(RTLD_DEFAULT, identifier) != NULL;\n}\n\nvoid LibraryHooks::RemoveHooks()\n{\n RDCERR(\"Removing hooks is not possible on this platform\");\n}\n\n\/\/ android only hooking functions, not used on apple\nScopedSuppressHooking::ScopedSuppressHooking()\n{\n}\n\nScopedSuppressHooking::~ScopedSuppressHooking()\n{\n}\n\nvoid LibraryHooks::Refresh()\n{\n}Implement hooking support on apple\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2016-2018 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"common\/threading.h\"\n#include \"hooks\/hooks.h\"\n#include \"strings\/string_utils.h\"\n\nThreading::CriticalSection libLock;\n\nstatic std::map> libraryCallbacks;\nstatic std::set libraryHooks;\nstatic std::vector functionHooks;\nstatic std::set libraryHandles;\n\nvoid *interposed_dlopen(const char *filename, int flag)\n{\n void *handle = dlopen(filename, flag);\n\n std::string baseFilename = filename ? basename(std::string(filename)) : \"\";\n\n {\n SCOPED_LOCK(libLock);\n\n \/\/ we don't redirect to ourselves, but we do remember this handle so we can intercept any\n \/\/ subsequent dlsym calls.\n if(libraryHooks.find(baseFilename) != libraryHooks.end())\n libraryHandles.insert(handle);\n }\n\n return handle;\n}\n\nvoid *interposed_dlsym(void *handle, const char *name)\n{\n {\n SCOPED_LOCK(libLock);\n if(libraryHandles.find(handle) != libraryHandles.end())\n {\n for(FunctionHook &hook : functionHooks)\n if(hook.function == name)\n return hook.hook;\n }\n }\n\n return dlsym(handle, name);\n}\n\nstruct interposer\n{\n const void *replacment;\n const void *replacee;\n};\n\n__attribute__((used)) static interposer dlfuncs[] __attribute__((section(\"__DATA,__interpose\"))) = {\n {(const void *)(unsigned long)&interposed_dlsym, (const void *)(unsigned long)&dlsym},\n {(const void *)(unsigned long)&interposed_dlopen, (const void *)(unsigned long)&dlopen},\n};\n\nvoid LibraryHooks::BeginHookRegistration()\n{\n \/\/ nothing to do\n}\n\nbool LibraryHooks::Detect(const char *identifier)\n{\n return dlsym(RTLD_DEFAULT, identifier) != NULL;\n}\n\nvoid LibraryHooks::RemoveHooks()\n{\n RDCERR(\"Removing hooks is not possible on this platform\");\n}\n\nvoid LibraryHooks::EndHookRegistration()\n{\n \/\/ process libraries with callbacks by loading them if necessary (though we should be linked to\n \/\/ them for the dyld interposing)\n for(auto it = libraryCallbacks.begin(); it != libraryCallbacks.end(); ++it)\n {\n std::string libName = it->first;\n void *handle = dlopen(libName.c_str(), RTLD_NOW | RTLD_GLOBAL);\n\n if(handle)\n {\n for(FunctionLoadCallback cb : it->second)\n if(cb)\n cb(handle);\n\n \/\/ don't call callbacks again if the library is dlopen'd again\n it->second.clear();\n }\n }\n\n \/\/ get the original pointers for all hooks now. All of the ones we will be able to get should now\n \/\/ be available in the default namespace straight away\n for(FunctionHook &hook : functionHooks)\n {\n if(hook.orig && *hook.orig == NULL)\n {\n *hook.orig = dlsym(RTLD_NEXT, hook.function.c_str());\n RDCASSERT(*hook.orig != hook.hook, hook.function);\n }\n }\n}\n\nvoid LibraryHooks::Refresh()\n{\n \/\/ don't need to refresh on mac\n}\n\nvoid LibraryHooks::RegisterFunctionHook(const char *libraryName, const FunctionHook &hook)\n{\n \/\/ we don't use the library name\n (void)libraryName;\n\n SCOPED_LOCK(libLock);\n functionHooks.push_back(hook);\n}\n\nvoid LibraryHooks::RegisterLibraryHook(char const *name, FunctionLoadCallback cb)\n{\n SCOPED_LOCK(libLock);\n\n \/\/ we match by basename for library hooks\n libraryHooks.insert(basename(std::string(name)));\n\n if(cb)\n libraryCallbacks[name].push_back(cb);\n}\n\nvoid LibraryHooks::IgnoreLibrary(const char *libraryName)\n{\n}\n\n\/\/ android only hooking functions, not used on apple\nScopedSuppressHooking::ScopedSuppressHooking()\n{\n}\n\nScopedSuppressHooking::~ScopedSuppressHooking()\n{\n}<|endoftext|>"} {"text":"\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"api\/app\/renderdoc_app.h\"\n#include \"common\/threading.h\"\n#include \"os\/os_specific.h\"\n#include \"strings\/string_utils.h\"\n\nusing std::string;\n\nnamespace Keyboard\n{\nvoid Init()\n{\n}\n\nbool PlatformHasKeyInput()\n{\n return false;\n}\n\nvoid AddInputWindow(WindowingSystem windowSystem, void *wnd)\n{\n}\n\nvoid RemoveInputWindow(WindowingSystem windowSystem, void *wnd)\n{\n}\n\nbool GetKeyState(int key)\n{\n return false;\n}\n}\n\nnamespace FileIO\n{\nstring GetTempRootPath()\n{\n return \"\/tmp\";\n}\n\nstring GetAppFolderFilename(const string &filename)\n{\n const char *homedir = NULL;\n if(getenv(\"HOME\") != NULL)\n {\n homedir = getenv(\"HOME\");\n RDCLOG(\"$HOME value is %s\", homedir);\n }\n else\n {\n RDCLOG(\"$HOME value is NULL\");\n homedir = getpwuid(getuid())->pw_dir;\n }\n\n string ret = string(homedir) + \"\/.renderdoc\/\";\n\n mkdir(ret.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\n return ret + filename;\n}\n\nvoid GetExecutableFilename(string &selfName)\n{\n char path[512] = {0};\n readlink(\"\/proc\/self\/exe\", path, 511);\n\n selfName = string(path);\n}\n\nint LibraryLocator = 42;\n\nvoid GetLibraryFilename(string &selfName)\n{\n \/\/ this is a hack, but the only reliable way to find the absolute path to the library.\n \/\/ dladdr would be fine but it returns the wrong result for symbols in the library\n\n string librenderdoc_path;\n\n FILE *f = fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n \/\/ read the whole thing in one go. There's no need to try and be tight with\n \/\/ this allocation, so just make sure we can read everything.\n char *map_string = new char[1024 * 1024];\n memset(map_string, 0, 1024 * 1024);\n\n ::fread(map_string, 1, 1024 * 1024, f);\n\n ::fclose(f);\n\n char *c = strstr(map_string, \"\/librenderdoc.so\");\n\n if(c)\n {\n \/\/ walk backwards until we hit the start of the line\n while(c > map_string)\n {\n c--;\n\n if(c[0] == '\\n')\n {\n c++;\n break;\n }\n }\n\n \/\/ walk forwards across the address range (00400000-0040c000)\n while(isalnum(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ permissions (r-xp)\n while(isalpha(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ offset (0000b000)\n while(isalnum(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ dev\n while(isalnum(c[0]) || c[0] == ':')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ inode\n while(isdigit(c[0]))\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ FINALLY we are at the start of the actual path\n char *end = strchr(c, '\\n');\n\n if(end)\n librenderdoc_path = string(c, end - c);\n }\n\n delete[] map_string;\n }\n\n if(librenderdoc_path.empty())\n {\n RDCWARN(\"Couldn't get librenderdoc.so path from \/proc\/self\/maps, falling back to dladdr\");\n\n Dl_info info;\n if(dladdr(&LibraryLocator, &info))\n librenderdoc_path = info.dli_fname;\n }\n\n selfName = librenderdoc_path;\n}\n};\n\nnamespace StringFormat\n{\n\/\/ cache iconv_t descriptor to save on iconv_open\/iconv_close each time\niconv_t iconvWide2UTF8 = (iconv_t)-1;\niconv_t iconvUTF82Wide = (iconv_t)-1;\n\n\/\/ iconv is not thread safe when sharing an iconv_t descriptor\n\/\/ I don't expect much contention but if it happens we could TryLock\n\/\/ before creating a temporary iconv_t, or hold two iconv_ts, or something.\nThreading::CriticalSection iconvLock;\n\nvoid Shutdown()\n{\n SCOPED_LOCK(iconvLock);\n\n if(iconvWide2UTF8 != (iconv_t)-1)\n iconv_close(iconvWide2UTF8);\n iconvWide2UTF8 = (iconv_t)-1;\n\n if(iconvUTF82Wide != (iconv_t)-1)\n iconv_close(iconvUTF82Wide);\n iconvUTF82Wide = (iconv_t)-1;\n}\n\nstd::string Wide2UTF8(const std::wstring &s)\n{\n \/\/ include room for null terminator, assuming unicode input (not ucs)\n \/\/ utf-8 characters can be max 4 bytes.\n size_t len = (s.length() + 1) * 4;\n\n std::vector charBuffer(len);\n\n size_t ret;\n\n {\n SCOPED_LOCK(iconvLock);\n\n if(iconvWide2UTF8 == (iconv_t)-1)\n iconvWide2UTF8 = iconv_open(\"UTF-8\", \"WCHAR_T\");\n\n if(iconvWide2UTF8 == (iconv_t)-1)\n {\n RDCERR(\"Couldn't open iconv for WCHAR_T to UTF-8: %d\", errno);\n return \"\";\n }\n\n char *inbuf = (char *)s.c_str();\n size_t insize = (s.length() + 1) * sizeof(wchar_t); \/\/ include null terminator\n char *outbuf = &charBuffer[0];\n size_t outsize = len;\n\n ret = iconv(iconvWide2UTF8, &inbuf, &insize, &outbuf, &outsize);\n }\n\n if(ret == (size_t)-1)\n {\n#if ENABLED(RDOC_DEVEL)\n RDCWARN(\"Failed to convert wstring\");\n#endif\n return \"\";\n }\n\n \/\/ convert to string from null-terminated string - utf-8 never contains\n \/\/ 0 bytes before the null terminator, and this way we don't care if\n \/\/ charBuffer is larger than the string\n return std::string(&charBuffer[0]);\n}\n\nstd::wstring UTF82Wide(const std::string &s)\n{\n \/\/ include room for null terminator, for ascii input we need at least as many output chars as\n \/\/ input.\n size_t len = s.length() + 1;\n\n std::vector wcharBuffer(len);\n\n size_t ret;\n\n {\n SCOPED_LOCK(iconvLock);\n\n if(iconvUTF82Wide == (iconv_t)-1)\n iconvUTF82Wide = iconv_open(\"WCHAR_T\", \"UTF-8\");\n\n if(iconvUTF82Wide == (iconv_t)-1)\n {\n RDCERR(\"Couldn't open iconv for UTF-8 to WCHAR_T: %d\", errno);\n return L\"\";\n }\n\n char *inbuf = (char *)s.c_str();\n size_t insize = s.length() + 1; \/\/ include null terminator\n char *outbuf = (char *)&wcharBuffer[0];\n size_t outsize = len * sizeof(wchar_t);\n\n ret = iconv(iconvUTF82Wide, &inbuf, &insize, &outbuf, &outsize);\n }\n\n if(ret == (size_t)-1)\n {\n#if ENABLED(RDOC_DEVEL)\n RDCWARN(\"Failed to convert wstring\");\n#endif\n return L\"\";\n }\n\n \/\/ convert to string from null-terminated string\n return std::wstring(&wcharBuffer[0]);\n}\n};\n\nnamespace OSUtility\n{\nvoid WriteOutput(int channel, const char *str)\n{\n if(channel == OSUtility::Output_StdOut)\n {\n fprintf(stdout, \"%s\", str);\n fflush(stdout);\n }\n else if(channel == OSUtility::Output_StdErr)\n {\n fprintf(stderr, \"%s\", str);\n fflush(stderr);\n }\n}\n\nuint64_t GetMachineIdent()\n{\n uint64_t ret = MachineIdent_Linux;\n\n#if defined(_M_ARM) || defined(__arm__)\n ret |= MachineIdent_Arch_ARM;\n#else\n ret |= MachineIdent_Arch_x86;\n#endif\n\n#if ENABLED(RDOC_X64)\n ret |= MachineIdent_64bit;\n#else\n ret |= MachineIdent_32bit;\n#endif\n\n return ret;\n}\n};\nRemove dangling 'using std::string'\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"api\/app\/renderdoc_app.h\"\n#include \"common\/threading.h\"\n#include \"os\/os_specific.h\"\n#include \"strings\/string_utils.h\"\n\nnamespace Keyboard\n{\nvoid Init()\n{\n}\n\nbool PlatformHasKeyInput()\n{\n return false;\n}\n\nvoid AddInputWindow(WindowingSystem windowSystem, void *wnd)\n{\n}\n\nvoid RemoveInputWindow(WindowingSystem windowSystem, void *wnd)\n{\n}\n\nbool GetKeyState(int key)\n{\n return false;\n}\n}\n\nnamespace FileIO\n{\nstd::string GetTempRootPath()\n{\n return \"\/tmp\";\n}\n\nstd::string GetAppFolderFilename(const std::string &filename)\n{\n const char *homedir = NULL;\n if(getenv(\"HOME\") != NULL)\n {\n homedir = getenv(\"HOME\");\n RDCLOG(\"$HOME value is %s\", homedir);\n }\n else\n {\n RDCLOG(\"$HOME value is NULL\");\n homedir = getpwuid(getuid())->pw_dir;\n }\n\n std::string ret = std::string(homedir) + \"\/.renderdoc\/\";\n\n mkdir(ret.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);\n\n return ret + filename;\n}\n\nvoid GetExecutableFilename(std::string &selfName)\n{\n char path[512] = {0};\n readlink(\"\/proc\/self\/exe\", path, 511);\n\n selfName = std::string(path);\n}\n\nint LibraryLocator = 42;\n\nvoid GetLibraryFilename(std::string &selfName)\n{\n \/\/ this is a hack, but the only reliable way to find the absolute path to the library.\n \/\/ dladdr would be fine but it returns the wrong result for symbols in the library\n\n std::string librenderdoc_path;\n\n FILE *f = fopen(\"\/proc\/self\/maps\", \"r\");\n\n if(f)\n {\n \/\/ read the whole thing in one go. There's no need to try and be tight with\n \/\/ this allocation, so just make sure we can read everything.\n char *map_string = new char[1024 * 1024];\n memset(map_string, 0, 1024 * 1024);\n\n ::fread(map_string, 1, 1024 * 1024, f);\n\n ::fclose(f);\n\n char *c = strstr(map_string, \"\/librenderdoc.so\");\n\n if(c)\n {\n \/\/ walk backwards until we hit the start of the line\n while(c > map_string)\n {\n c--;\n\n if(c[0] == '\\n')\n {\n c++;\n break;\n }\n }\n\n \/\/ walk forwards across the address range (00400000-0040c000)\n while(isalnum(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ permissions (r-xp)\n while(isalpha(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ offset (0000b000)\n while(isalnum(c[0]) || c[0] == '-')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ dev\n while(isalnum(c[0]) || c[0] == ':')\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ inode\n while(isdigit(c[0]))\n c++;\n\n \/\/ whitespace\n while(c[0] == ' ')\n c++;\n\n \/\/ FINALLY we are at the start of the actual path\n char *end = strchr(c, '\\n');\n\n if(end)\n librenderdoc_path = std::string(c, end - c);\n }\n\n delete[] map_string;\n }\n\n if(librenderdoc_path.empty())\n {\n RDCWARN(\"Couldn't get librenderdoc.so path from \/proc\/self\/maps, falling back to dladdr\");\n\n Dl_info info;\n if(dladdr(&LibraryLocator, &info))\n librenderdoc_path = info.dli_fname;\n }\n\n selfName = librenderdoc_path;\n}\n};\n\nnamespace StringFormat\n{\n\/\/ cache iconv_t descriptor to save on iconv_open\/iconv_close each time\niconv_t iconvWide2UTF8 = (iconv_t)-1;\niconv_t iconvUTF82Wide = (iconv_t)-1;\n\n\/\/ iconv is not thread safe when sharing an iconv_t descriptor\n\/\/ I don't expect much contention but if it happens we could TryLock\n\/\/ before creating a temporary iconv_t, or hold two iconv_ts, or something.\nThreading::CriticalSection iconvLock;\n\nvoid Shutdown()\n{\n SCOPED_LOCK(iconvLock);\n\n if(iconvWide2UTF8 != (iconv_t)-1)\n iconv_close(iconvWide2UTF8);\n iconvWide2UTF8 = (iconv_t)-1;\n\n if(iconvUTF82Wide != (iconv_t)-1)\n iconv_close(iconvUTF82Wide);\n iconvUTF82Wide = (iconv_t)-1;\n}\n\nstd::string Wide2UTF8(const std::wstring &s)\n{\n \/\/ include room for null terminator, assuming unicode input (not ucs)\n \/\/ utf-8 characters can be max 4 bytes.\n size_t len = (s.length() + 1) * 4;\n\n std::vector charBuffer(len);\n\n size_t ret;\n\n {\n SCOPED_LOCK(iconvLock);\n\n if(iconvWide2UTF8 == (iconv_t)-1)\n iconvWide2UTF8 = iconv_open(\"UTF-8\", \"WCHAR_T\");\n\n if(iconvWide2UTF8 == (iconv_t)-1)\n {\n RDCERR(\"Couldn't open iconv for WCHAR_T to UTF-8: %d\", errno);\n return \"\";\n }\n\n char *inbuf = (char *)s.c_str();\n size_t insize = (s.length() + 1) * sizeof(wchar_t); \/\/ include null terminator\n char *outbuf = &charBuffer[0];\n size_t outsize = len;\n\n ret = iconv(iconvWide2UTF8, &inbuf, &insize, &outbuf, &outsize);\n }\n\n if(ret == (size_t)-1)\n {\n#if ENABLED(RDOC_DEVEL)\n RDCWARN(\"Failed to convert wstring\");\n#endif\n return \"\";\n }\n\n \/\/ convert to string from null-terminated string - utf-8 never contains\n \/\/ 0 bytes before the null terminator, and this way we don't care if\n \/\/ charBuffer is larger than the string\n return std::string(&charBuffer[0]);\n}\n\nstd::wstring UTF82Wide(const std::string &s)\n{\n \/\/ include room for null terminator, for ascii input we need at least as many output chars as\n \/\/ input.\n size_t len = s.length() + 1;\n\n std::vector wcharBuffer(len);\n\n size_t ret;\n\n {\n SCOPED_LOCK(iconvLock);\n\n if(iconvUTF82Wide == (iconv_t)-1)\n iconvUTF82Wide = iconv_open(\"WCHAR_T\", \"UTF-8\");\n\n if(iconvUTF82Wide == (iconv_t)-1)\n {\n RDCERR(\"Couldn't open iconv for UTF-8 to WCHAR_T: %d\", errno);\n return L\"\";\n }\n\n char *inbuf = (char *)s.c_str();\n size_t insize = s.length() + 1; \/\/ include null terminator\n char *outbuf = (char *)&wcharBuffer[0];\n size_t outsize = len * sizeof(wchar_t);\n\n ret = iconv(iconvUTF82Wide, &inbuf, &insize, &outbuf, &outsize);\n }\n\n if(ret == (size_t)-1)\n {\n#if ENABLED(RDOC_DEVEL)\n RDCWARN(\"Failed to convert wstring\");\n#endif\n return L\"\";\n }\n\n \/\/ convert to string from null-terminated string\n return std::wstring(&wcharBuffer[0]);\n}\n};\n\nnamespace OSUtility\n{\nvoid WriteOutput(int channel, const char *str)\n{\n if(channel == OSUtility::Output_StdOut)\n {\n fprintf(stdout, \"%s\", str);\n fflush(stdout);\n }\n else if(channel == OSUtility::Output_StdErr)\n {\n fprintf(stderr, \"%s\", str);\n fflush(stderr);\n }\n}\n\nuint64_t GetMachineIdent()\n{\n uint64_t ret = MachineIdent_Linux;\n\n#if defined(_M_ARM) || defined(__arm__)\n ret |= MachineIdent_Arch_ARM;\n#else\n ret |= MachineIdent_Arch_x86;\n#endif\n\n#if ENABLED(RDOC_X64)\n ret |= MachineIdent_64bit;\n#else\n ret |= MachineIdent_32bit;\n#endif\n\n return ret;\n}\n};\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * E.S.O. - ACS project\n *\n * \"@(#) $Id: acsservicesdaemonStop.cpp,v 1.1 2008\/06\/30 07:38:28 msekoran Exp $\"\n *\n * who when what\n * -------- ---------- ----------------------------------------------\n *\/\n\n\/** @file acsservicesdaemonStop.cpp\n * acsservicesdaemonStop is used to remotely stop ACS Services Deamon.\n * @htmlonly\n *

\n * @endhtmlonly\n *\/ \n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic struct option long_options[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"instance\", required_argument, 0, 'i'},\n {\"host\", required_argument, 0, 'H'},\n {\"daemon\", required_argument, 0, 'd'},\n {0, 0, 0, '\\0'}};\n\nvoid \nusage(const char *argv)\n{\n ACE_OS::printf (\"\\n\\tusage: %s {-h}\", argv);\n ACE_OS::printf (\"\\t -h, --help show this help message\\n\");\n ACE_OS::printf (\"\\t -i, --instance ACS instance to use\\n\");\n ACE_OS::printf (\"\\t -H, --host Host where to stop the daemon\\n\");\n ACE_OS::printf (\"\\t -d, --daemon Daemon reference\\n\");\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n int c;\n ACE_CString daemonRef;\n ACE_CString hostName;\n for(;;)\n {\n int option_index = 0;\n c = getopt_long (argc, argv, \"hd:H:\",\n long_options, &option_index); \n if (c==-1) break;\n switch(c)\n {\n case 'h':\n usage(argv[0]);\n return 0;\n case 'd':\n daemonRef = optarg;\n break;\n case 'H':\n hostName = optarg;\n break;\n }\n }\n\n\tLoggingProxy * logger = new LoggingProxy(0, 0, 31);\n\tif (logger)\n\t{\n\t\tLoggingProxy::init(logger);\n\t\tLoggingProxy::ProcessName(argv[0]);\n\t\tLoggingProxy::ThreadName(\"main\");\n\t}\n\telse\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed to initialize logging.\"));\n\n\ttry\n\t{\n\t\t\/\/ Initialize the ORB.\n\t\tCORBA::ORB_var orb = CORBA::ORB_init (argc,argv,\"TAO\");\n\n\t\t\/\/ construct default one\n if (daemonRef.length() == 0)\n\t {\n if(hostName.length() == 0)\n {\n\t hostName = ACSPorts::getIP();\n } \n\t daemonRef = \"corbaloc::\";\n\t daemonRef = daemonRef + hostName + \":\" + ACSPorts::getServicesDaemonPort().c_str() + \"\/\" + ::acsdaemon::servicesDaemonServiceName;\n\t ACS_SHORT_LOG((LM_INFO, \"Using local Services Daemon reference: '%s'\", daemonRef.c_str()));\n\t \n\t }\n else\n {\n ACS_SHORT_LOG((LM_INFO, \"Services Daemon reference obtained via command line: '%s'\", daemonRef.c_str()));\n }\n\n\n\t\tCORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());\n\t\tif (CORBA::is_nil(obj.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_ERROR, \"Failed to resolve reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\t\tacsdaemon::ServicesDaemon_var daemon = acsdaemon::ServicesDaemon::_narrow(obj.in());\n\t\tif (CORBA::is_nil(daemon.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_ERROR, \"Failed to narrow reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\n ACS_SHORT_LOG((LM_INFO, \"Calling shutdown().\"));\n\n daemon->shutdown();\n\n ACS_SHORT_LOG((LM_INFO, \"Daemon shutdown message issued.\"));\n\n\n\t}\n\tcatch( maciErrType::NoPermissionEx &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_WARNING, \"Daemon is running in protected mode and cannot be shut down remotely!\\n\"));\n\t\treturn -1;\n\t}\n\tcatch( CORBA::Exception &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_ERROR, \"Failed.\"));\n\t\tACE_PRINT_EXCEPTION (ex, ACE_TEXT (\"Caught unexpected exception:\"));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\n\n\n\nadded comment about why we need to specify the acs instance here\/*******************************************************************************\n * E.S.O. - ACS project\n *\n * \"@(#) $Id: acsservicesdaemonStop.cpp,v 1.2 2008\/10\/21 16:06:50 hsommer Exp $\"\n *\n * who when what\n * -------- ---------- ----------------------------------------------\n *\/\n\n\/** @file acsservicesdaemonStop.cpp\n * acsservicesdaemonStop is used to remotely stop ACS Services Deamon.\n * @htmlonly\n *

\n * @endhtmlonly\n *\/ \n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic struct option long_options[] = {\n {\"help\", no_argument, 0, 'h'},\n {\"instance\", required_argument, 0, 'i'},\n {\"host\", required_argument, 0, 'H'},\n {\"daemon\", required_argument, 0, 'd'},\n {0, 0, 0, '\\0'}};\n\nvoid \nusage(const char *argv)\n{\n ACE_OS::printf (\"\\n\\tusage: %s {-h}\", argv);\n ACE_OS::printf (\"\\t -h, --help show this help message\\n\");\n ACE_OS::printf (\"\\t -i, --instance ACS instance to use\\n\"); \/\/ HSO: what does that mean? We have one daemon for all instances...\n ACE_OS::printf (\"\\t -H, --host Host where to stop the daemon\\n\");\n ACE_OS::printf (\"\\t -d, --daemon Daemon reference\\n\");\n}\n\n\nint\nmain (int argc, char *argv[])\n{\n int c;\n ACE_CString daemonRef;\n ACE_CString hostName;\n for(;;)\n {\n int option_index = 0;\n c = getopt_long (argc, argv, \"hd:H:\",\n long_options, &option_index); \n if (c==-1) break;\n switch(c)\n {\n case 'h':\n usage(argv[0]);\n return 0;\n case 'd':\n daemonRef = optarg;\n break;\n case 'H':\n hostName = optarg;\n break;\n }\n }\n\n\tLoggingProxy * logger = new LoggingProxy(0, 0, 31);\n\tif (logger)\n\t{\n\t\tLoggingProxy::init(logger);\n\t\tLoggingProxy::ProcessName(argv[0]);\n\t\tLoggingProxy::ThreadName(\"main\");\n\t}\n\telse\n\t\tACS_SHORT_LOG((LM_INFO, \"Failed to initialize logging.\"));\n\n\ttry\n\t{\n\t\t\/\/ Initialize the ORB.\n\t\tCORBA::ORB_var orb = CORBA::ORB_init (argc,argv,\"TAO\");\n\n\t\t\/\/ construct default one\n if (daemonRef.length() == 0)\n\t {\n if(hostName.length() == 0)\n {\n\t hostName = ACSPorts::getIP();\n } \n\t daemonRef = \"corbaloc::\";\n\t daemonRef = daemonRef + hostName + \":\" + ACSPorts::getServicesDaemonPort().c_str() + \"\/\" + ::acsdaemon::servicesDaemonServiceName;\n\t ACS_SHORT_LOG((LM_INFO, \"Using local Services Daemon reference: '%s'\", daemonRef.c_str()));\n\t \n\t }\n else\n {\n ACS_SHORT_LOG((LM_INFO, \"Services Daemon reference obtained via command line: '%s'\", daemonRef.c_str()));\n }\n\n\n\t\tCORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());\n\t\tif (CORBA::is_nil(obj.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_ERROR, \"Failed to resolve reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\t\tacsdaemon::ServicesDaemon_var daemon = acsdaemon::ServicesDaemon::_narrow(obj.in());\n\t\tif (CORBA::is_nil(daemon.in()))\n\t\t{\n\t\t\tACS_SHORT_LOG((LM_ERROR, \"Failed to narrow reference '%s'.\", daemonRef.c_str()));\n\t\t\treturn -1;\n\t\t}\n\n\n ACS_SHORT_LOG((LM_INFO, \"Calling shutdown().\"));\n\n daemon->shutdown();\n\n ACS_SHORT_LOG((LM_INFO, \"Daemon shutdown message issued.\"));\n\n\n\t}\n\tcatch( maciErrType::NoPermissionEx &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_WARNING, \"Daemon is running in protected mode and cannot be shut down remotely!\\n\"));\n\t\treturn -1;\n\t}\n\tcatch( CORBA::Exception &ex )\n\t{\n\t\tACS_SHORT_LOG((LM_ERROR, \"Failed.\"));\n\t\tACE_PRINT_EXCEPTION (ex, ACE_TEXT (\"Caught unexpected exception:\"));\n\t\treturn -1;\n\t}\n\n\treturn 0;\n}\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/Containers\/Common.h\"\n#include \"..\/Debug\/Assertions.h\"\n#include \"..\/Debug\/Trace.h\"\n#include \"..\/Math\/Common.h\"\n#include \"..\/Memory\/SmallStackBuffer.h\"\n#include \"CodePage.h\"\n\n#include \"Float2String.h\"\n\n\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Characters;\nusing namespace Stroika::Foundation::Memory;\n\n\n\n\n\n\/*\n ********************************************************************************\n ********************************* Float2String *********************************\n ********************************************************************************\n *\/\nnamespace {\n template \n inline String Float2String_ (FLOAT_TYPE f, const Float2StringOptions& options)\n {\n if (std::isnan (f)) {\n return String ();\n }\n stringstream s;\n if (options.fUseLocale.IsPresent ()) {\n s.imbue (*options.fUseLocale);\n }\n else {\n static const locale kCLocale_ = locale::classic ();\n s.imbue (kCLocale_);\n }\n if (options.fPrecision.IsPresent ()) {\n s << setprecision (*options.fPrecision);\n }\n if (options.fFmtFlags.IsPresent ()) {\n s << setiosflags (*options.fFmtFlags);\n }\n s << f;\n String tmp = String::FromAscii (s.str ());\n if (options.fTrimTrailingZeros) {\n \/\/ strip trailing zeros - except for the last first one after the decimal point\n size_t pastDot = tmp.find ('.');\n if (pastDot != String::npos) {\n pastDot++;\n size_t pPastLastZero = tmp.length ();\n for (; (pPastLastZero - 1) > pastDot; --pPastLastZero) {\n if (tmp[pPastLastZero - 1] != '0') {\n break;\n }\n }\n tmp = tmp.SubString (0, pPastLastZero);\n }\n }\n return tmp;\n }\n\n}\nString Characters::Float2String (float f, const Float2StringOptions& options)\n{\n return Float2String_ (f, options);\n}\n\nString Characters::Float2String (double f, const Float2StringOptions& options)\n{\n return Float2String_ (f, options);\n}\n\nString Characters::Float2String (long double f, const Float2StringOptions& options)\n{\n return Float2String_ (f, options);\n}\n\n\nremove obsolete file Float2String.cpp<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include \n#elif qPlatform_POSIX\n#include \n#endif\n#include \n\n#include \"..\/..\/Execution\/Exceptions.h\"\n#include \"..\/..\/Execution\/OperationNotSupportedException.h\"\n\n#include \"SocketStream.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Streams;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\n\/*\n ********************************************************************************\n ********************* IO::Network::SocketStream::Rep_ **************************\n ********************************************************************************\n *\/\nclass SocketStream::Rep_ : public InputOutputStream::_IRep {\npublic:\n Rep_ (const ConnectionOrientedSocket::Ptr& sd)\n : InputOutputStream::Ptr::_IRep ()\n , fSD_ (sd)\n {\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetReadOffset () const override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual size_t Read (Byte* intoStart, Byte* intoEnd) override\n {\n return fSD_.Read (intoStart, intoEnd);\n }\n virtual Memory::Optional ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override\n {\n return fSD_.ReadNonBlocking (intoStart, intoEnd);\n }\n virtual SeekOffsetType GetWriteOffset () const override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual void Write (const Byte* start, const Byte* end) override\n {\n fSD_.Write (start, end);\n }\n virtual void Flush () override\n {\n \/\/ socket has no flush API, so write must do the trick...\n }\n\nprivate:\n ConnectionOrientedSocket::Ptr fSD_;\n};\n\n\/*\n ********************************************************************************\n **************************** IO::Network::SocketStream *************************\n ********************************************************************************\n *\/\nauto SocketStream::New (const ConnectionOrientedSocket::Ptr& sd) -> Ptr\n{\n return make_shared (sd);\n}\n\n\/*\n ********************************************************************************\n ******************** IO::Network::SocketStream::Ptr ****************************\n ********************************************************************************\n *\/\nSocketStream::Ptr::Ptr (const shared_ptr& from)\n : inherited (from)\n{\n}\nfixed small syntax error where clang more picky\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qPlatform_Windows\n#include \n#elif qPlatform_POSIX\n#include \n#endif\n#include \n\n#include \"..\/..\/Execution\/Exceptions.h\"\n#include \"..\/..\/Execution\/OperationNotSupportedException.h\"\n\n#include \"SocketStream.h\"\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Streams;\nusing namespace Stroika::Foundation::IO;\nusing namespace Stroika::Foundation::IO::Network;\n\n\/*\n ********************************************************************************\n ********************* IO::Network::SocketStream::Rep_ **************************\n ********************************************************************************\n *\/\nclass SocketStream::Rep_ : public InputOutputStream::_IRep {\npublic:\n Rep_ (const ConnectionOrientedSocket::Ptr& sd)\n : InputOutputStream::_IRep ()\n , fSD_ (sd)\n {\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetReadOffset () const override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual size_t Read (Byte* intoStart, Byte* intoEnd) override\n {\n return fSD_.Read (intoStart, intoEnd);\n }\n virtual Memory::Optional ReadNonBlocking (ElementType* intoStart, ElementType* intoEnd) override\n {\n return fSD_.ReadNonBlocking (intoStart, intoEnd);\n }\n virtual SeekOffsetType GetWriteOffset () const override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached (); \/\/ not seekable\n return 0;\n }\n virtual void Write (const Byte* start, const Byte* end) override\n {\n fSD_.Write (start, end);\n }\n virtual void Flush () override\n {\n \/\/ socket has no flush API, so write must do the trick...\n }\n\nprivate:\n ConnectionOrientedSocket::Ptr fSD_;\n};\n\n\/*\n ********************************************************************************\n **************************** IO::Network::SocketStream *************************\n ********************************************************************************\n *\/\nauto SocketStream::New (const ConnectionOrientedSocket::Ptr& sd) -> Ptr\n{\n return make_shared (sd);\n}\n\n\/*\n ********************************************************************************\n ******************** IO::Network::SocketStream::Ptr ****************************\n ********************************************************************************\n *\/\nSocketStream::Ptr::Ptr (const shared_ptr& from)\n : inherited (from)\n{\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPolhemusInterface.h\"\n#include \"mitkTestingMacros.h\"\n#include \"mitkStandardFileLocations.h\"\n#include \n\n\/\/ Testing\n#include \"mitkTestingMacros.h\"\n#include \"mitkTestFixture.h\"\n\nclass mitkPolhemusTrackingDeviceHardwareTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkPolhemusTrackingDeviceHardwareTestSuite);\n \/\/ Test the append method\n MITK_TEST(testInterface);\n CPPUNIT_TEST_SUITE_END();\n\n\npublic:\n void setUp() override\n {\n\n }\n void tearDown() override\n {\n\n }\n\n void testInterface()\n {\n mitk::PolhemusInterface::Pointer myInterface = mitk::PolhemusInterface::New();\n CPPUNIT_ASSERT_MESSAGE(\"Testing connection.\", myInterface->Connect());\n CPPUNIT_ASSERT_MESSAGE(\"Start tracking.\", myInterface->StartTracking());\n\n CPPUNIT_ASSERT_MESSAGE(\"Tracking 20 frames ...\", true);\n for (int i = 0; i < 20; i++)\n {\n std::vector lastFrame = myInterface->GetLastFrame();\n MITK_INFO << \"Frame \" << i;\n for (int j = 0; j < lastFrame.size(); j++)\n {\n MITK_INFO << \"[\" << j << \"]\" << \" Pos:\" << lastFrame.at(j).pos << \" Rot:\" << lastFrame.at(j).rot;\n }\n }\n\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkPolhemusTrackingDeviceHardware)\nFixed type mismatch\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkPolhemusInterface.h\"\n#include \"mitkTestingMacros.h\"\n#include \"mitkStandardFileLocations.h\"\n#include \n\n\/\/ Testing\n#include \"mitkTestingMacros.h\"\n#include \"mitkTestFixture.h\"\n\nclass mitkPolhemusTrackingDeviceHardwareTestSuite : public mitk::TestFixture\n{\n CPPUNIT_TEST_SUITE(mitkPolhemusTrackingDeviceHardwareTestSuite);\n \/\/ Test the append method\n MITK_TEST(testInterface);\n CPPUNIT_TEST_SUITE_END();\n\n\npublic:\n void setUp() override\n {\n\n }\n void tearDown() override\n {\n\n }\n\n void testInterface()\n {\n mitk::PolhemusInterface::Pointer myInterface = mitk::PolhemusInterface::New();\n CPPUNIT_ASSERT_MESSAGE(\"Testing connection.\", myInterface->Connect());\n CPPUNIT_ASSERT_MESSAGE(\"Start tracking.\", myInterface->StartTracking());\n\n CPPUNIT_ASSERT_MESSAGE(\"Tracking 20 frames ...\", true);\n for (int i = 0; i < 20; i++)\n {\n std::vector lastFrame = myInterface->GetLastFrame();\n MITK_INFO << \"Frame \" << i;\n for (size_t j = 0; j < lastFrame.size(); j++)\n {\n MITK_INFO << \"[\" << j << \"]\" << \" Pos:\" << lastFrame.at(j).pos << \" Rot:\" << lastFrame.at(j).rot;\n }\n }\n\n }\n\n};\n\nMITK_TEST_SUITE_REGISTRATION(mitkPolhemusTrackingDeviceHardware)\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/eula_view.h\"\n\n#include \n#include \n#include \n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/customization_document.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen_delegate.h\"\n#include \"chrome\/browser\/chromeos\/login\/rounded_rect_painter.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"views\/controls\/button\/checkbox.h\"\n#include \"views\/controls\/button\/native_button.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/grid_layout.h\"\n#include \"views\/layout_manager.h\"\n#include \"views\/standard_layout.h\"\n\nnamespace {\n\nconst int kBorderSize = 10;\nconst int kMargin = 20;\nconst int kLastButtonHorizontalMargin = 10;\nconst int kCheckBowWidth = 22;\nconst int kTextMargin = 10;\n\n\/\/ TODO(glotov): this URL should be changed to actual Google ChromeOS EULA.\n\/\/ See crbug.com\/4647\nconst char kGoogleEulaUrl[] = \"about:terms\";\n\nenum kLayoutColumnsets {\n SINGLE_CONTROL_ROW,\n SINGLE_CONTROL_WITH_SHIFT_ROW,\n SINGLE_LINK_WITH_SHIFT_ROW,\n LAST_ROW\n};\n\n\/\/ A simple LayoutManager that causes the associated view's one child to be\n\/\/ sized to match the bounds of its parent except the bounds, if set.\nstruct FillLayoutWithBorder : public views::LayoutManager {\n \/\/ Overridden from LayoutManager:\n virtual void Layout(views::View* host) {\n DCHECK(host->GetChildViewCount());\n host->GetChildViewAt(0)->SetBounds(host->GetLocalBounds(false));\n }\n virtual gfx::Size GetPreferredSize(views::View* host) {\n return gfx::Size(host->width(), host->height());\n }\n};\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nEulaView::EulaView(chromeos::ScreenObserver* observer)\n : google_eula_label_(NULL),\n google_eula_view_(NULL),\n usage_statistics_checkbox_(NULL),\n learn_more_link_(NULL),\n oem_eula_label_(NULL),\n oem_eula_view_(NULL),\n system_security_settings_link_(NULL),\n cancel_button_(NULL),\n continue_button_(NULL),\n observer_(observer) {\n}\n\nEulaView::~EulaView() {\n}\n\n\/\/ Convenience function to set layout's columnsets for this screen.\nstatic void SetUpGridLayout(views::GridLayout* layout) {\n static const int kPadding = kBorderSize + kMargin;\n views::ColumnSet* column_set = layout->AddColumnSet(SINGLE_CONTROL_ROW);\n column_set->AddPaddingColumn(0, kPadding);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(SINGLE_CONTROL_WITH_SHIFT_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(SINGLE_LINK_WITH_SHIFT_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin + kCheckBowWidth);\n column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(LAST_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin);\n column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kLastButtonHorizontalMargin + kBorderSize);\n}\n\nvoid EulaView::Init() {\n \/\/ Use rounded rect background.\n views::Painter* painter = CreateWizardPainter(\n &BorderDefinition::kScreenBorder);\n set_background(\n views::Background::CreateBackgroundPainter(true, painter));\n\n \/\/ Layout created controls.\n views::GridLayout* layout = new views::GridLayout(this);\n SetLayoutManager(layout);\n SetUpGridLayout(layout);\n\n static const int kPadding = kBorderSize + kMargin;\n layout->AddPaddingRow(0, kPadding);\n layout->StartRow(0, SINGLE_CONTROL_ROW);\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n gfx::Font label_font =\n rb.GetFont(ResourceBundle::MediumFont).DeriveFont(0, gfx::Font::NORMAL);\n google_eula_label_ = new views::Label(std::wstring(), label_font);\n layout->AddView(google_eula_label_, 1, 1,\n views::GridLayout::LEADING, views::GridLayout::FILL);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(1, SINGLE_CONTROL_ROW);\n views::View* box_view = new views::View();\n box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));\n box_view->SetLayoutManager(new FillLayoutWithBorder());\n layout->AddView(box_view);\n\n google_eula_view_ = new DOMView();\n box_view->AddChildView(google_eula_view_);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(0, SINGLE_CONTROL_WITH_SHIFT_ROW);\n usage_statistics_checkbox_ = new views::Checkbox();\n usage_statistics_checkbox_->SetMultiLine(true);\n usage_statistics_checkbox_->SetChecked(\n GoogleUpdateSettings::GetCollectStatsConsent());\n layout->AddView(usage_statistics_checkbox_);\n\n layout->StartRow(0, SINGLE_LINK_WITH_SHIFT_ROW);\n learn_more_link_ = new views::Link();\n learn_more_link_->SetController(this);\n layout->AddView(learn_more_link_);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(0, SINGLE_CONTROL_ROW);\n oem_eula_label_ = new views::Label(std::wstring(), label_font);\n layout->AddView(oem_eula_label_, 1, 1,\n views::GridLayout::LEADING, views::GridLayout::FILL);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(1, SINGLE_CONTROL_ROW);\n box_view = new views::View();\n box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));\n box_view->SetLayoutManager(new FillLayoutWithBorder());\n layout->AddView(box_view);\n\n oem_eula_view_ = new DOMView();\n box_view->AddChildView(oem_eula_view_);\n\n layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);\n layout->StartRow(0, LAST_ROW);\n system_security_settings_link_ = new views::Link();\n system_security_settings_link_->SetController(this);\n layout->AddView(system_security_settings_link_);\n\n cancel_button_ = new views::NativeButton(this, std::wstring());\n cancel_button_->SetEnabled(false);\n layout->AddView(cancel_button_);\n\n continue_button_ = new views::NativeButton(this, std::wstring());\n layout->AddView(continue_button_);\n layout->AddPaddingRow(0, kPadding);\n\n UpdateLocalizedStrings();\n}\n\nvoid EulaView::LoadEulaView(DOMView* eula_view,\n views::Label* eula_label,\n const GURL& eula_url) {\n Profile* profile = ProfileManager::GetDefaultProfile();\n eula_view->Init(profile,\n SiteInstance::CreateSiteInstanceForURL(profile, eula_url));\n eula_view->LoadURL(eula_url);\n eula_view->tab_contents()->set_delegate(this);\n}\n\nvoid EulaView::UpdateLocalizedStrings() {\n \/\/ Load Google EULA and its title.\n LoadEulaView(google_eula_view_, google_eula_label_, GURL(kGoogleEulaUrl));\n\n \/\/ Load OEM EULA and its title.\n const StartupCustomizationDocument *customization =\n WizardController::default_controller()->GetCustomization();\n if (customization) {\n const FilePath eula_page_path = customization->GetEULAPagePath(\n g_browser_process->GetApplicationLocale());\n if (!eula_page_path.empty()) {\n const std::string page_path = std::string(chrome::kFileScheme) +\n chrome::kStandardSchemeSeparator + eula_page_path.value();\n LoadEulaView(oem_eula_view_, oem_eula_label_, GURL(page_path));\n } else {\n LOG(ERROR) << \"No eula found for locale: \"\n << g_browser_process->GetApplicationLocale();\n }\n } else {\n LOG(ERROR) << \"No manifest found.\";\n }\n\n \/\/ Load other labels from resources.\n usage_statistics_checkbox_->SetLabel(\n l10n_util::GetString(IDS_EULA_CHECKBOX_ENABLE_LOGGING));\n learn_more_link_->SetText(\n l10n_util::GetString(IDS_LEARN_MORE));\n system_security_settings_link_->SetText(\n l10n_util::GetString(IDS_EULA_SYSTEM_SECURITY_SETTINGS_LINK));\n continue_button_->SetLabel(\n l10n_util::GetString(IDS_EULA_ACCEPT_AND_CONTINUE_BUTTON));\n cancel_button_->SetLabel(\n l10n_util::GetString(IDS_CANCEL));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::View: implementation:\n\nvoid EulaView::OnLocaleChanged() {\n UpdateLocalizedStrings();\n Layout();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::ButtonListener implementation:\n\nvoid EulaView::ButtonPressed(views::Button* sender, const views::Event& event) {\n if (sender == continue_button_) {\n if (usage_statistics_checkbox_) {\n GoogleUpdateSettings::SetCollectStatsConsent(\n usage_statistics_checkbox_->checked());\n }\n observer_->OnExit(ScreenObserver::EULA_ACCEPTED);\n }\n \/\/ TODO(glotov): handle cancel button.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::LinkController implementation:\n\nvoid EulaView::LinkActivated(views::Link* source, int event_flags) {\n \/\/ TODO(glotov): handle link clicks.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabContentsDelegate implementation:\n\n\/\/ Convenience function. Queries |eula_view| for HTML title and, if it\n\/\/ is ready, assigns it to |eula_label| and returns true so the caller\n\/\/ view calls Layout().\nstatic bool PublishTitleIfReady(const TabContents* contents,\n DOMView* eula_view,\n views::Label* eula_label) {\n if (contents != eula_view->tab_contents())\n return false;\n eula_label->SetText(UTF16ToWide(eula_view->tab_contents()->GetTitle()));\n return true;\n}\n\nvoid EulaView::NavigationStateChanged(const TabContents* contents,\n unsigned changed_flags) {\n if (changed_flags & TabContents::INVALIDATE_TITLE) {\n if (PublishTitleIfReady(contents, google_eula_view_, google_eula_label_) ||\n PublishTitleIfReady(contents, oem_eula_view_, oem_eula_label_)) {\n Layout();\n }\n }\n}\n\n} \/\/ namespace chromeos\nInitial locale is used if current locale is not handled by manifest.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/chromeos\/login\/eula_view.h\"\n\n#include \n#include \n#include \n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/browser\/chromeos\/customization_document.h\"\n#include \"chrome\/browser\/chromeos\/login\/network_screen_delegate.h\"\n#include \"chrome\/browser\/chromeos\/login\/rounded_rect_painter.h\"\n#include \"chrome\/browser\/chromeos\/login\/wizard_controller.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/site_instance.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"chrome\/installer\/util\/google_update_settings.h\"\n#include \"grit\/chromium_strings.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"views\/controls\/button\/checkbox.h\"\n#include \"views\/controls\/button\/native_button.h\"\n#include \"views\/controls\/label.h\"\n#include \"views\/grid_layout.h\"\n#include \"views\/layout_manager.h\"\n#include \"views\/standard_layout.h\"\n\nnamespace {\n\nconst int kBorderSize = 10;\nconst int kMargin = 20;\nconst int kLastButtonHorizontalMargin = 10;\nconst int kCheckBowWidth = 22;\nconst int kTextMargin = 10;\n\n\/\/ TODO(glotov): this URL should be changed to actual Google ChromeOS EULA.\n\/\/ See crbug.com\/4647\nconst char kGoogleEulaUrl[] = \"about:terms\";\n\nenum kLayoutColumnsets {\n SINGLE_CONTROL_ROW,\n SINGLE_CONTROL_WITH_SHIFT_ROW,\n SINGLE_LINK_WITH_SHIFT_ROW,\n LAST_ROW\n};\n\n\/\/ A simple LayoutManager that causes the associated view's one child to be\n\/\/ sized to match the bounds of its parent except the bounds, if set.\nstruct FillLayoutWithBorder : public views::LayoutManager {\n \/\/ Overridden from LayoutManager:\n virtual void Layout(views::View* host) {\n DCHECK(host->GetChildViewCount());\n host->GetChildViewAt(0)->SetBounds(host->GetLocalBounds(false));\n }\n virtual gfx::Size GetPreferredSize(views::View* host) {\n return gfx::Size(host->width(), host->height());\n }\n};\n\n} \/\/ namespace\n\nnamespace chromeos {\n\nEulaView::EulaView(chromeos::ScreenObserver* observer)\n : google_eula_label_(NULL),\n google_eula_view_(NULL),\n usage_statistics_checkbox_(NULL),\n learn_more_link_(NULL),\n oem_eula_label_(NULL),\n oem_eula_view_(NULL),\n system_security_settings_link_(NULL),\n cancel_button_(NULL),\n continue_button_(NULL),\n observer_(observer) {\n}\n\nEulaView::~EulaView() {\n}\n\n\/\/ Convenience function to set layout's columnsets for this screen.\nstatic void SetUpGridLayout(views::GridLayout* layout) {\n static const int kPadding = kBorderSize + kMargin;\n views::ColumnSet* column_set = layout->AddColumnSet(SINGLE_CONTROL_ROW);\n column_set->AddPaddingColumn(0, kPadding);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(SINGLE_CONTROL_WITH_SHIFT_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(SINGLE_LINK_WITH_SHIFT_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin + kCheckBowWidth);\n column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kPadding);\n\n column_set = layout->AddColumnSet(LAST_ROW);\n column_set->AddPaddingColumn(0, kPadding + kTextMargin);\n column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::FILL, 1,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 0,\n views::GridLayout::USE_PREF, 0, 0);\n column_set->AddPaddingColumn(0, kLastButtonHorizontalMargin + kBorderSize);\n}\n\nvoid EulaView::Init() {\n \/\/ Use rounded rect background.\n views::Painter* painter = CreateWizardPainter(\n &BorderDefinition::kScreenBorder);\n set_background(\n views::Background::CreateBackgroundPainter(true, painter));\n\n \/\/ Layout created controls.\n views::GridLayout* layout = new views::GridLayout(this);\n SetLayoutManager(layout);\n SetUpGridLayout(layout);\n\n static const int kPadding = kBorderSize + kMargin;\n layout->AddPaddingRow(0, kPadding);\n layout->StartRow(0, SINGLE_CONTROL_ROW);\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n gfx::Font label_font =\n rb.GetFont(ResourceBundle::MediumFont).DeriveFont(0, gfx::Font::NORMAL);\n google_eula_label_ = new views::Label(std::wstring(), label_font);\n layout->AddView(google_eula_label_, 1, 1,\n views::GridLayout::LEADING, views::GridLayout::FILL);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(1, SINGLE_CONTROL_ROW);\n views::View* box_view = new views::View();\n box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));\n box_view->SetLayoutManager(new FillLayoutWithBorder());\n layout->AddView(box_view);\n\n google_eula_view_ = new DOMView();\n box_view->AddChildView(google_eula_view_);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(0, SINGLE_CONTROL_WITH_SHIFT_ROW);\n usage_statistics_checkbox_ = new views::Checkbox();\n usage_statistics_checkbox_->SetMultiLine(true);\n usage_statistics_checkbox_->SetChecked(\n GoogleUpdateSettings::GetCollectStatsConsent());\n layout->AddView(usage_statistics_checkbox_);\n\n layout->StartRow(0, SINGLE_LINK_WITH_SHIFT_ROW);\n learn_more_link_ = new views::Link();\n learn_more_link_->SetController(this);\n layout->AddView(learn_more_link_);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(0, SINGLE_CONTROL_ROW);\n oem_eula_label_ = new views::Label(std::wstring(), label_font);\n layout->AddView(oem_eula_label_, 1, 1,\n views::GridLayout::LEADING, views::GridLayout::FILL);\n\n layout->AddPaddingRow(0, kRelatedControlSmallVerticalSpacing);\n layout->StartRow(1, SINGLE_CONTROL_ROW);\n box_view = new views::View();\n box_view->set_border(views::Border::CreateSolidBorder(1, SK_ColorBLACK));\n box_view->SetLayoutManager(new FillLayoutWithBorder());\n layout->AddView(box_view);\n\n oem_eula_view_ = new DOMView();\n box_view->AddChildView(oem_eula_view_);\n\n layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);\n layout->StartRow(0, LAST_ROW);\n system_security_settings_link_ = new views::Link();\n system_security_settings_link_->SetController(this);\n layout->AddView(system_security_settings_link_);\n\n cancel_button_ = new views::NativeButton(this, std::wstring());\n cancel_button_->SetEnabled(false);\n layout->AddView(cancel_button_);\n\n continue_button_ = new views::NativeButton(this, std::wstring());\n layout->AddView(continue_button_);\n layout->AddPaddingRow(0, kPadding);\n\n UpdateLocalizedStrings();\n}\n\nvoid EulaView::LoadEulaView(DOMView* eula_view,\n views::Label* eula_label,\n const GURL& eula_url) {\n Profile* profile = ProfileManager::GetDefaultProfile();\n eula_view->Init(profile,\n SiteInstance::CreateSiteInstanceForURL(profile, eula_url));\n eula_view->LoadURL(eula_url);\n eula_view->tab_contents()->set_delegate(this);\n}\n\nvoid EulaView::UpdateLocalizedStrings() {\n \/\/ Load Google EULA and its title.\n LoadEulaView(google_eula_view_, google_eula_label_, GURL(kGoogleEulaUrl));\n\n \/\/ Load OEM EULA and its title.\n const StartupCustomizationDocument *customization =\n WizardController::default_controller()->GetCustomization();\n if (customization) {\n std::string locale = g_browser_process->GetApplicationLocale();\n FilePath eula_page_path = customization->GetEULAPagePath(locale);\n if (eula_page_path.empty()) {\n LOG(INFO) << \"No eula found for locale: \" << locale;\n locale = customization->initial_locale();\n eula_page_path = customization->GetEULAPagePath(locale);\n }\n if (!eula_page_path.empty()) {\n const std::string page_path = std::string(chrome::kFileScheme) +\n chrome::kStandardSchemeSeparator + eula_page_path.value();\n LoadEulaView(oem_eula_view_, oem_eula_label_, GURL(page_path));\n } else {\n LOG(INFO) << \"No eula found for locale: \" << locale;\n }\n } else {\n LOG(ERROR) << \"No manifest found.\";\n }\n\n \/\/ Load other labels from resources.\n usage_statistics_checkbox_->SetLabel(\n l10n_util::GetString(IDS_EULA_CHECKBOX_ENABLE_LOGGING));\n learn_more_link_->SetText(\n l10n_util::GetString(IDS_LEARN_MORE));\n system_security_settings_link_->SetText(\n l10n_util::GetString(IDS_EULA_SYSTEM_SECURITY_SETTINGS_LINK));\n continue_button_->SetLabel(\n l10n_util::GetString(IDS_EULA_ACCEPT_AND_CONTINUE_BUTTON));\n cancel_button_->SetLabel(\n l10n_util::GetString(IDS_CANCEL));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::View: implementation:\n\nvoid EulaView::OnLocaleChanged() {\n UpdateLocalizedStrings();\n Layout();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::ButtonListener implementation:\n\nvoid EulaView::ButtonPressed(views::Button* sender, const views::Event& event) {\n if (sender == continue_button_) {\n if (usage_statistics_checkbox_) {\n GoogleUpdateSettings::SetCollectStatsConsent(\n usage_statistics_checkbox_->checked());\n }\n observer_->OnExit(ScreenObserver::EULA_ACCEPTED);\n }\n \/\/ TODO(glotov): handle cancel button.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ views::LinkController implementation:\n\nvoid EulaView::LinkActivated(views::Link* source, int event_flags) {\n \/\/ TODO(glotov): handle link clicks.\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ TabContentsDelegate implementation:\n\n\/\/ Convenience function. Queries |eula_view| for HTML title and, if it\n\/\/ is ready, assigns it to |eula_label| and returns true so the caller\n\/\/ view calls Layout().\nstatic bool PublishTitleIfReady(const TabContents* contents,\n DOMView* eula_view,\n views::Label* eula_label) {\n if (contents != eula_view->tab_contents())\n return false;\n eula_label->SetText(UTF16ToWide(eula_view->tab_contents()->GetTitle()));\n return true;\n}\n\nvoid EulaView::NavigationStateChanged(const TabContents* contents,\n unsigned changed_flags) {\n if (changed_flags & TabContents::INVALIDATE_TITLE) {\n if (PublishTitleIfReady(contents, google_eula_view_, google_eula_label_) ||\n PublishTitleIfReady(contents, oem_eula_view_, oem_eula_label_)) {\n Layout();\n }\n }\n}\n\n} \/\/ namespace chromeos\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/file_path.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/dom_ui\/new_tab_ui.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/pref_value_store.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n\nclass NewTabUITest : public UITest {\n public:\n NewTabUITest() {\n dom_automation_enabled_ = true;\n \/\/ Set home page to the empty string so that we can set the home page using\n \/\/ preferences.\n homepage_ = L\"\";\n\n \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n UITest::DEFAULT_THEME));\n }\n};\n\nTEST_F(NewTabUITest, NTPHasThumbnails) {\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Blank thumbnails on the NTP have the class 'filler' applied to the div.\n \/\/ If all the thumbnails load, there should be no div's with 'filler'.\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('filler').length == 0)\",\n action_max_timeout_ms()));\n}\n\n\/\/ Fails about 5% of the time on XP. http:\/\/crbug.com\/45001\n#if defined(OS_WIN)\n#define ChromeInternalLoadsNTP FLAKY_ChromeInternalLoadsNTP\n#endif\nTEST_F(NewTabUITest, ChromeInternalLoadsNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n scoped_refptr tab = window->GetTab(0);\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Ensure there are some thumbnails loaded in the page.\n int thumbnails_count = -1;\n ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('thumbnail-container').length)\",\n &thumbnails_count));\n EXPECT_GT(thumbnails_count, 0);\n}\n\nTEST_F(NewTabUITest, UpdateUserPrefsVersion) {\n \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n PrefService prefs(new PrefValueStore(\n NULL, \/* no enforced prefs *\/\n new JsonPrefStore(\n FilePath(),\n ChromeThread::GetMessageLoopProxyForThread(ChromeThread::FILE)),\n \/* user prefs *\/\n NULL \/* no advised prefs *\/));\n\n \/\/ Does the migration\n NewTabUI::RegisterUserPrefs(&prefs);\n\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs.GetInteger(prefs::kNTPPrefVersion));\n\n \/\/ Reset the version\n prefs.ClearPref(prefs::kNTPPrefVersion);\n ASSERT_EQ(0, prefs.GetInteger(prefs::kNTPPrefVersion));\n\n bool migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);\n ASSERT_TRUE(migrated);\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs.GetInteger(prefs::kNTPPrefVersion));\n\n migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);\n ASSERT_FALSE(migrated);\n}\n\nTEST_F(NewTabUITest, HomePageLink) {\n scoped_refptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n ASSERT_TRUE(\n browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n scoped_refptr tab = browser->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ TODO(arv): Extract common patterns for doing js testing.\n\n \/\/ Fire click. Because tip service is turned off for testing, we first\n \/\/ force the \"make this my home page\" tip to appear.\n \/\/ TODO(arv): Find screen position of element and use a lower level click\n \/\/ emulation.\n bool result;\n ASSERT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" tipCache = [{\\\"set_homepage_tip\\\":\\\"Make this the home page\\\"}];\"\n L\" renderTip();\"\n L\" var e = document.createEvent('Event');\"\n L\" e.initEvent('click', true, true);\"\n L\" var el = document.querySelector('#tip-line > button');\"\n L\" el.dispatchEvent(e);\"\n L\" return true;\"\n L\"})()\"\n L\")\",\n &result));\n ASSERT_TRUE(result);\n\n \/\/ Make sure text of \"set as home page\" tip has been removed.\n std::wstring tip_text_content;\n ASSERT_TRUE(tab->ExecuteAndExtractString(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" var el = document.querySelector('#tip-line');\"\n L\" return el.textContent;\"\n L\"})()\"\n L\")\",\n &tip_text_content));\n ASSERT_EQ(L\"\", tip_text_content);\n\n \/\/ Make sure that the notification is visible\n bool has_class;\n ASSERT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" var el = document.querySelector('#notification');\"\n L\" return el.classList.contains('show');\"\n L\"})()\"\n L\")\",\n &has_class));\n ASSERT_TRUE(has_class);\n\n bool is_home_page;\n ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,\n &is_home_page));\n ASSERT_TRUE(is_home_page);\n}\nMark NewTabUITest.ChromeInternalLoadsNTP flaky on all platforms.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/test\/ui\/ui_test.h\"\n\n#include \"base\/file_path.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/dom_ui\/new_tab_ui.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/pref_value_store.h\"\n#include \"chrome\/common\/json_pref_store.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/test\/automation\/browser_proxy.h\"\n#include \"chrome\/test\/automation\/tab_proxy.h\"\n#include \"chrome\/test\/automation\/window_proxy.h\"\n\nclass NewTabUITest : public UITest {\n public:\n NewTabUITest() {\n dom_automation_enabled_ = true;\n \/\/ Set home page to the empty string so that we can set the home page using\n \/\/ preferences.\n homepage_ = L\"\";\n\n \/\/ Setup the DEFAULT_THEME profile (has fake history entries).\n set_template_user_data(UITest::ComputeTypicalUserDataSource(\n UITest::DEFAULT_THEME));\n }\n};\n\nTEST_F(NewTabUITest, NTPHasThumbnails) {\n \/\/ Switch to the \"new tab\" tab, which should be any new tab after the\n \/\/ first (the first is about:blank).\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Blank thumbnails on the NTP have the class 'filler' applied to the div.\n \/\/ If all the thumbnails load, there should be no div's with 'filler'.\n scoped_refptr tab = window->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('filler').length == 0)\",\n action_max_timeout_ms()));\n}\n\n\/\/ Fails about ~5% of the time on all platforms. http:\/\/crbug.com\/45001\nTEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) {\n scoped_refptr window(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(window.get());\n\n \/\/ Go to the \"new tab page\" using its old url, rather than chrome:\/\/newtab.\n scoped_refptr tab = window->GetTab(0);\n ASSERT_TRUE(tab.get());\n ASSERT_TRUE(tab->NavigateToURLAsync(GURL(\"chrome-internal:\")));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n \/\/ Ensure there are some thumbnails loaded in the page.\n int thumbnails_count = -1;\n ASSERT_TRUE(tab->ExecuteAndExtractInt(L\"\",\n L\"window.domAutomationController.send(\"\n L\"document.getElementsByClassName('thumbnail-container').length)\",\n &thumbnails_count));\n EXPECT_GT(thumbnails_count, 0);\n}\n\nTEST_F(NewTabUITest, UpdateUserPrefsVersion) {\n \/\/ PrefService with JSON user-pref file only, no enforced or advised prefs.\n PrefService prefs(new PrefValueStore(\n NULL, \/* no enforced prefs *\/\n new JsonPrefStore(\n FilePath(),\n ChromeThread::GetMessageLoopProxyForThread(ChromeThread::FILE)),\n \/* user prefs *\/\n NULL \/* no advised prefs *\/));\n\n \/\/ Does the migration\n NewTabUI::RegisterUserPrefs(&prefs);\n\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs.GetInteger(prefs::kNTPPrefVersion));\n\n \/\/ Reset the version\n prefs.ClearPref(prefs::kNTPPrefVersion);\n ASSERT_EQ(0, prefs.GetInteger(prefs::kNTPPrefVersion));\n\n bool migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);\n ASSERT_TRUE(migrated);\n ASSERT_EQ(NewTabUI::current_pref_version(),\n prefs.GetInteger(prefs::kNTPPrefVersion));\n\n migrated = NewTabUI::UpdateUserPrefsVersion(&prefs);\n ASSERT_FALSE(migrated);\n}\n\nTEST_F(NewTabUITest, HomePageLink) {\n scoped_refptr browser(automation()->GetBrowserWindow(0));\n ASSERT_TRUE(browser.get());\n\n ASSERT_TRUE(\n browser->SetBooleanPreference(prefs::kHomePageIsNewTabPage, false));\n\n \/\/ Bring up a new tab page.\n ASSERT_TRUE(browser->RunCommand(IDC_NEW_TAB));\n int load_time;\n ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time));\n\n scoped_refptr tab = browser->GetActiveTab();\n ASSERT_TRUE(tab.get());\n\n \/\/ TODO(arv): Extract common patterns for doing js testing.\n\n \/\/ Fire click. Because tip service is turned off for testing, we first\n \/\/ force the \"make this my home page\" tip to appear.\n \/\/ TODO(arv): Find screen position of element and use a lower level click\n \/\/ emulation.\n bool result;\n ASSERT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" tipCache = [{\\\"set_homepage_tip\\\":\\\"Make this the home page\\\"}];\"\n L\" renderTip();\"\n L\" var e = document.createEvent('Event');\"\n L\" e.initEvent('click', true, true);\"\n L\" var el = document.querySelector('#tip-line > button');\"\n L\" el.dispatchEvent(e);\"\n L\" return true;\"\n L\"})()\"\n L\")\",\n &result));\n ASSERT_TRUE(result);\n\n \/\/ Make sure text of \"set as home page\" tip has been removed.\n std::wstring tip_text_content;\n ASSERT_TRUE(tab->ExecuteAndExtractString(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" var el = document.querySelector('#tip-line');\"\n L\" return el.textContent;\"\n L\"})()\"\n L\")\",\n &tip_text_content));\n ASSERT_EQ(L\"\", tip_text_content);\n\n \/\/ Make sure that the notification is visible\n bool has_class;\n ASSERT_TRUE(tab->ExecuteAndExtractBool(L\"\",\n L\"window.domAutomationController.send(\"\n L\"(function() {\"\n L\" var el = document.querySelector('#notification');\"\n L\" return el.classList.contains('show');\"\n L\"})()\"\n L\")\",\n &has_class));\n ASSERT_TRUE(has_class);\n\n bool is_home_page;\n ASSERT_TRUE(browser->GetBooleanPreference(prefs::kHomePageIsNewTabPage,\n &is_home_page));\n ASSERT_TRUE(is_home_page);\n}\n<|endoftext|>"} {"text":"Mark all tests in the DownloadTest suite as flaky under Windows (as discussed in this review).<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/trace_event_analyzer.h\"\n#include \"base\/version.h\"\n#include \"chrome\/browser\/gpu_blacklist.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/base\/tracing.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/gpu_data_manager.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n\nusing content::GpuDataManager;\nusing content::GpuFeatureType;\n\nnamespace {\n\ntypedef uint32 GpuResultFlags;\n#define EXPECT_NO_GPU_PROCESS GpuResultFlags(1<<0)\n\/\/ Expect a SwapBuffers to occur (see gles2_cmd_decoder.cc).\n#define EXPECT_GPU_SWAP_BUFFERS GpuResultFlags(1<<1)\n\nclass GpuFeatureTest : public InProcessBrowserTest {\n public:\n GpuFeatureTest() {}\n\n virtual void SetUpInProcessBrowserTestFixture() {\n FilePath test_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));\n gpu_test_dir_ = test_dir.AppendASCII(\"gpu\");\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n \/\/ This enables DOM automation for tab contents.\n EnableDOMAutomation();\n\n InProcessBrowserTest::SetUpCommandLine(command_line);\n\n \/\/ Do not use mesa if real GPU is required.\n if (!command_line->HasSwitch(\"enable-gpu\")) {\n#if !defined(OS_MACOSX)\n CHECK(test_launcher_utils::OverrideGLImplementation(\n command_line, gfx::kGLImplementationOSMesaName)) <<\n \"kUseGL must not be set by test framework code!\";\n#endif\n }\n command_line->AppendSwitch(switches::kDisablePopupBlocking);\n }\n\n void SetupBlacklist(const std::string& json_blacklist) {\n GpuBlacklist* blacklist = GpuBlacklist::GetInstance();\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n \"1.0\", json_blacklist, GpuBlacklist::kAllOs));\n blacklist->UpdateGpuDataManager();\n }\n\n \/\/ If expected_reply is NULL, we don't check the reply content.\n void RunTest(const FilePath& url,\n const char* expected_reply,\n bool new_tab) {\n FilePath test_path;\n test_path = gpu_test_dir_.Append(url);\n ASSERT_TRUE(file_util::PathExists(test_path))\n << \"Missing test file: \" << test_path.value();\n\n ui_test_utils::DOMMessageQueue message_queue;\n if (new_tab) {\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), net::FilePathToFileURL(test_path),\n NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE);\n } else {\n ui_test_utils::NavigateToURL(\n browser(), net::FilePathToFileURL(test_path));\n }\n\n std::string result;\n \/\/ Wait for message indicating the test has finished running.\n ASSERT_TRUE(message_queue.WaitForMessage(&result));\n if (expected_reply)\n EXPECT_STREQ(expected_reply, result.c_str());\n }\n\n void RunTest(const FilePath& url, GpuResultFlags expectations) {\n using trace_analyzer::Query;\n using trace_analyzer::TraceAnalyzer;\n\n ASSERT_TRUE(tracing::BeginTracing(\"test_gpu\"));\n\n \/\/ Have to use a new tab for the blacklist to work.\n RunTest(url, NULL, true);\n\n std::string json_events;\n ASSERT_TRUE(tracing::EndTracing(&json_events));\n\n scoped_ptr analyzer(TraceAnalyzer::Create(json_events));\n analyzer->AssociateBeginEndEvents();\n trace_analyzer::TraceEventVector events;\n\n \/\/ This measurement is flaky, because the GPU process is sometimes\n \/\/ started before the test (always with force-compositing-mode on CrOS).\n if (expectations & EXPECT_NO_GPU_PROCESS) {\n EXPECT_EQ(0u, analyzer->FindEvents(\n Query::MatchBeginName(\"OnGraphicsInfoCollected\"), &events));\n }\n\n \/\/ Check for swap buffers if expected:\n if (expectations & EXPECT_GPU_SWAP_BUFFERS) {\n EXPECT_GT(analyzer->FindEvents(Query::EventName() ==\n Query::String(\"SwapBuffers\"), &events),\n size_t(0));\n }\n }\n\n protected:\n FilePath gpu_test_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_compositing\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass AcceleratedCompositingTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AcceleratedCompositingTest,\n AcceleratedCompositingDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass WebGLTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableExperimentalWebGL);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(WebGLTest, WebGLDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, MultisamplingAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n \/\/ Multisampling is not supported if running on top of osmesa.\n std::string use_gl = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kUseGL);\n if (use_gl == gfx::kGLImplementationOSMesaName)\n return;\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"TRUE\\\"\", true);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, MultisamplingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"multisampling\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_MULTISAMPLING);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"FALSE\\\"\", true);\n}\n\nclass WebGLMultisamplingTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableGLMultisampling);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(WebGLMultisamplingTest, MultisamplingDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"FALSE\\\"\", true);\n}\n\nclass Canvas2DEnabledTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableAccelerated2dCanvas);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(Canvas2DEnabledTest, Canvas2DAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(Canvas2DEnabledTest, Canvas2DBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_2d_canvas\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass Canvas2DDisabledTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(Canvas2DDisabledTest, Canvas2DDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest,\n CanOpenPopupAndRenderWithWebGLCanvas) {\n const FilePath url(FILE_PATH_LITERAL(\"webgl_popup.html\"));\n RunTest(url, \"\\\"SUCCESS\\\"\", false);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, CanOpenPopupAndRenderWith2DCanvas) {\n const FilePath url(FILE_PATH_LITERAL(\"canvas_popup.html\"));\n RunTest(url, \"\\\"SUCCESS\\\"\", false);\n}\n\nclass ThreadedCompositorTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableThreadedCompositing);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(ThreadedCompositorTest, ThreadedCompositor) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\n} \/\/ namespace anonymous\n\nRevert 124346 - Add basic threaded compositor test to gpu_feature_browsertest.cc\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/path_service.h\"\n#include \"base\/test\/trace_event_analyzer.h\"\n#include \"base\/version.h\"\n#include \"chrome\/browser\/gpu_blacklist.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/test\/base\/in_process_browser_test.h\"\n#include \"chrome\/test\/base\/test_launcher_utils.h\"\n#include \"chrome\/test\/base\/tracing.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/gpu_data_manager.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"net\/base\/net_util.h\"\n#include \"ui\/gfx\/gl\/gl_switches.h\"\n\nusing content::GpuDataManager;\nusing content::GpuFeatureType;\n\nnamespace {\n\ntypedef uint32 GpuResultFlags;\n#define EXPECT_NO_GPU_PROCESS GpuResultFlags(1<<0)\n\/\/ Expect a SwapBuffers to occur (see gles2_cmd_decoder.cc).\n#define EXPECT_GPU_SWAP_BUFFERS GpuResultFlags(1<<1)\n\nclass GpuFeatureTest : public InProcessBrowserTest {\n public:\n GpuFeatureTest() {}\n\n virtual void SetUpInProcessBrowserTestFixture() {\n FilePath test_dir;\n ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_dir));\n gpu_test_dir_ = test_dir.AppendASCII(\"gpu\");\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) {\n \/\/ This enables DOM automation for tab contents.\n EnableDOMAutomation();\n\n InProcessBrowserTest::SetUpCommandLine(command_line);\n\n \/\/ Do not use mesa if real GPU is required.\n if (!command_line->HasSwitch(\"enable-gpu\")) {\n#if !defined(OS_MACOSX)\n CHECK(test_launcher_utils::OverrideGLImplementation(\n command_line, gfx::kGLImplementationOSMesaName)) <<\n \"kUseGL must not be set by test framework code!\";\n#endif\n }\n command_line->AppendSwitch(switches::kDisablePopupBlocking);\n }\n\n void SetupBlacklist(const std::string& json_blacklist) {\n GpuBlacklist* blacklist = GpuBlacklist::GetInstance();\n ASSERT_TRUE(blacklist->LoadGpuBlacklist(\n \"1.0\", json_blacklist, GpuBlacklist::kAllOs));\n blacklist->UpdateGpuDataManager();\n }\n\n \/\/ If expected_reply is NULL, we don't check the reply content.\n void RunTest(const FilePath& url,\n const char* expected_reply,\n bool new_tab) {\n FilePath test_path;\n test_path = gpu_test_dir_.Append(url);\n ASSERT_TRUE(file_util::PathExists(test_path))\n << \"Missing test file: \" << test_path.value();\n\n ui_test_utils::DOMMessageQueue message_queue;\n if (new_tab) {\n ui_test_utils::NavigateToURLWithDisposition(\n browser(), net::FilePathToFileURL(test_path),\n NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_NONE);\n } else {\n ui_test_utils::NavigateToURL(\n browser(), net::FilePathToFileURL(test_path));\n }\n\n std::string result;\n \/\/ Wait for message indicating the test has finished running.\n ASSERT_TRUE(message_queue.WaitForMessage(&result));\n if (expected_reply)\n EXPECT_STREQ(expected_reply, result.c_str());\n }\n\n void RunTest(const FilePath& url, GpuResultFlags expectations) {\n using trace_analyzer::Query;\n using trace_analyzer::TraceAnalyzer;\n\n ASSERT_TRUE(tracing::BeginTracing(\"test_gpu\"));\n\n \/\/ Have to use a new tab for the blacklist to work.\n RunTest(url, NULL, true);\n\n std::string json_events;\n ASSERT_TRUE(tracing::EndTracing(&json_events));\n\n scoped_ptr analyzer(TraceAnalyzer::Create(json_events));\n analyzer->AssociateBeginEndEvents();\n trace_analyzer::TraceEventVector events;\n\n \/\/ This measurement is flaky, because the GPU process is sometimes\n \/\/ started before the test (always with force-compositing-mode on CrOS).\n if (expectations & EXPECT_NO_GPU_PROCESS) {\n EXPECT_EQ(0u, analyzer->FindEvents(\n Query::MatchBeginName(\"OnGraphicsInfoCollected\"), &events));\n }\n\n \/\/ Check for swap buffers if expected:\n if (expectations & EXPECT_GPU_SWAP_BUFFERS) {\n EXPECT_GT(analyzer->FindEvents(Query::EventName() ==\n Query::String(\"SwapBuffers\"), &events),\n size_t(0));\n }\n }\n\n protected:\n FilePath gpu_test_dir_;\n};\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, AcceleratedCompositingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_compositing\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass AcceleratedCompositingTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(AcceleratedCompositingTest,\n AcceleratedCompositingDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_compositing.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, WebGLBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"webgl\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_WEBGL);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass WebGLTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableExperimentalWebGL);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(WebGLTest, WebGLDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_webgl.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, MultisamplingAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n \/\/ Multisampling is not supported if running on top of osmesa.\n std::string use_gl = CommandLine::ForCurrentProcess()->GetSwitchValueASCII(\n switches::kUseGL);\n if (use_gl == gfx::kGLImplementationOSMesaName)\n return;\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"TRUE\\\"\", true);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, MultisamplingBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"multisampling\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_MULTISAMPLING);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"FALSE\\\"\", true);\n}\n\nclass WebGLMultisamplingTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableGLMultisampling);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(WebGLMultisamplingTest, MultisamplingDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_multisampling.html\"));\n RunTest(url, \"\\\"FALSE\\\"\", true);\n}\n\nclass Canvas2DEnabledTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kEnableAccelerated2dCanvas);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(Canvas2DEnabledTest, Canvas2DAllowed) {\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, 0);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_GPU_SWAP_BUFFERS);\n}\n\nIN_PROC_BROWSER_TEST_F(Canvas2DEnabledTest, Canvas2DBlocked) {\n const std::string json_blacklist =\n \"{\\n\"\n \" \\\"name\\\": \\\"gpu blacklist\\\",\\n\"\n \" \\\"version\\\": \\\"1.0\\\",\\n\"\n \" \\\"entries\\\": [\\n\"\n \" {\\n\"\n \" \\\"id\\\": 1,\\n\"\n \" \\\"blacklist\\\": [\\n\"\n \" \\\"accelerated_2d_canvas\\\"\\n\"\n \" ]\\n\"\n \" }\\n\"\n \" ]\\n\"\n \"}\";\n SetupBlacklist(json_blacklist);\n GpuFeatureType type = GpuDataManager::GetInstance()->GetGpuFeatureType();\n EXPECT_EQ(type, content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS);\n\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nclass Canvas2DDisabledTest : public GpuFeatureTest {\n public:\n virtual void SetUpCommandLine(CommandLine* command_line) {\n GpuFeatureTest::SetUpCommandLine(command_line);\n command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);\n }\n};\n\nIN_PROC_BROWSER_TEST_F(Canvas2DDisabledTest, Canvas2DDisabled) {\n const FilePath url(FILE_PATH_LITERAL(\"feature_canvas2d.html\"));\n RunTest(url, EXPECT_NO_GPU_PROCESS);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest,\n CanOpenPopupAndRenderWithWebGLCanvas) {\n const FilePath url(FILE_PATH_LITERAL(\"webgl_popup.html\"));\n RunTest(url, \"\\\"SUCCESS\\\"\", false);\n}\n\nIN_PROC_BROWSER_TEST_F(GpuFeatureTest, CanOpenPopupAndRenderWith2DCanvas) {\n const FilePath url(FILE_PATH_LITERAL(\"canvas_popup.html\"));\n RunTest(url, \"\\\"SUCCESS\\\"\", false);\n}\n\n} \/\/ namespace anonymous\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include \n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down. Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"\"\n \"\"\n \"\"\n \"<\/head>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n} \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n GetProfilePath(&user_data_dir_);\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n if (!overridden_user_dir_.empty()) {\n PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n if (!chrome::GetChromeFrameUserDataDirectory(path))\n return false;\n *path = path->Append(GetProfileName());\n return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n DCHECK(g_browser_process == NULL);\n SystemMonitor system_monitor;\n\n \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n \/\/ will cause problems when it tries to intercept URL requests.\n PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n icu_util::Initialize();\n\n chrome::RegisterPathProvider();\n app::RegisterPathProvider();\n\n \/\/ Load Chrome.dll as our resource dll.\n FilePath dll;\n PathService::Get(base::DIR_MODULE, &dll);\n dll = dll.Append(chrome::kBrowserResourcesDll);\n HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n DCHECK(res_mod);\n _AtlBaseModule.SetResourceInstance(res_mod);\n\n ResourceBundle::InitSharedInstance(L\"en-US\");\n\n CommandLine* cmd = CommandLine::ForCurrentProcess();\n cmd->AppendSwitch(switches::kDisableWebResources);\n cmd->AppendSwitch(switches::kSingleProcess);\n\n browser_process_.reset(new BrowserProcessImpl(*cmd));\n RenderProcessHost::set_run_renderer_in_process(true);\n \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n DCHECK(g_browser_process);\n\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(FilePath(user_data()));\n PrefService* prefs = profile->GetPrefs();\n DCHECK(prefs != NULL);\n\n WebCacheManager::RegisterPrefs(prefs);\n PrefService* local_state = browser_process_->local_state();\n local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n browser::RegisterLocalState(local_state);\n\n \/\/ Override some settings to avoid hitting some preferences that have not\n \/\/ been registered.\n prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n browser_process_.reset();\n g_browser_process = NULL;\n process_singleton_.reset();\n\n ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n : NetTestSuite(argc, argv),\n chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n \/\/ Register the main thread by instantiating it, but don't call any methods.\n main_thread_.reset(new ChromeThread(ChromeThread::UI,\n MessageLoop::current()));\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n fake_chrome_.Initialize();\n pss_subclass_.reset(new ProcessSingletonSubclass(this));\n EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n fake_chrome_.Shutdown();\n}\n\nDWORD WINAPI NavigateIE(void* param) {\n return 0;\n win_util::ScopedCOMInitializer com;\n BSTR url = reinterpret_cast(param);\n\n bool found = false;\n int retries = 0;\n const int kMaxRetries = 20;\n while (!found && retries < kMaxRetries) {\n ScopedComPtr windows;\n HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,\n IID_IShellWindows, reinterpret_cast(windows.Receive()));\n DCHECK(SUCCEEDED(hr)) << \"CoCreateInstance\";\n\n if (SUCCEEDED(hr)) {\n hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);\n long count = 0; \/\/ NOLINT\n windows->get_Count(&count);\n VARIANT i = { VT_I4 };\n for (i.lVal = 0; i.lVal < count; ++i.lVal) {\n ScopedComPtr folder;\n windows->Item(i, folder.Receive());\n if (folder != NULL) {\n ScopedComPtr browser;\n if (SUCCEEDED(browser.QueryFrom(folder))) {\n found = true;\n browser->Stop();\n Sleep(1000);\n VARIANT empty = ScopedVariant::kEmptyVariant;\n hr = browser->Navigate(url, &empty, &empty, &empty, &empty);\n DCHECK(SUCCEEDED(hr)) << \"Failed to navigate\";\n break;\n }\n }\n }\n }\n if (!found) {\n DLOG(INFO) << \"Waiting for browser to initialize...\";\n ::Sleep(100);\n retries++;\n }\n }\n\n DCHECK(retries < kMaxRetries);\n DCHECK(found);\n\n ::SysFreeString(url);\n\n return 0;\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n if (!ShouldLaunchBrowser())\n return;\n\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n\n test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n test_http_server_->AddResponse(&chrome_frame_html_);\n std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n kTestServerPort).c_str());\n\n \/\/ Launch IE. This launches IE correctly on Vista too.\n ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n EXPECT_TRUE(ie_process.IsValid());\n\n \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n \/\/ disable IE8's prebinding until CF properly handles that situation.\n \/\/\n \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n \/\/ Value name: EnablePreBinding (REG_DWORD)\n \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n if (ShouldLaunchBrowser()) {\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n \/\/ Start by replicating some of the steps that would otherwise be\n \/\/ done by TestSuite::Initialize. We can't call the base class\n \/\/ directly because it will attempt to initialize some things such as\n \/\/ ICU that have already been initialized for this process.\n InitializeLogging();\n base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif \/\/ !defined(PURIFY)\n\n \/\/ Next, do some initialization for NetTestSuite.\n NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n const std::string& channel_id) {\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(fake_chrome_.user_data());\n\n AutomationProviderList* list =\n g_browser_process->InitAutomationProviderList();\n DCHECK(list);\n list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n test_http_server_.reset();\n StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n DCHECK(MessageLoop::current());\n DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n DCHECK_EQ(test_thread_.IsValid(), false);\n test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n &test_thread_id_));\n DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n \/\/ Needed for some url request tests like the intercept job tests, etc.\n NotificationService service;\n CFUrlRequestUnittestRunner* me =\n reinterpret_cast(param);\n me->Run();\n me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n NewRunnableFunction(TakeDownBrowser, me));\n return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n CFUrlRequestUnittestRunner* me) {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n FilePath exe;\n PathService::Get(base::FILE_EXE, &exe);\n FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n logging::InitLogging(log_filename.value().c_str(),\n logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE);\n \/\/ We want process and thread IDs because we may have multiple processes.\n \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n if (::testing::FLAGS_gtest_filter.length() &&\n ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n \/\/ Don't override user specified filters.\n return;\n }\n\n const char* disabled_tests[] = {\n \/\/ Tests disabled since they're testing the same functionality used\n \/\/ by the TestAutomationProvider.\n \"URLRequestTest.Intercept\",\n \"URLRequestTest.InterceptNetworkError\",\n \"URLRequestTest.InterceptRestartRequired\",\n \"URLRequestTest.InterceptRespectsCancelMain\",\n \"URLRequestTest.InterceptRespectsCancelRedirect\",\n \"URLRequestTest.InterceptRespectsCancelFinal\",\n \"URLRequestTest.InterceptRespectsCancelInRestart\",\n \"URLRequestTest.InterceptRedirect\",\n \"URLRequestTest.InterceptServerError\",\n \"URLRequestTestFTP.*\",\n\n \/\/ Tests that are currently not working:\n\n \/\/ Temporarily disabled because they needs user input (login dialog).\n \"URLRequestTestHTTP.BasicAuth\",\n \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n \"HTTPSRequestTest.HTTPSMismatchedTest\",\n \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n \/\/ Tests chrome's network stack's cache (might not apply to CF).\n \"URLRequestTestHTTP.VaryHeader\",\n\n \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n \"URLRequestTest.DoNotSaveCookies\",\n\n \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n \/\/ now.\n \"URLRequestTestHTTP.GetTest_NoCache\",\n };\n\n std::string filter(\"-\"); \/\/ All following filters will be negative.\n for (int i = 0; i < arraysize(disabled_tests); ++i) {\n if (i > 0)\n filter += \":\";\n filter += disabled_tests[i];\n }\n\n ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n DialogWatchdog watchdog;\n \/\/ See url_request_unittest.cc for these credentials.\n SupplyProxyCredentials credentials(\"user\", \"secret\");\n watchdog.AddObserver(&credentials);\n testing::InitGoogleTest(&argc, argv);\n FilterDisabledTests();\n PluginService::EnableChromePlugins(false);\n CFUrlRequestUnittestRunner test_suite(argc, argv);\n test_suite.RunMainUIThread();\n return 0;\n}\nFix chrome frame net tests that were failing on some machines. Checking in straight away as per Robert's request.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome_frame\/test\/net\/fake_external_tab.h\"\n\n#include \n\n#include \"app\/app_paths.h\"\n#include \"app\/resource_bundle.h\"\n#include \"app\/win_util.h\"\n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/i18n\/icu_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_bstr_win.h\"\n#include \"base\/scoped_comptr_win.h\"\n#include \"base\/scoped_variant_win.h\"\n\n#include \"chrome\/browser\/browser_prefs.h\"\n#include \"chrome\/browser\/plugin_service.h\"\n#include \"chrome\/browser\/process_singleton.h\"\n#include \"chrome\/browser\/profile_manager.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/browser\/renderer_host\/web_cache_manager.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_paths_internal.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n#include \"chrome_frame\/utils.h\"\n#include \"chrome_frame\/test\/chrome_frame_test_utils.h\"\n#include \"chrome_frame\/test\/net\/dialog_watchdog.h\"\n#include \"chrome_frame\/test\/net\/test_automation_resource_message_filter.h\"\n\nnamespace {\n\n\/\/ A special command line switch to allow developers to manually launch the\n\/\/ browser and debug CF inside the browser.\nconst wchar_t kManualBrowserLaunch[] = L\"manual-browser\";\n\n\/\/ Pops up a message box after the test environment has been set up\n\/\/ and before tearing it down. Useful for when debugging tests and not\n\/\/ the test environment that's been set up.\nconst wchar_t kPromptAfterSetup[] = L\"prompt-after-setup\";\n\nconst int kTestServerPort = 4666;\n\/\/ The test HTML we use to initialize Chrome Frame.\n\/\/ Note that there's a little trick in there to avoid an extra URL request\n\/\/ that the browser will otherwise make for the site's favicon.\n\/\/ If we don't do this the browser will create a new URL request after\n\/\/ the CF page has been initialized and that URL request will confuse the\n\/\/ global URL instance counter in the unit tests and subsequently trip\n\/\/ some DCHECKs.\nconst char kChromeFrameHtml[] = \"\"\n \"\"\n \"\"\n \"<\/head>Chrome Frame should now be loaded<\/body><\/html>\";\n\nbool ShouldLaunchBrowser() {\n return !CommandLine::ForCurrentProcess()->HasSwitch(kManualBrowserLaunch);\n}\n\nbool PromptAfterSetup() {\n return CommandLine::ForCurrentProcess()->HasSwitch(kPromptAfterSetup);\n}\n\n} \/\/ end namespace\n\nFakeExternalTab::FakeExternalTab() {\n PathService::Get(chrome::DIR_USER_DATA, &overridden_user_dir_);\n GetProfilePath(&user_data_dir_);\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir_);\n process_singleton_.reset(new ProcessSingleton(user_data_dir_));\n}\n\nFakeExternalTab::~FakeExternalTab() {\n if (!overridden_user_dir_.empty()) {\n PathService::Override(chrome::DIR_USER_DATA, overridden_user_dir_);\n }\n}\n\nstd::wstring FakeExternalTab::GetProfileName() {\n return L\"iexplore\";\n}\n\nbool FakeExternalTab::GetProfilePath(FilePath* path) {\n if (!chrome::GetChromeFrameUserDataDirectory(path))\n return false;\n *path = path->Append(GetProfileName());\n return true;\n}\n\nvoid FakeExternalTab::Initialize() {\n DCHECK(g_browser_process == NULL);\n SystemMonitor system_monitor;\n\n \/\/ The gears plugin causes the PluginRequestInterceptor to kick in and it\n \/\/ will cause problems when it tries to intercept URL requests.\n PathService::Override(chrome::FILE_GEARS_PLUGIN, FilePath());\n\n icu_util::Initialize();\n\n chrome::RegisterPathProvider();\n app::RegisterPathProvider();\n\n \/\/ Load Chrome.dll as our resource dll.\n FilePath dll;\n PathService::Get(base::DIR_MODULE, &dll);\n dll = dll.Append(chrome::kBrowserResourcesDll);\n HMODULE res_mod = ::LoadLibraryExW(dll.value().c_str(),\n NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);\n DCHECK(res_mod);\n _AtlBaseModule.SetResourceInstance(res_mod);\n\n ResourceBundle::InitSharedInstance(L\"en-US\");\n\n CommandLine* cmd = CommandLine::ForCurrentProcess();\n cmd->AppendSwitch(switches::kDisableWebResources);\n cmd->AppendSwitch(switches::kSingleProcess);\n\n browser_process_.reset(new BrowserProcessImpl(*cmd));\n \/\/ BrowserProcessImpl's constructor should set g_browser_process.\n DCHECK(g_browser_process);\n \/\/ Set the app locale and create the child threads.\n g_browser_process->set_application_locale(\"en-US\");\n g_browser_process->db_thread();\n g_browser_process->file_thread();\n g_browser_process->io_thread();\n\n RenderProcessHost::set_run_renderer_in_process(true);\n\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(FilePath(user_data()));\n PrefService* prefs = profile->GetPrefs();\n DCHECK(prefs != NULL);\n\n WebCacheManager::RegisterPrefs(prefs);\n PrefService* local_state = browser_process_->local_state();\n local_state->RegisterStringPref(prefs::kApplicationLocale, L\"\");\n local_state->RegisterBooleanPref(prefs::kMetricsReportingEnabled, false);\n\n browser::RegisterLocalState(local_state);\n\n \/\/ Override some settings to avoid hitting some preferences that have not\n \/\/ been registered.\n prefs->SetBoolean(prefs::kPasswordManagerEnabled, false);\n prefs->SetBoolean(prefs::kAlternateErrorPagesEnabled, false);\n prefs->SetBoolean(prefs::kSafeBrowsingEnabled, false);\n\n profile->InitExtensions();\n}\n\nvoid FakeExternalTab::Shutdown() {\n browser_process_.reset();\n g_browser_process = NULL;\n process_singleton_.reset();\n\n ResourceBundle::CleanupSharedInstance();\n}\n\nCFUrlRequestUnittestRunner::CFUrlRequestUnittestRunner(int argc, char** argv)\n : NetTestSuite(argc, argv),\n chrome_frame_html_(\"\/chrome_frame\", kChromeFrameHtml) {\n \/\/ Register the main thread by instantiating it, but don't call any methods.\n main_thread_.reset(new ChromeThread(ChromeThread::UI,\n MessageLoop::current()));\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n fake_chrome_.Initialize();\n pss_subclass_.reset(new ProcessSingletonSubclass(this));\n EXPECT_TRUE(pss_subclass_->Subclass(fake_chrome_.user_data()));\n StartChromeFrameInHostBrowser();\n}\n\nCFUrlRequestUnittestRunner::~CFUrlRequestUnittestRunner() {\n fake_chrome_.Shutdown();\n}\n\nDWORD WINAPI NavigateIE(void* param) {\n return 0;\n win_util::ScopedCOMInitializer com;\n BSTR url = reinterpret_cast(param);\n\n bool found = false;\n int retries = 0;\n const int kMaxRetries = 20;\n while (!found && retries < kMaxRetries) {\n ScopedComPtr windows;\n HRESULT hr = ::CoCreateInstance(__uuidof(ShellWindows), NULL, CLSCTX_ALL,\n IID_IShellWindows, reinterpret_cast(windows.Receive()));\n DCHECK(SUCCEEDED(hr)) << \"CoCreateInstance\";\n\n if (SUCCEEDED(hr)) {\n hr = HRESULT_FROM_WIN32(ERROR_NOT_FOUND);\n long count = 0; \/\/ NOLINT\n windows->get_Count(&count);\n VARIANT i = { VT_I4 };\n for (i.lVal = 0; i.lVal < count; ++i.lVal) {\n ScopedComPtr folder;\n windows->Item(i, folder.Receive());\n if (folder != NULL) {\n ScopedComPtr browser;\n if (SUCCEEDED(browser.QueryFrom(folder))) {\n found = true;\n browser->Stop();\n Sleep(1000);\n VARIANT empty = ScopedVariant::kEmptyVariant;\n hr = browser->Navigate(url, &empty, &empty, &empty, &empty);\n DCHECK(SUCCEEDED(hr)) << \"Failed to navigate\";\n break;\n }\n }\n }\n }\n if (!found) {\n DLOG(INFO) << \"Waiting for browser to initialize...\";\n ::Sleep(100);\n retries++;\n }\n }\n\n DCHECK(retries < kMaxRetries);\n DCHECK(found);\n\n ::SysFreeString(url);\n\n return 0;\n}\n\nvoid CFUrlRequestUnittestRunner::StartChromeFrameInHostBrowser() {\n if (!ShouldLaunchBrowser())\n return;\n\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n\n test_http_server_.reset(new test_server::SimpleWebServer(kTestServerPort));\n test_http_server_->AddResponse(&chrome_frame_html_);\n std::wstring url(StringPrintf(L\"http:\/\/localhost:%i\/chrome_frame\",\n kTestServerPort).c_str());\n\n \/\/ Launch IE. This launches IE correctly on Vista too.\n ScopedHandle ie_process(chrome_frame_test::LaunchIE(url));\n EXPECT_TRUE(ie_process.IsValid());\n\n \/\/ NOTE: If you're running IE8 and CF is not being loaded, you need to\n \/\/ disable IE8's prebinding until CF properly handles that situation.\n \/\/\n \/\/ HKCU\\Software\\Microsoft\\Internet Explorer\\Main\n \/\/ Value name: EnablePreBinding (REG_DWORD)\n \/\/ Value: 0\n}\n\nvoid CFUrlRequestUnittestRunner::ShutDownHostBrowser() {\n if (ShouldLaunchBrowser()) {\n win_util::ScopedCOMInitializer com;\n chrome_frame_test::CloseAllIEWindows();\n }\n}\n\n\/\/ Override virtual void Initialize to not call icu initialize\nvoid CFUrlRequestUnittestRunner::Initialize() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n\n \/\/ Start by replicating some of the steps that would otherwise be\n \/\/ done by TestSuite::Initialize. We can't call the base class\n \/\/ directly because it will attempt to initialize some things such as\n \/\/ ICU that have already been initialized for this process.\n InitializeLogging();\n base::Time::UseHighResolutionTimer(true);\n\n#if !defined(PURIFY) && defined(OS_WIN)\n logging::SetLogAssertHandler(UnitTestAssertHandler);\n#endif \/\/ !defined(PURIFY)\n\n \/\/ Next, do some initialization for NetTestSuite.\n NetTestSuite::InitializeTestThread();\n}\n\nvoid CFUrlRequestUnittestRunner::Shutdown() {\n DCHECK(::GetCurrentThreadId() == test_thread_id_);\n NetTestSuite::Shutdown();\n}\n\nvoid CFUrlRequestUnittestRunner::OnConnectAutomationProviderToChannel(\n const std::string& channel_id) {\n Profile* profile = g_browser_process->profile_manager()->\n GetDefaultProfile(fake_chrome_.user_data());\n\n AutomationProviderList* list =\n g_browser_process->InitAutomationProviderList();\n DCHECK(list);\n list->AddProvider(TestAutomationProvider::NewAutomationProvider(profile,\n channel_id, this));\n}\n\nvoid CFUrlRequestUnittestRunner::OnInitialTabLoaded() {\n test_http_server_.reset();\n StartTests();\n}\n\nvoid CFUrlRequestUnittestRunner::RunMainUIThread() {\n DCHECK(MessageLoop::current());\n DCHECK(MessageLoop::current()->type() == MessageLoop::TYPE_UI);\n MessageLoop::current()->Run();\n}\n\nvoid CFUrlRequestUnittestRunner::StartTests() {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to run\", \"\", MB_OK);\n\n DCHECK_EQ(test_thread_.IsValid(), false);\n test_thread_.Set(::CreateThread(NULL, 0, RunAllUnittests, this, 0,\n &test_thread_id_));\n DCHECK(test_thread_.IsValid());\n}\n\n\/\/ static\nDWORD CFUrlRequestUnittestRunner::RunAllUnittests(void* param) {\n PlatformThread::SetName(\"CFUrlRequestUnittestRunner\");\n \/\/ Needed for some url request tests like the intercept job tests, etc.\n NotificationService service;\n CFUrlRequestUnittestRunner* me =\n reinterpret_cast(param);\n me->Run();\n me->fake_chrome_.ui_loop()->PostTask(FROM_HERE,\n NewRunnableFunction(TakeDownBrowser, me));\n return 0;\n}\n\n\/\/ static\nvoid CFUrlRequestUnittestRunner::TakeDownBrowser(\n CFUrlRequestUnittestRunner* me) {\n if (PromptAfterSetup())\n MessageBoxA(NULL, \"click ok to exit\", \"\", MB_OK);\n\n me->ShutDownHostBrowser();\n}\n\nvoid CFUrlRequestUnittestRunner::InitializeLogging() {\n FilePath exe;\n PathService::Get(base::FILE_EXE, &exe);\n FilePath log_filename = exe.ReplaceExtension(FILE_PATH_LITERAL(\"log\"));\n logging::InitLogging(log_filename.value().c_str(),\n logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,\n logging::LOCK_LOG_FILE,\n logging::DELETE_OLD_LOG_FILE);\n \/\/ We want process and thread IDs because we may have multiple processes.\n \/\/ Note: temporarily enabled timestamps in an effort to catch bug 6361.\n logging::SetLogItems(true, true, true, true);\n}\n\nvoid FilterDisabledTests() {\n if (::testing::FLAGS_gtest_filter.length() &&\n ::testing::FLAGS_gtest_filter.Compare(\"*\") != 0) {\n \/\/ Don't override user specified filters.\n return;\n }\n\n const char* disabled_tests[] = {\n \/\/ Tests disabled since they're testing the same functionality used\n \/\/ by the TestAutomationProvider.\n \"URLRequestTest.Intercept\",\n \"URLRequestTest.InterceptNetworkError\",\n \"URLRequestTest.InterceptRestartRequired\",\n \"URLRequestTest.InterceptRespectsCancelMain\",\n \"URLRequestTest.InterceptRespectsCancelRedirect\",\n \"URLRequestTest.InterceptRespectsCancelFinal\",\n \"URLRequestTest.InterceptRespectsCancelInRestart\",\n \"URLRequestTest.InterceptRedirect\",\n \"URLRequestTest.InterceptServerError\",\n \"URLRequestTestFTP.*\",\n\n \/\/ Tests that are currently not working:\n\n \/\/ Temporarily disabled because they needs user input (login dialog).\n \"URLRequestTestHTTP.BasicAuth\",\n \"URLRequestTestHTTP.BasicAuthWithCookies\",\n\n \/\/ HTTPS tests temporarily disabled due to the certificate error dialog.\n \/\/ TODO(tommi): The tests currently fail though, so need to fix.\n \"HTTPSRequestTest.HTTPSMismatchedTest\",\n \"HTTPSRequestTest.HTTPSExpiredTest\",\n\n \/\/ Tests chrome's network stack's cache (might not apply to CF).\n \"URLRequestTestHTTP.VaryHeader\",\n\n \/\/ I suspect we can only get this one to work (if at all) on IE8 and\n \/\/ later by using the new INTERNET_OPTION_SUPPRESS_BEHAVIOR flags\n \/\/ See http:\/\/msdn.microsoft.com\/en-us\/library\/aa385328(VS.85).aspx\n \"URLRequestTest.DoNotSaveCookies\",\n\n \/\/ TODO(ananta): This test has been consistently failing. Disabling it for\n \/\/ now.\n \"URLRequestTestHTTP.GetTest_NoCache\",\n };\n\n std::string filter(\"-\"); \/\/ All following filters will be negative.\n for (int i = 0; i < arraysize(disabled_tests); ++i) {\n if (i > 0)\n filter += \":\";\n filter += disabled_tests[i];\n }\n\n ::testing::FLAGS_gtest_filter = filter;\n}\n\nint main(int argc, char** argv) {\n DialogWatchdog watchdog;\n \/\/ See url_request_unittest.cc for these credentials.\n SupplyProxyCredentials credentials(\"user\", \"secret\");\n watchdog.AddObserver(&credentials);\n testing::InitGoogleTest(&argc, argv);\n FilterDisabledTests();\n PluginService::EnableChromePlugins(false);\n CFUrlRequestUnittestRunner test_suite(argc, argv);\n test_suite.RunMainUIThread();\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n\nnamespace eos { namespace chain {\nstruct shared_authority {\n shared_authority( chainbase::allocator alloc )\n :accounts(alloc),keys(alloc)\n {}\n\n shared_authority& operator=(const Authority& a) {\n threshold = a.threshold;\n accounts = decltype(accounts)(a.accounts.begin(), a.accounts.end(), accounts.get_allocator());\n keys = decltype(keys)(a.keys.begin(), a.keys.end(), keys.get_allocator());\n return *this;\n }\n shared_authority& operator=(Authority&& a) {\n threshold = a.threshold;\n accounts.reserve(a.accounts.size());\n for (auto& p : a.accounts)\n accounts.emplace_back(std::move(p));\n keys.reserve(a.keys.size());\n for (auto& p : a.keys)\n keys.emplace_back(std::move(p));\n return *this;\n }\n\n UInt32 threshold = 0;\n shared_vector accounts;\n shared_vector keys;\n};\n\n\/**\n * @brief This class determines whether a set of signing keys are sufficient to satisfy an authority or not\n *\n * To determine whether an authority is satisfied or not, we first determine which keys have approved of a message, and\n * then determine whether that list of keys is sufficient to satisfy the authority. This class takes a list of keys and\n * provides the @ref satisfied method to determine whether that list of keys satisfies a provided authority.\n *\n * @tparam F A callable which takes a single argument of type @ref AccountPermission and returns the corresponding\n * authority\n *\/\ntemplate\nclass AuthorityChecker {\n F PermissionToAuthority;\n const flat_set& signingKeys;\n\npublic:\n AuthorityChecker(F PermissionToAuthority, const flat_set& signingKeys)\n : PermissionToAuthority(PermissionToAuthority), signingKeys(signingKeys) {}\n\n bool satisfied(const types::AccountPermission& permission) const {\n return satisfied(PermissionToAuthority(permission));\n }\n template\n bool satisfied(const AuthorityType& authority) const {\n UInt32 weight = 0;\n for (const auto& kpw : authority.keys)\n if (signingKeys.count(kpw.key)) {\n weight += kpw.weight;\n if (weight >= authority.threshold)\n return true;\n }\n for (const auto& apw : authority.accounts)\n\/\/#warning TODO: Recursion limit? Yes: implement as producer-configurable parameter \n if (satisfied(apw.permission)) {\n weight += apw.weight;\n if (weight >= authority.threshold)\n return true;\n }\n return false;\n }\n};\n\ninline bool operator < ( const types::AccountPermission& a, const types::AccountPermission& b ) {\n return std::tie( a.account, a.permission ) < std::tie( b.account, b.permission );\n}\ntemplate\nAuthorityChecker MakeAuthorityChecker(F&& pta, const flat_set& signingKeys) {\n return AuthorityChecker(std::forward(pta), signingKeys);\n}\n\n\/**\n * Makes sure all keys are unique and sorted and all account permissions are unique and sorted\n *\/\ninline bool validate( types::Authority& auth ) {\n const types::KeyPermissionWeight* prev = nullptr;\n for( const auto& k : auth.keys ) {\n if( !prev ) prev = &k;\n else if( prev->key < k.key ) return false;\n }\n const types::AccountPermissionWeight* pa = nullptr;\n for( const auto& a : auth.accounts ) {\n if( !pa ) pa = &a;\n else if( pa->permission < a.permission ) return false;\n }\n return true;\n}\n\n} } \/\/ namespace eos::chain\n\nFC_REFLECT(eos::chain::shared_authority, (threshold)(accounts)(keys))\nAdd satisfiability check to validate(Authority)#pragma once\n#include \n#include \n\nnamespace eos { namespace chain {\nstruct shared_authority {\n shared_authority( chainbase::allocator alloc )\n :accounts(alloc),keys(alloc)\n {}\n\n shared_authority& operator=(const Authority& a) {\n threshold = a.threshold;\n accounts = decltype(accounts)(a.accounts.begin(), a.accounts.end(), accounts.get_allocator());\n keys = decltype(keys)(a.keys.begin(), a.keys.end(), keys.get_allocator());\n return *this;\n }\n shared_authority& operator=(Authority&& a) {\n threshold = a.threshold;\n accounts.reserve(a.accounts.size());\n for (auto& p : a.accounts)\n accounts.emplace_back(std::move(p));\n keys.reserve(a.keys.size());\n for (auto& p : a.keys)\n keys.emplace_back(std::move(p));\n return *this;\n }\n\n UInt32 threshold = 0;\n shared_vector accounts;\n shared_vector keys;\n};\n\n\/**\n * @brief This class determines whether a set of signing keys are sufficient to satisfy an authority or not\n *\n * To determine whether an authority is satisfied or not, we first determine which keys have approved of a message, and\n * then determine whether that list of keys is sufficient to satisfy the authority. This class takes a list of keys and\n * provides the @ref satisfied method to determine whether that list of keys satisfies a provided authority.\n *\n * @tparam F A callable which takes a single argument of type @ref AccountPermission and returns the corresponding\n * authority\n *\/\ntemplate\nclass AuthorityChecker {\n F PermissionToAuthority;\n const flat_set& signingKeys;\n\npublic:\n AuthorityChecker(F PermissionToAuthority, const flat_set& signingKeys)\n : PermissionToAuthority(PermissionToAuthority), signingKeys(signingKeys) {}\n\n bool satisfied(const types::AccountPermission& permission) const {\n return satisfied(PermissionToAuthority(permission));\n }\n template\n bool satisfied(const AuthorityType& authority) const {\n UInt32 weight = 0;\n for (const auto& kpw : authority.keys)\n if (signingKeys.count(kpw.key)) {\n weight += kpw.weight;\n if (weight >= authority.threshold)\n return true;\n }\n for (const auto& apw : authority.accounts)\n\/\/#warning TODO: Recursion limit? Yes: implement as producer-configurable parameter \n if (satisfied(apw.permission)) {\n weight += apw.weight;\n if (weight >= authority.threshold)\n return true;\n }\n return false;\n }\n};\n\ninline bool operator < ( const types::AccountPermission& a, const types::AccountPermission& b ) {\n return std::tie( a.account, a.permission ) < std::tie( b.account, b.permission );\n}\ntemplate\nAuthorityChecker MakeAuthorityChecker(F&& pta, const flat_set& signingKeys) {\n return AuthorityChecker(std::forward(pta), signingKeys);\n}\n\n\/**\n * Makes sure all keys are unique and sorted and all account permissions are unique and sorted and that authority can\n * be satisfied\n *\/\ninline bool validate( types::Authority& auth ) {\n const types::KeyPermissionWeight* prev = nullptr;\n decltype(auth.threshold) totalWeight = 0;\n\n for( const auto& k : auth.keys ) {\n if( !prev ) prev = &k;\n else if( prev->key < k.key ) return false;\n totalWeight += k.weight;\n }\n const types::AccountPermissionWeight* pa = nullptr;\n for( const auto& a : auth.accounts ) {\n if( !pa ) pa = &a;\n else if( pa->permission < a.permission ) return false;\n totalWeight += a.weight;\n }\n return totalWeight >= auth.threshold;\n}\n\n} } \/\/ namespace eos::chain\n\nFC_REFLECT(eos::chain::shared_authority, (threshold)(accounts)(keys))\n<|endoftext|>"} {"text":"\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\ntemplate class mrpt::CTraitsTest>;\n\nusing cb_t = int;\n\nTEST(circular_buffer_tests, EmptyPop)\n{\n\tmrpt::containers::circular_buffer cb(10);\n\ttry\n\t{\n\t\tcb_t ret;\n\t\tcb.pop(ret);\n\t\tGTEST_FAIL() << \"Exception was expected but didn't happen!\";\n\t}\n\tcatch (std::exception&)\n\t{\n\t\t\/\/ OK\n\t}\n}\nTEST(circular_buffer_tests, EmptyPopAfterPushes)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\tfor (size_t nWr = 0; nWr < LEN; nWr++)\n\t{\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(12);\n\t\tcb_t ret;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.pop(ret);\n\t\t\/\/ The next one must fail:\n\t\ttry\n\t\t{\n\t\t\tcb.pop(ret);\n\t\t\tGTEST_FAIL() << \"Exception was expected but didn't happen!\";\n\t\t}\n\t\tcatch (std::exception&)\n\t\t{\n\t\t\t\/\/ OK\n\t\t}\n\t}\n}\n\nTEST(circular_buffer_tests, RandomWriteAndPeek)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\n\tfor (size_t iter = 0; iter < 1000; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % LEN;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(i);\n\t\tcb_t ret;\n\t\tfor (size_t i = 0; i < nWr; i++)\n\t\t{\n\t\t\tret = cb.peek(i);\n\t\t\tEXPECT_EQ(ret, cb_t(i));\n\t\t}\n\t\tfor (size_t i = 0; i < nWr; i++)\n\t\t{\n\t\t\tcb.pop(ret);\n\t\t\tEXPECT_EQ(ret, cb_t(i));\n\t\t}\n\t}\n}\nTEST(circular_buffer_tests, RandomWriteManyAndPeek)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\tstd::vector dum_buf;\n\n\tfor (size_t iter = 0; iter < 1000; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\t1 +\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % (LEN - 1);\n\t\tdum_buf.resize(nWr);\n\t\tcb.push_many(&dum_buf[0], nWr);\n\t\tcb_t ret;\n\t\tif (iter % 1)\n\t\t{\n\t\t\tfor (size_t i = 0; i < nWr; i++) ret = cb.peek(i);\n\t\t\tMRPT_UNUSED_PARAM(ret);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcb.peek_many(&dum_buf[0], nWr);\n\t\t}\n\t\tcb.pop_many(&dum_buf[0], nWr);\n\t}\n}\nTEST(circular_buffer_tests, RandomWriteAndPeekOverrun)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\n\tfor (size_t iter = 0; iter < 100; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % LEN;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(i);\n\t\tcb_t ret;\n\t\tfor (unsigned k = 0; k < 5; k++)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tret = cb.peek(nWr + k);\n\t\t\t\tGTEST_FAIL() << \"Exception was expected but didn't happen!\";\n\t\t\t}\n\t\t\tcatch (std::exception&)\n\t\t\t{\n\t\t\t\t\/\/ OK\n\t\t\t}\n\t\t}\n\t\tfor (size_t i = 0; i < nWr; i++) cb.pop(ret);\n\t}\n}\n\nTEST(circular_buffer_tests, Size)\n{\n\tmrpt::containers::circular_buffer cb(10);\n\tfor (size_t i = 0; i < cb.capacity() - 1; i++)\n\t{\n\t\tcb.push(0);\n\t\tEXPECT_EQ(cb.size(), i + 1);\n\t}\n\tEXPECT_ANY_THROW(cb.push(0));\n\tfor (size_t i = 0; i < cb.capacity() - 1; i++)\n\t{\n\t\tcb.pop();\n\t\tEXPECT_EQ(cb.size(), cb.capacity() - 2 - i);\n\t}\n}\nEXPECT_THROW in circularbuffer_unittest\/* +------------------------------------------------------------------------+\n | Mobile Robot Programming Toolkit (MRPT) |\n | http:\/\/www.mrpt.org\/ |\n | |\n | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |\n | See: http:\/\/www.mrpt.org\/Authors - All rights reserved. |\n | Released under BSD License. See details in http:\/\/www.mrpt.org\/License |\n +------------------------------------------------------------------------+ *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\ntemplate class mrpt::CTraitsTest>;\n\nusing cb_t = int;\n\nTEST(circular_buffer_tests, EmptyPop)\n{\n\tmrpt::containers::circular_buffer cb(10);\n\ttry\n\t{\n\t\tcb_t ret;\n\tEXPECT_THROW(cb.pop(ret),std::exception);\n}\nTEST(circular_buffer_tests, EmptyPopAfterPushes)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\tfor (size_t nWr = 0; nWr < LEN; nWr++)\n\t{\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(12);\n\t\tcb_t ret;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.pop(ret);\n\t\t\/\/ The next one must fail:\n\t\tEXPECT_THROW(cb.pop(ret),std::exception);\n\t}\n}\n\nTEST(circular_buffer_tests, RandomWriteAndPeek)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\n\tfor (size_t iter = 0; iter < 1000; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % LEN;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(i);\n\t\tcb_t ret;\n\t\tfor (size_t i = 0; i < nWr; i++)\n\t\t{\n\t\t\tret = cb.peek(i);\n\t\t\tEXPECT_EQ(ret, cb_t(i));\n\t\t}\n\t\tfor (size_t i = 0; i < nWr; i++)\n\t\t{\n\t\t\tcb.pop(ret);\n\t\t\tEXPECT_EQ(ret, cb_t(i));\n\t\t}\n\t}\n}\nTEST(circular_buffer_tests, RandomWriteManyAndPeek)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\tstd::vector dum_buf;\n\n\tfor (size_t iter = 0; iter < 1000; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\t1 +\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % (LEN - 1);\n\t\tdum_buf.resize(nWr);\n\t\tcb.push_many(&dum_buf[0], nWr);\n\t\tcb_t ret;\n\t\tif (iter % 1)\n\t\t{\n\t\t\tfor (size_t i = 0; i < nWr; i++) ret = cb.peek(i);\n\t\t\tMRPT_UNUSED_PARAM(ret);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tcb.peek_many(&dum_buf[0], nWr);\n\t\t}\n\t\tcb.pop_many(&dum_buf[0], nWr);\n\t}\n}\nTEST(circular_buffer_tests, RandomWriteAndPeekOverrun)\n{\n\tconst size_t LEN = 20;\n\tmrpt::containers::circular_buffer cb(LEN);\n\n\tfor (size_t iter = 0; iter < 100; iter++)\n\t{\n\t\tconst size_t nWr =\n\t\t\tmrpt::random::getRandomGenerator().drawUniform32bit() % LEN;\n\t\tfor (size_t i = 0; i < nWr; i++) cb.push(i);\n\t\tcb_t ret;\n\t\tfor (unsigned k = 0; k < 5; k++)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tret = cb.peek(nWr + k);\n\t\t\t\tGTEST_FAIL() << \"Exception was expected but didn't happen!\";\n\t\t\t}\n\t\t\tcatch (std::exception&)\n\t\t\t{\n\t\t\t\t\/\/ OK\n\t\t\t}\n\t\t}\n\t\tfor (size_t i = 0; i < nWr; i++) cb.pop(ret);\n\t}\n}\n\nTEST(circular_buffer_tests, Size)\n{\n\tmrpt::containers::circular_buffer cb(10);\n\tfor (size_t i = 0; i < cb.capacity() - 1; i++)\n\t{\n\t\tcb.push(0);\n\t\tEXPECT_EQ(cb.size(), i + 1);\n\t}\n\tEXPECT_ANY_THROW(cb.push(0));\n\tfor (size_t i = 0; i < cb.capacity() - 1; i++)\n\t{\n\t\tcb.pop();\n\t\tEXPECT_EQ(cb.size(), cb.capacity() - 2 - i);\n\t}\n}\n<|endoftext|>"} {"text":"`yli::load::load_CSV_texture`: use `std::holds_alternative`.<|endoftext|>"} {"text":"Remove a CHECK() which was firing.<|endoftext|>"} {"text":"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/extensions\/extension_loader_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/path_util.h\"\n#include \"chrome\/browser\/extensions\/unpacked_installer.h\"\n#include \"chrome\/browser\/extensions\/zipfile_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/chrome_select_file_policy.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/browser\/web_ui_data_source.h\"\n#include \"extensions\/browser\/extension_system.h\"\n#include \"extensions\/browser\/file_highlighter.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"third_party\/re2\/re2\/re2.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/shell_dialogs\/select_file_dialog.h\"\n\nnamespace extensions {\n\nnamespace {\n\n\/\/ Read a file to a string and return.\nstd::string ReadFileToString(const base::FilePath& path) {\n std::string data;\n \/\/ This call can fail, but it doesn't matter for our purposes. If it fails,\n \/\/ we simply return an empty string for the manifest, and ignore it.\n base::ReadFileToString(path, &data);\n return data;\n}\n\n} \/\/ namespace\n\nclass ExtensionLoaderHandler::FileHelper\n : public ui::SelectFileDialog::Listener {\n public:\n explicit FileHelper(ExtensionLoaderHandler* loader_handler);\n ~FileHelper() override;\n\n \/\/ Create a FileDialog for the user to select the unpacked extension\n \/\/ directory.\n void ChooseFile();\n\n private:\n \/\/ ui::SelectFileDialog::Listener implementation.\n void FileSelected(const base::FilePath& path,\n int index,\n void* params) override;\n void MultiFilesSelected(const std::vector& files,\n void* params) override;\n\n \/\/ The associated ExtensionLoaderHandler. Weak, but guaranteed to be alive,\n \/\/ as it owns this object.\n ExtensionLoaderHandler* loader_handler_;\n\n \/\/ The dialog used to pick a directory when loading an unpacked extension.\n scoped_refptr load_extension_dialog_;\n\n \/\/ The last selected directory, so we can start in the same spot.\n base::FilePath last_unpacked_directory_;\n\n \/\/ The title of the dialog.\n base::string16 title_;\n\n DISALLOW_COPY_AND_ASSIGN(FileHelper);\n};\n\nExtensionLoaderHandler::FileHelper::FileHelper(\n ExtensionLoaderHandler* loader_handler)\n : loader_handler_(loader_handler),\n title_(l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY)) {\n}\n\nExtensionLoaderHandler::FileHelper::~FileHelper() {\n \/\/ There may be a pending file dialog; inform it the listener is destroyed so\n \/\/ it doesn't try and call back.\n if (load_extension_dialog_.get())\n load_extension_dialog_->ListenerDestroyed();\n}\n\nvoid ExtensionLoaderHandler::FileHelper::ChooseFile() {\n static const int kFileTypeIndex = 0; \/\/ No file type information to index.\n static const ui::SelectFileDialog::Type kSelectType =\n ui::SelectFileDialog::SELECT_FOLDER;\n\n if (!load_extension_dialog_.get()) {\n load_extension_dialog_ = ui::SelectFileDialog::Create(\n this,\n new ChromeSelectFilePolicy(\n loader_handler_->web_ui()->GetWebContents()));\n }\n\n load_extension_dialog_->SelectFile(\n kSelectType,\n title_,\n last_unpacked_directory_,\n NULL,\n kFileTypeIndex,\n base::FilePath::StringType(),\n loader_handler_->web_ui()->GetWebContents()->GetTopLevelNativeWindow(),\n NULL);\n\n content::RecordComputedAction(\"Options_LoadUnpackedExtension\");\n}\n\nvoid ExtensionLoaderHandler::FileHelper::FileSelected(\n const base::FilePath& path, int index, void* params) {\n loader_handler_->LoadUnpackedExtensionImpl(path);\n}\n\nvoid ExtensionLoaderHandler::FileHelper::MultiFilesSelected(\n const std::vector& files, void* params) {\n NOTREACHED();\n}\n\nExtensionLoaderHandler::ExtensionLoaderHandler(Profile* profile)\n : profile_(profile),\n file_helper_(new FileHelper(this)),\n extension_error_reporter_observer_(this),\n ui_ready_(false),\n weak_ptr_factory_(this) {\n DCHECK(profile_);\n extension_error_reporter_observer_.Add(ExtensionErrorReporter::GetInstance());\n}\n\nExtensionLoaderHandler::~ExtensionLoaderHandler() {\n}\n\nvoid ExtensionLoaderHandler::GetLocalizedValues(\n content::WebUIDataSource* source) {\n source->AddString(\n \"extensionLoadErrorHeading\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_HEADING));\n source->AddString(\n \"extensionLoadErrorMessage\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE));\n source->AddString(\n \"extensionLoadErrorRetry\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_RETRY));\n source->AddString(\n \"extensionLoadErrorGiveUp\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_GIVE_UP));\n source->AddString(\n \"extensionLoadCouldNotLoadManifest\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_COULD_NOT_LOAD_MANIFEST));\n source->AddString(\n \"extensionLoadAdditionalFailures\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ADDITIONAL_FAILURES));\n}\n\nvoid ExtensionLoaderHandler::RegisterMessages() {\n \/\/ We observe WebContents in order to detect page refreshes, since notifying\n \/\/ the frontend of load failures must be delayed until the page finishes\n \/\/ loading. We never call Observe(NULL) because this object is constructed\n \/\/ on page load and persists between refreshes.\n content::WebContentsObserver::Observe(web_ui()->GetWebContents());\n\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderLoadUnpacked\",\n base::Bind(&ExtensionLoaderHandler::HandleLoadUnpacked,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderRetry\",\n base::Bind(&ExtensionLoaderHandler::HandleRetry,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderIgnoreFailure\",\n base::Bind(&ExtensionLoaderHandler::HandleIgnoreFailure,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderDisplayFailures\",\n base::Bind(&ExtensionLoaderHandler::HandleDisplayFailures,\n weak_ptr_factory_.GetWeakPtr()));\n}\n\nvoid ExtensionLoaderHandler::HandleLoadUnpacked(const base::ListValue* args) {\n DCHECK(args->empty());\n file_helper_->ChooseFile();\n}\n\nvoid ExtensionLoaderHandler::HandleRetry(const base::ListValue* args) {\n DCHECK(args->empty());\n const base::FilePath file_path = failed_paths_.back();\n failed_paths_.pop_back();\n LoadUnpackedExtensionImpl(file_path);\n}\n\nvoid ExtensionLoaderHandler::HandleIgnoreFailure(const base::ListValue* args) {\n DCHECK(args->empty());\n failed_paths_.pop_back();\n}\n\nvoid ExtensionLoaderHandler::HandleDisplayFailures(\n const base::ListValue* args) {\n DCHECK(args->empty());\n ui_ready_ = true;\n\n \/\/ Notify the frontend of any load failures that were triggered while the\n \/\/ chrome:\/\/extensions page was loading.\n if (!failures_.empty())\n NotifyFrontendOfFailure();\n}\n\nvoid ExtensionLoaderHandler::LoadUnpackedExtensionImpl(\n const base::FilePath& file_path) {\n if (EndsWith(file_path.AsUTF16Unsafe(),\n base::ASCIIToUTF16(\".zip\"),\n false \/* case insensitive *\/)) {\n scoped_refptr installer = ZipFileInstaller::Create(\n ExtensionSystem::Get(profile_)->extension_service());\n\n \/\/ We do our own error handling, so we don't want a load failure to trigger\n \/\/ a dialog.\n installer->set_be_noisy_on_failure(false);\n\n installer->LoadFromZipFile(file_path);\n } else {\n scoped_refptr installer = UnpackedInstaller::Create(\n ExtensionSystem::Get(profile_)->extension_service());\n\n \/\/ We do our own error handling, so we don't want a load failure to trigger\n \/\/ a dialog.\n installer->set_be_noisy_on_failure(false);\n\n installer->Load(file_path);\n }\n}\n\nvoid ExtensionLoaderHandler::OnLoadFailure(\n content::BrowserContext* browser_context,\n const base::FilePath& file_path,\n const std::string& error) {\n \/\/ Only show errors from our browser context.\n if (web_ui()->GetWebContents()->GetBrowserContext() != browser_context)\n return;\n\n size_t line = 0u;\n size_t column = 0u;\n std::string regex =\n base::StringPrintf(\"%s Line: (\\\\d+), column: (\\\\d+), .*\",\n manifest_errors::kManifestParseError);\n \/\/ If this was a JSON parse error, we can highlight the exact line with the\n \/\/ error. Otherwise, we should still display the manifest (for consistency,\n \/\/ reference, and so that if we ever make this really fancy and add an editor,\n \/\/ it's ready).\n \/\/\n \/\/ This regex call can fail, but if it does, we just don't highlight anything.\n re2::RE2::FullMatch(error, regex, &line, &column);\n\n \/\/ This will read the manifest and call AddFailure with the read manifest\n \/\/ contents.\n base::PostTaskAndReplyWithResult(\n content::BrowserThread::GetBlockingPool(),\n FROM_HERE,\n base::Bind(&ReadFileToString, file_path.Append(kManifestFilename)),\n base::Bind(&ExtensionLoaderHandler::AddFailure,\n weak_ptr_factory_.GetWeakPtr(),\n file_path,\n error,\n line));\n}\n\nvoid ExtensionLoaderHandler::DidStartNavigationToPendingEntry(\n const GURL& url,\n content::NavigationController::ReloadType reload_type) {\n \/\/ In the event of a page reload, we ensure that the frontend is not notified\n \/\/ until the UI finishes loading, so we set |ui_ready_| to false. This is\n \/\/ balanced in HandleDisplayFailures, which is called when the frontend is\n \/\/ ready to receive failure notifications.\n if (reload_type != content::NavigationController::NO_RELOAD)\n ui_ready_ = false;\n}\n\nvoid ExtensionLoaderHandler::AddFailure(\n const base::FilePath& file_path,\n const std::string& error,\n size_t line_number,\n const std::string& manifest) {\n failed_paths_.push_back(file_path);\n base::FilePath prettified_path = path_util::PrettifyPath(file_path);\n\n scoped_ptr manifest_value(new base::DictionaryValue());\n SourceHighlighter highlighter(manifest, line_number);\n \/\/ If the line number is 0, this highlights no regions, but still adds the\n \/\/ full manifest.\n highlighter.SetHighlightedRegions(manifest_value.get());\n\n scoped_ptr failure(new base::DictionaryValue());\n failure->Set(\"path\",\n new base::StringValue(prettified_path.LossyDisplayName()));\n failure->Set(\"error\", new base::StringValue(base::UTF8ToUTF16(error)));\n failure->Set(\"manifest\", manifest_value.release());\n failures_.Append(failure.release());\n\n \/\/ Only notify the frontend if the frontend UI is ready.\n if (ui_ready_)\n NotifyFrontendOfFailure();\n}\n\nvoid ExtensionLoaderHandler::NotifyFrontendOfFailure() {\n web_ui()->CallJavascriptFunction(\n \"extensions.ExtensionLoader.notifyLoadFailed\",\n failures_);\n failures_.Clear();\n}\n\n} \/\/ namespace extensions\nExclude zip-file loading from \"Load Unpacked Extension\"\/\/ Copyright 2014 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/webui\/extensions\/extension_loader_handler.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/memory\/ref_counted.h\"\n#include \"base\/strings\/string16.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/stringprintf.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/path_util.h\"\n#include \"chrome\/browser\/extensions\/unpacked_installer.h\"\n#include \"chrome\/browser\/extensions\/zipfile_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/chrome_select_file_policy.h\"\n#include \"chrome\/grit\/generated_resources.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"content\/public\/browser\/user_metrics.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"content\/public\/browser\/web_ui.h\"\n#include \"content\/public\/browser\/web_ui_data_source.h\"\n#include \"extensions\/browser\/extension_system.h\"\n#include \"extensions\/browser\/file_highlighter.h\"\n#include \"extensions\/common\/constants.h\"\n#include \"extensions\/common\/extension.h\"\n#include \"extensions\/common\/manifest_constants.h\"\n#include \"third_party\/re2\/re2\/re2.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/shell_dialogs\/select_file_dialog.h\"\n\nnamespace extensions {\n\nnamespace {\n\n\/\/ Read a file to a string and return.\nstd::string ReadFileToString(const base::FilePath& path) {\n std::string data;\n \/\/ This call can fail, but it doesn't matter for our purposes. If it fails,\n \/\/ we simply return an empty string for the manifest, and ignore it.\n base::ReadFileToString(path, &data);\n return data;\n}\n\n} \/\/ namespace\n\nclass ExtensionLoaderHandler::FileHelper\n : public ui::SelectFileDialog::Listener {\n public:\n explicit FileHelper(ExtensionLoaderHandler* loader_handler);\n ~FileHelper() override;\n\n \/\/ Create a FileDialog for the user to select the unpacked extension\n \/\/ directory.\n void ChooseFile();\n\n private:\n \/\/ ui::SelectFileDialog::Listener implementation.\n void FileSelected(const base::FilePath& path,\n int index,\n void* params) override;\n void MultiFilesSelected(const std::vector& files,\n void* params) override;\n\n \/\/ The associated ExtensionLoaderHandler. Weak, but guaranteed to be alive,\n \/\/ as it owns this object.\n ExtensionLoaderHandler* loader_handler_;\n\n \/\/ The dialog used to pick a directory when loading an unpacked extension.\n scoped_refptr load_extension_dialog_;\n\n \/\/ The last selected directory, so we can start in the same spot.\n base::FilePath last_unpacked_directory_;\n\n \/\/ The title of the dialog.\n base::string16 title_;\n\n DISALLOW_COPY_AND_ASSIGN(FileHelper);\n};\n\nExtensionLoaderHandler::FileHelper::FileHelper(\n ExtensionLoaderHandler* loader_handler)\n : loader_handler_(loader_handler),\n title_(l10n_util::GetStringUTF16(IDS_EXTENSION_LOAD_FROM_DIRECTORY)) {\n}\n\nExtensionLoaderHandler::FileHelper::~FileHelper() {\n \/\/ There may be a pending file dialog; inform it the listener is destroyed so\n \/\/ it doesn't try and call back.\n if (load_extension_dialog_.get())\n load_extension_dialog_->ListenerDestroyed();\n}\n\nvoid ExtensionLoaderHandler::FileHelper::ChooseFile() {\n static const int kFileTypeIndex = 0; \/\/ No file type information to index.\n static const ui::SelectFileDialog::Type kSelectType =\n ui::SelectFileDialog::SELECT_FOLDER;\n\n if (!load_extension_dialog_.get()) {\n load_extension_dialog_ = ui::SelectFileDialog::Create(\n this,\n new ChromeSelectFilePolicy(\n loader_handler_->web_ui()->GetWebContents()));\n }\n\n load_extension_dialog_->SelectFile(\n kSelectType,\n title_,\n last_unpacked_directory_,\n NULL,\n kFileTypeIndex,\n base::FilePath::StringType(),\n loader_handler_->web_ui()->GetWebContents()->GetTopLevelNativeWindow(),\n NULL);\n\n content::RecordComputedAction(\"Options_LoadUnpackedExtension\");\n}\n\nvoid ExtensionLoaderHandler::FileHelper::FileSelected(\n const base::FilePath& path, int index, void* params) {\n loader_handler_->LoadUnpackedExtensionImpl(path);\n}\n\nvoid ExtensionLoaderHandler::FileHelper::MultiFilesSelected(\n const std::vector& files, void* params) {\n NOTREACHED();\n}\n\nExtensionLoaderHandler::ExtensionLoaderHandler(Profile* profile)\n : profile_(profile),\n file_helper_(new FileHelper(this)),\n extension_error_reporter_observer_(this),\n ui_ready_(false),\n weak_ptr_factory_(this) {\n DCHECK(profile_);\n extension_error_reporter_observer_.Add(ExtensionErrorReporter::GetInstance());\n}\n\nExtensionLoaderHandler::~ExtensionLoaderHandler() {\n}\n\nvoid ExtensionLoaderHandler::GetLocalizedValues(\n content::WebUIDataSource* source) {\n source->AddString(\n \"extensionLoadErrorHeading\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_HEADING));\n source->AddString(\n \"extensionLoadErrorMessage\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_MESSAGE));\n source->AddString(\n \"extensionLoadErrorRetry\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_RETRY));\n source->AddString(\n \"extensionLoadErrorGiveUp\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ERROR_GIVE_UP));\n source->AddString(\n \"extensionLoadCouldNotLoadManifest\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_COULD_NOT_LOAD_MANIFEST));\n source->AddString(\n \"extensionLoadAdditionalFailures\",\n l10n_util::GetStringUTF16(IDS_EXTENSIONS_LOAD_ADDITIONAL_FAILURES));\n}\n\nvoid ExtensionLoaderHandler::RegisterMessages() {\n \/\/ We observe WebContents in order to detect page refreshes, since notifying\n \/\/ the frontend of load failures must be delayed until the page finishes\n \/\/ loading. We never call Observe(NULL) because this object is constructed\n \/\/ on page load and persists between refreshes.\n content::WebContentsObserver::Observe(web_ui()->GetWebContents());\n\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderLoadUnpacked\",\n base::Bind(&ExtensionLoaderHandler::HandleLoadUnpacked,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderRetry\",\n base::Bind(&ExtensionLoaderHandler::HandleRetry,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderIgnoreFailure\",\n base::Bind(&ExtensionLoaderHandler::HandleIgnoreFailure,\n weak_ptr_factory_.GetWeakPtr()));\n web_ui()->RegisterMessageCallback(\n \"extensionLoaderDisplayFailures\",\n base::Bind(&ExtensionLoaderHandler::HandleDisplayFailures,\n weak_ptr_factory_.GetWeakPtr()));\n}\n\nvoid ExtensionLoaderHandler::HandleLoadUnpacked(const base::ListValue* args) {\n DCHECK(args->empty());\n file_helper_->ChooseFile();\n}\n\nvoid ExtensionLoaderHandler::HandleRetry(const base::ListValue* args) {\n DCHECK(args->empty());\n const base::FilePath file_path = failed_paths_.back();\n failed_paths_.pop_back();\n LoadUnpackedExtensionImpl(file_path);\n}\n\nvoid ExtensionLoaderHandler::HandleIgnoreFailure(const base::ListValue* args) {\n DCHECK(args->empty());\n failed_paths_.pop_back();\n}\n\nvoid ExtensionLoaderHandler::HandleDisplayFailures(\n const base::ListValue* args) {\n DCHECK(args->empty());\n ui_ready_ = true;\n\n \/\/ Notify the frontend of any load failures that were triggered while the\n \/\/ chrome:\/\/extensions page was loading.\n if (!failures_.empty())\n NotifyFrontendOfFailure();\n}\n\nvoid ExtensionLoaderHandler::LoadUnpackedExtensionImpl(\n const base::FilePath& file_path) {\n scoped_refptr installer = UnpackedInstaller::Create(\n ExtensionSystem::Get(profile_)->extension_service());\n\n \/\/ We do our own error handling, so we don't want a load failure to trigger\n \/\/ a dialog.\n installer->set_be_noisy_on_failure(false);\n\n installer->Load(file_path);\n}\n\nvoid ExtensionLoaderHandler::OnLoadFailure(\n content::BrowserContext* browser_context,\n const base::FilePath& file_path,\n const std::string& error) {\n \/\/ Only show errors from our browser context.\n if (web_ui()->GetWebContents()->GetBrowserContext() != browser_context)\n return;\n\n size_t line = 0u;\n size_t column = 0u;\n std::string regex =\n base::StringPrintf(\"%s Line: (\\\\d+), column: (\\\\d+), .*\",\n manifest_errors::kManifestParseError);\n \/\/ If this was a JSON parse error, we can highlight the exact line with the\n \/\/ error. Otherwise, we should still display the manifest (for consistency,\n \/\/ reference, and so that if we ever make this really fancy and add an editor,\n \/\/ it's ready).\n \/\/\n \/\/ This regex call can fail, but if it does, we just don't highlight anything.\n re2::RE2::FullMatch(error, regex, &line, &column);\n\n \/\/ This will read the manifest and call AddFailure with the read manifest\n \/\/ contents.\n base::PostTaskAndReplyWithResult(\n content::BrowserThread::GetBlockingPool(),\n FROM_HERE,\n base::Bind(&ReadFileToString, file_path.Append(kManifestFilename)),\n base::Bind(&ExtensionLoaderHandler::AddFailure,\n weak_ptr_factory_.GetWeakPtr(),\n file_path,\n error,\n line));\n}\n\nvoid ExtensionLoaderHandler::DidStartNavigationToPendingEntry(\n const GURL& url,\n content::NavigationController::ReloadType reload_type) {\n \/\/ In the event of a page reload, we ensure that the frontend is not notified\n \/\/ until the UI finishes loading, so we set |ui_ready_| to false. This is\n \/\/ balanced in HandleDisplayFailures, which is called when the frontend is\n \/\/ ready to receive failure notifications.\n if (reload_type != content::NavigationController::NO_RELOAD)\n ui_ready_ = false;\n}\n\nvoid ExtensionLoaderHandler::AddFailure(\n const base::FilePath& file_path,\n const std::string& error,\n size_t line_number,\n const std::string& manifest) {\n failed_paths_.push_back(file_path);\n base::FilePath prettified_path = path_util::PrettifyPath(file_path);\n\n scoped_ptr manifest_value(new base::DictionaryValue());\n SourceHighlighter highlighter(manifest, line_number);\n \/\/ If the line number is 0, this highlights no regions, but still adds the\n \/\/ full manifest.\n highlighter.SetHighlightedRegions(manifest_value.get());\n\n scoped_ptr failure(new base::DictionaryValue());\n failure->Set(\"path\",\n new base::StringValue(prettified_path.LossyDisplayName()));\n failure->Set(\"error\", new base::StringValue(base::UTF8ToUTF16(error)));\n failure->Set(\"manifest\", manifest_value.release());\n failures_.Append(failure.release());\n\n \/\/ Only notify the frontend if the frontend UI is ready.\n if (ui_ready_)\n NotifyFrontendOfFailure();\n}\n\nvoid ExtensionLoaderHandler::NotifyFrontendOfFailure() {\n web_ui()->CallJavascriptFunction(\n \"extensions.ExtensionLoader.notifyLoadFailed\",\n failures_);\n failures_.Clear();\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"#include\n#include\n#include\n#include\"head.h\"\n#include\nusing namespace std;\nvoid str::disp()\n{\n int i;\n cout<>n;\n}\nvoid str::countocc()\n{\n int i;\n for(i=0;i64)&&(n[i]<91))\n {\n count[n[i]-65]+=1;\n }\n if((n[i]>96)&&(n[i]<123))\n {\n count[n[i]-97]+=1;\n }\n }\n}\nstr scase(str s)\n{\n int i;\n for(i=0;i64)&&(s.n[i]<91))\n s.n[i]=s.n[i]+32;\n\t else if((s.n[i]>96)&&(s.n[i]<123))\n\t s.n[i]=s.n[i]-32;\n else\n\t s.n[i]+=0;\n }\n\t return s;\n}\nstr str::operator+(str s1)\n{\n str s;\n s.n=strcat(n,s1.n);\n s.len=len+s1.len;\n return s;\n}\nvoid str::randomizer()\n{\n int i;\n cout<<\"Enter length\"<>len;\n n=new char[len+1];\n unsigned seed,b;\n b=rand()%len;\n seed=rand()%b;\n default_random_engine generator(seed);\n for(i=0;i distribution(65,122);\n int a = distribution(generator);\n if(a<91||a>96)\n\t {\n\t n[i]=a;\n\t }\n\t else\n\t {\n\t uniform_int_distribution distribution(65,90);\n\t a=distribution(generator);\n\t n[i]=a;\n }\n }\n}\nvoid str::sort()\n{\n int i,j;\n for(i=1;in[j])\n {\n char t;\n t=n[i];\n n[i]=n[j];\n n[j]=t;\n }\n else if(n[i]Delete functions.cpp<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ table_factory.cpp\n\/\/\n\/\/ Identification: src\/storage\/table_factory.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"storage\/table_factory.h\"\n\n#include \"common\/exception.h\"\n#include \"common\/logger.h\"\n#include \"index\/index.h\"\n#include \"storage\/data_table.h\"\n#include \"storage\/storage_manager.h\"\n#include \"storage\/temp_table.h\"\n\n#include \n\nnamespace peloton {\nnamespace storage {\n\nDataTable *TableFactory::GetDataTable(oid_t database_id, oid_t relation_id,\n catalog::Schema *schema,\n std::string table_name,\n size_t tuples_per_tilegroup_count,\n bool own_schema, bool adapt_table,\n bool is_catalog) {\n DataTable *table = new DataTable(schema, table_name, database_id, relation_id,\n tuples_per_tilegroup_count, own_schema,\n adapt_table, is_catalog);\n\n return table;\n}\n\nTempTable *TableFactory::GetTempTable(catalog::Schema *schema,\n bool own_schema) {\n TempTable *table = new TempTable(INVALID_OID, schema, own_schema);\n return (table);\n}\n\nbool TableFactory::DropDataTable(oid_t database_oid, oid_t table_oid) {\n auto storage_manager = storage::StorageManager::GetInstance();\n try {\n DataTable *table = (DataTable *)storage_manager->GetTableWithOid(\n database_oid, table_oid);\n delete table;\n } catch (CatalogException &e) {\n return false;\n }\n return true;\n}\n\n} \/\/ namespace storage\n} \/\/ namespace peloton\nRemoving unused header\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ table_factory.cpp\n\/\/\n\/\/ Identification: src\/storage\/table_factory.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"storage\/table_factory.h\"\n\n#include \"common\/exception.h\"\n#include \"common\/logger.h\"\n#include \"index\/index.h\"\n#include \"storage\/data_table.h\"\n#include \"storage\/storage_manager.h\"\n#include \"storage\/temp_table.h\"\n\n\nnamespace peloton {\nnamespace storage {\n\nDataTable *TableFactory::GetDataTable(oid_t database_id, oid_t relation_id,\n catalog::Schema *schema,\n std::string table_name,\n size_t tuples_per_tilegroup_count,\n bool own_schema, bool adapt_table,\n bool is_catalog) {\n DataTable *table = new DataTable(schema, table_name, database_id, relation_id,\n tuples_per_tilegroup_count, own_schema,\n adapt_table, is_catalog);\n\n return table;\n}\n\nTempTable *TableFactory::GetTempTable(catalog::Schema *schema,\n bool own_schema) {\n TempTable *table = new TempTable(INVALID_OID, schema, own_schema);\n return (table);\n}\n\nbool TableFactory::DropDataTable(oid_t database_oid, oid_t table_oid) {\n auto storage_manager = storage::StorageManager::GetInstance();\n try {\n DataTable *table = (DataTable *)storage_manager->GetTableWithOid(\n database_oid, table_oid);\n delete table;\n } catch (CatalogException &e) {\n return false;\n }\n return true;\n}\n\n} \/\/ namespace storage\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"systemc\/core\/scheduler.hh\"\n\n#include \"base\/fiber.hh\"\n#include \"base\/logging.hh\"\n#include \"sim\/eventq.hh\"\n#include \"systemc\/core\/kernel.hh\"\n#include \"systemc\/ext\/core\/sc_main.hh\"\n\nnamespace sc_gem5\n{\n\nScheduler::Scheduler() :\n eq(nullptr), readyEvent(this, false, ReadyPriority),\n pauseEvent(this, false, PausePriority),\n stopEvent(this, false, StopPriority),\n scMain(nullptr),\n starvationEvent(this, false, StarvationPriority),\n _started(false), _paused(false), _stopped(false),\n maxTickEvent(this, false, MaxTickPriority),\n _numCycles(0), _current(nullptr), initDone(false),\n runOnce(false)\n{}\n\nScheduler::~Scheduler()\n{\n \/\/ Clear out everything that belongs to us to make sure nobody tries to\n \/\/ clear themselves out after the scheduler goes away.\n clear();\n}\n\nvoid\nScheduler::clear()\n{\n \/\/ Delta notifications.\n for (auto &e: deltas)\n e->deschedule();\n deltas.clear();\n\n \/\/ Timed notifications.\n for (auto &tsp: timeSlots) {\n TimeSlot *&ts = tsp.second;\n for (auto &e: ts->events)\n e->deschedule();\n deschedule(ts);\n }\n timeSlots.clear();\n\n \/\/ gem5 events.\n if (readyEvent.scheduled())\n deschedule(&readyEvent);\n if (pauseEvent.scheduled())\n deschedule(&pauseEvent);\n if (stopEvent.scheduled())\n deschedule(&stopEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n if (maxTickEvent.scheduled())\n deschedule(&maxTickEvent);\n\n Process *p;\n while ((p = toFinalize.getNext()))\n p->popListNode();\n while ((p = initList.getNext()))\n p->popListNode();\n while ((p = readyList.getNext()))\n p->popListNode();\n\n Channel *c;\n while ((c = updateList.getNext()))\n c->popListNode();\n}\n\nvoid\nScheduler::initPhase()\n{\n for (Process *p = toFinalize.getNext(); p; p = toFinalize.getNext()) {\n p->finalize();\n p->popListNode();\n }\n\n for (Process *p = initList.getNext(); p; p = initList.getNext()) {\n p->finalize();\n p->popListNode();\n p->ready();\n }\n\n update();\n\n for (auto &e: deltas)\n e->run();\n deltas.clear();\n\n for (auto ets: eventsToSchedule)\n eq->schedule(ets.first, ets.second);\n eventsToSchedule.clear();\n\n if (_started) {\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n kernel->status(::sc_core::SC_RUNNING);\n }\n\n initDone = true;\n}\n\nvoid\nScheduler::reg(Process *p)\n{\n if (initDone) {\n \/\/ If we're past initialization, finalize static sensitivity.\n p->finalize();\n \/\/ Mark the process as ready.\n p->ready();\n } else {\n \/\/ Otherwise, record that this process should be initialized once we\n \/\/ get there.\n initList.pushLast(p);\n }\n}\n\nvoid\nScheduler::dontInitialize(Process *p)\n{\n if (initDone) {\n \/\/ Pop this process off of the ready list.\n p->popListNode();\n } else {\n \/\/ Push this process onto the list of processes which still need\n \/\/ their static sensitivity to be finalized. That implicitly pops it\n \/\/ off the list of processes to be initialized\/marked ready.\n toFinalize.pushLast(p);\n }\n}\n\nvoid\nScheduler::yield()\n{\n _current = readyList.getNext();\n if (!_current) {\n \/\/ There are no more processes, so return control to evaluate.\n Fiber::primaryFiber()->run();\n } else {\n _current->popListNode();\n \/\/ Switch to whatever Fiber is supposed to run this process. All\n \/\/ Fibers which aren't running should be parked at this line.\n _current->fiber()->run();\n \/\/ If the current process needs to be manually started, start it.\n if (_current && _current->needsStart()) {\n _current->needsStart(false);\n _current->run();\n }\n }\n if (_current && _current->excWrapper) {\n \/\/ Make sure this isn't a method process.\n assert(!_current->needsStart());\n auto ew = _current->excWrapper;\n _current->excWrapper = nullptr;\n ew->throw_it();\n }\n}\n\nvoid\nScheduler::ready(Process *p)\n{\n \/\/ Clump methods together to minimize context switching.\n if (p->procKind() == ::sc_core::SC_METHOD_PROC_)\n readyList.pushFirst(p);\n else\n readyList.pushLast(p);\n\n scheduleReadyEvent();\n}\n\nvoid\nScheduler::requestUpdate(Channel *c)\n{\n updateList.pushLast(c);\n scheduleReadyEvent();\n}\n\nvoid\nScheduler::scheduleReadyEvent()\n{\n \/\/ Schedule the evaluate and update phases.\n if (!readyEvent.scheduled()) {\n schedule(&readyEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n }\n}\n\nvoid\nScheduler::scheduleStarvationEvent()\n{\n if (!starvationEvent.scheduled()) {\n schedule(&starvationEvent);\n if (readyEvent.scheduled())\n deschedule(&readyEvent);\n }\n}\n\nvoid\nScheduler::runReady()\n{\n bool empty = readyList.empty();\n\n \/\/ The evaluation phase.\n do {\n yield();\n } while (!readyList.empty());\n\n if (!empty)\n _numCycles++;\n\n \/\/ The update phase.\n update();\n\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n\n \/\/ The delta phase.\n for (auto &e: deltas)\n e->run();\n deltas.clear();\n\n if (runOnce)\n schedulePause();\n}\n\nvoid\nScheduler::update()\n{\n Channel *channel = updateList.getNext();\n while (channel) {\n channel->popListNode();\n channel->update();\n channel = updateList.getNext();\n }\n}\n\nvoid\nScheduler::pause()\n{\n _paused = true;\n kernel->status(::sc_core::SC_PAUSED);\n runOnce = false;\n scMain->run();\n}\n\nvoid\nScheduler::stop()\n{\n _stopped = true;\n kernel->stop();\n\n clear();\n\n runOnce = false;\n scMain->run();\n}\n\nvoid\nScheduler::start(Tick max_tick, bool run_to_time)\n{\n \/\/ We should be running from sc_main. Keep track of that Fiber to return\n \/\/ to later.\n scMain = Fiber::currentFiber();\n\n _started = true;\n _paused = false;\n _stopped = false;\n runToTime = run_to_time;\n\n maxTick = max_tick;\n\n if (initDone) {\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n kernel->status(::sc_core::SC_RUNNING);\n }\n\n schedule(&maxTickEvent, maxTick);\n\n \/\/ Return to gem5 to let it run events, etc.\n Fiber::primaryFiber()->run();\n\n if (pauseEvent.scheduled())\n deschedule(&pauseEvent);\n if (stopEvent.scheduled())\n deschedule(&stopEvent);\n if (maxTickEvent.scheduled())\n deschedule(&maxTickEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n}\n\nvoid\nScheduler::oneCycle()\n{\n runOnce = true;\n start(::MaxTick, false);\n}\n\nvoid\nScheduler::schedulePause()\n{\n if (pauseEvent.scheduled())\n return;\n\n schedule(&pauseEvent);\n}\n\nvoid\nScheduler::scheduleStop(bool finish_delta)\n{\n if (stopEvent.scheduled())\n return;\n\n if (!finish_delta) {\n \/\/ If we're not supposed to finish the delta cycle, flush all\n \/\/ pending activity.\n clear();\n }\n schedule(&stopEvent);\n}\n\nScheduler scheduler;\n\n} \/\/ namespace sc_gem5\nsystemc: When sc_start-ing with zero time, ensure the ready event runs.\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"systemc\/core\/scheduler.hh\"\n\n#include \"base\/fiber.hh\"\n#include \"base\/logging.hh\"\n#include \"sim\/eventq.hh\"\n#include \"systemc\/core\/kernel.hh\"\n#include \"systemc\/ext\/core\/sc_main.hh\"\n\nnamespace sc_gem5\n{\n\nScheduler::Scheduler() :\n eq(nullptr), readyEvent(this, false, ReadyPriority),\n pauseEvent(this, false, PausePriority),\n stopEvent(this, false, StopPriority),\n scMain(nullptr),\n starvationEvent(this, false, StarvationPriority),\n _started(false), _paused(false), _stopped(false),\n maxTickEvent(this, false, MaxTickPriority),\n _numCycles(0), _current(nullptr), initDone(false),\n runOnce(false)\n{}\n\nScheduler::~Scheduler()\n{\n \/\/ Clear out everything that belongs to us to make sure nobody tries to\n \/\/ clear themselves out after the scheduler goes away.\n clear();\n}\n\nvoid\nScheduler::clear()\n{\n \/\/ Delta notifications.\n for (auto &e: deltas)\n e->deschedule();\n deltas.clear();\n\n \/\/ Timed notifications.\n for (auto &tsp: timeSlots) {\n TimeSlot *&ts = tsp.second;\n for (auto &e: ts->events)\n e->deschedule();\n deschedule(ts);\n }\n timeSlots.clear();\n\n \/\/ gem5 events.\n if (readyEvent.scheduled())\n deschedule(&readyEvent);\n if (pauseEvent.scheduled())\n deschedule(&pauseEvent);\n if (stopEvent.scheduled())\n deschedule(&stopEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n if (maxTickEvent.scheduled())\n deschedule(&maxTickEvent);\n\n Process *p;\n while ((p = toFinalize.getNext()))\n p->popListNode();\n while ((p = initList.getNext()))\n p->popListNode();\n while ((p = readyList.getNext()))\n p->popListNode();\n\n Channel *c;\n while ((c = updateList.getNext()))\n c->popListNode();\n}\n\nvoid\nScheduler::initPhase()\n{\n for (Process *p = toFinalize.getNext(); p; p = toFinalize.getNext()) {\n p->finalize();\n p->popListNode();\n }\n\n for (Process *p = initList.getNext(); p; p = initList.getNext()) {\n p->finalize();\n p->popListNode();\n p->ready();\n }\n\n update();\n\n for (auto &e: deltas)\n e->run();\n deltas.clear();\n\n for (auto ets: eventsToSchedule)\n eq->schedule(ets.first, ets.second);\n eventsToSchedule.clear();\n\n if (_started) {\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n kernel->status(::sc_core::SC_RUNNING);\n }\n\n initDone = true;\n}\n\nvoid\nScheduler::reg(Process *p)\n{\n if (initDone) {\n \/\/ If we're past initialization, finalize static sensitivity.\n p->finalize();\n \/\/ Mark the process as ready.\n p->ready();\n } else {\n \/\/ Otherwise, record that this process should be initialized once we\n \/\/ get there.\n initList.pushLast(p);\n }\n}\n\nvoid\nScheduler::dontInitialize(Process *p)\n{\n if (initDone) {\n \/\/ Pop this process off of the ready list.\n p->popListNode();\n } else {\n \/\/ Push this process onto the list of processes which still need\n \/\/ their static sensitivity to be finalized. That implicitly pops it\n \/\/ off the list of processes to be initialized\/marked ready.\n toFinalize.pushLast(p);\n }\n}\n\nvoid\nScheduler::yield()\n{\n _current = readyList.getNext();\n if (!_current) {\n \/\/ There are no more processes, so return control to evaluate.\n Fiber::primaryFiber()->run();\n } else {\n _current->popListNode();\n \/\/ Switch to whatever Fiber is supposed to run this process. All\n \/\/ Fibers which aren't running should be parked at this line.\n _current->fiber()->run();\n \/\/ If the current process needs to be manually started, start it.\n if (_current && _current->needsStart()) {\n _current->needsStart(false);\n _current->run();\n }\n }\n if (_current && _current->excWrapper) {\n \/\/ Make sure this isn't a method process.\n assert(!_current->needsStart());\n auto ew = _current->excWrapper;\n _current->excWrapper = nullptr;\n ew->throw_it();\n }\n}\n\nvoid\nScheduler::ready(Process *p)\n{\n \/\/ Clump methods together to minimize context switching.\n if (p->procKind() == ::sc_core::SC_METHOD_PROC_)\n readyList.pushFirst(p);\n else\n readyList.pushLast(p);\n\n scheduleReadyEvent();\n}\n\nvoid\nScheduler::requestUpdate(Channel *c)\n{\n updateList.pushLast(c);\n scheduleReadyEvent();\n}\n\nvoid\nScheduler::scheduleReadyEvent()\n{\n \/\/ Schedule the evaluate and update phases.\n if (!readyEvent.scheduled()) {\n schedule(&readyEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n }\n}\n\nvoid\nScheduler::scheduleStarvationEvent()\n{\n if (!starvationEvent.scheduled()) {\n schedule(&starvationEvent);\n if (readyEvent.scheduled())\n deschedule(&readyEvent);\n }\n}\n\nvoid\nScheduler::runReady()\n{\n bool empty = readyList.empty();\n\n \/\/ The evaluation phase.\n do {\n yield();\n } while (!readyList.empty());\n\n if (!empty)\n _numCycles++;\n\n \/\/ The update phase.\n update();\n\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n\n \/\/ The delta phase.\n for (auto &e: deltas)\n e->run();\n deltas.clear();\n\n if (runOnce)\n schedulePause();\n}\n\nvoid\nScheduler::update()\n{\n Channel *channel = updateList.getNext();\n while (channel) {\n channel->popListNode();\n channel->update();\n channel = updateList.getNext();\n }\n}\n\nvoid\nScheduler::pause()\n{\n _paused = true;\n kernel->status(::sc_core::SC_PAUSED);\n runOnce = false;\n scMain->run();\n}\n\nvoid\nScheduler::stop()\n{\n _stopped = true;\n kernel->stop();\n\n clear();\n\n runOnce = false;\n scMain->run();\n}\n\nvoid\nScheduler::start(Tick max_tick, bool run_to_time)\n{\n \/\/ We should be running from sc_main. Keep track of that Fiber to return\n \/\/ to later.\n scMain = Fiber::currentFiber();\n\n _started = true;\n _paused = false;\n _stopped = false;\n runToTime = run_to_time;\n\n maxTick = max_tick;\n\n if (initDone) {\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n kernel->status(::sc_core::SC_RUNNING);\n }\n\n schedule(&maxTickEvent, maxTick);\n\n \/\/ Return to gem5 to let it run events, etc.\n Fiber::primaryFiber()->run();\n\n if (pauseEvent.scheduled())\n deschedule(&pauseEvent);\n if (stopEvent.scheduled())\n deschedule(&stopEvent);\n if (maxTickEvent.scheduled())\n deschedule(&maxTickEvent);\n if (starvationEvent.scheduled())\n deschedule(&starvationEvent);\n}\n\nvoid\nScheduler::oneCycle()\n{\n runOnce = true;\n scheduleReadyEvent();\n start(::MaxTick, false);\n}\n\nvoid\nScheduler::schedulePause()\n{\n if (pauseEvent.scheduled())\n return;\n\n schedule(&pauseEvent);\n}\n\nvoid\nScheduler::scheduleStop(bool finish_delta)\n{\n if (stopEvent.scheduled())\n return;\n\n if (!finish_delta) {\n \/\/ If we're not supposed to finish the delta cycle, flush all\n \/\/ pending activity.\n clear();\n }\n schedule(&stopEvent);\n}\n\nScheduler scheduler;\n\n} \/\/ namespace sc_gem5\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __SYSTEMC_CORE_SCHEDULER_HH__\n#define __SYSTEMC_CORE_SCHEDULER_HH__\n\n#include \n\n#include \"base\/logging.hh\"\n#include \"sim\/eventq.hh\"\n#include \"systemc\/core\/channel.hh\"\n#include \"systemc\/core\/list.hh\"\n#include \"systemc\/core\/process.hh\"\n\nclass Fiber;\n\nnamespace sc_gem5\n{\n\ntypedef NodeList ProcessList;\ntypedef NodeList ChannelList;\n\n\/*\n * The scheduler supports three different mechanisms, the initialization phase,\n * delta cycles, and timed notifications.\n *\n * INITIALIZATION PHASE\n *\n * The initialization phase has three parts:\n * 1. Run requested channel updates.\n * 2. Make processes which need to initialize runnable (methods and threads\n * which didn't have dont_initialize called on them).\n * 3. Process delta notifications.\n *\n * First, the Kernel SimObject calls the update() method during its startup()\n * callback which handles the requested channel updates. The Kernel also\n * schedules an event to be run at time 0 with a slightly elevated priority\n * so that it happens before any \"normal\" event.\n *\n * When that t0 event happens, it calls the schedulers prepareForInit method\n * which performs step 2 above. That indirectly causes the scheduler's\n * readyEvent to be scheduled with slightly lowered priority, ensuring it\n * happens after any \"normal\" event.\n *\n * Because delta notifications are scheduled at the standard priority, all\n * of those events will happen next, performing step 3 above. Once they finish,\n * if the readyEvent was scheduled above, there shouldn't be any higher\n * priority events in front of it. When it runs, it will start the first\n * evaluate phase of the first delta cycle.\n *\n * DELTA CYCLE\n *\n * A delta cycle has three phases within it.\n * 1. The evaluate phase where runnable processes are allowed to run.\n * 2. The update phase where requested channel updates hapen.\n * 3. The delta notification phase where delta notifications happen.\n *\n * The readyEvent runs the first two steps of the delta cycle. It first goes\n * through the list of runnable processes and executes them until the set is\n * empty, and then immediately runs the update phase. Since these are all part\n * of the same event, there's no chance for other events to intervene and\n * break the required order above.\n *\n * During the update phase above, the spec forbids any action which would make\n * a process runnable. That means that once the update phase finishes, the set\n * of runnable processes will be empty. There may, however, have been some\n * delta notifications\/timeouts which will have been scheduled during either\n * the evaluate or update phase above. Because those are scheduled at the\n * normal priority, they will now happen together until there aren't any\n * delta events left.\n *\n * If any processes became runnable during the delta notification phase, the\n * readyEvent will have been scheduled and will have been waiting patiently\n * behind the delta notification events. That will now run, effectively\n * starting the next delta cycle.\n *\n * TIMED NOTIFICATION PHASE\n *\n * If no processes became runnable, the event queue will continue to process\n * events until it comes across a timed notification, aka a notification\n * scheduled to happen in the future. Like delta notification events, those\n * will all happen together since the readyEvent priority is lower,\n * potentially marking new processes as ready. Once these events finish, the\n * readyEvent may run, starting the next delta cycle.\n *\n * PAUSE\/STOP\n *\n * To inject a pause from sc_pause which should happen after the current delta\n * cycle's delta notification phase, an event is scheduled with a lower than\n * normal priority, but higher than the readyEvent. That ensures that any\n * delta notifications which are scheduled with normal priority will happen\n * first, since those are part of the current delta cycle. Then the pause\n * event will happen before the next readyEvent which would start the next\n * delta cycle. All of these events are scheduled for the current time, and so\n * would happen before any timed notifications went off.\n *\n * To inject a stop from sc_stop, the delta cycles should stop before even the\n * delta notifications have happened, but after the evaluate and update phases.\n * For that, a stop event with slightly higher than normal priority will be\n * scheduled so that it happens before any of the delta notification events\n * which are at normal priority.\n *\n * MAX RUN TIME\n *\n * When sc_start is called, it's possible to pass in a maximum time the\n * simulation should run to, at which point sc_pause is implicitly called.\n * That's implemented by scheduling an event at the max time with a priority\n * which is lower than all the others so that it happens only if time would\n * advance. When that event triggers, it calls the same function as the pause\n * event.\n *\/\n\nclass Scheduler\n{\n public:\n Scheduler();\n\n const std::string name() const { return \"systemc_scheduler\"; }\n\n uint64_t numCycles() { return _numCycles; }\n Process *current() { return _current; }\n\n \/\/ Prepare for initialization.\n void prepareForInit();\n\n \/\/ Register a process with the scheduler.\n void reg(Process *p);\n\n \/\/ Tell the scheduler not to initialize a process.\n void dontInitialize(Process *p);\n\n \/\/ Run the next process, if there is one.\n void yield();\n\n \/\/ Put a process on the ready list.\n void ready(Process *p);\n\n \/\/ Schedule an update for a given channel.\n void requestUpdate(Channel *c);\n\n \/\/ Run the given process immediately, preempting whatever may be running.\n void\n runNow(Process *p)\n {\n \/\/ If a process is running, schedule it\/us to run again.\n if (_current)\n readyList.pushFirst(_current);\n \/\/ Schedule p to run first.\n readyList.pushFirst(p);\n yield();\n }\n\n \/\/ Set an event queue for scheduling events.\n void setEventQueue(EventQueue *_eq) { eq = _eq; }\n\n \/\/ Get the current time according to gem5.\n Tick getCurTick() { return eq ? eq->getCurTick() : 0; }\n\n \/\/ For scheduling delayed\/timed notifications\/timeouts.\n void\n schedule(::Event *event, Tick tick)\n {\n pendingTicks[tick]++;\n\n if (initReady)\n eq->schedule(event, tick);\n else\n eventsToSchedule[event] = tick;\n }\n\n \/\/ For descheduling delayed\/timed notifications\/timeouts.\n void\n deschedule(::Event *event)\n {\n auto it = pendingTicks.find(event->when());\n if (--it->second == 0)\n pendingTicks.erase(it);\n\n if (initReady)\n eq->deschedule(event);\n else\n eventsToSchedule.erase(event);\n }\n\n \/\/ Tell the scheduler than an event fired for bookkeeping purposes.\n void\n eventHappened()\n {\n auto it = pendingTicks.begin();\n if (--it->second == 0)\n pendingTicks.erase(it);\n\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n }\n\n \/\/ Pending activity ignores gem5 activity, much like how a systemc\n \/\/ simulation wouldn't know about asynchronous external events (socket IO\n \/\/ for instance) that might happen before time advances in a pure\n \/\/ systemc simulation. Also the spec lists what specific types of pending\n \/\/ activity needs to be counted, which obviously doesn't include gem5\n \/\/ events.\n\n \/\/ Return whether there's pending systemc activity at this time.\n bool\n pendingCurr()\n {\n if (!readyList.empty() || !updateList.empty())\n return true;\n return pendingTicks.size() &&\n pendingTicks.begin()->first == getCurTick();\n }\n\n \/\/ Return whether there are pending timed notifications or timeouts.\n bool\n pendingFuture()\n {\n switch (pendingTicks.size()) {\n case 0: return false;\n case 1: return pendingTicks.begin()->first > getCurTick();\n default: return true;\n }\n }\n\n \/\/ Return how many ticks there are until the first pending event, if any.\n Tick\n timeToPending()\n {\n if (!readyList.empty() || !updateList.empty())\n return 0;\n else if (pendingTicks.size())\n return pendingTicks.begin()->first - getCurTick();\n else\n return MaxTick - getCurTick();\n }\n\n \/\/ Run scheduled channel updates.\n void update();\n\n void setScMainFiber(Fiber *sc_main) { scMain = sc_main; }\n\n void start(Tick max_tick, bool run_to_time);\n\n void schedulePause();\n void scheduleStop(bool finish_delta);\n\n bool paused() { return _paused; }\n bool stopped() { return _stopped; }\n\n private:\n typedef const EventBase::Priority Priority;\n static Priority DefaultPriority = EventBase::Default_Pri;\n\n static Priority StopPriority = DefaultPriority - 1;\n static Priority PausePriority = DefaultPriority + 1;\n static Priority ReadyPriority = DefaultPriority + 2;\n static Priority StarvationPriority = ReadyPriority;\n static Priority MaxTickPriority = DefaultPriority + 3;\n\n EventQueue *eq;\n std::map pendingTicks;\n\n void runReady();\n EventWrapper readyEvent;\n void scheduleReadyEvent();\n\n void pause();\n void stop();\n EventWrapper pauseEvent;\n EventWrapper stopEvent;\n Fiber *scMain;\n\n bool\n starved()\n {\n return (readyList.empty() && updateList.empty() &&\n (pendingTicks.empty() ||\n pendingTicks.begin()->first > maxTick) &&\n initList.empty());\n }\n EventWrapper starvationEvent;\n void scheduleStarvationEvent();\n\n bool _started;\n bool _paused;\n bool _stopped;\n\n Tick maxTick;\n EventWrapper maxTickEvent;\n\n uint64_t _numCycles;\n\n Process *_current;\n\n bool initReady;\n bool runToTime;\n\n ProcessList initList;\n ProcessList toFinalize;\n ProcessList readyList;\n\n ChannelList updateList;\n\n std::map<::Event *, Tick> eventsToSchedule;\n};\n\nextern Scheduler scheduler;\n\n} \/\/ namespace sc_gem5\n\n#endif \/\/ __SYSTEMC_CORE_SCHEDULER_H__\nsystemc: Fix the priority of the maximum time event.\/*\n * Copyright 2018 Google, Inc.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __SYSTEMC_CORE_SCHEDULER_HH__\n#define __SYSTEMC_CORE_SCHEDULER_HH__\n\n#include \n\n#include \"base\/logging.hh\"\n#include \"sim\/eventq.hh\"\n#include \"systemc\/core\/channel.hh\"\n#include \"systemc\/core\/list.hh\"\n#include \"systemc\/core\/process.hh\"\n\nclass Fiber;\n\nnamespace sc_gem5\n{\n\ntypedef NodeList ProcessList;\ntypedef NodeList ChannelList;\n\n\/*\n * The scheduler supports three different mechanisms, the initialization phase,\n * delta cycles, and timed notifications.\n *\n * INITIALIZATION PHASE\n *\n * The initialization phase has three parts:\n * 1. Run requested channel updates.\n * 2. Make processes which need to initialize runnable (methods and threads\n * which didn't have dont_initialize called on them).\n * 3. Process delta notifications.\n *\n * First, the Kernel SimObject calls the update() method during its startup()\n * callback which handles the requested channel updates. The Kernel also\n * schedules an event to be run at time 0 with a slightly elevated priority\n * so that it happens before any \"normal\" event.\n *\n * When that t0 event happens, it calls the schedulers prepareForInit method\n * which performs step 2 above. That indirectly causes the scheduler's\n * readyEvent to be scheduled with slightly lowered priority, ensuring it\n * happens after any \"normal\" event.\n *\n * Because delta notifications are scheduled at the standard priority, all\n * of those events will happen next, performing step 3 above. Once they finish,\n * if the readyEvent was scheduled above, there shouldn't be any higher\n * priority events in front of it. When it runs, it will start the first\n * evaluate phase of the first delta cycle.\n *\n * DELTA CYCLE\n *\n * A delta cycle has three phases within it.\n * 1. The evaluate phase where runnable processes are allowed to run.\n * 2. The update phase where requested channel updates hapen.\n * 3. The delta notification phase where delta notifications happen.\n *\n * The readyEvent runs the first two steps of the delta cycle. It first goes\n * through the list of runnable processes and executes them until the set is\n * empty, and then immediately runs the update phase. Since these are all part\n * of the same event, there's no chance for other events to intervene and\n * break the required order above.\n *\n * During the update phase above, the spec forbids any action which would make\n * a process runnable. That means that once the update phase finishes, the set\n * of runnable processes will be empty. There may, however, have been some\n * delta notifications\/timeouts which will have been scheduled during either\n * the evaluate or update phase above. Because those are scheduled at the\n * normal priority, they will now happen together until there aren't any\n * delta events left.\n *\n * If any processes became runnable during the delta notification phase, the\n * readyEvent will have been scheduled and will have been waiting patiently\n * behind the delta notification events. That will now run, effectively\n * starting the next delta cycle.\n *\n * TIMED NOTIFICATION PHASE\n *\n * If no processes became runnable, the event queue will continue to process\n * events until it comes across a timed notification, aka a notification\n * scheduled to happen in the future. Like delta notification events, those\n * will all happen together since the readyEvent priority is lower,\n * potentially marking new processes as ready. Once these events finish, the\n * readyEvent may run, starting the next delta cycle.\n *\n * PAUSE\/STOP\n *\n * To inject a pause from sc_pause which should happen after the current delta\n * cycle's delta notification phase, an event is scheduled with a lower than\n * normal priority, but higher than the readyEvent. That ensures that any\n * delta notifications which are scheduled with normal priority will happen\n * first, since those are part of the current delta cycle. Then the pause\n * event will happen before the next readyEvent which would start the next\n * delta cycle. All of these events are scheduled for the current time, and so\n * would happen before any timed notifications went off.\n *\n * To inject a stop from sc_stop, the delta cycles should stop before even the\n * delta notifications have happened, but after the evaluate and update phases.\n * For that, a stop event with slightly higher than normal priority will be\n * scheduled so that it happens before any of the delta notification events\n * which are at normal priority.\n *\n * MAX RUN TIME\n *\n * When sc_start is called, it's possible to pass in a maximum time the\n * simulation should run to, at which point sc_pause is implicitly called. The\n * simulation is supposed to run up to the latest timed notification phase\n * which is less than or equal to the maximum time. In other words it should\n * run timed notifications at the maximum time, but not the subsequent evaluate\n * phase. That's implemented by scheduling an event at the max time with a\n * priority which is lower than all the others except the ready event. Timed\n * notifications will happen before it fires, but it will override any ready\n * event and prevent the evaluate phase from starting.\n *\/\n\nclass Scheduler\n{\n public:\n Scheduler();\n\n const std::string name() const { return \"systemc_scheduler\"; }\n\n uint64_t numCycles() { return _numCycles; }\n Process *current() { return _current; }\n\n \/\/ Prepare for initialization.\n void prepareForInit();\n\n \/\/ Register a process with the scheduler.\n void reg(Process *p);\n\n \/\/ Tell the scheduler not to initialize a process.\n void dontInitialize(Process *p);\n\n \/\/ Run the next process, if there is one.\n void yield();\n\n \/\/ Put a process on the ready list.\n void ready(Process *p);\n\n \/\/ Schedule an update for a given channel.\n void requestUpdate(Channel *c);\n\n \/\/ Run the given process immediately, preempting whatever may be running.\n void\n runNow(Process *p)\n {\n \/\/ If a process is running, schedule it\/us to run again.\n if (_current)\n readyList.pushFirst(_current);\n \/\/ Schedule p to run first.\n readyList.pushFirst(p);\n yield();\n }\n\n \/\/ Set an event queue for scheduling events.\n void setEventQueue(EventQueue *_eq) { eq = _eq; }\n\n \/\/ Get the current time according to gem5.\n Tick getCurTick() { return eq ? eq->getCurTick() : 0; }\n\n \/\/ For scheduling delayed\/timed notifications\/timeouts.\n void\n schedule(::Event *event, Tick tick)\n {\n pendingTicks[tick]++;\n\n if (initReady)\n eq->schedule(event, tick);\n else\n eventsToSchedule[event] = tick;\n }\n\n \/\/ For descheduling delayed\/timed notifications\/timeouts.\n void\n deschedule(::Event *event)\n {\n auto it = pendingTicks.find(event->when());\n if (--it->second == 0)\n pendingTicks.erase(it);\n\n if (initReady)\n eq->deschedule(event);\n else\n eventsToSchedule.erase(event);\n }\n\n \/\/ Tell the scheduler than an event fired for bookkeeping purposes.\n void\n eventHappened()\n {\n auto it = pendingTicks.begin();\n if (--it->second == 0)\n pendingTicks.erase(it);\n\n if (starved() && !runToTime)\n scheduleStarvationEvent();\n }\n\n \/\/ Pending activity ignores gem5 activity, much like how a systemc\n \/\/ simulation wouldn't know about asynchronous external events (socket IO\n \/\/ for instance) that might happen before time advances in a pure\n \/\/ systemc simulation. Also the spec lists what specific types of pending\n \/\/ activity needs to be counted, which obviously doesn't include gem5\n \/\/ events.\n\n \/\/ Return whether there's pending systemc activity at this time.\n bool\n pendingCurr()\n {\n if (!readyList.empty() || !updateList.empty())\n return true;\n return pendingTicks.size() &&\n pendingTicks.begin()->first == getCurTick();\n }\n\n \/\/ Return whether there are pending timed notifications or timeouts.\n bool\n pendingFuture()\n {\n switch (pendingTicks.size()) {\n case 0: return false;\n case 1: return pendingTicks.begin()->first > getCurTick();\n default: return true;\n }\n }\n\n \/\/ Return how many ticks there are until the first pending event, if any.\n Tick\n timeToPending()\n {\n if (!readyList.empty() || !updateList.empty())\n return 0;\n else if (pendingTicks.size())\n return pendingTicks.begin()->first - getCurTick();\n else\n return MaxTick - getCurTick();\n }\n\n \/\/ Run scheduled channel updates.\n void update();\n\n void setScMainFiber(Fiber *sc_main) { scMain = sc_main; }\n\n void start(Tick max_tick, bool run_to_time);\n\n void schedulePause();\n void scheduleStop(bool finish_delta);\n\n bool paused() { return _paused; }\n bool stopped() { return _stopped; }\n\n private:\n typedef const EventBase::Priority Priority;\n static Priority DefaultPriority = EventBase::Default_Pri;\n\n static Priority StopPriority = DefaultPriority - 1;\n static Priority PausePriority = DefaultPriority + 1;\n static Priority MaxTickPriority = DefaultPriority + 2;\n static Priority ReadyPriority = DefaultPriority + 3;\n static Priority StarvationPriority = ReadyPriority;\n\n EventQueue *eq;\n std::map pendingTicks;\n\n void runReady();\n EventWrapper readyEvent;\n void scheduleReadyEvent();\n\n void pause();\n void stop();\n EventWrapper pauseEvent;\n EventWrapper stopEvent;\n Fiber *scMain;\n\n bool\n starved()\n {\n return (readyList.empty() && updateList.empty() &&\n (pendingTicks.empty() ||\n pendingTicks.begin()->first > maxTick) &&\n initList.empty());\n }\n EventWrapper starvationEvent;\n void scheduleStarvationEvent();\n\n bool _started;\n bool _paused;\n bool _stopped;\n\n Tick maxTick;\n EventWrapper maxTickEvent;\n\n uint64_t _numCycles;\n\n Process *_current;\n\n bool initReady;\n bool runToTime;\n\n ProcessList initList;\n ProcessList toFinalize;\n ProcessList readyList;\n\n ChannelList updateList;\n\n std::map<::Event *, Tick> eventsToSchedule;\n};\n\nextern Scheduler scheduler;\n\n} \/\/ namespace sc_gem5\n\n#endif \/\/ __SYSTEMC_CORE_SCHEDULER_H__\n<|endoftext|>"} {"text":"#include \n#include \n#ifndef _MSC_VER\n#include \n#include \n#include \n#else\n#include \n#endif\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linux-perf-events.h\"\n#ifdef __linux__\n#include \n#endif\n\/\/#define DEBUG\n#include \"simdjson\/common_defs.h\"\n#include \"simdjson\/jsonioutil.h\"\n#include \"simdjson\/jsonparser.h\"\n#include \"simdjson\/parsedjson.h\"\n#include \"simdjson\/stage1_find_marks.h\"\n#include \"simdjson\/stage2_build_tape.h\"\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n bool verbose = false;\n bool dump = false;\n bool jsonoutput = false;\n bool forceoneiteration = false;\n bool justdata = false;\n#ifndef _MSC_VER\n int c;\n\n while ((c = getopt(argc, argv, \"1vdt\")) != -1) {\n switch (c) {\n case 't':\n justdata = true;\n break;\n case 'v':\n verbose = true;\n break;\n case 'd':\n dump = true;\n break;\n case 'j':\n jsonoutput = true;\n break;\n case '1':\n forceoneiteration = true;\n break;\n default:\n abort();\n }\n}\n#else\n int optind = 1;\n#endif\n if (optind >= argc) {\n cerr << \"Usage: \" << argv[0] << \" \" << endl;\n exit(1);\n }\n const char *filename = argv[optind];\n if (optind + 1 < argc) {\n cerr << \"warning: ignoring everything after \" << argv[optind + 1] << endl;\n }\n if (verbose) {\n cout << \"[verbose] loading \" << filename << endl;\n}\n std::string_view p;\n try {\n p = get_corpus(filename);\n } catch (const std::exception &e) { \/\/ caught by reference to base\n std::cout << \"Could not load the file \" << filename << std::endl;\n return EXIT_FAILURE;\n }\n if (verbose) {\n cout << \"[verbose] loaded \" << filename << \" (\" << p.size() << \" bytes)\"\n << endl;\n}\n#if defined(DEBUG)\n const uint32_t iterations = 1;\n#else\n const uint32_t iterations =\n forceoneiteration ? 1 : (p.size() < 1 * 1000 * 1000 ? 1000 : 10);\n#endif\n vector res;\n res.resize(iterations);\n\n#if !defined(__linux__)\n#define SQUASH_COUNTERS\n if (justdata) {\n printf(\"justdata (-t) flag only works under linux.\\n\");\n }\n#endif\n\n#ifndef SQUASH_COUNTERS\n vector evts;\n evts.push_back(PERF_COUNT_HW_CPU_CYCLES);\n evts.push_back(PERF_COUNT_HW_INSTRUCTIONS);\n evts.push_back(PERF_COUNT_HW_BRANCH_MISSES);\n evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES);\n evts.push_back(PERF_COUNT_HW_CACHE_MISSES);\n LinuxEvents unified(evts);\n vector results;\n results.resize(evts.size());\n unsigned long cy0 = 0, cy1 = 0, cy2 = 0;\n unsigned long cl0 = 0, cl1 = 0, cl2 = 0;\n unsigned long mis0 = 0, mis1 = 0, mis2 = 0;\n unsigned long cref0 = 0, cref1 = 0, cref2 = 0;\n unsigned long cmis0 = 0, cmis1 = 0, cmis2 = 0;\n#endif\n bool isok = true;\n\n for (uint32_t i = 0; i < iterations; i++) {\n if (verbose) {\n cout << \"[verbose] iteration # \" << i << endl;\n}\n#ifndef SQUASH_COUNTERS\n unified.start();\n#endif\n ParsedJson pj;\n bool allocok = pj.allocateCapacity(p.size());\n if (!allocok) {\n std::cerr << \"failed to allocate memory\" << std::endl;\n return EXIT_FAILURE;\n }\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy0 += results[0];\n cl0 += results[1];\n mis0 += results[2];\n cref0 += results[3];\n cmis0 += results[4];\n#endif\n if (verbose) {\n cout << \"[verbose] allocated memory for parsed JSON \" << endl;\n}\n\n auto start = std::chrono::steady_clock::now();\n#ifndef SQUASH_COUNTERS\n unified.start();\n#endif\n isok = find_structural_bits(p.data(), p.size(), pj);\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy1 += results[0];\n cl1 += results[1];\n mis1 += results[2];\n cref1 += results[3];\n cmis1 += results[4];\n if (!isok) {\n cout << \"Failed out during stage 1\\n\";\n break;\n }\n unified.start();\n#endif\n\n isok = isok && !unified_machine(p.data(), p.size(), pj);\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy2 += results[0];\n cl2 += results[1];\n mis2 += results[2];\n cref2 += results[3];\n cmis2 += results[4];\n if (!isok) {\n cout << \"Failed out during stage 2\\n\";\n break;\n }\n#endif\n\n auto end = std::chrono::steady_clock::now();\n std::chrono::duration secs = end - start;\n res[i] = secs.count();\n }\n ParsedJson pj = build_parsed_json(p); \/\/ do the parsing again to get the stats\n if (!pj.isValid()) {\n std::cerr << \"Could not parse. \" << std::endl;\n return EXIT_FAILURE;\n }\n#ifndef SQUASH_COUNTERS\n unsigned long total = cy0 + cy1 + cy2;\n if (justdata) {\n float cpb0 = (double)cy0 \/ (iterations * p.size());\n float cpb1 = (double)cy1 \/ (iterations * p.size());\n float cpb2 = (double)cy2 \/ (iterations * p.size());\n float cpbtotal = (double)total \/ (iterations * p.size());\n char *newfile = (char *)malloc(strlen(filename) + 1);\n if (newfile == NULL)\n return EXIT_FAILURE;\n ::strcpy(newfile, filename);\n char *snewfile = ::basename(newfile);\n size_t nl = strlen(snewfile);\n for (size_t j = nl - 1; j > 0; j--) {\n if (snewfile[j] == '.') {\n snewfile[j] = '\\0';\n break;\n }\n }\n printf(\"\\\"%s\\\"\\t%f\\t%f\\t%f\\t%f\\n\", snewfile, cpb0, cpb1, cpb2,\n cpbtotal);\n free(newfile);\n } else {\n printf(\"number of bytes %ld number of structural chars %u ratio %.3f\\n\",\n p.size(), pj.n_structural_indexes,\n (double)pj.n_structural_indexes \/ p.size());\n printf(\"mem alloc instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache accesses: \"\n \"%10lu (failure %10lu)\\n\",\n cl0 \/ iterations, cy0 \/ iterations, 100. * cy0 \/ total,\n (double)cl0 \/ cy0, mis0 \/ iterations, (double)cy0 \/ mis0,\n cref1 \/ iterations, cmis0 \/ iterations);\n printf(\" mem alloc runs at %.2f cycles per input byte.\\n\",\n (double)cy0 \/ (iterations * p.size()));\n printf(\"stage 1 instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache accesses: \"\n \"%10lu (failure %10lu)\\n\",\n cl1 \/ iterations, cy1 \/ iterations, 100. * cy1 \/ total,\n (double)cl1 \/ cy1, mis1 \/ iterations, (double)cy1 \/ mis1,\n cref1 \/ iterations, cmis1 \/ iterations);\n printf(\" stage 1 runs at %.2f cycles per input byte.\\n\",\n (double)cy1 \/ (iterations * p.size()));\n\n printf(\"stage 2 instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache \"\n \"accesses: %10lu (failure %10lu)\\n\",\n cl2 \/ iterations, cy2 \/ iterations, 100. * cy2 \/ total,\n (double)cl2 \/ cy2, mis2 \/ iterations, (double)cy2 \/ mis2,\n cref2 \/ iterations, cmis2 \/ iterations);\n printf(\" stage 2 runs at %.2f cycles per input byte and \",\n (double)cy2 \/ (iterations * p.size()));\n printf(\"%.2f cycles per structural character.\\n\",\n (double)cy2 \/ (iterations * pj.n_structural_indexes));\n\n printf(\" all stages: %.2f cycles per input byte.\\n\",\n (double)total \/ (iterations * p.size()));\n }\n#endif\n double min_result = *min_element(res.begin(), res.end());\n if (!justdata) {\n cout << \"Min: \" << min_result << \" bytes read: \" << p.size()\n << \" Gigabytes\/second: \" << (p.size()) \/ (min_result * 1000000000.0)\n << \"\\n\";\n}\n if (jsonoutput) {\n isok = isok && pj.printjson(std::cout);\n }\n if (dump) {\n isok = isok && pj.dump_raw_tape(std::cout);\n }\n aligned_free((void *)p.data());\n if (!isok) {\n fprintf(stderr, \" Parsing failed. \\n \");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\nbenchmark\/parse.cpp doesn't need intrinsics for itself.#include \n#include \n#ifndef _MSC_VER\n#include \n#include \n#endif\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"linux-perf-events.h\"\n#ifdef __linux__\n#include \n#endif\n\/\/#define DEBUG\n#include \"simdjson\/common_defs.h\"\n#include \"simdjson\/jsonioutil.h\"\n#include \"simdjson\/jsonparser.h\"\n#include \"simdjson\/parsedjson.h\"\n#include \"simdjson\/stage1_find_marks.h\"\n#include \"simdjson\/stage2_build_tape.h\"\nusing namespace std;\n\nint main(int argc, char *argv[]) {\n bool verbose = false;\n bool dump = false;\n bool jsonoutput = false;\n bool forceoneiteration = false;\n bool justdata = false;\n#ifndef _MSC_VER\n int c;\n\n while ((c = getopt(argc, argv, \"1vdt\")) != -1) {\n switch (c) {\n case 't':\n justdata = true;\n break;\n case 'v':\n verbose = true;\n break;\n case 'd':\n dump = true;\n break;\n case 'j':\n jsonoutput = true;\n break;\n case '1':\n forceoneiteration = true;\n break;\n default:\n abort();\n }\n}\n#else\n int optind = 1;\n#endif\n if (optind >= argc) {\n cerr << \"Usage: \" << argv[0] << \" \" << endl;\n exit(1);\n }\n const char *filename = argv[optind];\n if (optind + 1 < argc) {\n cerr << \"warning: ignoring everything after \" << argv[optind + 1] << endl;\n }\n if (verbose) {\n cout << \"[verbose] loading \" << filename << endl;\n}\n std::string_view p;\n try {\n p = get_corpus(filename);\n } catch (const std::exception &e) { \/\/ caught by reference to base\n std::cout << \"Could not load the file \" << filename << std::endl;\n return EXIT_FAILURE;\n }\n if (verbose) {\n cout << \"[verbose] loaded \" << filename << \" (\" << p.size() << \" bytes)\"\n << endl;\n}\n#if defined(DEBUG)\n const uint32_t iterations = 1;\n#else\n const uint32_t iterations =\n forceoneiteration ? 1 : (p.size() < 1 * 1000 * 1000 ? 1000 : 10);\n#endif\n vector res;\n res.resize(iterations);\n\n#if !defined(__linux__)\n#define SQUASH_COUNTERS\n if (justdata) {\n printf(\"justdata (-t) flag only works under linux.\\n\");\n }\n#endif\n\n#ifndef SQUASH_COUNTERS\n vector evts;\n evts.push_back(PERF_COUNT_HW_CPU_CYCLES);\n evts.push_back(PERF_COUNT_HW_INSTRUCTIONS);\n evts.push_back(PERF_COUNT_HW_BRANCH_MISSES);\n evts.push_back(PERF_COUNT_HW_CACHE_REFERENCES);\n evts.push_back(PERF_COUNT_HW_CACHE_MISSES);\n LinuxEvents unified(evts);\n vector results;\n results.resize(evts.size());\n unsigned long cy0 = 0, cy1 = 0, cy2 = 0;\n unsigned long cl0 = 0, cl1 = 0, cl2 = 0;\n unsigned long mis0 = 0, mis1 = 0, mis2 = 0;\n unsigned long cref0 = 0, cref1 = 0, cref2 = 0;\n unsigned long cmis0 = 0, cmis1 = 0, cmis2 = 0;\n#endif\n bool isok = true;\n\n for (uint32_t i = 0; i < iterations; i++) {\n if (verbose) {\n cout << \"[verbose] iteration # \" << i << endl;\n}\n#ifndef SQUASH_COUNTERS\n unified.start();\n#endif\n ParsedJson pj;\n bool allocok = pj.allocateCapacity(p.size());\n if (!allocok) {\n std::cerr << \"failed to allocate memory\" << std::endl;\n return EXIT_FAILURE;\n }\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy0 += results[0];\n cl0 += results[1];\n mis0 += results[2];\n cref0 += results[3];\n cmis0 += results[4];\n#endif\n if (verbose) {\n cout << \"[verbose] allocated memory for parsed JSON \" << endl;\n}\n\n auto start = std::chrono::steady_clock::now();\n#ifndef SQUASH_COUNTERS\n unified.start();\n#endif\n isok = find_structural_bits(p.data(), p.size(), pj);\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy1 += results[0];\n cl1 += results[1];\n mis1 += results[2];\n cref1 += results[3];\n cmis1 += results[4];\n if (!isok) {\n cout << \"Failed out during stage 1\\n\";\n break;\n }\n unified.start();\n#endif\n\n isok = isok && !unified_machine(p.data(), p.size(), pj);\n#ifndef SQUASH_COUNTERS\n unified.end(results);\n cy2 += results[0];\n cl2 += results[1];\n mis2 += results[2];\n cref2 += results[3];\n cmis2 += results[4];\n if (!isok) {\n cout << \"Failed out during stage 2\\n\";\n break;\n }\n#endif\n\n auto end = std::chrono::steady_clock::now();\n std::chrono::duration secs = end - start;\n res[i] = secs.count();\n }\n ParsedJson pj = build_parsed_json(p); \/\/ do the parsing again to get the stats\n if (!pj.isValid()) {\n std::cerr << \"Could not parse. \" << std::endl;\n return EXIT_FAILURE;\n }\n#ifndef SQUASH_COUNTERS\n unsigned long total = cy0 + cy1 + cy2;\n if (justdata) {\n float cpb0 = (double)cy0 \/ (iterations * p.size());\n float cpb1 = (double)cy1 \/ (iterations * p.size());\n float cpb2 = (double)cy2 \/ (iterations * p.size());\n float cpbtotal = (double)total \/ (iterations * p.size());\n char *newfile = (char *)malloc(strlen(filename) + 1);\n if (newfile == NULL)\n return EXIT_FAILURE;\n ::strcpy(newfile, filename);\n char *snewfile = ::basename(newfile);\n size_t nl = strlen(snewfile);\n for (size_t j = nl - 1; j > 0; j--) {\n if (snewfile[j] == '.') {\n snewfile[j] = '\\0';\n break;\n }\n }\n printf(\"\\\"%s\\\"\\t%f\\t%f\\t%f\\t%f\\n\", snewfile, cpb0, cpb1, cpb2,\n cpbtotal);\n free(newfile);\n } else {\n printf(\"number of bytes %ld number of structural chars %u ratio %.3f\\n\",\n p.size(), pj.n_structural_indexes,\n (double)pj.n_structural_indexes \/ p.size());\n printf(\"mem alloc instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache accesses: \"\n \"%10lu (failure %10lu)\\n\",\n cl0 \/ iterations, cy0 \/ iterations, 100. * cy0 \/ total,\n (double)cl0 \/ cy0, mis0 \/ iterations, (double)cy0 \/ mis0,\n cref1 \/ iterations, cmis0 \/ iterations);\n printf(\" mem alloc runs at %.2f cycles per input byte.\\n\",\n (double)cy0 \/ (iterations * p.size()));\n printf(\"stage 1 instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache accesses: \"\n \"%10lu (failure %10lu)\\n\",\n cl1 \/ iterations, cy1 \/ iterations, 100. * cy1 \/ total,\n (double)cl1 \/ cy1, mis1 \/ iterations, (double)cy1 \/ mis1,\n cref1 \/ iterations, cmis1 \/ iterations);\n printf(\" stage 1 runs at %.2f cycles per input byte.\\n\",\n (double)cy1 \/ (iterations * p.size()));\n\n printf(\"stage 2 instructions: %10lu cycles: %10lu (%.2f %%) ins\/cycles: \"\n \"%.2f mis. branches: %10lu (cycles\/mis.branch %.2f) cache \"\n \"accesses: %10lu (failure %10lu)\\n\",\n cl2 \/ iterations, cy2 \/ iterations, 100. * cy2 \/ total,\n (double)cl2 \/ cy2, mis2 \/ iterations, (double)cy2 \/ mis2,\n cref2 \/ iterations, cmis2 \/ iterations);\n printf(\" stage 2 runs at %.2f cycles per input byte and \",\n (double)cy2 \/ (iterations * p.size()));\n printf(\"%.2f cycles per structural character.\\n\",\n (double)cy2 \/ (iterations * pj.n_structural_indexes));\n\n printf(\" all stages: %.2f cycles per input byte.\\n\",\n (double)total \/ (iterations * p.size()));\n }\n#endif\n double min_result = *min_element(res.begin(), res.end());\n if (!justdata) {\n cout << \"Min: \" << min_result << \" bytes read: \" << p.size()\n << \" Gigabytes\/second: \" << (p.size()) \/ (min_result * 1000000000.0)\n << \"\\n\";\n}\n if (jsonoutput) {\n isok = isok && pj.printjson(std::cout);\n }\n if (dump) {\n isok = isok && pj.dump_raw_tape(std::cout);\n }\n aligned_free((void *)p.data());\n if (!isok) {\n fprintf(stderr, \" Parsing failed. \\n \");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"planning: update scenario status member field to make scenario transfor work.<|endoftext|>"} {"text":"#include \"types\/hit_record.hpp\"\n\n#include \n#include \n#include \n\nusing std::numeric_limits;\nusing std::string;\nusing std::stringstream;\nusing std::endl;\n\nnamespace fr {\n\nHitRecord::HitRecord(uint32_t worker, uint32_t mesh) :\n worker(worker),\n mesh(mesh),\n geom(geom) {\n t = numeric_limits::infinity();\n}\n\nHitRecord::HitRecord(uint32_t worker, uint32_t mesh, float t) :\n worker(worker),\n mesh(mesh),\n t(t),\n geom(geom) {}\n\nHitRecord::HitRecord() :\n geom() {\n worker = numeric_limits::max();\n mesh = numeric_limits::max();\n t = numeric_limits::infinity();\n}\n\nstring ToString(const HitRecord& strong, const string& indent) {\n stringstream stream;\n string pad = indent + \"| \";\n stream << \"HitRecord {\" << endl <<\n indent << \"| worker = \" << strong.worker << endl <<\n indent << \"| mesh = \" << strong.mesh << endl <<\n indent << \"| t = \" << strong.t << endl <<\n indent << \"| geom = \" << ToString(strong.geom, pad) <<\n indent << \"}\";\n return stream.str();\n}\n\n} \/\/ namespace fr\nWeird default initialization of local geometry.#include \"types\/hit_record.hpp\"\n\n#include \n#include \n#include \n\nusing std::numeric_limits;\nusing std::string;\nusing std::stringstream;\nusing std::endl;\n\nnamespace fr {\n\nHitRecord::HitRecord(uint32_t worker, uint32_t mesh) :\n worker(worker),\n mesh(mesh),\n geom() {\n t = numeric_limits::infinity();\n}\n\nHitRecord::HitRecord(uint32_t worker, uint32_t mesh, float t) :\n worker(worker),\n mesh(mesh),\n t(t),\n geom() {}\n\nHitRecord::HitRecord() :\n geom() {\n worker = numeric_limits::max();\n mesh = numeric_limits::max();\n t = numeric_limits::infinity();\n}\n\nstring ToString(const HitRecord& strong, const string& indent) {\n stringstream stream;\n string pad = indent + \"| \";\n stream << \"HitRecord {\" << endl <<\n indent << \"| worker = \" << strong.worker << endl <<\n indent << \"| mesh = \" << strong.mesh << endl <<\n indent << \"| t = \" << strong.t << endl <<\n indent << \"| geom = \" << ToString(strong.geom, pad) <<\n indent << \"}\";\n return stream.str();\n}\n\n} \/\/ namespace fr\n<|endoftext|>"} {"text":"\/\/ Copyright 2017 Per Grön. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nusing namespace ShkCache;\n\nnamespace shk {\n\nclass ConfigService final : public ShkCache::Config::Service {\n grpc::Status Get(\n grpc::ServerContext* context,\n const flatbuffers::BufferRef* request,\n flatbuffers::BufferRef* response) override {\n \/\/ Create a response from the incoming request name.\n _builder.Clear();\n\n auto store_config = CreateStoreConfig(\n _builder,\n \/*soft_store_entry_size_limit:*\/1,\n \/*hard_store_entry_size_limit:*\/2);\n auto config_get_response = CreateConfigGetResponse(\n _builder,\n store_config);\n\n _builder.Finish(config_get_response);\n\n \/\/ Since we keep reusing the same FlatBufferBuilder, the memory it owns\n \/\/ remains valid until the next call (this BufferRef doesn't own the\n \/\/ memory it points to).\n *response = flatbuffers::BufferRef(\n _builder.GetBufferPointer(),\n _builder.GetSize());\n return grpc::Status::OK;\n }\n\n private:\n flatbuffers::FlatBufferBuilder _builder;\n};\n\n\/\/ Track the server instance, so we can terminate it later.\ngrpc::Server *server_instance = nullptr;\n\/\/ Mutex to protec this variable.\nstd::mutex wait_for_server;\nstd::condition_variable server_instance_cv;\n\n\/\/ This function implements the server thread.\nvoid RunServer() {\n auto server_address = \"0.0.0.0:50051\";\n\n ConfigService config_service;\n grpc::ServerBuilder builder;\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n builder.RegisterService(&config_service);\n\n \/\/ Start the server. Lock to change the variable we're changing.\n wait_for_server.lock();\n server_instance = builder.BuildAndStart().release();\n wait_for_server.unlock();\n server_instance_cv.notify_one();\n\n std::cout << \"Server listening on \" << server_address << std::endl;\n \/\/ This will block the thread and serve requests.\n server_instance->Wait();\n}\n\nint main(int \/*argc*\/, const char * \/*argv*\/[]) {\n \/\/ Launch server.\n std::thread server_thread(RunServer);\n\n \/\/ wait for server to spin up.\n std::unique_lock lock(wait_for_server);\n while (!server_instance) {\n server_instance_cv.wait(lock);\n }\n\n \/\/ Now connect the client.\n auto channel = grpc::CreateChannel(\n \"localhost:50051\",\n grpc::InsecureChannelCredentials());\n auto stub = ShkCache::Config::NewStub(channel);\n\n flatbuffers::FlatBufferBuilder fbb;\n {\n grpc::ClientContext context;\n auto config_get_request = ShkCache::CreateConfigGetRequest(fbb);\n fbb.Finish(config_get_request);\n auto request = flatbuffers::BufferRef(\n fbb.GetBufferPointer(), fbb.GetSize());\n flatbuffers::BufferRef response;\n\n \/\/ The actual RPC.\n auto status = stub->Get(&context, request, &response);\n\n if (status.ok()) {\n if (!response.Verify()) {\n std::cout << \"Verification failed!\" << std::endl;\n } else {\n auto root = response.GetRoot();\n if (auto config = root->config()) {\n std::cout <<\n \"RPC response: \" << config->soft_store_entry_size_limit() <<\n \", \" << config->hard_store_entry_size_limit() << std::endl;\n } else {\n std::cout << \"RPC response: [no config]\" << std::endl;\n }\n }\n } else {\n std::cout << \"RPC failed\" << std::endl;\n }\n }\n\n server_instance->Shutdown();\n\n server_thread.join();\n\n delete server_instance;\n\n return 0;\n}\n\n} \/\/ namespace shk\n\nint main(int argc, const char *argv[]) {\n return shk::main(argc, argv);\n}\nSwitch to an async gRPC client (very basic)\/\/ Copyright 2017 Per Grön. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\nusing namespace ShkCache;\n\nnamespace shk {\n\nclass ConfigService final : public ShkCache::Config::Service {\n grpc::Status Get(\n grpc::ServerContext* context,\n const flatbuffers::BufferRef* request,\n flatbuffers::BufferRef* response) override {\n \/\/ Create a response from the incoming request name.\n _builder.Clear();\n\n auto store_config = CreateStoreConfig(\n _builder,\n \/*soft_store_entry_size_limit:*\/1,\n \/*hard_store_entry_size_limit:*\/2);\n auto config_get_response = CreateConfigGetResponse(\n _builder,\n store_config);\n\n _builder.Finish(config_get_response);\n\n \/\/ Since we keep reusing the same FlatBufferBuilder, the memory it owns\n \/\/ remains valid until the next call (this BufferRef doesn't own the\n \/\/ memory it points to).\n *response = flatbuffers::BufferRef(\n _builder.GetBufferPointer(),\n _builder.GetSize());\n return grpc::Status::OK;\n }\n\n private:\n flatbuffers::FlatBufferBuilder _builder;\n};\n\n\/\/ Track the server instance, so we can terminate it later.\ngrpc::Server *server_instance = nullptr;\n\/\/ Mutex to protec this variable.\nstd::mutex wait_for_server;\nstd::condition_variable server_instance_cv;\n\n\/\/ This function implements the server thread.\nvoid RunServer() {\n auto server_address = \"0.0.0.0:50051\";\n\n ConfigService config_service;\n grpc::ServerBuilder builder;\n builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());\n builder.RegisterService(&config_service);\n\n \/\/ Start the server. Lock to change the variable we're changing.\n wait_for_server.lock();\n server_instance = builder.BuildAndStart().release();\n wait_for_server.unlock();\n server_instance_cv.notify_one();\n\n std::cout << \"Server listening on \" << server_address << std::endl;\n \/\/ This will block the thread and serve requests.\n server_instance->Wait();\n}\n\nint main(int \/*argc*\/, const char * \/*argv*\/[]) {\n \/\/ Launch server.\n std::thread server_thread(RunServer);\n\n \/\/ wait for server to spin up.\n std::unique_lock lock(wait_for_server);\n while (!server_instance) {\n server_instance_cv.wait(lock);\n }\n\n \/\/ Now connect the client.\n auto channel = grpc::CreateChannel(\n \"localhost:50051\",\n grpc::InsecureChannelCredentials());\n auto stub = ShkCache::Config::NewStub(channel);\n\n flatbuffers::FlatBufferBuilder fbb;\n {\n grpc::CompletionQueue cq;\n\n grpc::ClientContext context;\n auto config_get_request = ShkCache::CreateConfigGetRequest(fbb);\n fbb.Finish(config_get_request);\n auto request = flatbuffers::BufferRef(\n fbb.GetBufferPointer(), fbb.GetSize());\n std::unique_ptr>> rpc(\n stub->AsyncGet(&context, request, &cq));\n\n flatbuffers::BufferRef response;\n grpc::Status status;\n rpc->Finish(&response, &status, (void *)1);\n\n void *got_tag;\n bool ok = false;\n cq.Next(&got_tag, &ok);\n if (ok && got_tag == (void *)1) {\n if (!response.Verify()) {\n std::cout << \"Verification failed!\" << std::endl;\n } else {\n auto root = response.GetRoot();\n if (auto config = root->config()) {\n std::cout <<\n \"RPC response: \" << config->soft_store_entry_size_limit() <<\n \", \" << config->hard_store_entry_size_limit() << std::endl;\n } else {\n std::cout << \"RPC response: [no config]\" << std::endl;\n }\n }\n } else if (ok) {\n std::cout << \"Unknown response tag\" << std::endl;\n } else {\n std::cout << \"Request not ok\" << std::endl;\n }\n }\n\n server_instance->Shutdown();\n\n server_thread.join();\n\n delete server_instance;\n\n return 0;\n}\n\n} \/\/ namespace shk\n\nint main(int argc, const char *argv[]) {\n return shk::main(argc, argv);\n}\n<|endoftext|>"} {"text":"\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n\/* \n * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370\n * Author: Alessandro Scalzo\n * email: alessandro.scalzo@iit.it\n * website: www.robotcub.org\n * Permission is granted to copy, distribute, and\/or modify this program\n * under the terms of the GNU General Public License, version 2 or any\n * later version published by the Free Software Foundation.\n *\n * A copy of the license can be found at\n * http:\/\/www.robotcub.org\/icub\/license\/gpl.txt\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n * Public License for more details\n*\/\n\n#include \"TestMotors.h\"\n\n#include \n\nTestMotors::TestMotors(yarp::os::Property& configuration) : UnitTest(configuration)\n{}\n\nTestMotors::~TestMotors()\n{\n if (m_aTargetVal) delete [] m_aTargetVal;\n if (m_aMaxErr) delete [] m_aMaxErr;\n if (m_aMinErr) delete [] m_aMinErr;\n if (m_aRefVel) delete [] m_aRefVel;\n if (m_aRefAcc) delete [] m_aRefAcc;\n if (m_aTimeout) delete [] m_aTimeout;\n if (m_aHome) delete [] m_aHome;\n}\n\nbool TestMotors::init(yarp::os::Property& configuration)\n{\n m_aTargetVal=NULL;\n m_aMaxErr=NULL;\n m_aMinErr=NULL;\n m_aRefVel=NULL;\n m_aRefAcc=NULL;\n m_aTimeout=NULL;\n m_aHome=NULL;\n m_initialized=false;\n\n iEncoders=NULL;\n iPosition=NULL;\n\n if (!configuration.check(\"portname\"))\n {\n fprintf(stderr, \"Missing portname parameter, cannot open device\\n\");\n return false;\n }\n m_portname=configuration.find(\"portname\").asString();\n\n if (!configuration.check(\"joints\"))\n {\n fprintf(stderr, \"Missing joints parameter, cannot open device\\n\");\n return false;\n }\n m_NumJoints=configuration.find(\"joints\").asInt();\n\n if (configuration.check(\"target\"))\n {\n yarp::os::Bottle bot=configuration.findGroup(\"target\").tail();\n\n int n=m_NumJointsgetAxes(&nJoints);\n\n Logger::checkTrue(m_NumJoints==nJoints, \"expected number of joints is consistent\");\n\n \/\/\/\/\/\/\/ check individual joints\n Logger::report(\"Checking individual joints...\\n\");\n for (int joint=0; jointsetRefAcceleration(joint, m_aRefAcc[joint]), \n \"setting reference acceleration on joint %d\", joint);\n\n Logger::checkTrue(iPosition->setRefSpeed(joint, m_aRefVel[joint]), \n \"setting reference speed on joint %d\", joint);\n\n \/\/ wait some time\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n bool read=false;\n\n printf(\"Checking encoders\");\n while(timeNowgetEncoder(joint,m_aHome+joint);\n yarp::os::Time::delay(0.1);\n printf(\".\");\n }\n printf(\"\\n\");\n Logger::checkTrue(read, \"read encoder\");\n\n Logger::checkTrue(iPosition->positionMove(joint, m_aTargetVal[joint]), \n \"moving joint %d to %.2lf\", joint, m_aTargetVal[joint]);\n\n printf(\"Waiting timeout %.2lf\", m_aTimeout[joint]);\n bool reached=false;\n while(timeNowgetEncoder(joint,&pos);\n\n reached=isApproxEqual(pos, m_aTargetVal[joint], m_aMinErr[joint], m_aMaxErr[joint]);\n\n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n printf(\"\\n\");\n Logger::checkTrue(reached, \"reached position\");\n }\n\n \/\/\/\/\/\/\/\/ check multiple joints\n Logger::report(\"Checking multiple joints...\\n\");\n if (m_aRefAcc!=NULL)\n Logger::checkTrue(iPosition->setRefAccelerations(m_aRefAcc), \n \"setting reference acceleration on all joints\");\n\n Logger::checkTrue(iPosition->setRefSpeeds(m_aRefVel), \n \"setting reference speed on all joints\");\n\n\n Logger::checkTrue(iPosition->positionMove(m_aHome), \n \"moving all joints to home\");\n\n \/\/ wait some time\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n \n double timeout=m_aTimeout[0];\n for(int j=0; jgetEncoders(encoders);\n\n reached=isApproxEqual(encoders, m_aTargetVal, m_aMinErr, m_aMaxErr, m_NumJoints);\n\n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n delete [] encoders;\n\n printf(\"\\n\");\n Logger::checkTrue(reached, \"reached position\");\n\n if (reached)\n {\n bool *done=new bool [m_NumJoints];\n bool ret=iPosition->checkMotionDone(done);\n\n bool ok=isTrue(done, m_NumJoints);\n\n Logger::checkTrue(ok&&ret, \"checking checkMotionDone\");\n\n delete [] done;\n }\n\n return true;\n}\n\nbool TestMotors::release()\n{\n Logger::report(\"Homing robot\\n\");\n\n iPosition->positionMove(m_aHome);\n double *encoders;\n bool *done;\n encoders=new double [m_NumJoints];\n done = new bool [m_NumJoints];\n\n bool reached=false;\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n while(timeNowgetEncoders(encoders);\n\n iPosition->checkMotionDone(done);\n\n reached=isTrue(done, m_NumJoints);\n \n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n\n printf(\"\\n\");\n delete [] encoders;\n delete [] done;\n\n return true;\n}fixed potential glitch in checkmotiondone\/\/ -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-\n\n\/* \n * Copyright (C) 2010 RobotCub Consortium, European Commission FP6 Project IST-004370\n * Author: Alessandro Scalzo\n * email: alessandro.scalzo@iit.it\n * website: www.robotcub.org\n * Permission is granted to copy, distribute, and\/or modify this program\n * under the terms of the GNU General Public License, version 2 or any\n * later version published by the Free Software Foundation.\n *\n * A copy of the license can be found at\n * http:\/\/www.robotcub.org\/icub\/license\/gpl.txt\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n * Public License for more details\n*\/\n\n#include \"TestMotors.h\"\n\n#include \n\nTestMotors::TestMotors(yarp::os::Property& configuration) : UnitTest(configuration)\n{}\n\nTestMotors::~TestMotors()\n{\n if (m_aTargetVal) delete [] m_aTargetVal;\n if (m_aMaxErr) delete [] m_aMaxErr;\n if (m_aMinErr) delete [] m_aMinErr;\n if (m_aRefVel) delete [] m_aRefVel;\n if (m_aRefAcc) delete [] m_aRefAcc;\n if (m_aTimeout) delete [] m_aTimeout;\n if (m_aHome) delete [] m_aHome;\n}\n\nbool TestMotors::init(yarp::os::Property& configuration)\n{\n m_aTargetVal=NULL;\n m_aMaxErr=NULL;\n m_aMinErr=NULL;\n m_aRefVel=NULL;\n m_aRefAcc=NULL;\n m_aTimeout=NULL;\n m_aHome=NULL;\n m_initialized=false;\n\n iEncoders=NULL;\n iPosition=NULL;\n\n if (!configuration.check(\"portname\"))\n {\n fprintf(stderr, \"Missing portname parameter, cannot open device\\n\");\n return false;\n }\n m_portname=configuration.find(\"portname\").asString();\n\n if (!configuration.check(\"joints\"))\n {\n fprintf(stderr, \"Missing joints parameter, cannot open device\\n\");\n return false;\n }\n m_NumJoints=configuration.find(\"joints\").asInt();\n\n if (configuration.check(\"target\"))\n {\n yarp::os::Bottle bot=configuration.findGroup(\"target\").tail();\n\n int n=m_NumJointsgetAxes(&nJoints);\n\n Logger::checkTrue(m_NumJoints==nJoints, \"expected number of joints is consistent\");\n\n \/\/\/\/\/\/\/ check individual joints\n Logger::report(\"Checking individual joints...\\n\");\n for (int joint=0; jointsetRefAcceleration(joint, m_aRefAcc[joint]), \n \"setting reference acceleration on joint %d\", joint);\n\n Logger::checkTrue(iPosition->setRefSpeed(joint, m_aRefVel[joint]), \n \"setting reference speed on joint %d\", joint);\n\n \/\/ wait some time\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n bool read=false;\n\n printf(\"Checking encoders\");\n while(timeNowgetEncoder(joint,m_aHome+joint);\n yarp::os::Time::delay(0.1);\n printf(\".\");\n }\n printf(\"\\n\");\n Logger::checkTrue(read, \"read encoder\");\n\n Logger::checkTrue(iPosition->positionMove(joint, m_aTargetVal[joint]), \n \"moving joint %d to %.2lf\", joint, m_aTargetVal[joint]);\n\n printf(\"Waiting timeout %.2lf\", m_aTimeout[joint]);\n bool reached=false;\n while(timeNowgetEncoder(joint,&pos);\n\n reached=isApproxEqual(pos, m_aTargetVal[joint], m_aMinErr[joint], m_aMaxErr[joint]);\n\n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n printf(\"\\n\");\n Logger::checkTrue(reached, \"reached position\");\n }\n\n \/\/\/\/\/\/\/\/ check multiple joints\n Logger::report(\"Checking multiple joints...\\n\");\n if (m_aRefAcc!=NULL)\n Logger::checkTrue(iPosition->setRefAccelerations(m_aRefAcc), \n \"setting reference acceleration on all joints\");\n\n Logger::checkTrue(iPosition->setRefSpeeds(m_aRefVel), \n \"setting reference speed on all joints\");\n\n\n Logger::checkTrue(iPosition->positionMove(m_aHome), \n \"moving all joints to home\");\n\n \/\/ wait some time\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n \n double timeout=m_aTimeout[0];\n for(int j=0; jgetEncoders(encoders);\n\n reached=isApproxEqual(encoders, m_aTargetVal, m_aMinErr, m_aMaxErr, m_NumJoints);\n\n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n delete [] encoders;\n\n printf(\"\\n\");\n Logger::checkTrue(reached, \"reached position\");\n\n if (reached)\n {\n bool *done_vector=new bool [m_NumJoints];\n\n \/\/ check checkMotionDone.\n \/\/ because the previous movement was approximate, the robot\n \/\/ could still be moving so we need to iterate a few times\n\n int times=10;\n bool doneAll=false;\n bool ret=false;\n \n while(times>0 && !doneAll)\n {\n ret=iPosition->checkMotionDone(done_vector);\n doneAll=isTrue(done_vector, m_NumJoints);\n if (!doneAll)\n yarp::os::Time::delay(0.1);\n }\n\n Logger::checkTrue(doneAll&&ret, \"checking checkMotionDone\");\n\n delete [] done_vector;\n }\n\n return true;\n}\n\nbool TestMotors::release()\n{\n Logger::report(\"Homing robot\\n\");\n\n iPosition->positionMove(m_aHome);\n double *encoders;\n bool *done;\n encoders=new double [m_NumJoints];\n done = new bool [m_NumJoints];\n\n bool reached=false;\n double timeStart=yarp::os::Time::now();\n double timeNow=timeStart;\n while(timeNowgetEncoders(encoders);\n\n iPosition->checkMotionDone(done);\n\n reached=isTrue(done, m_NumJoints);\n \n printf(\".\");\n timeNow=yarp::os::Time::now();\n yarp::os::Time::delay(0.1);\n }\n\n printf(\"\\n\");\n delete [] encoders;\n delete [] done;\n\n return true;\n}<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n#include \"FileUtils.h\"\n\nclass SDLWav\n{\npublic:\n SDLWav(const char* filename) :\n m_audioBuf(nullptr),\n m_audioLen(0),\n m_spec()\n {\n SDL_LoadWAV(filename, &m_spec, &m_audioBuf, &m_audioLen);\n assert(m_spec.freq == 44100);\n assert(m_spec.format == AUDIO_S16);\n assert(m_spec.channels == 1);\n std::cout << filename << \" has \" << (m_audioLen >> 1) << \" samples\\n\";\n }\n\n ~SDLWav()\n {\n if (m_audioBuf)\n {\n SDL_FreeWAV(m_audioBuf);\n }\n }\n\n explicit operator bool() const\n {\n return (m_audioBuf != nullptr && m_audioLen > 0);\n }\n\n const SDL_AudioSpec& GetSpec() const\n {\n return m_spec;\n }\n\n const int16_t* GetSamplePtr() const\n {\n return reinterpret_cast(m_audioBuf);\n }\n\n uint32_t GetNumSamples() const\n {\n assert((m_audioLen % 2) == 0);\n return (m_audioLen >> 1);\n }\n\nprivate:\n Uint8* m_audioBuf;\n Uint32 m_audioLen;\n SDL_AudioSpec m_spec;\n};\n\nint pgtaMain(SDL_AudioDeviceID audioDevice)\n{\n PGTA::PGTADevice pgtaDevice;\n if (!pgtaDevice.Initialize())\n {\n return -1;\n }\n\n \/\/ load track data to memory\n \/\/ \"tracks\/demo.track\"\n std::string trackSource;\n if (!ReadBinaryFileToString(\"tracks\/test.track\", trackSource))\n {\n return -1;\n }\n\n HPGTATrack demoTrack = nullptr;\n const char* source = trackSource.data();\n const size_t length = trackSource.length();\n if (pgtaDevice.CreateTracks(1, &source, &length, &demoTrack) <= 0 || !demoTrack)\n {\n return -1;\n }\n\n auto trackData = pgtaGetTrackData(demoTrack);\n int numSamples = trackData.numSamples;\n std::vector audioData(numSamples);\n for (int i = 0; i < numSamples; ++i)\n {\n auto& data = audioData[i];\n int16_t id = trackData.samples[i].id;\n const char* file = trackData.samples[i].defaultFile;\n SDLWav audio(file);\n uint32_t audioLength = audio.GetNumSamples();\n data = new int16_t[audioLength];\n memcpy(data, audio.GetSamplePtr() , audioLength * sizeof data[0]);\n\n pgtaBindTrackSample(demoTrack, id, audioData[i], audioLength);\n }\n\n PGTAConfig config;\n config.audioDesc.samplesPerSecond = 44100;\n config.audioDesc.bytesPerSample = 2;\n config.audioDesc.channels = 1;\n config.mixAhead = 0.1f;\n PGTA::PGTAContext pgtaContext(pgtaDevice.CreateContext(config));\n\n pgtaContext.BindTrack(demoTrack);\n\n utils::RunLoop(0.01f, [&](double \/*absoluteTime*\/, float delta)\n {\n const PGTABuffer output = pgtaContext.Update(delta);\n SDL_QueueAudio(audioDevice, output.samples, static_cast(output.numSamples * 2));\n return (output.samples != nullptr) && (output.numSamples > 0);\n });\n\n for (auto& i : audioData)\n {\n delete[] i;\n }\n return 0;\n}\n\nint main()\n{\n SDL_Init(SDL_INIT_EVERYTHING);\n\n SDL_AudioSpec audioSpec;\n SDL_zero(audioSpec);\n audioSpec.freq = 44100;\n audioSpec.format = AUDIO_S16;\n audioSpec.channels = 1;\n audioSpec.samples = 4096;\n SDL_AudioDeviceID audioDevice = SDL_OpenAudioDevice(nullptr, false, &audioSpec, nullptr, 0);\n\n int ret = 0;\n if (audioDevice > 1)\n {\n SDL_PauseAudioDevice(audioDevice, 0);\n ret = pgtaMain(audioDevice);\n SDL_CloseAudioDevice(audioDevice);\n }\n\n SDL_Quit();\n return ret;\n}\nCleaned up EngineTest and fixed working directory when running through a debugger\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n#include \"FileUtils.h\"\n\nclass SDLWav\n{\npublic:\n SDLWav(const char* filename) :\n m_audioBuf(nullptr),\n m_audioLen(0),\n m_spec()\n {\n SDL_LoadWAV(filename, &m_spec, &m_audioBuf, &m_audioLen);\n assert(m_spec.freq == 44100);\n assert(m_spec.format == AUDIO_S16);\n assert(m_spec.channels == 1);\n std::cout << filename << \" has \" << (m_audioLen >> 1) << \" samples\\n\";\n }\n\n ~SDLWav()\n {\n if (m_audioBuf)\n {\n SDL_FreeWAV(m_audioBuf);\n }\n }\n\n explicit operator bool() const\n {\n return (m_audioBuf != nullptr && m_audioLen > 0);\n }\n\n const SDL_AudioSpec& GetSpec() const\n {\n return m_spec;\n }\n\n const int16_t* GetSamplePtr() const\n {\n return reinterpret_cast(m_audioBuf);\n }\n\n uint32_t GetNumSamples() const\n {\n assert((m_audioLen % 2) == 0);\n return (m_audioLen >> 1);\n }\n\nprivate:\n Uint8* m_audioBuf;\n Uint32 m_audioLen;\n SDL_AudioSpec m_spec;\n};\n\nint pgtaMain(SDL_AudioDeviceID audioDevice)\n{\n PGTA::PGTADevice pgtaDevice;\n if (!pgtaDevice.Initialize())\n {\n return -1;\n }\n\n \/\/ load track data to memory\n \/\/ \"tracks\/demo.track\"\n std::string trackSource;\n if (!ReadBinaryFileToString(\"tracks\/test.track\", trackSource))\n {\n return -1;\n }\n\n HPGTATrack demoTrack = nullptr;\n const char* source = trackSource.data();\n const size_t length = trackSource.length();\n if (pgtaDevice.CreateTracks(1, &source, &length, &demoTrack) <= 0 || !demoTrack)\n {\n return -1;\n }\n\n const PGTATrackData trackData = pgtaGetTrackData(demoTrack);\n const int numSamples = trackData.numSamples;\n\n std::vector audioFiles;\n audioFiles.reserve(numSamples);\n for (int i = 0; i < numSamples; ++i)\n {\n const PGTASampleData* sampleData = (trackData.samples + i);\n audioFiles.emplace_back(sampleData->defaultFile);\n pgtaBindTrackSample(demoTrack, sampleData->id,\n audioFiles[i].GetSamplePtr(),\n audioFiles[i].GetNumSamples());\n }\n\n PGTAConfig config;\n config.audioDesc.samplesPerSecond = 44100;\n config.audioDesc.bytesPerSample = 2;\n config.audioDesc.channels = 1;\n config.mixAhead = 0.1f;\n PGTA::PGTAContext pgtaContext(pgtaDevice.CreateContext(config));\n\n pgtaContext.BindTrack(demoTrack);\n utils::RunLoop(0.01f, [&](double \/*absoluteTime*\/, float delta)\n {\n const PGTABuffer output = pgtaContext.Update(delta);\n SDL_QueueAudio(audioDevice, output.samples, static_cast(output.numSamples * 2));\n return (output.samples != nullptr) && (output.numSamples > 0);\n });\n return 0;\n}\n\nint main()\n{\n utils::FixWorkingDirectory();\n SDL_Init(SDL_INIT_EVERYTHING);\n\n SDL_AudioSpec audioSpec;\n SDL_zero(audioSpec);\n audioSpec.freq = 44100;\n audioSpec.format = AUDIO_S16;\n audioSpec.channels = 1;\n audioSpec.samples = 4096;\n SDL_AudioDeviceID audioDevice = SDL_OpenAudioDevice(nullptr, false, &audioSpec, nullptr, 0);\n\n int ret = 0;\n if (audioDevice > 1)\n {\n SDL_PauseAudioDevice(audioDevice, 0);\n ret = pgtaMain(audioDevice);\n SDL_CloseAudioDevice(audioDevice);\n }\n\n SDL_Quit();\n return ret;\n}\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \"config.h\"\n\nTEST(Config, TestDefault) {\n EXPECT_NO_FATAL_FAILURE(Core::Config::getInstance(\"test.ini\"));\n}\n\nTEST(Config, TestDatabase) {\n Core::Config &config = Core::Config::getInstance();\n const ::configFile::Database &dbb = config.database();\n EXPECT_EQ(\"localhost\", dbb.host());\n EXPECT_EQ(\"osirose\", dbb.database());\n EXPECT_EQ(\"root\", dbb.user());\n EXPECT_EQ(\"\", dbb.password());\n EXPECT_EQ(3306, dbb.port());\n}\n\nTEST(Config, TestServer) {\n Core::Config &config = Core::Config::getInstance();\n const ::configFile::Server &sd = config.serverdata();\n EXPECT_EQ(0, sd.id());\n EXPECT_EQ(\"127.0.0.1\", sd.ip());\n EXPECT_EQ(100, sd.accesslevel());\n EXPECT_EQ(0, sd.parentid());\n EXPECT_EQ(100, sd.maxconnections());\n EXPECT_EQ(true, sd.usethreads());\n EXPECT_EQ(0, sd.mode());\n}\nAdapted current tests to conform to the changed defaults#include \"gtest\/gtest.h\"\n#include \"config.h\"\n\nTEST(Config, TestDefault) {\n EXPECT_NO_FATAL_FAILURE(Core::Config::getInstance(\"test.ini\"));\n}\n\nTEST(Config, TestDatabase) {\n Core::Config &config = Core::Config::getInstance();\n const ::configFile::Database &dbb = config.database();\n EXPECT_EQ(\"localhost\", dbb.host());\n EXPECT_EQ(\"osirose\", dbb.database());\n EXPECT_EQ(\"root\", dbb.user());\n EXPECT_EQ(\"\", dbb.password());\n EXPECT_EQ(3306, dbb.port());\n}\n\nTEST(Config, TestServer) {\n Core::Config &config = Core::Config::getInstance();\n const ::configFile::Server &sd = config.serverdata();\n EXPECT_EQ(0, sd.id());\n EXPECT_EQ(\"127.0.0.1\", sd.ip());\n EXPECT_EQ(100, sd.accesslevel());\n EXPECT_EQ(0, sd.parentid());\n EXPECT_EQ(0, sd.maxconnections());\n EXPECT_EQ(true, sd.usethreads());\n EXPECT_EQ(0, sd.mode());\n}\n<|endoftext|>"} {"text":"\/**\n * Copyright © 2019 IBM Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"pel.hpp\"\n\n#include \"bcd_time.hpp\"\n#include \"extended_user_header.hpp\"\n#include \"failing_mtms.hpp\"\n#include \"json_utils.hpp\"\n#include \"log_id.hpp\"\n#include \"pel_rules.hpp\"\n#include \"pel_values.hpp\"\n#include \"section_factory.hpp\"\n#include \"src.hpp\"\n#include \"stream.hpp\"\n#include \"user_data_formats.hpp\"\n\n#include \n#include \n\nnamespace openpower\n{\nnamespace pels\n{\nnamespace message = openpower::pels::message;\nnamespace pv = openpower::pels::pel_values;\n\nconstexpr auto unknownValue = \"Unknown\";\n\nPEL::PEL(const message::Entry& entry, uint32_t obmcLogID, uint64_t timestamp,\n phosphor::logging::Entry::Level severity,\n const AdditionalData& additionalData,\n const DataInterfaceBase& dataIface)\n{\n _ph = std::make_unique(entry.componentID, obmcLogID,\n timestamp);\n _uh = std::make_unique(entry, severity);\n\n auto src = std::make_unique(entry, additionalData, dataIface);\n\n auto euh = std::make_unique(dataIface, entry, *src);\n\n _optionalSections.push_back(std::move(src));\n _optionalSections.push_back(std::move(euh));\n\n auto mtms = std::make_unique(dataIface);\n _optionalSections.push_back(std::move(mtms));\n\n auto ud = util::makeSysInfoUserDataSection(additionalData, dataIface);\n _optionalSections.push_back(std::move(ud));\n\n if (!additionalData.empty())\n {\n ud = util::makeADUserDataSection(additionalData);\n\n \/\/ To be safe, check there isn't too much data\n if (size() + ud->header().size <= _maxPELSize)\n {\n _optionalSections.push_back(std::move(ud));\n }\n }\n\n _ph->setSectionCount(2 + _optionalSections.size());\n\n checkRulesAndFix();\n}\n\nPEL::PEL(std::vector& data) : PEL(data, 0)\n{\n}\n\nPEL::PEL(std::vector& data, uint32_t obmcLogID)\n{\n populateFromRawData(data, obmcLogID);\n}\n\nvoid PEL::populateFromRawData(std::vector& data, uint32_t obmcLogID)\n{\n Stream pelData{data};\n _ph = std::make_unique(pelData);\n if (obmcLogID != 0)\n {\n _ph->setOBMCLogID(obmcLogID);\n }\n\n _uh = std::make_unique(pelData);\n\n \/\/ Use the section factory to create the rest of the objects\n for (size_t i = 2; i < _ph->sectionCount(); i++)\n {\n auto section = section_factory::create(pelData);\n _optionalSections.push_back(std::move(section));\n }\n}\n\nbool PEL::valid() const\n{\n bool valid = _ph->valid();\n\n if (valid)\n {\n valid = _uh->valid();\n }\n\n if (valid)\n {\n if (!std::all_of(_optionalSections.begin(), _optionalSections.end(),\n [](const auto& section) { return section->valid(); }))\n {\n valid = false;\n }\n }\n\n return valid;\n}\n\nvoid PEL::setCommitTime()\n{\n auto now = std::chrono::system_clock::now();\n _ph->setCommitTimestamp(getBCDTime(now));\n}\n\nvoid PEL::assignID()\n{\n _ph->setID(generatePELID());\n}\n\nvoid PEL::flatten(std::vector& pelBuffer) const\n{\n Stream pelData{pelBuffer};\n\n if (!valid())\n {\n using namespace phosphor::logging;\n log(\"Unflattening an invalid PEL\");\n }\n\n _ph->flatten(pelData);\n _uh->flatten(pelData);\n\n for (auto& section : _optionalSections)\n {\n section->flatten(pelData);\n }\n}\n\nstd::vector PEL::data() const\n{\n std::vector pelData;\n flatten(pelData);\n return pelData;\n}\n\nsize_t PEL::size() const\n{\n size_t size = 0;\n\n if (_ph)\n {\n size += _ph->header().size;\n }\n\n if (_uh)\n {\n size += _uh->header().size;\n }\n\n for (const auto& section : _optionalSections)\n {\n size += section->header().size;\n }\n\n return size;\n}\n\nstd::optional PEL::primarySRC() const\n{\n auto src = std::find_if(\n _optionalSections.begin(), _optionalSections.end(), [](auto& section) {\n return section->header().id ==\n static_cast(SectionID::primarySRC);\n });\n if (src != _optionalSections.end())\n {\n return static_cast(src->get());\n }\n\n return std::nullopt;\n}\n\nvoid PEL::checkRulesAndFix()\n{\n auto [actionFlags, eventType] =\n pel_rules::check(_uh->actionFlags(), _uh->eventType(), _uh->severity());\n\n _uh->setActionFlags(actionFlags);\n _uh->setEventType(eventType);\n}\n\nvoid PEL::printSectionInJSON(const Section& section, std::string& buf,\n std::map& pluralSections,\n message::Registry& registry) const\n{\n char tmpB[5];\n uint8_t id[] = {static_cast(section.header().id >> 8),\n static_cast(section.header().id)};\n sprintf(tmpB, \"%c%c\", id[0], id[1]);\n std::string sectionID(tmpB);\n std::string sectionName = pv::sectionTitles.count(sectionID)\n ? pv::sectionTitles.at(sectionID)\n : \"Unknown Section\";\n\n \/\/ Add a count if there are multiple of this type of section\n auto count = pluralSections.find(section.header().id);\n if (count != pluralSections.end())\n {\n sectionName += \" \" + std::to_string(count->second);\n count->second++;\n }\n\n if (section.valid())\n {\n auto json = (sectionID == \"PS\" || sectionID == \"SS\")\n ? section.getJSON(registry)\n : section.getJSON();\n\n buf += \"\\\"\" + sectionName + \"\\\": {\\n\";\n\n if (json)\n {\n buf += *json + \"\\n},\\n\";\n }\n else\n {\n jsonInsert(buf, pv::sectionVer,\n getNumberString(\"%d\", section.header().version), 1);\n jsonInsert(buf, pv::subSection,\n getNumberString(\"%d\", section.header().subType), 1);\n jsonInsert(buf, pv::createdBy,\n getNumberString(\"0x%X\", section.header().componentID),\n 1);\n\n std::vector data;\n Stream s{data};\n section.flatten(s);\n std::string dstr =\n dumpHex(std::data(data) + SectionHeader::flattenedSize(),\n data.size(), 2);\n\n std::string jsonIndent(indentLevel, 0x20);\n buf += jsonIndent + \"\\\"Data\\\": [\\n\";\n buf += dstr;\n buf += jsonIndent + \"]\\n\";\n buf += \"},\\n\";\n }\n }\n else\n {\n buf += \"\\n\\\"Invalid Section\\\": [\\n \\\"invalid\\\"\\n],\\n\";\n }\n}\n\nstd::map PEL::getPluralSections() const\n{\n std::map sectionCounts;\n\n for (const auto& section : optionalSections())\n {\n if (sectionCounts.find(section->header().id) == sectionCounts.end())\n {\n sectionCounts[section->header().id] = 1;\n }\n else\n {\n sectionCounts[section->header().id]++;\n }\n }\n\n std::map sections;\n for (const auto& [id, count] : sectionCounts)\n {\n if (count > 1)\n {\n \/\/ Start with 0 here and printSectionInJSON()\n \/\/ will increment it as it goes.\n sections.emplace(id, 0);\n }\n }\n\n return sections;\n}\n\nvoid PEL::toJSON(message::Registry& registry) const\n{\n auto sections = getPluralSections();\n\n std::string buf = \"{\\n\";\n printSectionInJSON(*(_ph.get()), buf, sections, registry);\n printSectionInJSON(*(_uh.get()), buf, sections, registry);\n for (auto& section : this->optionalSections())\n {\n printSectionInJSON(*(section.get()), buf, sections, registry);\n }\n buf += \"}\";\n std::size_t found = buf.rfind(\",\");\n if (found != std::string::npos)\n buf.replace(found, 1, \"\");\n std::cout << buf << std::endl;\n}\n\nnamespace util\n{\n\nstd::unique_ptr makeJSONUserDataSection(const nlohmann::json& json)\n{\n auto jsonString = json.dump();\n std::vector jsonData(jsonString.begin(), jsonString.end());\n\n \/\/ Pad to a 4 byte boundary\n while ((jsonData.size() % 4) != 0)\n {\n jsonData.push_back(0);\n }\n\n return std::make_unique(\n static_cast(ComponentID::phosphorLogging),\n static_cast(UserDataFormat::json),\n static_cast(UserDataFormatVersion::json), jsonData);\n}\n\nstd::unique_ptr makeADUserDataSection(const AdditionalData& ad)\n{\n assert(!ad.empty());\n nlohmann::json json;\n\n \/\/ Remove the 'ESEL' entry, as it contains a full PEL in the value.\n if (ad.getValue(\"ESEL\"))\n {\n auto newAD = ad;\n newAD.remove(\"ESEL\");\n json = newAD.toJSON();\n }\n else\n {\n json = ad.toJSON();\n }\n\n return makeJSONUserDataSection(json);\n}\n\nvoid addProcessNameToJSON(nlohmann::json& json,\n const std::optional& pid,\n const DataInterfaceBase& dataIface)\n{\n std::string name{unknownValue};\n\n try\n {\n if (pid)\n {\n auto n = dataIface.getProcessName(*pid);\n if (n)\n {\n name = *n;\n }\n }\n }\n catch (std::exception& e)\n {\n }\n\n json[\"Process Name\"] = std::move(name);\n}\n\nvoid addBMCFWVersionIDToJSON(nlohmann::json& json,\n const DataInterfaceBase& dataIface)\n{\n auto id = dataIface.getBMCFWVersionID();\n if (id.empty())\n {\n id = unknownValue;\n }\n\n json[\"BMC Version ID\"] = std::move(id);\n}\n\nstd::string lastSegment(char separator, std::string data)\n{\n auto pos = data.find_last_of(separator);\n if (pos != std::string::npos)\n {\n data = data.substr(pos + 1);\n }\n\n return data;\n}\n\nvoid addStatesToJSON(nlohmann::json& json, const DataInterfaceBase& dataIface)\n{\n json[\"BMCState\"] = lastSegment('.', dataIface.getBMCState());\n json[\"ChassisState\"] = lastSegment('.', dataIface.getChassisState());\n json[\"HostState\"] = lastSegment('.', dataIface.getHostState());\n}\n\nstd::unique_ptr\n makeSysInfoUserDataSection(const AdditionalData& ad,\n const DataInterfaceBase& dataIface)\n{\n nlohmann::json json;\n\n addProcessNameToJSON(json, ad.getValue(\"_PID\"), dataIface);\n addBMCFWVersionIDToJSON(json, dataIface);\n addStatesToJSON(json, dataIface);\n\n return makeJSONUserDataSection(json);\n}\n\n} \/\/ namespace util\n\n} \/\/ namespace pels\n} \/\/ namespace openpower\nPEL: Change variable name in pel.cpp\/**\n * Copyright © 2019 IBM Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"pel.hpp\"\n\n#include \"bcd_time.hpp\"\n#include \"extended_user_header.hpp\"\n#include \"failing_mtms.hpp\"\n#include \"json_utils.hpp\"\n#include \"log_id.hpp\"\n#include \"pel_rules.hpp\"\n#include \"pel_values.hpp\"\n#include \"section_factory.hpp\"\n#include \"src.hpp\"\n#include \"stream.hpp\"\n#include \"user_data_formats.hpp\"\n\n#include \n#include \n\nnamespace openpower\n{\nnamespace pels\n{\nnamespace message = openpower::pels::message;\nnamespace pv = openpower::pels::pel_values;\nusing namespace phosphor::logging;\n\nconstexpr auto unknownValue = \"Unknown\";\n\nPEL::PEL(const message::Entry& regEntry, uint32_t obmcLogID, uint64_t timestamp,\n phosphor::logging::Entry::Level severity,\n const AdditionalData& additionalData,\n const DataInterfaceBase& dataIface)\n{\n _ph = std::make_unique(regEntry.componentID, obmcLogID,\n timestamp);\n _uh = std::make_unique(regEntry, severity);\n\n auto src = std::make_unique(regEntry, additionalData, dataIface);\n\n auto euh = std::make_unique(dataIface, regEntry, *src);\n\n _optionalSections.push_back(std::move(src));\n _optionalSections.push_back(std::move(euh));\n\n auto mtms = std::make_unique(dataIface);\n _optionalSections.push_back(std::move(mtms));\n\n auto ud = util::makeSysInfoUserDataSection(additionalData, dataIface);\n _optionalSections.push_back(std::move(ud));\n\n if (!additionalData.empty())\n {\n ud = util::makeADUserDataSection(additionalData);\n\n \/\/ To be safe, check there isn't too much data\n if (size() + ud->header().size <= _maxPELSize)\n {\n _optionalSections.push_back(std::move(ud));\n }\n }\n\n _ph->setSectionCount(2 + _optionalSections.size());\n\n checkRulesAndFix();\n}\n\nPEL::PEL(std::vector& data) : PEL(data, 0)\n{\n}\n\nPEL::PEL(std::vector& data, uint32_t obmcLogID)\n{\n populateFromRawData(data, obmcLogID);\n}\n\nvoid PEL::populateFromRawData(std::vector& data, uint32_t obmcLogID)\n{\n Stream pelData{data};\n _ph = std::make_unique(pelData);\n if (obmcLogID != 0)\n {\n _ph->setOBMCLogID(obmcLogID);\n }\n\n _uh = std::make_unique(pelData);\n\n \/\/ Use the section factory to create the rest of the objects\n for (size_t i = 2; i < _ph->sectionCount(); i++)\n {\n auto section = section_factory::create(pelData);\n _optionalSections.push_back(std::move(section));\n }\n}\n\nbool PEL::valid() const\n{\n bool valid = _ph->valid();\n\n if (valid)\n {\n valid = _uh->valid();\n }\n\n if (valid)\n {\n if (!std::all_of(_optionalSections.begin(), _optionalSections.end(),\n [](const auto& section) { return section->valid(); }))\n {\n valid = false;\n }\n }\n\n return valid;\n}\n\nvoid PEL::setCommitTime()\n{\n auto now = std::chrono::system_clock::now();\n _ph->setCommitTimestamp(getBCDTime(now));\n}\n\nvoid PEL::assignID()\n{\n _ph->setID(generatePELID());\n}\n\nvoid PEL::flatten(std::vector& pelBuffer) const\n{\n Stream pelData{pelBuffer};\n\n if (!valid())\n {\n log(\"Unflattening an invalid PEL\");\n }\n\n _ph->flatten(pelData);\n _uh->flatten(pelData);\n\n for (auto& section : _optionalSections)\n {\n section->flatten(pelData);\n }\n}\n\nstd::vector PEL::data() const\n{\n std::vector pelData;\n flatten(pelData);\n return pelData;\n}\n\nsize_t PEL::size() const\n{\n size_t size = 0;\n\n if (_ph)\n {\n size += _ph->header().size;\n }\n\n if (_uh)\n {\n size += _uh->header().size;\n }\n\n for (const auto& section : _optionalSections)\n {\n size += section->header().size;\n }\n\n return size;\n}\n\nstd::optional PEL::primarySRC() const\n{\n auto src = std::find_if(\n _optionalSections.begin(), _optionalSections.end(), [](auto& section) {\n return section->header().id ==\n static_cast(SectionID::primarySRC);\n });\n if (src != _optionalSections.end())\n {\n return static_cast(src->get());\n }\n\n return std::nullopt;\n}\n\nvoid PEL::checkRulesAndFix()\n{\n auto [actionFlags, eventType] =\n pel_rules::check(_uh->actionFlags(), _uh->eventType(), _uh->severity());\n\n _uh->setActionFlags(actionFlags);\n _uh->setEventType(eventType);\n}\n\nvoid PEL::printSectionInJSON(const Section& section, std::string& buf,\n std::map& pluralSections,\n message::Registry& registry) const\n{\n char tmpB[5];\n uint8_t id[] = {static_cast(section.header().id >> 8),\n static_cast(section.header().id)};\n sprintf(tmpB, \"%c%c\", id[0], id[1]);\n std::string sectionID(tmpB);\n std::string sectionName = pv::sectionTitles.count(sectionID)\n ? pv::sectionTitles.at(sectionID)\n : \"Unknown Section\";\n\n \/\/ Add a count if there are multiple of this type of section\n auto count = pluralSections.find(section.header().id);\n if (count != pluralSections.end())\n {\n sectionName += \" \" + std::to_string(count->second);\n count->second++;\n }\n\n if (section.valid())\n {\n auto json = (sectionID == \"PS\" || sectionID == \"SS\")\n ? section.getJSON(registry)\n : section.getJSON();\n\n buf += \"\\\"\" + sectionName + \"\\\": {\\n\";\n\n if (json)\n {\n buf += *json + \"\\n},\\n\";\n }\n else\n {\n jsonInsert(buf, pv::sectionVer,\n getNumberString(\"%d\", section.header().version), 1);\n jsonInsert(buf, pv::subSection,\n getNumberString(\"%d\", section.header().subType), 1);\n jsonInsert(buf, pv::createdBy,\n getNumberString(\"0x%X\", section.header().componentID),\n 1);\n\n std::vector data;\n Stream s{data};\n section.flatten(s);\n std::string dstr =\n dumpHex(std::data(data) + SectionHeader::flattenedSize(),\n data.size(), 2);\n\n std::string jsonIndent(indentLevel, 0x20);\n buf += jsonIndent + \"\\\"Data\\\": [\\n\";\n buf += dstr;\n buf += jsonIndent + \"]\\n\";\n buf += \"},\\n\";\n }\n }\n else\n {\n buf += \"\\n\\\"Invalid Section\\\": [\\n \\\"invalid\\\"\\n],\\n\";\n }\n}\n\nstd::map PEL::getPluralSections() const\n{\n std::map sectionCounts;\n\n for (const auto& section : optionalSections())\n {\n if (sectionCounts.find(section->header().id) == sectionCounts.end())\n {\n sectionCounts[section->header().id] = 1;\n }\n else\n {\n sectionCounts[section->header().id]++;\n }\n }\n\n std::map sections;\n for (const auto& [id, count] : sectionCounts)\n {\n if (count > 1)\n {\n \/\/ Start with 0 here and printSectionInJSON()\n \/\/ will increment it as it goes.\n sections.emplace(id, 0);\n }\n }\n\n return sections;\n}\n\nvoid PEL::toJSON(message::Registry& registry) const\n{\n auto sections = getPluralSections();\n\n std::string buf = \"{\\n\";\n printSectionInJSON(*(_ph.get()), buf, sections, registry);\n printSectionInJSON(*(_uh.get()), buf, sections, registry);\n for (auto& section : this->optionalSections())\n {\n printSectionInJSON(*(section.get()), buf, sections, registry);\n }\n buf += \"}\";\n std::size_t found = buf.rfind(\",\");\n if (found != std::string::npos)\n buf.replace(found, 1, \"\");\n std::cout << buf << std::endl;\n}\n\nnamespace util\n{\n\nstd::unique_ptr makeJSONUserDataSection(const nlohmann::json& json)\n{\n auto jsonString = json.dump();\n std::vector jsonData(jsonString.begin(), jsonString.end());\n\n \/\/ Pad to a 4 byte boundary\n while ((jsonData.size() % 4) != 0)\n {\n jsonData.push_back(0);\n }\n\n return std::make_unique(\n static_cast(ComponentID::phosphorLogging),\n static_cast(UserDataFormat::json),\n static_cast(UserDataFormatVersion::json), jsonData);\n}\n\nstd::unique_ptr makeADUserDataSection(const AdditionalData& ad)\n{\n assert(!ad.empty());\n nlohmann::json json;\n\n \/\/ Remove the 'ESEL' entry, as it contains a full PEL in the value.\n if (ad.getValue(\"ESEL\"))\n {\n auto newAD = ad;\n newAD.remove(\"ESEL\");\n json = newAD.toJSON();\n }\n else\n {\n json = ad.toJSON();\n }\n\n return makeJSONUserDataSection(json);\n}\n\nvoid addProcessNameToJSON(nlohmann::json& json,\n const std::optional& pid,\n const DataInterfaceBase& dataIface)\n{\n std::string name{unknownValue};\n\n try\n {\n if (pid)\n {\n auto n = dataIface.getProcessName(*pid);\n if (n)\n {\n name = *n;\n }\n }\n }\n catch (std::exception& e)\n {\n }\n\n json[\"Process Name\"] = std::move(name);\n}\n\nvoid addBMCFWVersionIDToJSON(nlohmann::json& json,\n const DataInterfaceBase& dataIface)\n{\n auto id = dataIface.getBMCFWVersionID();\n if (id.empty())\n {\n id = unknownValue;\n }\n\n json[\"BMC Version ID\"] = std::move(id);\n}\n\nstd::string lastSegment(char separator, std::string data)\n{\n auto pos = data.find_last_of(separator);\n if (pos != std::string::npos)\n {\n data = data.substr(pos + 1);\n }\n\n return data;\n}\n\nvoid addStatesToJSON(nlohmann::json& json, const DataInterfaceBase& dataIface)\n{\n json[\"BMCState\"] = lastSegment('.', dataIface.getBMCState());\n json[\"ChassisState\"] = lastSegment('.', dataIface.getChassisState());\n json[\"HostState\"] = lastSegment('.', dataIface.getHostState());\n}\n\nstd::unique_ptr\n makeSysInfoUserDataSection(const AdditionalData& ad,\n const DataInterfaceBase& dataIface)\n{\n nlohmann::json json;\n\n addProcessNameToJSON(json, ad.getValue(\"_PID\"), dataIface);\n addBMCFWVersionIDToJSON(json, dataIface);\n addStatesToJSON(json, dataIface);\n\n return makeJSONUserDataSection(json);\n}\n\n} \/\/ namespace util\n\n} \/\/ namespace pels\n} \/\/ namespace openpower\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \"Console.h\"\n#include \"EditLineReader.h\"\n\nusing std::string;\nusing ccons::Console;\nusing ccons::EditLineReader;\n\nstatic llvm::cl::opt\n\tDebugMode(\"ccons-debug\", llvm::cl::desc(\"Print debugging information\"));\n\n\nint main(const int argc, char **argv)\n{\n\tllvm::cl::ParseCommandLineOptions(argc, argv, \"ccons Interactive C Console\\n\");\n\tllvm::sys::PrintStackTraceOnErrorSignal();\n\n\tif (DebugMode)\n\t\tfprintf(stderr, \"NOTE: Debugging information will be displayed.\\n\");\n\n\tConsole console(DebugMode);\n\n\tEditLineReader reader;\n\tconst char *line = reader.readLine(console.prompt(), console.input());\n\twhile (line) {\n\t\tconsole.process(line);\n\t\tline = reader.readLine(console.prompt(), console.input());\n\t}\n\n\treturn 0;\n}\n\nfirst stab at multi-process architecture. portability thrown out the window...#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"Console.h\"\n#include \"EditLineReader.h\"\n\nusing std::string;\nusing ccons::Console;\nusing ccons::LineReader;\nusing ccons::EditLineReader;\nusing ccons::StdInLineReader;\n\nstatic llvm::cl::opt\n\tDebugMode(\"ccons-debug\", llvm::cl::desc(\"Print debugging information\"));\nstatic llvm::cl::opt\n\tUseStdIo(\"use-std-io\", llvm::cl::desc(\"Use standard IO for input and output\"));\nstatic llvm::cl::opt\n\tMultiProcess(\"multi-process\", llvm::cl::desc(\"Run in multi-process mode\"));\n\nstatic void *pipe_input(void *ptr)\n{\n\tFILE *ps = (FILE *) ptr;\n\tchar buf[1024];\n\twhile (1) {\n\t\tconst char *s = fgets(buf, sizeof(buf), ps);\n\t\tif (s) printf(\"%s\", buf);\n\t}\n\treturn NULL;\n}\n\nint main(const int argc, char **argv)\n{\n\tllvm::cl::ParseCommandLineOptions(argc, argv, \"ccons Interactive C Console\\n\");\n\tllvm::sys::PrintStackTraceOnErrorSignal();\n\n\tif (DebugMode)\n\t\tfprintf(stderr, \"NOTE: Debugging information will be displayed.\\n\");\n\n\tConsole console(DebugMode);\n\tllvm::OwningPtr reader;\n\n\tFILE *ps;\n\tpthread_t reader_thread;\n\n\tif (MultiProcess) {\n\t\tps = popen(\".\/ccons --use-std-io\", \"r+\");\n\t\tassert(ps);\n\t\tfcntl(fileno(ps), F_SETFL, O_NONBLOCK);\n\t\tpthread_create(&reader_thread, NULL, pipe_input, (void *) ps);\n\t}\n\n\tif (UseStdIo)\n\t\treader.reset(new StdInLineReader);\n\telse\n\t\treader.reset(new EditLineReader);\n\n\tconst char *line = reader->readLine(console.prompt(), console.input());\n\twhile (line) {\n\t\tif (MultiProcess) {\n\t\t\tfputs(line, ps);\n\t\t\tusleep(100000);\n\t\t} else {\n\t\t\tconsole.process(line);\n\t\t}\n\t\tline = reader->readLine(console.prompt(), console.input());\n\t}\n\n\tif (MultiProcess)\n\t\tpclose(ps);\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"Console.h\"\n\nusing std::string;\nusing ccons::Console;\n\nstatic Console * cc;\n\nstatic const char *ccons_prompt(EditLine *e)\n{\n\treturn (cc ? cc->prompt() : \"??? \");\n}\n\nint main(const int argc, const char **argv)\n{\n\tEditLine *e = el_init(\"ccons\", stdin, stdout, stderr);\n\tel_set(e, EL_PROMPT, ccons_prompt);\n\n\tConsole console;\n\tcc = &console;\n\tconst char *line = el_gets(e, NULL);\n\twhile (line) {\n\t\tconsole.process(line);\n\t\t\/\/ FIXME: el_push() is broken... the second parameter should be const char *\n\t\tel_push(e, const_cast(console.input()));\n\t\tline = el_gets(e, NULL);\n\t}\n\tel_end(e);\n\n\treturn 0;\n}\n\nadd command history and set the default editing mode to emacs#include \n#include \n#include \n\n#include \"Console.h\"\n\nusing std::string;\nusing ccons::Console;\n\nstatic Console * cc;\n\nstatic const char *ccons_prompt(EditLine *e)\n{\n\treturn (cc ? cc->prompt() : \"??? \");\n}\n\nint main(const int argc, const char **argv)\n{\n\tHistEvent event;\n\tHistory *h = history_init();\n\thistory(h, &event, H_SETSIZE, INT_MAX);\n\n\tEditLine *e = el_init(\"ccons\", stdin, stdout, stderr);\n\tel_set(e, EL_PROMPT, ccons_prompt);\n\tel_set(e, EL_EDITOR, \"emacs\");\n\tel_set(e, EL_HIST, history, h);\n\n\tConsole console;\n\tcc = &console;\n\tconst char *line = el_gets(e, NULL);\n\twhile (line) {\n\t\tconsole.process(line);\n\t\thistory(h, &event, H_ENTER, line);\n\t\t\/\/ FIXME: el_push() is broken... the second parameter should be const char *\n\t\tel_push(e, const_cast(console.input()));\n\t\tline = el_gets(e, NULL);\n\t}\n\tel_end(e);\n\thistory_end(h);\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"#include \".\/constraint_updater.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/graphics\/vertex_array.h\"\n#include \"..\/graphics\/render_data.h\"\nBOOST_GEOMETRY_REGISTER_POINT_2D(Eigen::Vector2i, int, cs::cartesian, x(), y())\n#include \".\/boost_polygon_concepts.h\"\n\nnamespace bg = boost::geometry;\n\n\/\/ ccw, open polygon\ntypedef bg::model::polygon polygon;\n\nConstraintUpdater::ConstraintUpdater(\n Graphics::Gl *gl, std::shared_ptr shaderManager,\n int width, int height)\n : gl(gl), shaderManager(shaderManager), width(width), height(height)\n{\n shaderId = shaderManager->addShader(\":\/shader\/constraint.vert\",\n \":\/shader\/colorImmediate.frag\");\n\n Eigen::Affine3f pixelToNDCTransform(\n Eigen::Translation3f(Eigen::Vector3f(-1, 1, 0)) *\n Eigen::Scaling(Eigen::Vector3f(2.0f \/ width, -2.0f \/ height, 1)));\n pixelToNDC = pixelToNDCTransform.matrix();\n}\n\npolygon createBoxPolygon(Eigen::Vector2i center, Eigen::Vector2i size)\n{\n polygon p;\n p.outer().push_back(\n Eigen::Vector2i(center.x() - size.x(), center.y() - size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() + size.x(), center.y() - size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() + size.x(), center.y() + size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() - size.x(), center.y() + size.y()));\n\n return p;\n}\n\nboost::polygon::polygon_with_holes_data minkowskiSum(const polygon &a,\n const polygon &b)\n{\n boost::polygon::polygon_with_holes_data aPoly;\n boost::polygon::set_points(aPoly, a.outer().begin(), a.outer().end());\n\n boost::polygon::polygon_with_holes_data bPoly;\n boost::polygon::set_points(bPoly, b.outer().begin(), b.outer().end());\n\n boost::polygon::polygon_set_data dilated;\n boost::polygon::detail::minkowski_offset::convolve_two_point_sequences(\n dilated, boost::polygon::begin_points(aPoly),\n boost::polygon::end_points(aPoly), boost::polygon::begin_points(bPoly),\n boost::polygon::end_points(bPoly));\n\n std::vector> polys;\n dilated.get(polys);\n assert(polys.size() == 1);\n\n return polys[0];\n}\n\nvoid ConstraintUpdater::addLabel(Eigen::Vector2i anchorPosition,\n Eigen::Vector2i labelSize,\n Eigen::Vector2i lastAnchorPosition,\n Eigen::Vector2i lastLabelPosition,\n Eigen::Vector2i lastLabelSize)\n{\n\n polygon oldLabel = createBoxPolygon(lastLabelPosition, lastLabelSize \/ 2);\n\n polygon oldLabelExtruded(oldLabel);\n for (auto point : oldLabel.outer())\n {\n Eigen::Vector2i p = anchorPosition + 1000 * (point - anchorPosition);\n oldLabelExtruded.outer().push_back(p);\n }\n\n polygon oldLabelExtrudedConvexHull;\n bg::convex_hull(oldLabelExtruded, oldLabelExtrudedConvexHull);\n\n int border = 2;\n polygon newLabel = createBoxPolygon(\n Eigen::Vector2i(0, 0), labelSize \/ 2 + Eigen::Vector2i(border, border));\n\n auto dilatedOldLabelExtruded =\n minkowskiSum(oldLabelExtrudedConvexHull, newLabel);\n std::vector> points(\n dilatedOldLabelExtruded.begin(), dilatedOldLabelExtruded.end());\n drawPolygon(points);\n drawPolygon(oldLabelExtrudedConvexHull.outer());\n\n polygon connectorPolygon;\n connectorPolygon.outer().push_back(lastAnchorPosition);\n Eigen::Vector2i throughLastAnchor =\n anchorPosition + 1000 * (lastAnchorPosition - anchorPosition);\n connectorPolygon.outer().push_back(throughLastAnchor);\n\n Eigen::Vector2i throughLastLabel =\n anchorPosition + 1000 * (lastLabelPosition - anchorPosition);\n connectorPolygon.outer().push_back(throughLastLabel);\n connectorPolygon.outer().push_back(lastLabelPosition);\n\n auto dilatedConnector = minkowskiSum(connectorPolygon, newLabel);\n std::vector> pointsConnector(\n dilatedConnector.begin(), dilatedConnector.end());\n drawPolygon(pointsConnector);\n drawPolygon(connectorPolygon.outer());\n}\n\nvoid ConstraintUpdater::clear()\n{\n gl->glViewport(0, 0, width, height);\n gl->glClearColor(0, 0, 0, 0);\n gl->glClear(GL_COLOR_BUFFER_BIT);\n}\n\ntemplate void ConstraintUpdater::drawPolygon(std::vector polygon)\n{\n std::vector positions;\n if (polygon.size() > 0)\n {\n auto point = polygon[0];\n positions.push_back(point.x());\n positions.push_back(height - point.y());\n positions.push_back(0.0f);\n }\n for (auto point : polygon)\n {\n positions.push_back(point.x());\n positions.push_back(height - point.y());\n positions.push_back(0.0f);\n }\n\n Graphics::VertexArray *vertexArray =\n new Graphics::VertexArray(gl, GL_TRIANGLE_FAN);\n vertexArray->addStream(positions);\n\n RenderData renderData;\n renderData.modelMatrix = Eigen::Matrix4f::Identity();\n renderData.viewMatrix = pixelToNDC;\n renderData.projectionMatrix = Eigen::Matrix4f::Identity();\n shaderManager->bind(shaderId, renderData);\n vertexArray->draw();\n}\n\nUse minkowski for two polygon sets to fix wrong result.#include \".\/constraint_updater.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/graphics\/vertex_array.h\"\n#include \"..\/graphics\/render_data.h\"\nBOOST_GEOMETRY_REGISTER_POINT_2D(Eigen::Vector2i, int, cs::cartesian, x(), y())\n#include \".\/boost_polygon_concepts.h\"\n\nnamespace bg = boost::geometry;\n\n\/\/ ccw, open polygon\ntypedef bg::model::polygon polygon;\n\nConstraintUpdater::ConstraintUpdater(\n Graphics::Gl *gl, std::shared_ptr shaderManager,\n int width, int height)\n : gl(gl), shaderManager(shaderManager), width(width), height(height)\n{\n shaderId = shaderManager->addShader(\":\/shader\/constraint.vert\",\n \":\/shader\/colorImmediate.frag\");\n\n Eigen::Affine3f pixelToNDCTransform(\n Eigen::Translation3f(Eigen::Vector3f(-1, 1, 0)) *\n Eigen::Scaling(Eigen::Vector3f(2.0f \/ width, -2.0f \/ height, 1)));\n pixelToNDC = pixelToNDCTransform.matrix();\n}\n\npolygon createBoxPolygon(Eigen::Vector2i center, Eigen::Vector2i size)\n{\n polygon p;\n p.outer().push_back(\n Eigen::Vector2i(center.x() - size.x(), center.y() - size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() + size.x(), center.y() - size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() + size.x(), center.y() + size.y()));\n p.outer().push_back(\n Eigen::Vector2i(center.x() - size.x(), center.y() + size.y()));\n\n return p;\n}\n\nboost::polygon::polygon_with_holes_data minkowskiSum(const polygon &a,\n const polygon &b)\n{\n boost::polygon::polygon_with_holes_data aPoly;\n boost::polygon::set_points(aPoly, a.outer().begin(), a.outer().end());\n\n boost::polygon::polygon_with_holes_data bPoly;\n boost::polygon::set_points(bPoly, b.outer().begin(), b.outer().end());\n\n boost::polygon::polygon_set_data dilated;\n boost::polygon::polygon_set_data aPolys;\n aPolys.insert(aPoly);\n boost::polygon::polygon_set_data bPolys;\n bPolys.insert(bPoly);\n boost::polygon::detail::minkowski_offset::convolve_two_polygon_sets(\n dilated, aPolys, bPolys);\n\n std::vector> polys;\n dilated.get(polys);\n assert(polys.size() == 1);\n\n return polys[0];\n}\n\nvoid ConstraintUpdater::addLabel(Eigen::Vector2i anchorPosition,\n Eigen::Vector2i labelSize,\n Eigen::Vector2i lastAnchorPosition,\n Eigen::Vector2i lastLabelPosition,\n Eigen::Vector2i lastLabelSize)\n{\n\n polygon oldLabel = createBoxPolygon(lastLabelPosition, lastLabelSize \/ 2);\n\n polygon oldLabelExtruded(oldLabel);\n for (auto point : oldLabel.outer())\n {\n Eigen::Vector2i p = anchorPosition + 1000 * (point - anchorPosition);\n oldLabelExtruded.outer().push_back(p);\n }\n\n polygon oldLabelExtrudedConvexHull;\n bg::convex_hull(oldLabelExtruded, oldLabelExtrudedConvexHull);\n\n int border = 2;\n polygon newLabel = createBoxPolygon(\n Eigen::Vector2i(0, 0), labelSize \/ 2 + Eigen::Vector2i(border, border));\n\n auto dilatedOldLabelExtruded =\n minkowskiSum(oldLabelExtrudedConvexHull, newLabel);\n std::vector> points(\n dilatedOldLabelExtruded.begin(), dilatedOldLabelExtruded.end());\n drawPolygon(points);\n drawPolygon(oldLabelExtrudedConvexHull.outer());\n\n polygon connectorPolygon;\n connectorPolygon.outer().push_back(lastAnchorPosition);\n Eigen::Vector2i throughLastAnchor =\n anchorPosition + 1000 * (lastAnchorPosition - anchorPosition);\n connectorPolygon.outer().push_back(throughLastAnchor);\n\n Eigen::Vector2i throughLastLabel =\n anchorPosition + 1000 * (lastLabelPosition - anchorPosition);\n connectorPolygon.outer().push_back(throughLastLabel);\n connectorPolygon.outer().push_back(lastLabelPosition);\n\n auto dilatedConnector = minkowskiSum(connectorPolygon, newLabel);\n std::vector> pointsConnector(\n dilatedConnector.begin(), dilatedConnector.end());\n drawPolygon(pointsConnector);\n drawPolygon(connectorPolygon.outer());\n}\n\nvoid ConstraintUpdater::clear()\n{\n gl->glViewport(0, 0, width, height);\n gl->glClearColor(0, 0, 0, 0);\n gl->glClear(GL_COLOR_BUFFER_BIT);\n}\n\ntemplate void ConstraintUpdater::drawPolygon(std::vector polygon)\n{\n std::vector positions;\n if (polygon.size() > 0)\n {\n auto point = polygon[0];\n positions.push_back(point.x());\n positions.push_back(height - point.y());\n positions.push_back(0.0f);\n }\n for (auto point : polygon)\n {\n positions.push_back(point.x());\n positions.push_back(height - point.y());\n positions.push_back(0.0f);\n }\n\n Graphics::VertexArray *vertexArray =\n new Graphics::VertexArray(gl, GL_TRIANGLE_FAN);\n vertexArray->addStream(positions);\n\n RenderData renderData;\n renderData.modelMatrix = Eigen::Matrix4f::Identity();\n renderData.viewMatrix = pixelToNDC;\n renderData.projectionMatrix = Eigen::Matrix4f::Identity();\n shaderManager->bind(shaderId, renderData);\n vertexArray->draw();\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"compiler_features.hpp\"\n\n#include \n#include \n#include \n#include \n\n\/* Usage:\n *\n * enum class my_flag : size_t {\n * foo0 = 0,\n * foo1 = 1,\n * \/\/ ...\n * foo10 = 10,\n * Last = foo10,\n * };\n *\n * using my_flags = caney::flags;\n * CANEY_FLAGS(my_flags)\n *\n * The base enum defines the indices to look up in a bitset; you should use an enum class so there are no predefined (and wrong) bit-wise operators.\n *\n * Bit operations |, & and ^ usually work on the complete bitset; only &, when one parameter is a single flag, will simple test whether the flag is set.\n *\/\n\n#define CANEY_FLAGS(Flags) \\\n\tFlags operator|(Flags::flag_t a, Flags::flag_t b) { return Flags(a) | b; } \\\n\tFlags operator|(Flags::flag_t a, Flags b) { return Flags(a) | b; } \\\n\tbool operator&(Flags::flag_t a, Flags::flag_t b) = delete; \\\n\tbool operator&(Flags::flag_t a, Flags b) { return b & a; } \\\n\tFlags operator^(Flags::flag_t a, Flags::flag_t b) { return Flags(a) ^ b; } \\\n\tFlags operator^(Flags::flag_t a, Flags b) { return Flags(a) ^ b; } \\\n\tFlags operator~(Flags::flag_t a) { return ~Flags(a); }\n\nnamespace caney {\n\tinline namespace stdv1 {\n\t\tnamespace impl_traits {\n\t\t\t\/\/ idea from http:\/\/stackoverflow.com\/a\/10724828\/1478356\n\t\t\ttemplate::value>\n\t\t\tstruct is_scoped_enum : std::false_type {\n\t\t\t};\n\n\t\t\ttemplate\n\t\t\tstruct is_scoped_enum\n\t\t\t\t: std::integral_constant<\n\t\t\t\t\tbool,\n\t\t\t\t\t!std::is_convertible>::value> {\n\t\t\t};\n\t\t}\n\n\t\ttemplate(FlagEnum::Last) + 1, typename Elem = std::uint32_t>\n\t\tclass flags {\n\t\tprivate:\n\t\t\ttypedef std::underlying_type_t enum_t;\n\t\tpublic:\n\t\t\tstatic_assert(impl_traits::is_scoped_enum::value, \"Only scoped enums allowed\");\n\t\t\tstatic_assert(!std::numeric_limits::is_signed, \"Only enums with unsigned underlying types allowed\");\n\t\t\tstatic_assert(std::numeric_limits::is_integer, \"Only unsigned integers allowed as underlying array elements for flags\");\n\t\t\tstatic_assert(!std::numeric_limits::is_signed, \"Only unsigned integers allowed as underlying array elements for flags\");\n\n\t\t\tstatic_assert(8 == CHAR_BIT, \"byte should have exactly 8 bits\");\n\t\t\tstatic constexpr std::size_t BITS_PER_ELEM = sizeof(Elem)*CHAR_BIT;\n\n\t\t\t\/\/ how many array entries are needed to store all bits\n\t\t\tstatic constexpr std::size_t ARRAY_SIZE = (Size + BITS_PER_ELEM - 1)\/BITS_PER_ELEM;\n\t\t\tstatic_assert(ARRAY_SIZE > 0, \"Invalid array size\");\n\n\t\t\t\/\/ usable bits in the last entry\n\t\t\tstatic constexpr Elem LAST_ENTRY_MASK = (Size % BITS_PER_ELEM == 0) ? ~Elem{0} : ((Elem{1} << (Size % BITS_PER_ELEM)) - Elem{1});\n\n\t\t\ttypedef std::array array_t;\n\t\t\ttypedef FlagEnum flag_t;\n\n\t\t\tstatic constexpr std::size_t size() {\n\t\t\t\treturn Size;\n\t\t\t}\n\n\t\t\tclass reference {\n\t\t\tpublic:\n\t\t\t\treference& operator=(bool value) {\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\tset();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treset();\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tvoid set() {\n\t\t\t\t\t*m_elem |= m_mask;\n\t\t\t\t}\n\n\t\t\t\tvoid reset() {\n\t\t\t\t\t*m_elem &= ~m_mask;\n\t\t\t\t}\n\n\t\t\t\tvoid flip() {\n\t\t\t\t\t*m_elem ^= m_mask;\n\t\t\t\t}\n\n\t\t\t\tbool test() const {\n\t\t\t\t\treturn 0 != (*m_elem & m_mask);\n\t\t\t\t}\n\n\t\t\t\texplicit operator bool() const {\n\t\t\t\t\treturn test();\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tfriend class flags;\n\t\t\t\texplicit reference(Elem& elem, Elem mask)\n\t\t\t\t: m_elem(&elem), m_mask(mask) {\n\t\t\t\t}\n\n\t\t\t\tElem* m_elem;\n\t\t\t\tElem m_mask;\n\t\t\t};\n\n\t\t\texplicit flags() = default;\n\t\t\texplicit flags(array_t const& raw)\n\t\t\t: m_array(raw) {\n\t\t\t}\n\t\t\t\/\/ implicit\n\t\t\tflags(flag_t flag)\n\t\t\t{\n\t\t\t\tset(flag);\n\t\t\t}\n\n\t\t\treference operator[](flag_t flag) {\n\t\t\t\tsize_t flagNdx{static_cast(flag)};\n\t\t\t\tElem const mask = Elem{1} << (flagNdx % BITS_PER_ELEM);\n\t\t\t\treturn reference(m_array[flagNdx \/ BITS_PER_ELEM], mask);\n\t\t\t}\n\n\t\t\tCANEY_RELAXED_CONSTEXPR bool operator[](flag_t flag) const {\n\t\t\t\tsize_t flagNdx{static_cast(flag)};\n\t\t\t\tElem const mask = Elem{1} << (flagNdx % BITS_PER_ELEM);\n\t\t\t\treturn 0 != (m_array[flagNdx \/ BITS_PER_ELEM] & mask);\n\t\t\t}\n\n\t\t\tconstexpr bool operator==(flags const& other) const {\n\t\t\t\treturn m_array == other.m_array;\n\t\t\t}\n\n\t\t\tconstexpr bool operator!=(flags const& other) const {\n\t\t\t\treturn m_array != other.m_array;\n\t\t\t}\n\n\t\t\tvoid set(flag_t flag) {\n\t\t\t\toperator[](flag).set();\n\t\t\t}\n\n\t\t\tvoid reset(flag_t flag) {\n\t\t\t\toperator[](flag).reset();\n\t\t\t}\n\n\t\t\tvoid flip(flag_t flag) {\n\t\t\t\toperator[](flag).flip();\n\t\t\t}\n\n\t\t\tconstexpr bool test(flag_t flag) const {\n\t\t\t\treturn operator[](flag);\n\t\t\t}\n\n\t\t\tvoid clear() {\n\t\t\t\tm_array = array_t{};\n\t\t\t}\n\n\t\t\tbool operator&=(flag_t) = delete;\n\t\t\tconstexpr bool operator&(flag_t flag) const {\n\t\t\t\treturn test(flag);\n\t\t\t}\n\n\t\t\tflags& operator&=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] &= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator&(flags const& other) const { flags tmp(*this); tmp &= other; return tmp; }\n\n\t\t\tflags& operator|=(flag_t flag) {\n\t\t\t\tset(flag);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tflags& operator|=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] |= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator|(flags const& other) const { flags tmp(*this); tmp |= other; return tmp; }\n\n\t\t\tflags& operator^=(flag_t flag) {\n\t\t\t\tflip(flag);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tflags& operator^=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] ^= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator^(flags const& other) const { flags tmp(*this); tmp ^= other; return tmp; }\n\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator~() const {\n\t\t\t\tflags tmp(*this);\n\t\t\t\ttmp.flip_all();\n\t\t\t\treturn tmp;\n\t\t\t}\n\n\t\t\tvoid flip_all() {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE - 1; ++i) {\n\t\t\t\t\tm_array[i] = ~m_array[i];\n\t\t\t\t}\n\t\t\t\tm_array[ARRAY_SIZE-1] ^= LAST_ENTRY_MASK;\n\t\t\t}\n\n\t\t\tconstexpr bool none() const {\n\t\t\t\treturn m_array == array_t{};\n\t\t\t}\n\n\t\t\tconstexpr bool any() const {\n\t\t\t\treturn !none();\n\t\t\t}\n\n\t\t\tCANEY_RELAXED_CONSTEXPR bool all() const {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE - 1; ++i) {\n\t\t\t\t\tif (0 != ~m_array[i]) return false;\n\t\t\t\t}\n\t\t\t\treturn m_array[ARRAY_SIZE-1] == LAST_ENTRY_MASK;\n\t\t\t}\n\n\t\t\tarray_t& underlying_array() {\n\t\t\t\treturn m_array;\n\t\t\t}\n\n\t\t\tarray_t const& underlying_array() const {\n\t\t\t\treturn m_array;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tarray_t m_array{};\n\t\t};\n\t}\n} \/\/ namespace caney\nfix gcc 4.9 warning in flags#pragma once\n\n#include \"compiler_features.hpp\"\n\n#include \n#include \n#include \n#include \n\n\/* Usage:\n *\n * enum class my_flag : size_t {\n * foo0 = 0,\n * foo1 = 1,\n * \/\/ ...\n * foo10 = 10,\n * Last = foo10,\n * };\n *\n * using my_flags = caney::flags;\n * CANEY_FLAGS(my_flags)\n *\n * The base enum defines the indices to look up in a bitset; you should use an enum class so there are no predefined (and wrong) bit-wise operators.\n *\n * Bit operations |, & and ^ usually work on the complete bitset; only &, when one parameter is a single flag, will simple test whether the flag is set.\n *\/\n\n#define CANEY_FLAGS(Flags) \\\n\tFlags operator|(Flags::flag_t a, Flags::flag_t b) { return Flags(a) | b; } \\\n\tFlags operator|(Flags::flag_t a, Flags b) { return Flags(a) | b; } \\\n\tbool operator&(Flags::flag_t a, Flags::flag_t b) = delete; \\\n\tbool operator&(Flags::flag_t a, Flags b) { return b & a; } \\\n\tFlags operator^(Flags::flag_t a, Flags::flag_t b) { return Flags(a) ^ b; } \\\n\tFlags operator^(Flags::flag_t a, Flags b) { return Flags(a) ^ b; } \\\n\tFlags operator~(Flags::flag_t a) { return ~Flags(a); }\n\nnamespace caney {\n\tinline namespace stdv1 {\n\t\tnamespace impl_traits {\n\t\t\t\/\/ idea from http:\/\/stackoverflow.com\/a\/10724828\/1478356\n\t\t\ttemplate::value>\n\t\t\tstruct is_scoped_enum : std::false_type {\n\t\t\t};\n\n\t\t\ttemplate\n\t\t\tstruct is_scoped_enum\n\t\t\t\t: std::integral_constant<\n\t\t\t\t\tbool,\n\t\t\t\t\t!std::is_convertible>::value> {\n\t\t\t};\n\t\t}\n\n\t\ttemplate(FlagEnum::Last) + 1, typename Elem = std::uint32_t>\n\t\tclass flags {\n\t\tprivate:\n\t\t\ttypedef std::underlying_type_t enum_t;\n\t\tpublic:\n\t\t\tstatic_assert(impl_traits::is_scoped_enum::value, \"Only scoped enums allowed\");\n\t\t\tstatic_assert(!std::numeric_limits::is_signed, \"Only enums with unsigned underlying types allowed\");\n\t\t\tstatic_assert(std::numeric_limits::is_integer, \"Only unsigned integers allowed as underlying array elements for flags\");\n\t\t\tstatic_assert(!std::numeric_limits::is_signed, \"Only unsigned integers allowed as underlying array elements for flags\");\n\n\t\t\tstatic_assert(8 == CHAR_BIT, \"byte should have exactly 8 bits\");\n\t\t\tstatic constexpr std::size_t BITS_PER_ELEM = sizeof(Elem)*CHAR_BIT;\n\n\t\t\t\/\/ how many array entries are needed to store all bits\n\t\t\tstatic constexpr std::size_t ARRAY_SIZE = (Size + BITS_PER_ELEM - 1)\/BITS_PER_ELEM;\n\t\t\tstatic_assert(ARRAY_SIZE > 0, \"Invalid array size\");\n\n\t\t\t\/\/ usable bits in the last entry\n\t\t\tstatic constexpr Elem LAST_ENTRY_MASK = (Size % BITS_PER_ELEM == 0) ? ~Elem{0} : ((Elem{1} << (Size % BITS_PER_ELEM)) - Elem{1});\n\n\t\t\ttypedef std::array array_t;\n\t\t\ttypedef FlagEnum flag_t;\n\n\t\t\tstatic constexpr std::size_t size() {\n\t\t\t\treturn Size;\n\t\t\t}\n\n\t\t\tclass reference {\n\t\t\tpublic:\n\t\t\t\treference& operator=(bool value) {\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\tset();\n\t\t\t\t\t} else {\n\t\t\t\t\t\treset();\n\t\t\t\t\t}\n\t\t\t\t\treturn *this;\n\t\t\t\t}\n\n\t\t\t\tvoid set() {\n\t\t\t\t\t*m_elem |= m_mask;\n\t\t\t\t}\n\n\t\t\t\tvoid reset() {\n\t\t\t\t\t*m_elem &= ~m_mask;\n\t\t\t\t}\n\n\t\t\t\tvoid flip() {\n\t\t\t\t\t*m_elem ^= m_mask;\n\t\t\t\t}\n\n\t\t\t\tbool test() const {\n\t\t\t\t\treturn 0 != (*m_elem & m_mask);\n\t\t\t\t}\n\n\t\t\t\texplicit operator bool() const {\n\t\t\t\t\treturn test();\n\t\t\t\t}\n\n\t\t\tprivate:\n\t\t\t\tfriend class flags;\n\t\t\t\texplicit reference(Elem& elem, Elem mask)\n\t\t\t\t: m_elem(&elem), m_mask(mask) {\n\t\t\t\t}\n\n\t\t\t\tElem* m_elem;\n\t\t\t\tElem m_mask;\n\t\t\t};\n\n\t\t\texplicit flags() = default;\n\t\t\texplicit flags(array_t const& raw)\n\t\t\t: m_array(raw) {\n\t\t\t}\n\t\t\t\/\/ implicit\n\t\t\tflags(flag_t flag)\n\t\t\t{\n\t\t\t\tset(flag);\n\t\t\t}\n\n\t\t\treference operator[](flag_t flag) {\n\t\t\t\tsize_t flagNdx{static_cast(flag)};\n\t\t\t\tElem const mask = Elem{1} << (flagNdx % BITS_PER_ELEM);\n\t\t\t\treturn reference(m_array[flagNdx \/ BITS_PER_ELEM], mask);\n\t\t\t}\n\n\t\t\tCANEY_RELAXED_CONSTEXPR bool operator[](flag_t flag) const {\n\t\t\t\tsize_t flagNdx{static_cast(flag)};\n\t\t\t\tElem const mask = Elem{1} << (flagNdx % BITS_PER_ELEM);\n\t\t\t\treturn 0 != (m_array[flagNdx \/ BITS_PER_ELEM] & mask);\n\t\t\t}\n\n\t\t\tconstexpr bool operator==(flags const& other) const {\n\t\t\t\treturn m_array == other.m_array;\n\t\t\t}\n\n\t\t\tconstexpr bool operator!=(flags const& other) const {\n\t\t\t\treturn m_array != other.m_array;\n\t\t\t}\n\n\t\t\tvoid set(flag_t flag) {\n\t\t\t\toperator[](flag).set();\n\t\t\t}\n\n\t\t\tvoid reset(flag_t flag) {\n\t\t\t\toperator[](flag).reset();\n\t\t\t}\n\n\t\t\tvoid flip(flag_t flag) {\n\t\t\t\toperator[](flag).flip();\n\t\t\t}\n\n\t\t\tconstexpr bool test(flag_t flag) const {\n\t\t\t\treturn operator[](flag);\n\t\t\t}\n\n\t\t\tvoid clear() {\n\t\t\t\tm_array = array_t{{}};\n\t\t\t}\n\n\t\t\tbool operator&=(flag_t) = delete;\n\t\t\tconstexpr bool operator&(flag_t flag) const {\n\t\t\t\treturn test(flag);\n\t\t\t}\n\n\t\t\tflags& operator&=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] &= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator&(flags const& other) const { flags tmp(*this); tmp &= other; return tmp; }\n\n\t\t\tflags& operator|=(flag_t flag) {\n\t\t\t\tset(flag);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tflags& operator|=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] |= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator|(flags const& other) const { flags tmp(*this); tmp |= other; return tmp; }\n\n\t\t\tflags& operator^=(flag_t flag) {\n\t\t\t\tflip(flag);\n\t\t\t\treturn *this;\n\t\t\t}\n\n\t\t\tflags& operator^=(flags const& other) {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE; ++i) {\n\t\t\t\t\tm_array[i] ^= other.m_array[i];\n\t\t\t\t}\n\t\t\t\treturn *this;\n\t\t\t}\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator^(flags const& other) const { flags tmp(*this); tmp ^= other; return tmp; }\n\n\t\t\tCANEY_RELAXED_CONSTEXPR flags operator~() const {\n\t\t\t\tflags tmp(*this);\n\t\t\t\ttmp.flip_all();\n\t\t\t\treturn tmp;\n\t\t\t}\n\n\t\t\tvoid flip_all() {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE - 1; ++i) {\n\t\t\t\t\tm_array[i] = ~m_array[i];\n\t\t\t\t}\n\t\t\t\tm_array[ARRAY_SIZE-1] ^= LAST_ENTRY_MASK;\n\t\t\t}\n\n\t\t\tconstexpr bool none() const {\n\t\t\t\treturn m_array == array_t{{}};\n\t\t\t}\n\n\t\t\tconstexpr bool any() const {\n\t\t\t\treturn !none();\n\t\t\t}\n\n\t\t\tCANEY_RELAXED_CONSTEXPR bool all() const {\n\t\t\t\tfor (size_t i = 0; i < ARRAY_SIZE - 1; ++i) {\n\t\t\t\t\tif (0 != ~m_array[i]) return false;\n\t\t\t\t}\n\t\t\t\treturn m_array[ARRAY_SIZE-1] == LAST_ENTRY_MASK;\n\t\t\t}\n\n\t\t\tarray_t& underlying_array() {\n\t\t\t\treturn m_array;\n\t\t\t}\n\n\t\t\tarray_t const& underlying_array() const {\n\t\t\t\treturn m_array;\n\t\t\t}\n\n\t\tprivate:\n\t\t\tarray_t m_array{{}};\n\t\t};\n\t}\n} \/\/ namespace caney\n<|endoftext|>"} {"text":"\/***********************************************************************\n cgi_jpeg.cpp - Example code showing how to fetch JPEG data from a BLOB\n \tcolumn and send it back to a browser that requested it by ID.\n\t\n\tUse load_jpeg.cpp to load JPEG files into the database we query.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \n\nusing namespace std;\nusing namespace mysqlpp;\n\n#define IMG_DATABASE\t\"mysql_cpp_data\"\n#define IMG_HOST\t\t\"localhost\"\n#define IMG_USER\t\t\"root\"\n#define IMG_PASSWORD \t\"nunyabinness\"\n\nint\nmain(int argc, char *argv[])\n{\n\tunsigned int img_id = 0;\n\tchar* cgi_query = getenv(\"QUERY_STRING\");\n\tif (cgi_query) {\n\t\tif ((strlen(cgi_query) < 4) || memcmp(cgi_query, \"id=\", 3)) {\n\t\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\t\tcout << \"ERROR: Bad query string\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\telse {\n\t\t\timg_id = atoi(cgi_query + 3);\n\t\t}\n\t}\n\telse {\n\t\tcerr << \"Put this program into a web server's cgi-bin \"\n\t\t\t\t\"directory, then\" << endl;\n\t\tcerr << \"invoke it with a URL like this:\" << endl;\n\t\tcerr << endl;\n\t\tcerr << \" http:\/\/server.name.com\/cgi-bin\/cgi_image?id=2\" <<\n\t\t\t\tendl;\n\t\tcerr << endl;\n\t\tcerr << \"This will retrieve the image with ID 2.\" << endl;\n\t\tcerr << endl;\n\t\tcerr << \"You will probably have to change some of the #defines \"\n\t\t\t\t\"at the top of\" << endl;\n\t\tcerr << \"examples\/cgi_image.cpp to allow the lookup to work.\" <<\n\t\t\t\tendl;\n\t\treturn 1;\n\t}\n\n\tConnection con(use_exceptions);\n\ttry {\n\t\tcon.connect(IMG_DATABASE, IMG_HOST, IMG_USER, IMG_PASSWORD);\n\t\tQuery query = con.query();\n\t\tquery << \"SELECT data FROM images WHERE id = \" << img_id;\n\t\tRow row;\n\t\tResult res = query.store();\n\t\tif (res && (res.num_rows() > 0) && (row = res.at(0))) {\n\t\t\tunsigned long length = row.at(0).size();\n\t\t\tcout << \"Content-type: image\/jpeg\" << endl;\n\t\t\tcout << \"Content-length: \" << length << endl << endl;\n\t\t\tfwrite(row.at(0).data(), 1, length, stdout);\n\t\t}\n\t\telse {\n\t\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\t\tcout << \"ERROR: No such image with ID \" << img_id << endl;\n\t\t}\n\t}\n\tcatch (const BadQuery& er) {\n\t\t\/\/ Handle any query errors\n\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\tcout << \"QUERY ERROR: \" << er.what() << endl;\n\t\treturn 1;\n\t}\n\tcatch (const Exception& er) {\n\t\t\/\/ Catch-all for any other MySQL++ exceptions\n\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\tcout << \"GENERAL ERROR: \" << er.what() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\nReworked cgi_jpeg example's code style a bit. Not necessarily better, just a step along the road toward making it use SSQLS.\/***********************************************************************\n cgi_jpeg.cpp - Example code showing how to fetch JPEG data from a BLOB\n \tcolumn and send it back to a browser that requested it by ID.\n\t\n\tUse load_jpeg.cpp to load JPEG files into the database we query.\n\n Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by\n MySQL AB, and (c) 2004-2007 by Educational Technology Resources, Inc.\n Others may also hold copyrights on code in this file. See the CREDITS\n file in the top directory of the distribution for details.\n\n This file is part of MySQL++.\n\n MySQL++ is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Lesser General Public License as published\n by the Free Software Foundation; either version 2.1 of the License, or\n (at your option) any later version.\n\n MySQL++ is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public\n License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with MySQL++; if not, write to the Free Software\n Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301\n USA\n***********************************************************************\/\n\n#include \n\nusing namespace std;\nusing namespace mysqlpp;\n\n#define IMG_DATABASE\t\"mysql_cpp_data\"\n#define IMG_HOST\t\t\"localhost\"\n#define IMG_USER\t\t\"root\"\n#define IMG_PASSWORD \t\"nunyabinness\"\n\nint\nmain()\n{\n\tunsigned int img_id = 0;\n\tchar* cgi_query = getenv(\"QUERY_STRING\");\n\tif (cgi_query) {\n\t\tif ((strlen(cgi_query) < 4) || memcmp(cgi_query, \"id=\", 3)) {\n\t\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\t\tcout << \"ERROR: Bad query string\" << endl;\n\t\t\treturn 1;\n\t\t}\n\t\telse {\n\t\t\timg_id = atoi(cgi_query + 3);\n\t\t}\n\t}\n\telse {\n\t\tcerr << \"Put this program into a web server's cgi-bin \"\n\t\t\t\t\"directory, then\" << endl;\n\t\tcerr << \"invoke it with a URL like this:\" << endl;\n\t\tcerr << endl;\n\t\tcerr << \" http:\/\/server.name.com\/cgi-bin\/cgi_image?id=2\" <<\n\t\t\t\tendl;\n\t\tcerr << endl;\n\t\tcerr << \"This will retrieve the image with ID 2.\" << endl;\n\t\tcerr << endl;\n\t\tcerr << \"You will probably have to change some of the #defines \"\n\t\t\t\t\"at the top of\" << endl;\n\t\tcerr << \"examples\/cgi_image.cpp to allow the lookup to work.\" <<\n\t\t\t\tendl;\n\t\treturn 1;\n\t}\n\n\tConnection con(use_exceptions);\n\ttry {\n\t\tcon.connect(IMG_DATABASE, IMG_HOST, IMG_USER, IMG_PASSWORD);\n\t\tQuery query = con.query();\n\t\tquery << \"SELECT data FROM images WHERE id = \" << img_id;\n\t\tResUse res = query.use();\n\t\tif (res) {\n\t\t\tRow row = res.fetch_row();\n\t\t\tunsigned long length = row.raw_size(0);\n\t\t\tcout << \"Content-type: image\/jpeg\" << endl;\n\t\t\tcout << \"Content-length: \" << length << endl << endl;\n\t\t\tfwrite(row.raw_data(0), 1, length, stdout);\n\t\t}\n\t\telse {\n\t\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\t\tcout << \"ERROR: No such image with ID \" << img_id << endl;\n\t\t}\n\t}\n\tcatch (const BadQuery& er) {\n\t\t\/\/ Handle any query errors\n\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\tcout << \"QUERY ERROR: \" << er.what() << endl;\n\t\treturn 1;\n\t}\n\tcatch (const Exception& er) {\n\t\t\/\/ Catch-all for any other MySQL++ exceptions\n\t\tcout << \"Content-type: text\/plain\" << endl << endl;\n\t\tcout << \"GENERAL ERROR: \" << er.what() << endl;\n\t\treturn 1;\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ #include \n\n\/\/ #include \n\/\/ #include \n\n\/\/ #include \"maths\/io\/vec3.h\"\n\/\/ #include \"datatypes\/meshes.h\"\n\/\/ #include \"cgal.h\"\n\n\/\/ namespace {\n\n\/\/ using possumwood::Meshes;\n\/\/ using possumwood::CGALPolyhedron;\n\n\/\/ dependency_graph::InAttr a_inMesh;\n\/\/ dependency_graph::InAttr> a_translation, a_rotation, a_scale;\n\/\/ dependency_graph::OutAttr a_outMesh;\n\n\/\/ dependency_graph::State compute(dependency_graph::Values& data) {\n\/\/ \tconst Imath::Vec3 tr = data.get(a_translation);\n\/\/ \tconst Imath::Vec3 rot = data.get(a_rotation);\n\/\/ \tconst Imath::Vec3 sc = data.get(a_scale);\n\n\/\/ \tImath::Matrix44 m1, m2, m3;\n\/\/ \tm1 = Imath::Euler(Imath::Vec3(rot.x * M_PI \/ 180.0,\n\/\/ \t rot.y * M_PI \/ 180.0,\n\/\/ \t rot.z * M_PI \/ 180.0))\n\/\/ \t .toMatrix44();\n\/\/ \tm2.setScale(sc);\n\/\/ \tm3.setTranslation(tr);\n\n\/\/ \tconst Imath::Matrix44 matrix = m1 * m2 * m3;\n\n\/\/ \tMeshes result;\n\/\/ \tfor(auto& inMesh : data.get(a_inMesh)) {\n\/\/ \t\tstd::unique_ptr newMesh(\n\/\/ \t\t new possumwood::CGALPolyhedron(inMesh.mesh()));\n\n\/\/ \t\tfor(auto it = newMesh->vertices_begin(); it != newMesh->vertices_end();\n\/\/ \t\t ++it) {\n\/\/ \t\t\tpossumwood::CGALPolyhedron::Point& pt = newMesh->point(*it);\n\n\/\/ \t\t\tImath::Vec3 p(pt[0], pt[1], pt[2]);\n\/\/ \t\t\tp *= matrix;\n\n\/\/ \t\t\tpt = possumwood::CGALKernel::Point_3(p.x, p.y, p.z);\n\/\/ \t\t}\n\n\/\/ \t\tresult.addMesh(inMesh.name(), std::move(newMesh));\n\/\/ \t}\n\n\/\/ \tdata.set(a_outMesh, result);\n\n\/\/ \treturn dependency_graph::State();\n\/\/ }\n\n\/\/ void init(possumwood::Metadata& meta) {\n\/\/ \tmeta.addAttribute(a_inMesh, \"in_mesh\");\n\/\/ \tmeta.addAttribute(a_translation, \"translation\",\n\/\/ \t Imath::Vec3(0, 0, 0));\n\/\/ \tmeta.addAttribute(a_rotation, \"rotation\", Imath::Vec3(0, 0, 0));\n\/\/ \tmeta.addAttribute(a_scale, \"scale\", Imath::Vec3(1, 1, 1));\n\/\/ \tmeta.addAttribute(a_outMesh, \"out_mesh\");\n\n\/\/ \tmeta.addInfluence(a_inMesh, a_outMesh);\n\/\/ \tmeta.addInfluence(a_translation, a_outMesh);\n\/\/ \tmeta.addInfluence(a_rotation, a_outMesh);\n\/\/ \tmeta.addInfluence(a_scale, a_outMesh);\n\n\/\/ \tmeta.setCompute(compute);\n\/\/ }\n\n\/\/ possumwood::NodeImplementation s_impl(\"cgal\/transform\", init);\n\/\/ }\nPorted CGAL Transform node to use new CGAL mesh representation#include \n\n#include \n#include \n\n#include \"maths\/io\/vec3.h\"\n#include \"datatypes\/meshes.h\"\n#include \"cgal.h\"\n\nnamespace {\n\nusing possumwood::Meshes;\nusing possumwood::CGALPolyhedron;\n\ndependency_graph::InAttr a_inMesh;\ndependency_graph::InAttr> a_translation, a_rotation, a_scale;\ndependency_graph::OutAttr a_outMesh;\n\ndependency_graph::State compute(dependency_graph::Values& data) {\n\tconst Imath::Vec3 tr = data.get(a_translation);\n\tconst Imath::Vec3 rot = data.get(a_rotation);\n\tconst Imath::Vec3 sc = data.get(a_scale);\n\n\tImath::Matrix44 m1, m2, m3;\n\tm1 =\n\t Imath::Euler(Imath::Vec3(rot.x * M_PI \/ 180.0, rot.y * M_PI \/ 180.0,\n\t rot.z * M_PI \/ 180.0))\n\t .toMatrix44();\n\tm2.setScale(sc);\n\tm3.setTranslation(tr);\n\n\tconst Imath::Matrix44 matrix = m1 * m2 * m3;\n\n\tMeshes result = data.get(a_inMesh);\n\tfor(auto& mesh : result) {\n\t\tfor(auto it = mesh.polyhedron().vertices_begin();\n\t\t it != mesh.polyhedron().vertices_end(); ++it) {\n\t\t\tpossumwood::CGALPolyhedron::Point& pt = it->point();;\n\n\t\t\tImath::Vec3 p(pt[0], pt[1], pt[2]);\n\t\t\tp *= matrix;\n\n\t\t\tpt = possumwood::CGALKernel::Point_3(p.x, p.y, p.z);\n\t\t}\n\t}\n\n\tdata.set(a_outMesh, result);\n\n\treturn dependency_graph::State();\n}\n\nvoid init(possumwood::Metadata& meta) {\n\tmeta.addAttribute(a_inMesh, \"in_mesh\");\n\tmeta.addAttribute(a_translation, \"translation\", Imath::Vec3(0, 0, 0));\n\tmeta.addAttribute(a_rotation, \"rotation\", Imath::Vec3(0, 0, 0));\n\tmeta.addAttribute(a_scale, \"scale\", Imath::Vec3(1, 1, 1));\n\tmeta.addAttribute(a_outMesh, \"out_mesh\");\n\n\tmeta.addInfluence(a_inMesh, a_outMesh);\n\tmeta.addInfluence(a_translation, a_outMesh);\n\tmeta.addInfluence(a_rotation, a_outMesh);\n\tmeta.addInfluence(a_scale, a_outMesh);\n\n\tmeta.setCompute(compute);\n}\n\npossumwood::NodeImplementation s_impl(\"cgal\/transform\", init);\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file primesieve_iterator.cpp\n\/\/\/ @brief C port of primesieve::iterator.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n\n\/\/\/ Convert pimpl pointer to std::vector\nstd::vector& to_vector(uint64_t* primes_pimpl)\n{\n std::vector* primes = reinterpret_cast*>(primes_pimpl);\n return *primes;\n}\n\n\/\/\/ Calculate an interval size that ensures a good load balance.\n\/\/\/ @param n Start or stop number.\n\/\/\/\nuint64_t get_interval_size(primesieve_iterator* pi, uint64_t n)\n{\n using config::ITERATOR_CACHE_SMALL;\n using config::ITERATOR_CACHE_MEDIUM;\n using config::ITERATOR_CACHE_LARGE;\n\n pi->count_++;\n double x = std::max(static_cast(n), 10.0);\n double sqrtx = std::sqrt(x);\n uint64_t sqrtx_primes = static_cast(sqrtx \/ (std::log(sqrtx) - 1));\n\n uint64_t max_primes = ITERATOR_CACHE_LARGE \/ sizeof(uint64_t);\n uint64_t primes = ((pi->count_ < 10) ? ITERATOR_CACHE_SMALL : ITERATOR_CACHE_MEDIUM) \/ sizeof(uint64_t);\n primes = std::min(std::max(primes, sqrtx_primes), max_primes);\n\n return static_cast(primes * std::log(x));\n}\n\n\/\/\/ Generate the primes inside [start, stop] and\n\/\/\/ store them in the primes vector.\n\/\/\/\nvoid generate_primes(primesieve_iterator* pi, uint64_t start, uint64_t stop)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (primes.empty() || primes[0] != PRIMESIEVE_ERROR)\n {\n try {\n primes.clear();\n primesieve::generate_primes(start, stop, &primes);\n } catch (std::exception&) {\n primes.clear();\n }\n if (primes.empty())\n {\n primes.resize(64, PRIMESIEVE_ERROR);\n errno = EDOM;\n }\n pi->primes_ = &primes[0];\n pi->size_ = primes.size();\n }\n}\n\n} \/\/ end anonymous namespace\n\n\/\/\/ C constructor\nvoid primesieve_init(primesieve_iterator* pi)\n{\n pi->primes_pimpl_ = reinterpret_cast(new std::vector);\n primesieve_skipto(pi, 0);\n}\n\n\/\/\/ C destructor\nvoid primesieve_free(primesieve_iterator* pi)\n{\n std::vector* primes = &to_vector(pi->primes_pimpl_);\n delete primes;\n}\n\n\/\/\/ Set primesieve_iterator to start\nvoid primesieve_skipto(primesieve_iterator* pi, uint64_t start)\n{\n pi->first_ = true;\n pi->adjust_skipto_ = false;\n pi->i_ = 0;\n pi->count_ = 0;\n pi->start_ = start;\n\n std::vector& primes = to_vector(pi->primes_pimpl_);\n\n if (!primes.empty() &&\n primes.front() <= pi->start_ &&\n primes.back() >= pi->start_)\n {\n pi->adjust_skipto_ = true;\n pi->i_ = std::lower_bound(primes.begin(), primes.end(), pi->start_) - primes.begin();\n }\n else\n primes.clear();\n}\n\n\/\/\/ Generate new next primes\nvoid generate_next_primes(primesieve_iterator* pi)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (pi->adjust_skipto_)\n {\n pi->adjust_skipto_ = false;\n if (pi->i_ > 0 && primes[pi->i_ - 1] >= pi->start_)\n pi->i_--;\n }\n else\n {\n uint64_t start = (pi->first_) ? pi->start_ : primes.back() + 1;\n uint64_t interval_size = get_interval_size(pi, start);\n uint64_t stop = (start < max_stop() - interval_size) ? start + interval_size : max_stop();\n generate_primes(pi, start, stop);\n pi->i_ = 0;\n }\n pi->first_ = false;\n}\n\n\/\/\/ Generate new previous primes\nvoid generate_previous_primes(primesieve_iterator* pi)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (pi->adjust_skipto_)\n {\n pi->adjust_skipto_ = false;\n if (pi->i_ > 0 && primes[pi->i_] > pi->start_)\n pi->i_--;\n }\n else\n {\n uint64_t stop = pi->start_;\n if (!pi->first_)\n stop = (primes.front() > 1) ? primes.front() - 1 : 0;\n uint64_t interval_size = get_interval_size(pi, stop);\n uint64_t start = (stop > interval_size) ? stop - interval_size : 0;\n generate_primes(pi, start, stop);\n pi->i_ = primes.size();\n }\n pi->first_ = false;\n}\nRefactoring\/\/\/\n\/\/\/ @file primesieve_iterator.cpp\n\/\/\/ @brief C port of primesieve::iterator.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace {\n\n\/\/\/ Convert pimpl pointer to std::vector\nstd::vector& to_vector(uint64_t* primes_pimpl)\n{\n std::vector* primes = reinterpret_cast*>(primes_pimpl);\n return *primes;\n}\n\n\/\/\/ Calculate an interval size that ensures a good load balance.\n\/\/\/ @param n Start or stop number.\n\/\/\/\nuint64_t get_interval_size(primesieve_iterator* pi, uint64_t n)\n{\n using config::ITERATOR_CACHE_SMALL;\n using config::ITERATOR_CACHE_MEDIUM;\n using config::ITERATOR_CACHE_LARGE;\n\n pi->count_++;\n double x = std::max(static_cast(n), 10.0);\n double sqrtx = std::sqrt(x);\n uint64_t sqrtx_primes = static_cast(sqrtx \/ (std::log(sqrtx) - 1));\n\n uint64_t max_primes = ITERATOR_CACHE_LARGE \/ sizeof(uint64_t);\n uint64_t primes = ((pi->count_ < 10) ? ITERATOR_CACHE_SMALL : ITERATOR_CACHE_MEDIUM) \/ sizeof(uint64_t);\n primes = std::min(std::max(primes, sqrtx_primes), max_primes);\n\n return static_cast(primes * std::log(x));\n}\n\n\/\/\/ Generate the primes inside [start, stop] and\n\/\/\/ store them in the primes vector.\n\/\/\/\nvoid generate_primes(primesieve_iterator* pi, uint64_t start, uint64_t stop)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (primes.empty() || primes[0] != PRIMESIEVE_ERROR)\n {\n try {\n primes.clear();\n primesieve::generate_primes(start, stop, &primes);\n } catch (std::exception&) {\n primes.clear();\n }\n if (primes.empty())\n {\n primes.resize(64, PRIMESIEVE_ERROR);\n errno = EDOM;\n }\n pi->primes_ = &primes[0];\n pi->size_ = primes.size();\n }\n}\n\n} \/\/ end anonymous namespace\n\n\/\/\/ C constructor\nvoid primesieve_init(primesieve_iterator* pi)\n{\n pi->primes_pimpl_ = reinterpret_cast(new std::vector);\n primesieve_skipto(pi, 0);\n}\n\n\/\/\/ C destructor\nvoid primesieve_free(primesieve_iterator* pi)\n{\n std::vector* primes = &to_vector(pi->primes_pimpl_);\n delete primes;\n}\n\n\/\/\/ Set primesieve_iterator to start\nvoid primesieve_skipto(primesieve_iterator* pi, uint64_t start)\n{\n pi->first_ = true;\n pi->adjust_skipto_ = false;\n pi->i_ = 0;\n pi->count_ = 0;\n pi->start_ = start;\n\n std::vector& primes = to_vector(pi->primes_pimpl_);\n\n if (!primes.empty() &&\n primes.front() <= pi->start_ &&\n primes.back() >= pi->start_)\n {\n pi->adjust_skipto_ = true;\n pi->i_ = std::lower_bound(primes.begin(), primes.end(), pi->start_) - primes.begin();\n }\n else\n primes.clear();\n}\n\n\/\/\/ Generate new next primes\nvoid generate_next_primes(primesieve_iterator* pi)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (pi->adjust_skipto_)\n {\n pi->adjust_skipto_ = false;\n if (pi->i_ > 0 && primes[pi->i_ - 1] >= pi->start_)\n pi->i_--;\n }\n else\n {\n uint64_t start = (pi->first_) ? pi->start_ : primes.back() + 1;\n uint64_t interval_size = get_interval_size(pi, start);\n uint64_t stop = (start < max_stop() - interval_size) ? start + interval_size : max_stop();\n generate_primes(pi, start, stop);\n pi->i_ = 0;\n }\n pi->first_ = false;\n}\n\n\/\/\/ Generate new previous primes\nvoid generate_previous_primes(primesieve_iterator* pi)\n{\n std::vector& primes = to_vector(pi->primes_pimpl_);\n if (pi->adjust_skipto_)\n {\n pi->adjust_skipto_ = false;\n if (pi->i_ > 0 && primes[pi->i_] > pi->start_)\n pi->i_--;\n }\n else\n {\n uint64_t stop = pi->start_;\n if (!pi->first_)\n stop = (primes.front() > 1) ? primes.front() - 1 : 0;\n uint64_t interval_size = get_interval_size(pi, stop);\n uint64_t start = (stop > interval_size) ? stop - interval_size : 0;\n generate_primes(pi, start, stop);\n pi->i_ = primes.size();\n }\n pi->first_ = false;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"diffutils.h\"\n#include \"differ.h\"\n#include \n#include \"texteditor\/fontsettings.h\"\n\nnamespace DiffEditor {\nnamespace Internal {\n\nstatic QList assemblyRows(const QList &lines,\n const QMap &lineSpans)\n{\n QList data;\n\n const int lineCount = lines.count();\n for (int i = 0; i <= lineCount; i++) {\n for (int j = 0; j < lineSpans.value(i); j++)\n data.append(TextLineData(TextLineData::Separator));\n if (i < lineCount)\n data.append(lines.at(i));\n }\n return data;\n}\n\nstatic bool lastLinesEqual(const QList &leftLines,\n const QList &rightLines)\n{\n const bool leftLineEqual = leftLines.count()\n ? leftLines.last().text.isEmpty()\n : true;\n const bool rightLineEqual = rightLines.count()\n ? rightLines.last().text.isEmpty()\n : true;\n return leftLineEqual && rightLineEqual;\n}\n\nstatic void handleLine(const QStringList &newLines,\n int line,\n QList *lines,\n int *lineNumber)\n{\n if (line < newLines.count()) {\n const QString text = newLines.at(line);\n if (lines->isEmpty() || line > 0) {\n if (line > 0)\n ++*lineNumber;\n lines->append(TextLineData(text));\n } else {\n lines->last().text += text;\n }\n }\n}\n\nstatic void handleDifference(const QString &text,\n QList *lines,\n int *lineNumber)\n{\n const QStringList newLines = text.split(QLatin1Char('\\n'));\n for (int line = 0; line < newLines.count(); ++line) {\n const int startPos = line > 0\n ? -1\n : lines->isEmpty() ? 0 : lines->last().text.count();\n handleLine(newLines, line, lines, lineNumber);\n const int endPos = line < newLines.count() - 1\n ? -1\n : lines->isEmpty() ? 0 : lines->last().text.count();\n if (!lines->isEmpty())\n lines->last().changedPositions.insert(startPos, endPos);\n }\n}\n\n\/*\n * leftDiffList can contain only deletions and equalities,\n * while rightDiffList can contain only insertions and equalities.\n * The number of equalities on both lists must be the same.\n*\/\nChunkData calculateOriginalData(const QList &leftDiffList,\n const QList &rightDiffList)\n{\n ChunkData chunkData;\n\n int i = 0;\n int j = 0;\n\n QList leftLines;\n QList rightLines;\n\n \/\/ \n QMap leftSpans;\n QMap rightSpans;\n \/\/ \n QMap equalLines;\n\n int leftLineNumber = 0;\n int rightLineNumber = 0;\n int leftLineAligned = -1;\n int rightLineAligned = -1;\n bool lastLineEqual = true;\n\n while (i <= leftDiffList.count() && j <= rightDiffList.count()) {\n const Diff leftDiff = i < leftDiffList.count()\n ? leftDiffList.at(i)\n : Diff(Diff::Equal);\n const Diff rightDiff = j < rightDiffList.count()\n ? rightDiffList.at(j)\n : Diff(Diff::Equal);\n\n if (leftDiff.command == Diff::Delete) {\n \/\/ process delete\n handleDifference(leftDiff.text, &leftLines, &leftLineNumber);\n lastLineEqual = lastLinesEqual(leftLines, rightLines);\n i++;\n }\n if (rightDiff.command == Diff::Insert) {\n \/\/ process insert\n handleDifference(rightDiff.text, &rightLines, &rightLineNumber);\n lastLineEqual = lastLinesEqual(leftLines, rightLines);\n j++;\n }\n if (leftDiff.command == Diff::Equal && rightDiff.command == Diff::Equal) {\n \/\/ process equal\n const QStringList newLeftLines = leftDiff.text.split(QLatin1Char('\\n'));\n const QStringList newRightLines = rightDiff.text.split(QLatin1Char('\\n'));\n\n int line = 0;\n\n while (line < qMax(newLeftLines.count(), newRightLines.count())) {\n handleLine(newLeftLines, line, &leftLines, &leftLineNumber);\n handleLine(newRightLines, line, &rightLines, &rightLineNumber);\n\n const int commonLineCount = qMin(newLeftLines.count(), newRightLines.count());\n if (line < commonLineCount) {\n \/\/ try to align\n const int leftDifference = leftLineNumber - leftLineAligned;\n const int rightDifference = rightLineNumber - rightLineAligned;\n\n if (leftDifference && rightDifference) {\n bool doAlign = true;\n if (line == 0 \/\/ omit alignment when first lines of equalities are empty and last generated lines are not equal\n && (newLeftLines.at(0).isEmpty() || newRightLines.at(0).isEmpty())\n && !lastLineEqual) {\n doAlign = false;\n }\n\n if (line == commonLineCount - 1) {\n \/\/ omit alignment when last lines of equalities are empty\n if (leftLines.last().text.isEmpty() || rightLines.last().text.isEmpty())\n doAlign = false;\n\n \/\/ unless it's the last dummy line (don't omit in that case)\n if (i == leftDiffList.count() && j == rightDiffList.count())\n doAlign = true;\n }\n\n if (doAlign) {\n \/\/ align here\n leftLineAligned = leftLineNumber;\n rightLineAligned = rightLineNumber;\n\n \/\/ insert separators if needed\n if (rightDifference > leftDifference)\n leftSpans.insert(leftLineNumber, rightDifference - leftDifference);\n else if (leftDifference > rightDifference)\n rightSpans.insert(rightLineNumber, leftDifference - rightDifference);\n }\n }\n }\n\n \/\/ check if lines are equal\n if ((line < commonLineCount - 1) \/\/ before the last common line in equality\n || (line == commonLineCount - 1 \/\/ or the last common line in equality\n && i == leftDiffList.count() \/\/ and it's the last iteration\n && j == rightDiffList.count())) {\n if (line > 0 || lastLineEqual)\n equalLines.insert(leftLineNumber, rightLineNumber);\n }\n\n if (line > 0)\n lastLineEqual = true;\n\n line++;\n }\n i++;\n j++;\n }\n }\n\n QList leftData = assemblyRows(leftLines,\n leftSpans);\n QList rightData = assemblyRows(rightLines,\n rightSpans);\n\n \/\/ fill ending separators\n for (int i = leftData.count(); i < rightData.count(); i++)\n leftData.append(TextLineData(TextLineData::Separator));\n for (int i = rightData.count(); i < leftData.count(); i++)\n rightData.append(TextLineData(TextLineData::Separator));\n\n const int visualLineCount = leftData.count();\n int leftLine = -1;\n int rightLine = -1;\n for (int i = 0; i < visualLineCount; i++) {\n const TextLineData &leftTextLine = leftData.at(i);\n const TextLineData &rightTextLine = rightData.at(i);\n RowData row(leftTextLine, rightTextLine);\n\n if (leftTextLine.textLineType == TextLineData::TextLine)\n ++leftLine;\n if (rightTextLine.textLineType == TextLineData::TextLine)\n ++rightLine;\n if (equalLines.value(leftLine, -2) == rightLine)\n row.equal = true;\n\n chunkData.rows.append(row);\n }\n return chunkData;\n}\n\nFileData calculateContextData(const ChunkData &originalData, int contextLinesNumber)\n{\n if (contextLinesNumber < 0)\n return FileData(originalData);\n\n const int joinChunkThreshold = 1;\n\n FileData fileData;\n QMap hiddenRows;\n int i = 0;\n while (i < originalData.rows.count()) {\n const RowData &row = originalData.rows[i];\n if (row.equal) {\n \/\/ count how many equal\n int equalRowStart = i;\n i++;\n while (i < originalData.rows.count()) {\n const RowData originalRow = originalData.rows.at(i);\n if (!originalRow.equal)\n break;\n i++;\n }\n const bool first = equalRowStart == 0; \/\/ includes first line?\n const bool last = i == originalData.rows.count(); \/\/ includes last line?\n\n const int firstLine = first ? 0 : equalRowStart + contextLinesNumber;\n const int lastLine = last ? originalData.rows.count() : i - contextLinesNumber;\n\n if (firstLine < lastLine - joinChunkThreshold) {\n for (int j = firstLine; j < lastLine; j++) {\n hiddenRows.insert(j, true);\n }\n }\n } else {\n \/\/ iterate to the next row\n i++;\n }\n }\n i = 0;\n while (i < originalData.rows.count()) {\n const bool contextChunk = hiddenRows.contains(i);\n ChunkData chunkData;\n chunkData.contextChunk = contextChunk;\n while (i < originalData.rows.count()) {\n if (contextChunk != hiddenRows.contains(i))\n break;\n RowData rowData = originalData.rows.at(i);\n chunkData.rows.append(rowData);\n ++i;\n }\n fileData.chunks.append(chunkData);\n }\n\n return fileData;\n}\n\nvoid addChangedPositions(int positionOffset, const QMap &originalChangedPositions, QMap *changedPositions)\n{\n QMapIterator it(originalChangedPositions);\n while (it.hasNext()) {\n it.next();\n const int startPos = it.key();\n const int endPos = it.value();\n const int newStartPos = startPos < 0 ? -1 : startPos + positionOffset;\n const int newEndPos = endPos < 0 ? -1 : endPos + positionOffset;\n if (startPos < 0 && !changedPositions->isEmpty())\n changedPositions->insert(changedPositions->lastKey(), newEndPos);\n else\n changedPositions->insert(newStartPos, newEndPos);\n }\n}\n\nQList colorPositions(\n const QTextCharFormat &format,\n QTextCursor &cursor,\n const QMap &positions)\n{\n QList lineSelections;\n\n cursor.setPosition(0);\n QMapIterator itPositions(positions);\n while (itPositions.hasNext()) {\n itPositions.next();\n\n cursor.setPosition(itPositions.key());\n cursor.setPosition(itPositions.value(), QTextCursor::KeepAnchor);\n\n QTextEdit::ExtraSelection selection;\n selection.cursor = cursor;\n selection.format = format;\n lineSelections.append(selection);\n }\n return lineSelections;\n}\n\nQTextCharFormat fullWidthFormatForTextStyle(const TextEditor::FontSettings &fontSettings,\n TextEditor::TextStyle textStyle)\n{\n QTextCharFormat format = fontSettings.toTextCharFormat(textStyle);\n format.setProperty(QTextFormat::FullWidthSelection, true);\n return format;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace DiffEditor\nDiff Editor: Fix compilation with Qt < 5.2.\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"diffutils.h\"\n#include \"differ.h\"\n#include \n#include \"texteditor\/fontsettings.h\"\n\nnamespace DiffEditor {\nnamespace Internal {\n\nstatic QList assemblyRows(const QList &lines,\n const QMap &lineSpans)\n{\n QList data;\n\n const int lineCount = lines.count();\n for (int i = 0; i <= lineCount; i++) {\n for (int j = 0; j < lineSpans.value(i); j++)\n data.append(TextLineData(TextLineData::Separator));\n if (i < lineCount)\n data.append(lines.at(i));\n }\n return data;\n}\n\nstatic bool lastLinesEqual(const QList &leftLines,\n const QList &rightLines)\n{\n const bool leftLineEqual = leftLines.count()\n ? leftLines.last().text.isEmpty()\n : true;\n const bool rightLineEqual = rightLines.count()\n ? rightLines.last().text.isEmpty()\n : true;\n return leftLineEqual && rightLineEqual;\n}\n\nstatic void handleLine(const QStringList &newLines,\n int line,\n QList *lines,\n int *lineNumber)\n{\n if (line < newLines.count()) {\n const QString text = newLines.at(line);\n if (lines->isEmpty() || line > 0) {\n if (line > 0)\n ++*lineNumber;\n lines->append(TextLineData(text));\n } else {\n lines->last().text += text;\n }\n }\n}\n\nstatic void handleDifference(const QString &text,\n QList *lines,\n int *lineNumber)\n{\n const QStringList newLines = text.split(QLatin1Char('\\n'));\n for (int line = 0; line < newLines.count(); ++line) {\n const int startPos = line > 0\n ? -1\n : lines->isEmpty() ? 0 : lines->last().text.count();\n handleLine(newLines, line, lines, lineNumber);\n const int endPos = line < newLines.count() - 1\n ? -1\n : lines->isEmpty() ? 0 : lines->last().text.count();\n if (!lines->isEmpty())\n lines->last().changedPositions.insert(startPos, endPos);\n }\n}\n\n\/*\n * leftDiffList can contain only deletions and equalities,\n * while rightDiffList can contain only insertions and equalities.\n * The number of equalities on both lists must be the same.\n*\/\nChunkData calculateOriginalData(const QList &leftDiffList,\n const QList &rightDiffList)\n{\n ChunkData chunkData;\n\n int i = 0;\n int j = 0;\n\n QList leftLines;\n QList rightLines;\n\n \/\/ \n QMap leftSpans;\n QMap rightSpans;\n \/\/ \n QMap equalLines;\n\n int leftLineNumber = 0;\n int rightLineNumber = 0;\n int leftLineAligned = -1;\n int rightLineAligned = -1;\n bool lastLineEqual = true;\n\n while (i <= leftDiffList.count() && j <= rightDiffList.count()) {\n const Diff leftDiff = i < leftDiffList.count()\n ? leftDiffList.at(i)\n : Diff(Diff::Equal);\n const Diff rightDiff = j < rightDiffList.count()\n ? rightDiffList.at(j)\n : Diff(Diff::Equal);\n\n if (leftDiff.command == Diff::Delete) {\n \/\/ process delete\n handleDifference(leftDiff.text, &leftLines, &leftLineNumber);\n lastLineEqual = lastLinesEqual(leftLines, rightLines);\n i++;\n }\n if (rightDiff.command == Diff::Insert) {\n \/\/ process insert\n handleDifference(rightDiff.text, &rightLines, &rightLineNumber);\n lastLineEqual = lastLinesEqual(leftLines, rightLines);\n j++;\n }\n if (leftDiff.command == Diff::Equal && rightDiff.command == Diff::Equal) {\n \/\/ process equal\n const QStringList newLeftLines = leftDiff.text.split(QLatin1Char('\\n'));\n const QStringList newRightLines = rightDiff.text.split(QLatin1Char('\\n'));\n\n int line = 0;\n\n while (line < qMax(newLeftLines.count(), newRightLines.count())) {\n handleLine(newLeftLines, line, &leftLines, &leftLineNumber);\n handleLine(newRightLines, line, &rightLines, &rightLineNumber);\n\n const int commonLineCount = qMin(newLeftLines.count(), newRightLines.count());\n if (line < commonLineCount) {\n \/\/ try to align\n const int leftDifference = leftLineNumber - leftLineAligned;\n const int rightDifference = rightLineNumber - rightLineAligned;\n\n if (leftDifference && rightDifference) {\n bool doAlign = true;\n if (line == 0 \/\/ omit alignment when first lines of equalities are empty and last generated lines are not equal\n && (newLeftLines.at(0).isEmpty() || newRightLines.at(0).isEmpty())\n && !lastLineEqual) {\n doAlign = false;\n }\n\n if (line == commonLineCount - 1) {\n \/\/ omit alignment when last lines of equalities are empty\n if (leftLines.last().text.isEmpty() || rightLines.last().text.isEmpty())\n doAlign = false;\n\n \/\/ unless it's the last dummy line (don't omit in that case)\n if (i == leftDiffList.count() && j == rightDiffList.count())\n doAlign = true;\n }\n\n if (doAlign) {\n \/\/ align here\n leftLineAligned = leftLineNumber;\n rightLineAligned = rightLineNumber;\n\n \/\/ insert separators if needed\n if (rightDifference > leftDifference)\n leftSpans.insert(leftLineNumber, rightDifference - leftDifference);\n else if (leftDifference > rightDifference)\n rightSpans.insert(rightLineNumber, leftDifference - rightDifference);\n }\n }\n }\n\n \/\/ check if lines are equal\n if ((line < commonLineCount - 1) \/\/ before the last common line in equality\n || (line == commonLineCount - 1 \/\/ or the last common line in equality\n && i == leftDiffList.count() \/\/ and it's the last iteration\n && j == rightDiffList.count())) {\n if (line > 0 || lastLineEqual)\n equalLines.insert(leftLineNumber, rightLineNumber);\n }\n\n if (line > 0)\n lastLineEqual = true;\n\n line++;\n }\n i++;\n j++;\n }\n }\n\n QList leftData = assemblyRows(leftLines,\n leftSpans);\n QList rightData = assemblyRows(rightLines,\n rightSpans);\n\n \/\/ fill ending separators\n for (int i = leftData.count(); i < rightData.count(); i++)\n leftData.append(TextLineData(TextLineData::Separator));\n for (int i = rightData.count(); i < leftData.count(); i++)\n rightData.append(TextLineData(TextLineData::Separator));\n\n const int visualLineCount = leftData.count();\n int leftLine = -1;\n int rightLine = -1;\n for (int i = 0; i < visualLineCount; i++) {\n const TextLineData &leftTextLine = leftData.at(i);\n const TextLineData &rightTextLine = rightData.at(i);\n RowData row(leftTextLine, rightTextLine);\n\n if (leftTextLine.textLineType == TextLineData::TextLine)\n ++leftLine;\n if (rightTextLine.textLineType == TextLineData::TextLine)\n ++rightLine;\n if (equalLines.value(leftLine, -2) == rightLine)\n row.equal = true;\n\n chunkData.rows.append(row);\n }\n return chunkData;\n}\n\nFileData calculateContextData(const ChunkData &originalData, int contextLinesNumber)\n{\n if (contextLinesNumber < 0)\n return FileData(originalData);\n\n const int joinChunkThreshold = 1;\n\n FileData fileData;\n QMap hiddenRows;\n int i = 0;\n while (i < originalData.rows.count()) {\n const RowData &row = originalData.rows[i];\n if (row.equal) {\n \/\/ count how many equal\n int equalRowStart = i;\n i++;\n while (i < originalData.rows.count()) {\n const RowData originalRow = originalData.rows.at(i);\n if (!originalRow.equal)\n break;\n i++;\n }\n const bool first = equalRowStart == 0; \/\/ includes first line?\n const bool last = i == originalData.rows.count(); \/\/ includes last line?\n\n const int firstLine = first ? 0 : equalRowStart + contextLinesNumber;\n const int lastLine = last ? originalData.rows.count() : i - contextLinesNumber;\n\n if (firstLine < lastLine - joinChunkThreshold) {\n for (int j = firstLine; j < lastLine; j++) {\n hiddenRows.insert(j, true);\n }\n }\n } else {\n \/\/ iterate to the next row\n i++;\n }\n }\n i = 0;\n while (i < originalData.rows.count()) {\n const bool contextChunk = hiddenRows.contains(i);\n ChunkData chunkData;\n chunkData.contextChunk = contextChunk;\n while (i < originalData.rows.count()) {\n if (contextChunk != hiddenRows.contains(i))\n break;\n RowData rowData = originalData.rows.at(i);\n chunkData.rows.append(rowData);\n ++i;\n }\n fileData.chunks.append(chunkData);\n }\n\n return fileData;\n}\n\nvoid addChangedPositions(int positionOffset, const QMap &originalChangedPositions, QMap *changedPositions)\n{\n QMapIterator it(originalChangedPositions);\n while (it.hasNext()) {\n it.next();\n const int startPos = it.key();\n const int endPos = it.value();\n const int newStartPos = startPos < 0 ? -1 : startPos + positionOffset;\n const int newEndPos = endPos < 0 ? -1 : endPos + positionOffset;\n if (startPos < 0 && !changedPositions->isEmpty()) {\n QMap::iterator last = changedPositions->end();\n --last;\n last.value() = newEndPos;\n } else\n changedPositions->insert(newStartPos, newEndPos);\n }\n}\n\nQList colorPositions(\n const QTextCharFormat &format,\n QTextCursor &cursor,\n const QMap &positions)\n{\n QList lineSelections;\n\n cursor.setPosition(0);\n QMapIterator itPositions(positions);\n while (itPositions.hasNext()) {\n itPositions.next();\n\n cursor.setPosition(itPositions.key());\n cursor.setPosition(itPositions.value(), QTextCursor::KeepAnchor);\n\n QTextEdit::ExtraSelection selection;\n selection.cursor = cursor;\n selection.format = format;\n lineSelections.append(selection);\n }\n return lineSelections;\n}\n\nQTextCharFormat fullWidthFormatForTextStyle(const TextEditor::FontSettings &fontSettings,\n TextEditor::TextStyle textStyle)\n{\n QTextCharFormat format = fontSettings.toTextCharFormat(textStyle);\n format.setProperty(QTextFormat::FullWidthSelection, true);\n return format;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace DiffEditor\n<|endoftext|>"} {"text":"#include \n#include \n#include \"moveit_recorder\/InteractiveRobot.h\"\n\ninline std::string get_option(const boost::program_options::variables_map& vm, const std::string& option, const std::string& default_str)\n{\n return vm.count(option) ? vm[option].as() : default_str;\n}\n\nint main(int argc, char** argv)\n{ \n ros::init(argc, argv, \"start_marker\");\n ros::NodeHandle node_handle;\n ros::AsyncSpinner spinner(1);\n spinner.start();\n \n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"robot_description\", boost::program_options::value(), \"robot description param name\")\n (\"to_marker_topic\", boost::program_options::value(), \"robot state topic FROM planning scene\")\n (\"from_marker_topic\", boost::program_options::value(), \"robot state topic TO planning scene\")\n (\"from_marker_pose_topic\", boost::program_options::value(), \"pose topic for robot end link pose\")\n (\"display_robot_topic\", boost::program_options::value(), \"display robot state topic\")\n (\"robot_marker_topic\", boost::program_options::value(), \"topic for robot visual markers\")\n (\"interactive_marker_topic\", boost::program_options::value(), \"topic for interactive marker\");\n\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\")) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n try\n {\n std::string robot_description = get_option(vm, \"robot_description\", \"robot_description\");\n std::string to_marker_topic = get_option(vm, \"to_marker_topic\", \"to_marker_state\");\n std::string from_marker_topic = get_option(vm, \"from_marker_topic\", \"from_marker_state\");\n std::string from_marker_pose_topic = get_option(vm, \"from_marker_pose_topic\", \"from_marker_pose\");\n std::string display_robot_topic = get_option(vm, \"display_robot_topic\", \"interactive_robot_state\");\n std::string robot_marker_topic = get_option(vm, \"robot_marker_topic\", \"interactive_robot_markers\");\n std::string interactive_marker_topic = get_option(vm, \"interactive_marker_topic\", \"interactive_robot_imarkers\");\n\n InteractiveRobot robot( robot_description,\n to_marker_topic,\n from_marker_topic,\n from_marker_pose_topic,\n display_robot_topic,\n robot_marker_topic,\n interactive_marker_topic);\n ros::spin();\n }\n catch(...)\n {\n\n }\n\n ros::shutdown();\n return 0;\n}\nadded arg for loading the right arm#include \n#include \n#include \"moveit_recorder\/InteractiveRobot.h\"\n\ninline std::string get_option(const boost::program_options::variables_map& vm, const std::string& option, const std::string& default_str)\n{\n return vm.count(option) ? vm[option].as() : default_str;\n}\n\nint main(int argc, char** argv)\n{ \n ros::init(argc, argv, \"start_marker\");\n ros::NodeHandle node_handle;\n ros::AsyncSpinner spinner(1);\n spinner.start();\n\n sleep(20);\n \n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"robot_description\", boost::program_options::value(), \"robot description param name\")\n (\"to_marker_topic\", boost::program_options::value(), \"robot state topic FROM planning scene\")\n (\"from_marker_topic\", boost::program_options::value(), \"robot state topic TO planning scene\")\n (\"from_marker_pose_topic\", boost::program_options::value(), \"pose topic for robot end link pose\")\n (\"display_robot_topic\", boost::program_options::value(), \"display robot state topic\")\n (\"robot_marker_topic\", boost::program_options::value(), \"topic for robot visual markers\")\n (\"interactive_marker_topic\", boost::program_options::value(), \"topic for interactive marker\");\n\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\")) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n try\n {\n std::string robot_description = get_option(vm, \"robot_description\", \"robot_description\");\n std::string to_marker_topic = get_option(vm, \"to_marker_topic\", \"to_marker_state\");\n std::string from_marker_topic = get_option(vm, \"from_marker_topic\", \"from_marker_state\");\n std::string from_marker_pose_topic = get_option(vm, \"from_marker_pose_topic\", \"from_marker_pose\");\n std::string display_robot_topic = get_option(vm, \"display_robot_topic\", \"interactive_robot_state\");\n std::string robot_marker_topic = get_option(vm, \"robot_marker_topic\", \"interactive_robot_markers\");\n std::string interactive_marker_topic = get_option(vm, \"interactive_marker_topic\", \"interactive_robot_imarkers\");\n\n InteractiveRobot robot( robot_description,\n to_marker_topic,\n from_marker_topic,\n from_marker_pose_topic,\n display_robot_topic,\n robot_marker_topic,\n interactive_marker_topic,\n \"right_arm\");\n ros::spin();\n }\n catch(...)\n {\n\n }\n\n ros::shutdown();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Magnum { namespace Examples {\n\nclass PrimitivesExample: public Platform::GlutApplication {\n public:\n explicit PrimitivesExample(const Arguments& arguments);\n\n void viewportEvent(const Vector2i& size) override;\n void drawEvent() override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseReleaseEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n\n private:\n Buffer indexBuffer, vertexBuffer;\n Mesh mesh;\n Shaders::Phong shader;\n\n Matrix4 transformation, projection;\n Vector2i previousMousePosition;\n Color3 color;\n};\n\nPrimitivesExample::PrimitivesExample(const Arguments& arguments): Platform::GlutApplication(arguments, Configuration().setTitle(\"Primitives example\")) {\n Renderer::setFeature(Renderer::Feature::DepthTest, true);\n Renderer::setFeature(Renderer::Feature::FaceCulling, true);\n\n Trade::MeshData3D cube = Primitives::Cube::solid();\n\n MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, cube.indices());\n\n MeshTools::interleave(mesh, vertexBuffer, Buffer::Usage::StaticDraw,\n cube.positions(0), cube.normals(0));\n mesh.setPrimitive(Mesh::Primitive::Triangles)\n .addInterleavedVertexBuffer(vertexBuffer, 0,\n Shaders::Phong::Position(), Shaders::Phong::Normal());\n\n transformation = Matrix4::rotationX(Deg(30.0f))*\n Matrix4::rotationY(Deg(40.0f));\n color = Color3::fromHSV(Deg(35.0f), 1.0f, 1.0f);\n}\n\nvoid PrimitivesExample::viewportEvent(const Vector2i& size) {\n defaultFramebuffer.setViewport({{}, size});\n\n projection = Matrix4::perspectiveProjection(Deg(35.0f), Float(size.x())\/size.y(), 0.01f, 100.0f)*\n Matrix4::translation(Vector3::zAxis(-10.0f));\n}\n\nvoid PrimitivesExample::drawEvent() {\n defaultFramebuffer.bind(FramebufferTarget::Draw);\n defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth);\n\n shader.setLightPosition({7.0f, 5.0f, 2.5f})\n .setLightColor(Color3(1.0f))\n .setDiffuseColor(color)\n .setAmbientColor(Color3::fromHSV(color.hue(), 1.0f, 0.3f))\n .setTransformationMatrix(transformation)\n .setNormalMatrix(transformation.rotation())\n .setProjectionMatrix(projection)\n .use();\n mesh.draw();\n\n swapBuffers();\n}\n\nvoid PrimitivesExample::mousePressEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left) return;\n\n previousMousePosition = event.position();\n event.setAccepted();\n}\n\nvoid PrimitivesExample::mouseReleaseEvent(MouseEvent& event) {\n color = Color3::fromHSV(color.hue() + Deg(50.0), 1.0f, 1.0f);\n\n event.setAccepted();\n redraw();\n}\n\nvoid PrimitivesExample::mouseMoveEvent(MouseMoveEvent& event) {\n Vector2 delta = 3.0f*Vector2(event.position() - previousMousePosition)\/defaultFramebuffer.viewport().size();\n transformation =\n Matrix4::rotationX(Rad(delta.y()))*\n transformation*\n Matrix4::rotationY(Rad(delta.x()));\n\n previousMousePosition = event.position();\n event.setAccepted();\n redraw();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::PrimitivesExample)\nprimitives: use non-asserting accessor.\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Magnum { namespace Examples {\n\nclass PrimitivesExample: public Platform::GlutApplication {\n public:\n explicit PrimitivesExample(const Arguments& arguments);\n\n void viewportEvent(const Vector2i& size) override;\n void drawEvent() override;\n void mousePressEvent(MouseEvent& event) override;\n void mouseReleaseEvent(MouseEvent& event) override;\n void mouseMoveEvent(MouseMoveEvent& event) override;\n\n private:\n Buffer indexBuffer, vertexBuffer;\n Mesh mesh;\n Shaders::Phong shader;\n\n Matrix4 transformation, projection;\n Vector2i previousMousePosition;\n Color3 color;\n};\n\nPrimitivesExample::PrimitivesExample(const Arguments& arguments): Platform::GlutApplication(arguments, Configuration().setTitle(\"Primitives example\")) {\n Renderer::setFeature(Renderer::Feature::DepthTest, true);\n Renderer::setFeature(Renderer::Feature::FaceCulling, true);\n\n Trade::MeshData3D cube = Primitives::Cube::solid();\n\n MeshTools::compressIndices(mesh, indexBuffer, Buffer::Usage::StaticDraw, cube.indices());\n\n MeshTools::interleave(mesh, vertexBuffer, Buffer::Usage::StaticDraw,\n cube.positions(0), cube.normals(0));\n mesh.setPrimitive(Mesh::Primitive::Triangles)\n .addInterleavedVertexBuffer(vertexBuffer, 0,\n Shaders::Phong::Position(), Shaders::Phong::Normal());\n\n transformation = Matrix4::rotationX(Deg(30.0f))*\n Matrix4::rotationY(Deg(40.0f));\n color = Color3::fromHSV(Deg(35.0f), 1.0f, 1.0f);\n}\n\nvoid PrimitivesExample::viewportEvent(const Vector2i& size) {\n defaultFramebuffer.setViewport({{}, size});\n\n projection = Matrix4::perspectiveProjection(Deg(35.0f), Float(size.x())\/size.y(), 0.01f, 100.0f)*\n Matrix4::translation(Vector3::zAxis(-10.0f));\n}\n\nvoid PrimitivesExample::drawEvent() {\n defaultFramebuffer.bind(FramebufferTarget::Draw);\n defaultFramebuffer.clear(FramebufferClear::Color|FramebufferClear::Depth);\n\n shader.setLightPosition({7.0f, 5.0f, 2.5f})\n .setLightColor(Color3(1.0f))\n .setDiffuseColor(color)\n .setAmbientColor(Color3::fromHSV(color.hue(), 1.0f, 0.3f))\n .setTransformationMatrix(transformation)\n .setNormalMatrix(transformation.rotationScaling()) \/** @todo better solution? *\/\n .setProjectionMatrix(projection)\n .use();\n mesh.draw();\n\n swapBuffers();\n}\n\nvoid PrimitivesExample::mousePressEvent(MouseEvent& event) {\n if(event.button() != MouseEvent::Button::Left) return;\n\n previousMousePosition = event.position();\n event.setAccepted();\n}\n\nvoid PrimitivesExample::mouseReleaseEvent(MouseEvent& event) {\n color = Color3::fromHSV(color.hue() + Deg(50.0), 1.0f, 1.0f);\n\n event.setAccepted();\n redraw();\n}\n\nvoid PrimitivesExample::mouseMoveEvent(MouseMoveEvent& event) {\n Vector2 delta = 3.0f*Vector2(event.position() - previousMousePosition)\/defaultFramebuffer.viewport().size();\n transformation =\n Matrix4::rotationX(Rad(delta.y()))*\n transformation*\n Matrix4::rotationY(Rad(delta.x()));\n\n previousMousePosition = event.position();\n event.setAccepted();\n redraw();\n}\n\n}}\n\nMAGNUM_APPLICATION_MAIN(Magnum::Examples::PrimitivesExample)\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014-2019 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ninline unsigned int GetSizeOfCompactSizeDiff(uint64_t nSizePrev, uint64_t nSizeNew)\n{\n assert(nSizePrev <= nSizeNew);\n return ::GetSizeOfCompactSize(nSizeNew) - ::GetSizeOfCompactSize(nSizePrev);\n}\n\nCKeyHolder::CKeyHolder(CWallet* pwallet) :\n reserveKey(pwallet)\n{\n reserveKey.GetReservedKey(pubKey, false);\n}\n\nvoid CKeyHolder::KeepKey()\n{\n reserveKey.KeepKey();\n}\n\nvoid CKeyHolder::ReturnKey()\n{\n reserveKey.ReturnKey();\n}\n\nCScript CKeyHolder::GetScriptForDestination() const\n{\n return ::GetScriptForDestination(pubKey.GetID());\n}\n\n\nCScript CKeyHolderStorage::AddKey(CWallet* pwallet)\n{\n auto keyHolderPtr = std::unique_ptr(new CKeyHolder(pwallet));\n auto script = keyHolderPtr->GetScriptForDestination();\n\n LOCK(cs_storage);\n storage.emplace_back(std::move(keyHolderPtr));\n LogPrintf(\"CKeyHolderStorage::%s -- storage size %lld\\n\", __func__, storage.size());\n return script;\n}\n\nvoid CKeyHolderStorage::KeepAll()\n{\n std::vector > tmp;\n {\n \/\/ don't hold cs_storage while calling KeepKey(), which might lock cs_wallet\n LOCK(cs_storage);\n std::swap(storage, tmp);\n }\n\n if (!tmp.empty()) {\n for (auto& key : tmp) {\n key->KeepKey();\n }\n LogPrintf(\"CKeyHolderStorage::%s -- %lld keys kept\\n\", __func__, tmp.size());\n }\n}\n\nvoid CKeyHolderStorage::ReturnAll()\n{\n std::vector > tmp;\n {\n \/\/ don't hold cs_storage while calling ReturnKey(), which might lock cs_wallet\n LOCK(cs_storage);\n std::swap(storage, tmp);\n }\n\n if (!tmp.empty()) {\n for (auto& key : tmp) {\n key->ReturnKey();\n }\n LogPrintf(\"CKeyHolderStorage::%s -- %lld keys returned\\n\", __func__, tmp.size());\n }\n}\n\nCTransactionBuilderOutput::CTransactionBuilderOutput(CTransactionBuilder* pTxBuilderIn, CWallet* pwalletIn, CAmount nAmountIn) :\n pTxBuilder(pTxBuilderIn),\n key(pwalletIn),\n nAmount(nAmountIn)\n{\n assert(pTxBuilder);\n CPubKey pubKey;\n key.GetReservedKey(pubKey, false);\n script = ::GetScriptForDestination(pubKey.GetID());\n}\n\nbool CTransactionBuilderOutput::UpdateAmount(const CAmount nNewAmount)\n{\n LOCK(pTxBuilder->cs_outputs);\n if (nNewAmount <= 0 || nNewAmount - nAmount > pTxBuilder->GetAmountLeft()) {\n return false;\n }\n nAmount = nNewAmount;\n return true;\n}\n\nCTransactionBuilder::CTransactionBuilder(CWallet* pwalletIn, const CompactTallyItem& tallyItemIn) :\n pwallet(pwalletIn),\n dummyReserveKey(pwalletIn),\n tallyItem(tallyItemIn)\n{\n \/\/ Generate a feerate which will be used to consider if the remainder is dust and will go into fees or not\n coinControl.m_discard_feerate = ::GetDiscardRate(::feeEstimator);\n \/\/ Generate a feerate which will be used by calculations of this class and also by CWallet::CreateTransaction\n coinControl.m_feerate = std::max(::feeEstimator.estimateSmartFee((int)::nTxConfirmTarget, nullptr, true), payTxFee);\n \/\/ Change always goes back to origin\n coinControl.destChange = tallyItemIn.txdest;\n \/\/ Only allow tallyItems inputs for tx creation\n coinControl.fAllowOtherInputs = false;\n \/\/ Select all tallyItem outputs in the coinControl so that CreateTransaction knows what to use\n for (const auto& outpoint : tallyItem.vecOutPoints) {\n coinControl.Select(outpoint);\n }\n \/\/ Create dummy tx to calculate the exact required fees upfront for accurate amount and fee calculations\n CMutableTransaction dummyTx;\n \/\/ Get a comparable dummy scriptPubKey\n CTransactionBuilderOutput dummyOutput(this, pwallet, 0);\n CScript dummyScript = dummyOutput.GetScript();\n dummyOutput.ReturnKey();\n \/\/ And create dummy signatures for all inputs\n SignatureData dummySignature;\n ProduceSignature(DummySignatureCreator(pwallet), dummyScript, dummySignature);\n for (auto out : tallyItem.vecOutPoints) {\n dummyTx.vin.emplace_back(out, dummySignature.scriptSig);\n }\n \/\/ Calculate required bytes for the dummy tx with tallyItem's inputs only\n nBytesBase = ::GetSerializeSize(dummyTx, SER_NETWORK, PROTOCOL_VERSION);\n \/\/ Calculate the output size\n nBytesOutput = ::GetSerializeSize(CTxOut(0, dummyScript), SER_NETWORK, PROTOCOL_VERSION);\n \/\/ Just to make sure..\n Clear();\n}\n\nCTransactionBuilder::~CTransactionBuilder()\n{\n Clear();\n}\n\nvoid CTransactionBuilder::Clear()\n{\n std::vector> vecOutputsTmp;\n {\n \/\/ Don't hold cs_outputs while clearing the outputs which might indirectly call lock cs_wallet\n LOCK(cs_outputs);\n std::swap(vecOutputs, vecOutputsTmp);\n vecOutputs.clear();\n }\n\n for (auto& key : vecOutputsTmp) {\n if (fKeepKeys) {\n key->KeepKey();\n } else {\n key->ReturnKey();\n }\n }\n \/\/ Always return this key just to make sure..\n dummyReserveKey.ReturnKey();\n}\n\nbool CTransactionBuilder::CouldAddOutput(CAmount nAmountOutput) const\n{\n if (nAmountOutput < 0) {\n return false;\n }\n \/\/ Adding another output can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n unsigned int nBytes = GetBytesTotal() + nBytesOutput + GetSizeOfCompactSizeDiff(1);\n return GetAmountLeft(GetAmountInitial(), GetAmountUsed() + nAmountOutput, GetFee(nBytes)) >= 0;\n}\n\nbool CTransactionBuilder::CouldAddOutputs(const std::vector& vecOutputAmounts) const\n{\n CAmount nAmountAdditional{0};\n assert(vecOutputAmounts.size() < INT_MAX);\n int nBytesAdditional = nBytesOutput * (int)vecOutputAmounts.size();\n for (const auto nAmountOutput : vecOutputAmounts) {\n if (nAmountOutput < 0) {\n return false;\n }\n nAmountAdditional += nAmountOutput;\n }\n \/\/ Adding other outputs can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n unsigned int nBytes = GetBytesTotal() + nBytesAdditional + GetSizeOfCompactSizeDiff(vecOutputAmounts.size());\n return GetAmountLeft(GetAmountInitial(), GetAmountUsed() + nAmountAdditional, GetFee(nBytes)) >= 0;\n}\n\nCTransactionBuilderOutput* CTransactionBuilder::AddOutput(CAmount nAmountOutput)\n{\n LOCK(cs_outputs);\n if (CouldAddOutput(nAmountOutput)) {\n vecOutputs.push_back(std::make_unique(this, pwallet, nAmountOutput));\n return vecOutputs.back().get();\n }\n return nullptr;\n}\n\nunsigned int CTransactionBuilder::GetBytesTotal() const\n{\n \/\/ Adding other outputs can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n return nBytesBase + vecOutputs.size() * nBytesOutput + ::GetSizeOfCompactSizeDiff(0, vecOutputs.size());\n}\n\nCAmount CTransactionBuilder::GetAmountLeft(const CAmount nAmountInitial, const CAmount nAmountUsed, const CAmount nFee)\n{\n return nAmountInitial - nAmountUsed - nFee;\n}\n\nCAmount CTransactionBuilder::GetAmountUsed() const\n{\n CAmount nAmountUsed{0};\n for (const auto& out : vecOutputs) {\n nAmountUsed += out->GetAmount();\n }\n return nAmountUsed;\n}\n\nCAmount CTransactionBuilder::GetFee(unsigned int nBytes) const\n{\n CAmount nFeeCalc = coinControl.m_feerate->GetFee(nBytes);\n CAmount nRequiredFee = GetRequiredFee(nBytes);\n if (nRequiredFee > nFeeCalc) {\n nFeeCalc = nRequiredFee;\n }\n if (nFeeCalc > ::maxTxFee) {\n nFeeCalc = ::maxTxFee;\n }\n return nFeeCalc;\n}\n\nint CTransactionBuilder::GetSizeOfCompactSizeDiff(size_t nAdd) const\n{\n size_t nSize = vecOutputs.size();\n unsigned int ret = ::GetSizeOfCompactSizeDiff(nSize, nSize + nAdd);\n assert(ret <= INT_MAX);\n return (int)ret;\n}\n\nbool CTransactionBuilder::IsDust(CAmount nAmount) const\n{\n return ::IsDust(CTxOut(nAmount, ::GetScriptForDestination(tallyItem.txdest)), coinControl.m_discard_feerate.get());\n}\n\nbool CTransactionBuilder::Commit(std::string& strResult)\n{\n CAmount nFeeRet = 0;\n int nChangePosRet = -1;\n\n \/\/ Transform the outputs to the format CWallet::CreateTransaction requires\n std::vector vecSend;\n {\n LOCK(cs_outputs);\n vecSend.reserve(vecOutputs.size());\n for (const auto& out : vecOutputs) {\n vecSend.push_back((CRecipient){out->GetScript(), out->GetAmount(), false});\n }\n }\n\n CTransactionRef tx;\n if (!pwallet->CreateTransaction(vecSend, tx, dummyReserveKey, nFeeRet, nChangePosRet, strResult, coinControl)) {\n return false;\n }\n\n CAmount nAmountLeft = GetAmountLeft();\n bool fDust = IsDust(nAmountLeft);\n \/\/ If there is a either remainder which is considered to be dust (will be added to fee in this case) or no amount left there should be no change output, return if there is a change output.\n if (nChangePosRet != -1 && fDust) {\n strResult = strprintf(\"Unexpected change output %s at position %d\", tx->vout[nChangePosRet].ToString(), nChangePosRet);\n return false;\n }\n\n \/\/ If there is a remainder which is not considered to be dust it should end up in a change output, return if not.\n if (nChangePosRet == -1 && !fDust) {\n strResult = strprintf(\"Change output missing: %d\", nAmountLeft);\n return false;\n }\n\n CAmount nFeeAdditional{0};\n unsigned int nBytesAdditional{0};\n\n if (fDust) {\n nFeeAdditional = nAmountLeft;\n } else {\n \/\/ Add a change output and GetSizeOfCompactSizeDiff(1) as another output can changes the serialized size of the vout size in CTransaction\n nBytesAdditional = nBytesOutput + GetSizeOfCompactSizeDiff(1);\n }\n\n \/\/ If the calculated fee does not match the fee returned by CreateTransaction aka if this check fails something is wrong!\n CAmount nFeeCalc = GetFee(GetBytesTotal() + nBytesAdditional) + nFeeAdditional;\n if (nFeeRet != nFeeCalc) {\n strResult = strprintf(\"Fee validation failed -> nFeeRet: %d, nFeeCalc: %d, nFeeAdditional: %d, nBytesAdditional: %d, %s\", nFeeRet, nFeeCalc, nFeeAdditional, nBytesAdditional, ToString());\n return false;\n }\n\n CValidationState state;\n if (!pwallet->CommitTransaction(tx, {}, {}, {}, dummyReserveKey, g_connman.get(), state)) {\n strResult = state.GetRejectReason();\n return false;\n }\n\n fKeepKeys = true;\n\n strResult = tx->GetHash().ToString();\n\n return true;\n}\n\nstd::string CTransactionBuilder::ToString() const\n{\n return strprintf(\"CTransactionBuilder(Amount initial: %d, Amount left: %d, Bytes base: %d, Bytes output: %d, Bytes total: %d, Amount used: %d, Outputs: %d, Fee rate: %d, Discard fee rate: %d, Fee: %d)\",\n GetAmountInitial(),\n GetAmountLeft(),\n nBytesBase,\n nBytesOutput,\n GetBytesTotal(),\n GetAmountUsed(),\n CountOutputs(),\n coinControl.m_feerate->GetFeePerK(),\n coinControl.m_discard_feerate->GetFeePerK(),\n GetFee(GetBytesTotal()));\n}\nprivatesend: Avoid interacting with keypool in CTransactionBuilder ctor (#3723)\/\/ Copyright (c) 2014-2019 The Dash Core developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ninline unsigned int GetSizeOfCompactSizeDiff(uint64_t nSizePrev, uint64_t nSizeNew)\n{\n assert(nSizePrev <= nSizeNew);\n return ::GetSizeOfCompactSize(nSizeNew) - ::GetSizeOfCompactSize(nSizePrev);\n}\n\nCKeyHolder::CKeyHolder(CWallet* pwallet) :\n reserveKey(pwallet)\n{\n reserveKey.GetReservedKey(pubKey, false);\n}\n\nvoid CKeyHolder::KeepKey()\n{\n reserveKey.KeepKey();\n}\n\nvoid CKeyHolder::ReturnKey()\n{\n reserveKey.ReturnKey();\n}\n\nCScript CKeyHolder::GetScriptForDestination() const\n{\n return ::GetScriptForDestination(pubKey.GetID());\n}\n\n\nCScript CKeyHolderStorage::AddKey(CWallet* pwallet)\n{\n auto keyHolderPtr = std::unique_ptr(new CKeyHolder(pwallet));\n auto script = keyHolderPtr->GetScriptForDestination();\n\n LOCK(cs_storage);\n storage.emplace_back(std::move(keyHolderPtr));\n LogPrintf(\"CKeyHolderStorage::%s -- storage size %lld\\n\", __func__, storage.size());\n return script;\n}\n\nvoid CKeyHolderStorage::KeepAll()\n{\n std::vector > tmp;\n {\n \/\/ don't hold cs_storage while calling KeepKey(), which might lock cs_wallet\n LOCK(cs_storage);\n std::swap(storage, tmp);\n }\n\n if (!tmp.empty()) {\n for (auto& key : tmp) {\n key->KeepKey();\n }\n LogPrintf(\"CKeyHolderStorage::%s -- %lld keys kept\\n\", __func__, tmp.size());\n }\n}\n\nvoid CKeyHolderStorage::ReturnAll()\n{\n std::vector > tmp;\n {\n \/\/ don't hold cs_storage while calling ReturnKey(), which might lock cs_wallet\n LOCK(cs_storage);\n std::swap(storage, tmp);\n }\n\n if (!tmp.empty()) {\n for (auto& key : tmp) {\n key->ReturnKey();\n }\n LogPrintf(\"CKeyHolderStorage::%s -- %lld keys returned\\n\", __func__, tmp.size());\n }\n}\n\nCTransactionBuilderOutput::CTransactionBuilderOutput(CTransactionBuilder* pTxBuilderIn, CWallet* pwalletIn, CAmount nAmountIn) :\n pTxBuilder(pTxBuilderIn),\n key(pwalletIn),\n nAmount(nAmountIn)\n{\n assert(pTxBuilder);\n CPubKey pubKey;\n key.GetReservedKey(pubKey, false);\n script = ::GetScriptForDestination(pubKey.GetID());\n}\n\nbool CTransactionBuilderOutput::UpdateAmount(const CAmount nNewAmount)\n{\n LOCK(pTxBuilder->cs_outputs);\n if (nNewAmount <= 0 || nNewAmount - nAmount > pTxBuilder->GetAmountLeft()) {\n return false;\n }\n nAmount = nNewAmount;\n return true;\n}\n\nCTransactionBuilder::CTransactionBuilder(CWallet* pwalletIn, const CompactTallyItem& tallyItemIn) :\n pwallet(pwalletIn),\n dummyReserveKey(pwalletIn),\n tallyItem(tallyItemIn)\n{\n \/\/ Generate a feerate which will be used to consider if the remainder is dust and will go into fees or not\n coinControl.m_discard_feerate = ::GetDiscardRate(::feeEstimator);\n \/\/ Generate a feerate which will be used by calculations of this class and also by CWallet::CreateTransaction\n coinControl.m_feerate = std::max(::feeEstimator.estimateSmartFee((int)::nTxConfirmTarget, nullptr, true), payTxFee);\n \/\/ Change always goes back to origin\n coinControl.destChange = tallyItemIn.txdest;\n \/\/ Only allow tallyItems inputs for tx creation\n coinControl.fAllowOtherInputs = false;\n \/\/ Select all tallyItem outputs in the coinControl so that CreateTransaction knows what to use\n for (const auto& outpoint : tallyItem.vecOutPoints) {\n coinControl.Select(outpoint);\n }\n \/\/ Create dummy tx to calculate the exact required fees upfront for accurate amount and fee calculations\n CMutableTransaction dummyTx;\n \/\/ Get a comparable dummy scriptPubKey, avoid writting\/flushing to the actual wallet db\n CScript dummyScript;\n {\n LOCK(pwallet->cs_wallet);\n WalletBatch dummyBatch(pwallet->GetDBHandle(), \"r+\", false);\n dummyBatch.TxnBegin();\n CPubKey dummyPubkey = pwallet->GenerateNewKey(dummyBatch, 0, false);\n dummyBatch.TxnAbort();\n dummyScript = ::GetScriptForDestination(dummyPubkey.GetID());\n }\n \/\/ Create dummy signatures for all inputs\n SignatureData dummySignature;\n ProduceSignature(DummySignatureCreator(pwallet), dummyScript, dummySignature);\n for (auto out : tallyItem.vecOutPoints) {\n dummyTx.vin.emplace_back(out, dummySignature.scriptSig);\n }\n \/\/ Calculate required bytes for the dummy tx with tallyItem's inputs only\n nBytesBase = ::GetSerializeSize(dummyTx, SER_NETWORK, PROTOCOL_VERSION);\n \/\/ Calculate the output size\n nBytesOutput = ::GetSerializeSize(CTxOut(0, dummyScript), SER_NETWORK, PROTOCOL_VERSION);\n \/\/ Just to make sure..\n Clear();\n}\n\nCTransactionBuilder::~CTransactionBuilder()\n{\n Clear();\n}\n\nvoid CTransactionBuilder::Clear()\n{\n std::vector> vecOutputsTmp;\n {\n \/\/ Don't hold cs_outputs while clearing the outputs which might indirectly call lock cs_wallet\n LOCK(cs_outputs);\n std::swap(vecOutputs, vecOutputsTmp);\n vecOutputs.clear();\n }\n\n for (auto& key : vecOutputsTmp) {\n if (fKeepKeys) {\n key->KeepKey();\n } else {\n key->ReturnKey();\n }\n }\n \/\/ Always return this key just to make sure..\n dummyReserveKey.ReturnKey();\n}\n\nbool CTransactionBuilder::CouldAddOutput(CAmount nAmountOutput) const\n{\n if (nAmountOutput < 0) {\n return false;\n }\n \/\/ Adding another output can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n unsigned int nBytes = GetBytesTotal() + nBytesOutput + GetSizeOfCompactSizeDiff(1);\n return GetAmountLeft(GetAmountInitial(), GetAmountUsed() + nAmountOutput, GetFee(nBytes)) >= 0;\n}\n\nbool CTransactionBuilder::CouldAddOutputs(const std::vector& vecOutputAmounts) const\n{\n CAmount nAmountAdditional{0};\n assert(vecOutputAmounts.size() < INT_MAX);\n int nBytesAdditional = nBytesOutput * (int)vecOutputAmounts.size();\n for (const auto nAmountOutput : vecOutputAmounts) {\n if (nAmountOutput < 0) {\n return false;\n }\n nAmountAdditional += nAmountOutput;\n }\n \/\/ Adding other outputs can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n unsigned int nBytes = GetBytesTotal() + nBytesAdditional + GetSizeOfCompactSizeDiff(vecOutputAmounts.size());\n return GetAmountLeft(GetAmountInitial(), GetAmountUsed() + nAmountAdditional, GetFee(nBytes)) >= 0;\n}\n\nCTransactionBuilderOutput* CTransactionBuilder::AddOutput(CAmount nAmountOutput)\n{\n LOCK(cs_outputs);\n if (CouldAddOutput(nAmountOutput)) {\n vecOutputs.push_back(std::make_unique(this, pwallet, nAmountOutput));\n return vecOutputs.back().get();\n }\n return nullptr;\n}\n\nunsigned int CTransactionBuilder::GetBytesTotal() const\n{\n \/\/ Adding other outputs can change the serialized size of the vout size hence + GetSizeOfCompactSizeDiff()\n return nBytesBase + vecOutputs.size() * nBytesOutput + ::GetSizeOfCompactSizeDiff(0, vecOutputs.size());\n}\n\nCAmount CTransactionBuilder::GetAmountLeft(const CAmount nAmountInitial, const CAmount nAmountUsed, const CAmount nFee)\n{\n return nAmountInitial - nAmountUsed - nFee;\n}\n\nCAmount CTransactionBuilder::GetAmountUsed() const\n{\n CAmount nAmountUsed{0};\n for (const auto& out : vecOutputs) {\n nAmountUsed += out->GetAmount();\n }\n return nAmountUsed;\n}\n\nCAmount CTransactionBuilder::GetFee(unsigned int nBytes) const\n{\n CAmount nFeeCalc = coinControl.m_feerate->GetFee(nBytes);\n CAmount nRequiredFee = GetRequiredFee(nBytes);\n if (nRequiredFee > nFeeCalc) {\n nFeeCalc = nRequiredFee;\n }\n if (nFeeCalc > ::maxTxFee) {\n nFeeCalc = ::maxTxFee;\n }\n return nFeeCalc;\n}\n\nint CTransactionBuilder::GetSizeOfCompactSizeDiff(size_t nAdd) const\n{\n size_t nSize = vecOutputs.size();\n unsigned int ret = ::GetSizeOfCompactSizeDiff(nSize, nSize + nAdd);\n assert(ret <= INT_MAX);\n return (int)ret;\n}\n\nbool CTransactionBuilder::IsDust(CAmount nAmount) const\n{\n return ::IsDust(CTxOut(nAmount, ::GetScriptForDestination(tallyItem.txdest)), coinControl.m_discard_feerate.get());\n}\n\nbool CTransactionBuilder::Commit(std::string& strResult)\n{\n CAmount nFeeRet = 0;\n int nChangePosRet = -1;\n\n \/\/ Transform the outputs to the format CWallet::CreateTransaction requires\n std::vector vecSend;\n {\n LOCK(cs_outputs);\n vecSend.reserve(vecOutputs.size());\n for (const auto& out : vecOutputs) {\n vecSend.push_back((CRecipient){out->GetScript(), out->GetAmount(), false});\n }\n }\n\n CTransactionRef tx;\n if (!pwallet->CreateTransaction(vecSend, tx, dummyReserveKey, nFeeRet, nChangePosRet, strResult, coinControl)) {\n return false;\n }\n\n CAmount nAmountLeft = GetAmountLeft();\n bool fDust = IsDust(nAmountLeft);\n \/\/ If there is a either remainder which is considered to be dust (will be added to fee in this case) or no amount left there should be no change output, return if there is a change output.\n if (nChangePosRet != -1 && fDust) {\n strResult = strprintf(\"Unexpected change output %s at position %d\", tx->vout[nChangePosRet].ToString(), nChangePosRet);\n return false;\n }\n\n \/\/ If there is a remainder which is not considered to be dust it should end up in a change output, return if not.\n if (nChangePosRet == -1 && !fDust) {\n strResult = strprintf(\"Change output missing: %d\", nAmountLeft);\n return false;\n }\n\n CAmount nFeeAdditional{0};\n unsigned int nBytesAdditional{0};\n\n if (fDust) {\n nFeeAdditional = nAmountLeft;\n } else {\n \/\/ Add a change output and GetSizeOfCompactSizeDiff(1) as another output can changes the serialized size of the vout size in CTransaction\n nBytesAdditional = nBytesOutput + GetSizeOfCompactSizeDiff(1);\n }\n\n \/\/ If the calculated fee does not match the fee returned by CreateTransaction aka if this check fails something is wrong!\n CAmount nFeeCalc = GetFee(GetBytesTotal() + nBytesAdditional) + nFeeAdditional;\n if (nFeeRet != nFeeCalc) {\n strResult = strprintf(\"Fee validation failed -> nFeeRet: %d, nFeeCalc: %d, nFeeAdditional: %d, nBytesAdditional: %d, %s\", nFeeRet, nFeeCalc, nFeeAdditional, nBytesAdditional, ToString());\n return false;\n }\n\n CValidationState state;\n if (!pwallet->CommitTransaction(tx, {}, {}, {}, dummyReserveKey, g_connman.get(), state)) {\n strResult = state.GetRejectReason();\n return false;\n }\n\n fKeepKeys = true;\n\n strResult = tx->GetHash().ToString();\n\n return true;\n}\n\nstd::string CTransactionBuilder::ToString() const\n{\n return strprintf(\"CTransactionBuilder(Amount initial: %d, Amount left: %d, Bytes base: %d, Bytes output: %d, Bytes total: %d, Amount used: %d, Outputs: %d, Fee rate: %d, Discard fee rate: %d, Fee: %d)\",\n GetAmountInitial(),\n GetAmountLeft(),\n nBytesBase,\n nBytesOutput,\n GetBytesTotal(),\n GetAmountUsed(),\n CountOutputs(),\n coinControl.m_feerate->GetFeePerK(),\n coinControl.m_discard_feerate->GetFeePerK(),\n GetFee(GetBytesTotal()));\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nstatic const string textureNames[]{\"spaceship1.png\",\n \"spaceship2.png\",\n \"spaceship3.png\",\n \"Spaceship-Drakir1.png\",\n \"Spaceship-Drakir2.png\",\n \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\",\n \"Spaceship-Drakir5.png\",\n \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n \"bullet.png\"};\n\nstatic sf::Texture *textures[11];\nstatic sf::Font myfont;\nstatic const string filepath = \"..\\\\res\/img\/\";\n\n#define MAX_ENEMIES 255\nstatic unsigned int currentEnemies = 0;\nstatic sf::Sprite enemies[MAX_ENEMIES];\n\nfloat playerMoveSpeed = 600.0f;\n\nstatic sf::Vector2f GetNewEnemyPos() {\n return sf::Vector2f(rand() % 1024, -128.0f);\n}\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\nsf::Sprite bulletsprite;\nsf::Texture *bulletTexture;\nsf::Text Text;\nvoid Loadcontent() {\n\n\tmyfont.loadFromFile(\"..\\\\res\/fonts\/AmericanCaptain.ttf\");\n\tText.setFont(myfont);\n\tText.setPosition(900,0);\n\tText.setCharacterSize(24);\n\tText.setColor(sf::Color::Red);\n\n\n for (size_t i = 0; i < 11; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Loading error!\");\n }\n }\n\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n bulletsprite.setTexture(*textures[10]);\n bulletsprite.setPosition(0, -128.0f);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(GetNewEnemyPos());\n }\n}\nvoid Normalize(sf::Vector2f &v) {\n auto length = sqrt(v.x * v.x + v.y * v.y);\n if (length == 0.0f) {\n return;\n }\n\n\n \/\/ normalize vector\n v.x \/= length;\n v.y \/= length;\n}\n\nstatic chrono::high_resolution_clock::time_point previous;\nstatic unsigned int score = 0;\n\nvoid Update(sf::RenderWindow &window) {\n\n chrono::high_resolution_clock::time_point now =\n chrono::high_resolution_clock::now();\n const unsigned int delta =\n (std::chrono::duration_cast>(\n now - previous))\n .count();\n\n const double deltaPercent =\n (((double)delta) \/ 1000000000.0); \/\/ delta as a percentage of 1 second\n previous = now;\n static float tick = 0.0f;\n tick += deltaPercent;\n currentEnemies = (unsigned int)ceil(tick * 0.6f) + 1;\n\n \/\/ cout << score << \" - \" << currentEnemies << \" - \" << delta << \" - \" <<\n \/\/ deltaPercent << endl;\n\n sf::Event e;\n sf::Vector2f moveDirection(0, 0);\n\n while (window.pollEvent(e)) {\n\t\n if (e.type == sf::Event::Closed)\n window.close();\n\n \/\/ keyboard event handling\n if (e.type == sf::Event::KeyPressed) {\n if (e.key.code == sf::Keyboard::Escape) {\n window.close();\n }\n if (e.key.code == sf::Keyboard::W || e.key.code == sf::Keyboard::Up) {\n moveDirection += sf::Vector2f(0, -1);\n }\n if (e.key.code == sf::Keyboard::S || e.key.code == sf::Keyboard::Down) {\n moveDirection += sf::Vector2f(0, 1);\n }\n if (e.key.code == sf::Keyboard::A || e.key.code == sf::Keyboard::Left) {\n moveDirection += sf::Vector2f(-1, 0);\n }\n if (e.key.code == sf::Keyboard::D || e.key.code == sf::Keyboard::Right) {\n moveDirection += sf::Vector2f(1, 0);\n }\n\t if (bulletsprite.getPosition().y <= -128.0f && e.key.code == sf::Keyboard::Space)\n\t {\n\t\t bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n\t\t\t playerSprite.getPosition().y - 1);\n\t }\n }\n \/\/ if the B button is pressed fire a bullet\n if (e.JoystickButtonPressed) {\n\n if (bulletsprite.getPosition().y <= -128.0f &&\n sf::Joystick::isButtonPressed(0, 1)) {\n bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n playerSprite.getPosition().y - 1);\n }\n }\n }\n\n \/\/ joystick input\n if (sf::Joystick::isConnected(0)) {\n float joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n float joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n if (abs(joystickX) > 40.0f) {\n moveDirection += sf::Vector2f(((signbit(joystickX)) * -2) + 1, 0);\n }\n if (abs(joystickY) > 40.0f) {\n moveDirection += sf::Vector2f(0, ((signbit(joystickY)) * -2) + 1);\n }\n }\n\n Normalize(moveDirection);\n moveDirection = (moveDirection * playerMoveSpeed) * (float)deltaPercent;\n\n playerSprite.setPosition(playerSprite.getPosition() + moveDirection);\n\n if (bulletsprite.getPosition().y > -128.0f) {\n bulletsprite.setPosition(bulletsprite.getPosition().x,\n bulletsprite.getPosition().y -\n 1000.0 * deltaPercent);\n }\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n if (i < currentEnemies) {\n \/\/ if not dead, move\n if (enemies[i].getPosition().y < 700.0) {\n enemies[i].setPosition(\n enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i) * 100.0 * deltaPercent,\n 100.0 * deltaPercent));\n \/\/ collisions\n if (bulletsprite.getGlobalBounds().intersects(\n enemies[i].getGlobalBounds())) {\n enemies[i].setPosition(GetNewEnemyPos());\n score += 100;\n }\n } else {\n \/\/ offscreen kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n } else {\n \/\/ if alive\n if (enemies[i].getPosition().y != -128.0f) {\n \/\/ kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n }\n }\n\n Text.setString(\"Score =\" + to_string(score + ceil(tick)));\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n window.draw(playerSprite);\n window.draw(bulletsprite);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n window.draw(enemies[i]);\n }\n\n\n window.draw(Text);\n window.display();\n \n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n previous = chrono::high_resolution_clock::now();\n while (window.isOpen()) {\n Update(window);\n Render(window);\n }\n return 0;\n}tracking enemies killed as they are being hit by the bullet before on screen#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nstatic const string textureNames[]{\"spaceship1.png\",\n \"spaceship2.png\",\n \"spaceship3.png\",\n \"Spaceship-Drakir1.png\",\n \"Spaceship-Drakir2.png\",\n \"Spaceship-Drakir3.png\",\n \"Spaceship-Drakir4.png\",\n \"Spaceship-Drakir5.png\",\n \"Spaceship-Drakir6.png\",\n \"Spaceship-Drakir7.png\",\n \"bullet.png\"};\n\nstatic sf::Texture *textures[11];\nstatic sf::Font myfont;\nstatic const string filepath = \"..\\\\res\/img\/\";\n\n#define MAX_ENEMIES 255\nstatic unsigned int currentEnemies = 0;\nstatic sf::Sprite enemies[MAX_ENEMIES];\n\nfloat playerMoveSpeed = 600.0f;\n int killedeneimies = 0;\nstatic sf::Vector2f GetNewEnemyPos() {\n return sf::Vector2f(rand() % 1024, -128.0f);\n}\n\nsf::Sprite playerSprite;\nsf::Texture *playerTexture;\nsf::Sprite bulletsprite;\nsf::Texture *bulletTexture;\nsf::Text Text;\nvoid Loadcontent() {\n\n\tmyfont.loadFromFile(\"..\\\\res\/fonts\/AmericanCaptain.ttf\");\n\tText.setFont(myfont);\n\tText.setPosition(700,0);\n\tText.setCharacterSize(24);\n\tText.setColor(sf::Color::Red);\n\n\n for (size_t i = 0; i < 11; i++) {\n textures[i] = new sf::Texture();\n if (!textures[i]->loadFromFile(filepath + textureNames[i])) {\n throw invalid_argument(\"Loading error!\");\n }\n }\n\n playerSprite.setTexture(*textures[0]);\n playerSprite.setPosition(512, 256);\n bulletsprite.setTexture(*textures[10]);\n bulletsprite.setPosition(0, -128.0f);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n enemies[i].setTexture(*textures[(i % 7) + 3]);\n enemies[i].setPosition(GetNewEnemyPos());\n }\n}\nvoid Normalize(sf::Vector2f &v) {\n auto length = sqrt(v.x * v.x + v.y * v.y);\n if (length == 0.0f) {\n return;\n }\n\n\n \/\/ normalize vector\n v.x \/= length;\n v.y \/= length;\n}\n\nstatic chrono::high_resolution_clock::time_point previous;\nstatic unsigned int score = 0;\n\nvoid Update(sf::RenderWindow &window) {\n\n chrono::high_resolution_clock::time_point now =\n chrono::high_resolution_clock::now();\n const unsigned int delta =\n (std::chrono::duration_cast>(\n now - previous))\n .count();\n\n const double deltaPercent =\n (((double)delta) \/ 1000000000.0); \/\/ delta as a percentage of 1 second\n previous = now;\n static float tick = 0.0f;\n tick += deltaPercent;\n currentEnemies = (unsigned int)ceil(tick * 0.6f) + 1;\n\n \/\/ cout << score << \" - \" << currentEnemies << \" - \" << delta << \" - \" <<\n \/\/ deltaPercent << endl;\n\n sf::Event e;\n sf::Vector2f moveDirection(0, 0);\n\n while (window.pollEvent(e)) {\n\t\n if (e.type == sf::Event::Closed)\n window.close();\n\n \/\/ keyboard event handling\n if (e.type == sf::Event::KeyPressed) {\n if (e.key.code == sf::Keyboard::Escape) {\n window.close();\n }\n if (e.key.code == sf::Keyboard::W || e.key.code == sf::Keyboard::Up) {\n moveDirection += sf::Vector2f(0, -1);\n }\n if (e.key.code == sf::Keyboard::S || e.key.code == sf::Keyboard::Down) {\n moveDirection += sf::Vector2f(0, 1);\n }\n if (e.key.code == sf::Keyboard::A || e.key.code == sf::Keyboard::Left) {\n moveDirection += sf::Vector2f(-1, 0);\n }\n if (e.key.code == sf::Keyboard::D || e.key.code == sf::Keyboard::Right) {\n moveDirection += sf::Vector2f(1, 0);\n }\n\t if (bulletsprite.getPosition().y <= -128.0f && e.key.code == sf::Keyboard::Space)\n\t {\n\t\t bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n\t\t\t playerSprite.getPosition().y - 1);\n\t }\n }\n \/\/ if the B button is pressed fire a bullet\n if (e.JoystickButtonPressed) {\n\n if (bulletsprite.getPosition().y <= -128.0f &&\n sf::Joystick::isButtonPressed(0, 1)) {\n bulletsprite.setPosition(playerSprite.getPosition().x + 30,\n playerSprite.getPosition().y - 1);\n }\n }\n }\n\n \/\/ joystick input\n if (sf::Joystick::isConnected(0)) {\n float joystickX = sf::Joystick::getAxisPosition(0, sf::Joystick::X);\n float joystickY = sf::Joystick::getAxisPosition(0, sf::Joystick::Y);\n\n if (abs(joystickX) > 40.0f) {\n moveDirection += sf::Vector2f(((signbit(joystickX)) * -2) + 1, 0);\n }\n if (abs(joystickY) > 40.0f) {\n moveDirection += sf::Vector2f(0, ((signbit(joystickY)) * -2) + 1);\n }\n }\n\n Normalize(moveDirection);\n moveDirection = (moveDirection * playerMoveSpeed) * (float)deltaPercent;\n\n playerSprite.setPosition(playerSprite.getPosition() + moveDirection);\n\n if (bulletsprite.getPosition().y > -128.0f) {\n bulletsprite.setPosition(bulletsprite.getPosition().x,\n bulletsprite.getPosition().y -\n 1000.0 * deltaPercent);\n }\n\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n if (i < currentEnemies) {\n \/\/ if not dead, move\n if (enemies[i].getPosition().y < 700.0) {\n enemies[i].setPosition(\n enemies[i].getPosition() +\n sf::Vector2f(sinf(tick + i) * 100.0 * deltaPercent,\n 100.0 * deltaPercent));\n \/\/ collisions\n if (bulletsprite.getGlobalBounds().intersects(\n enemies[i].getGlobalBounds())) {\n enemies[i].setPosition(GetNewEnemyPos());\n score += 100;\n\t\t killedeneimies += 1;\n }\n } else {\n \/\/ offscreen kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n } else {\n \/\/ if alive\n if (enemies[i].getPosition().y != -128.0f) {\n \/\/ kill\n enemies[i].setPosition(GetNewEnemyPos());\n }\n }\n }\n\n Text.setString(\"Score =\" + to_string(score + ceil(tick)) + \"\\n\" + \"number of enemies destroyed =\" + to_string(killedeneimies));\n}\n\nvoid Render(sf::RenderWindow &window) {\n window.clear();\n window.draw(playerSprite);\n window.draw(bulletsprite);\n for (size_t i = 0; i < MAX_ENEMIES; i++) {\n window.draw(enemies[i]);\n }\n\n\n window.draw(Text);\n window.display();\n \n}\n\nint main() {\n Loadcontent();\n sf::RenderWindow window(sf::VideoMode(1024, 768), \"Main Window\");\n window.setVerticalSyncEnabled(true);\n previous = chrono::high_resolution_clock::now();\n while (window.isOpen()) {\n\n\tUpdate(window);\n Render(window);\n }\n return 0;\n}<|endoftext|>"} {"text":"#include \"MemoryView.h\"\n#include \"ui_MemoryView.h\"\n#include \"Backend\/IBackendRequests.h\"\n\n#include \n#include \n\nnamespace prodbg {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate \nstatic void enumToCombo(QComboBox* combo, int startValue)\n{\n QMetaEnum me = QMetaEnum::fromType();\n\n for (int i = 0; i < me.keyCount(); ++i) {\n combo->addItem(QString::fromUtf8(me.key(i)));\n }\n\n combo->setCurrentIndex(startValue);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMemoryView::MemoryView(QWidget* parent)\n : Base(parent)\n , m_Ui(new Ui_MemoryView)\n{\n m_Ui->setupUi(this);\n\n connect(m_Ui->m_Address, &QLineEdit::returnPressed, this, &MemoryView::jumpAddressChanged);\n\n enumToCombo(m_Ui->m_Endianess, m_Ui->m_View->endianess());\n enumToCombo(m_Ui->m_Type, m_Ui->m_View->dataType());\n\n connect(m_Ui->m_Endianess, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::endianChanged);\n connect(m_Ui->m_Type, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::dataTypeChanged);\n\n QIntValidator* countValidator = new QIntValidator(1, 64, this);\n m_Ui->m_Count->setValidator(countValidator);\n\n connect(m_Ui->m_Count, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::countChanged);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMemoryView::~MemoryView()\n{\n printf(\"destruct MemoryView\\n\");\n delete m_Ui;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::endianChanged(int e)\n{\n m_Ui->m_View->setEndianess(static_cast(e));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::interfaceSet()\n{\n m_Ui->m_View->setBackendInterface(m_interface);\n\n if (m_interface) {\n connect(m_interface, &IBackendRequests::endResolveAddress, this, &MemoryView::endResolveAddress);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::dataTypeChanged(int t)\n{\n m_Ui->m_View->setDataType(static_cast(t));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::jumpAddressChanged()\n{\n jumpToAddressExpression(m_Ui->m_Address->text());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::jumpToAddressExpression(const QString& str)\n{\n if (m_interface) {\n m_interface->beginResolveAddress(str, &m_evalAddress);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::endResolveAddress(uint64_t* out)\n{\n if (!out) {\n m_Ui->m_View->setExpressionStatus(false);\n } else {\n m_Ui->m_View->setExpressionStatus(true);\n m_Ui->m_Address->setText(QStringLiteral(\"0x\") + QString::number(*out, 16));\n m_Ui->m_View->setAddress(*out);\n }\n\n m_Ui->m_View->update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::countChanged(const QString& text)\n{\n bool ok = false;\n int count = text.toInt(&ok, \/*base:*\/ 0);\n if (ok) {\n m_Ui->m_View->setElementsPerLine(count);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nvoid MemoryView::readSettings()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::writeSettings()\n{\n}\n\n}\nSave type and endian#include \"MemoryView.h\"\n#include \"ui_MemoryView.h\"\n#include \"Backend\/IBackendRequests.h\"\n#include \n#include \n#include \n\nnamespace prodbg {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate \nstatic void enumToCombo(QComboBox* combo, int startValue)\n{\n QMetaEnum me = QMetaEnum::fromType();\n\n for (int i = 0; i < me.keyCount(); ++i) {\n combo->addItem(QString::fromUtf8(me.key(i)));\n }\n\n combo->setCurrentIndex(startValue);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMemoryView::MemoryView(QWidget* parent)\n : Base(parent)\n , m_Ui(new Ui_MemoryView)\n{\n m_Ui->setupUi(this);\n\n connect(m_Ui->m_Address, &QLineEdit::returnPressed, this, &MemoryView::jumpAddressChanged);\n\n enumToCombo(m_Ui->m_Endianess, m_Ui->m_View->endianess());\n enumToCombo(m_Ui->m_Type, m_Ui->m_View->dataType());\n\n connect(m_Ui->m_Endianess, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::endianChanged);\n connect(m_Ui->m_Type, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::dataTypeChanged);\n\n QIntValidator* countValidator = new QIntValidator(1, 64, this);\n m_Ui->m_Count->setValidator(countValidator);\n\n connect(m_Ui->m_Count, static_cast(&QComboBox::currentIndexChanged), this,\n &MemoryView::countChanged);\n\n readSettings();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nMemoryView::~MemoryView()\n{\n writeSettings();\n printf(\"destruct MemoryView\\n\");\n delete m_Ui;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::endianChanged(int e)\n{\n m_Ui->m_View->setEndianess(static_cast(e));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::interfaceSet()\n{\n m_Ui->m_View->setBackendInterface(m_interface);\n\n if (m_interface) {\n connect(m_interface, &IBackendRequests::endResolveAddress, this, &MemoryView::endResolveAddress);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::dataTypeChanged(int t)\n{\n m_Ui->m_View->setDataType(static_cast(t));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::jumpAddressChanged()\n{\n jumpToAddressExpression(m_Ui->m_Address->text());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::jumpToAddressExpression(const QString& str)\n{\n if (m_interface) {\n m_interface->beginResolveAddress(str, &m_evalAddress);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::endResolveAddress(uint64_t* out)\n{\n if (!out) {\n m_Ui->m_View->setExpressionStatus(false);\n } else {\n m_Ui->m_View->setExpressionStatus(true);\n m_Ui->m_Address->setText(QStringLiteral(\"0x\") + QString::number(*out, 16));\n m_Ui->m_View->setAddress(*out);\n }\n\n m_Ui->m_View->update();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::countChanged(const QString& text)\n{\n bool ok = false;\n int count = text.toInt(&ok, \/*base:*\/ 0);\n if (ok) {\n m_Ui->m_View->setElementsPerLine(count);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \nvoid MemoryView::readSettings()\n{\n QSettings settings(QStringLiteral(\"TBL\"), QStringLiteral(\"ProDBG\"));\n\n \/\/ TODO: Support more than one memory view\n settings.beginGroup(QStringLiteral(\"MemoryView_0\"));\n m_Ui->m_Endianess->setCurrentIndex(settings.value(QStringLiteral(\"endian\")).toInt());\n m_Ui->m_Type->setCurrentIndex(settings.value(QStringLiteral(\"data_type\")).toInt());\n settings.endGroup();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MemoryView::writeSettings()\n{\n QSettings settings(QStringLiteral(\"TBL\"), QStringLiteral(\"ProDBG\"));\n\n \/\/ TODO: Support more than one memory view\n settings.beginGroup(QStringLiteral(\"MemoryView_0\"));\n settings.setValue(QStringLiteral(\"endian\"), m_Ui->m_Endianess->currentIndex());\n settings.setValue(QStringLiteral(\"data_type\"), m_Ui->m_Type->currentIndex());\n settings.setValue(QStringLiteral(\"count\"), m_Ui->m_Type->currentIndex());\n settings.endGroup();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n}\n<|endoftext|>"} {"text":"\/*\n\/\/ $Id$\n\/\/ Fennel is a library of data storage and processing components.\n\/\/ Copyright (C) 2005-2005 The Eigenbase Project\n\/\/ Copyright (C) 2003-2005 Disruptive Tech\n\/\/ Copyright (C) 2005-2005 LucidEra, Inc.\n\/\/ Portions Copyright (C) 1999-2005 John V. Sichi\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU General Public License as published by the Free\n\/\/ Software Foundation; either version 2 of the License, or (at your option)\n\/\/ any later version approved by The Eigenbase Project.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\n#include \"fennel\/common\/CommonPreamble.h\"\n#include \"fennel\/farrago\/CmdInterpreter.h\"\n#include \"fennel\/farrago\/JavaTraceTarget.h\"\n#include \"fennel\/exec\/ExecStreamGraphEmbryo.h\"\n#include \"fennel\/farrago\/ExecStreamBuilder.h\"\n#include \"fennel\/cache\/CacheParams.h\"\n#include \"fennel\/common\/ConfigMap.h\"\n#include \"fennel\/common\/FennelExcn.h\"\n#include \"fennel\/btree\/BTreeBuilder.h\"\n#include \"fennel\/db\/Database.h\"\n#include \"fennel\/db\/CheckpointThread.h\"\n#include \"fennel\/txn\/LogicalTxn.h\"\n#include \"fennel\/txn\/LogicalTxnLog.h\"\n#include \"fennel\/tuple\/StoredTypeDescriptorFactory.h\"\n#include \"fennel\/segment\/SegmentFactory.h\"\n#include \"fennel\/exec\/DfsTreeExecStreamScheduler.h\"\n#include \"fennel\/exec\/ExecStreamGraph.h\"\n#include \"fennel\/farrago\/ExecStreamFactory.h\"\n#include \"fennel\/ftrs\/FtrsTableWriterFactory.h\"\n\nFENNEL_BEGIN_CPPFILE(\"$Id$\");\n\nint64_t CmdInterpreter::executeCommand(\n ProxyCmd &cmd)\n{\n resultHandle = 0;\n \/\/ dispatch based on polymorphic command type\n FemVisitor::visitTbl.accept(*this,cmd);\n return resultHandle;\n}\n\nCmdInterpreter::DbHandle *CmdInterpreter::getDbHandle(\n SharedProxyDbHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nCmdInterpreter::TxnHandle *CmdInterpreter::getTxnHandle(\n SharedProxyTxnHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nCmdInterpreter::StreamGraphHandle *CmdInterpreter::getStreamGraphHandle(\n SharedProxyStreamGraphHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nSavepointId CmdInterpreter::getSavepointId(SharedProxySvptHandle pHandle)\n{\n return SavepointId(pHandle->getLongHandle());\n}\n\nvoid CmdInterpreter::setDbHandle(\n SharedProxyDbHandle,DbHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setTxnHandle(\n SharedProxyTxnHandle,TxnHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setStreamGraphHandle(\n SharedProxyStreamGraphHandle,StreamGraphHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setExecStreamHandle(\n SharedProxyStreamHandle,ExecStream *pStream)\n{\n resultHandle = reinterpret_cast(pStream);\n}\n\nvoid CmdInterpreter::setSvptHandle(\n SharedProxySvptHandle,SavepointId svptId)\n{\n resultHandle = opaqueToInt(svptId);\n}\n\nCmdInterpreter::DbHandle* CmdInterpreter::newDbHandle()\n{\n return new DbHandle();\n}\n\nCmdInterpreter::TxnHandle* CmdInterpreter::newTxnHandle()\n{\n return new TxnHandle();\n}\n\nCmdInterpreter::DbHandle::~DbHandle()\n{\n statsTimer.stop();\n \n \/\/ close database before trace\n pDb->close();\n --JniUtil::handleCount;\n}\n \nCmdInterpreter::TxnHandle::~TxnHandle()\n{\n --JniUtil::handleCount;\n}\n \nCmdInterpreter::StreamGraphHandle::~StreamGraphHandle()\n{\n if (javaRuntimeContext) {\n JniEnvAutoRef pEnv;\n pEnv->DeleteGlobalRef(javaRuntimeContext);\n }\n --JniUtil::handleCount;\n}\n \nvoid CmdInterpreter::visit(ProxyCmdOpenDatabase &cmd)\n{\n ConfigMap configMap;\n\n SharedProxyDatabaseParam pParam = cmd.getParams();\n for (; pParam; ++pParam) {\n configMap.setStringParam(pParam->getName(),pParam->getValue());\n }\n\n CacheParams cacheParams;\n cacheParams.readConfig(configMap);\n SharedCache pCache = Cache::newCache(cacheParams);\n\n DeviceMode openMode = cmd.isCreateDatabase()\n ? DeviceMode::createNew\n : DeviceMode::load;\n \n jobject javaTrace = getObjectFromLong(cmd.getJavaTraceHandle());\n\n std::auto_ptr pDbHandle(newDbHandle());\n ++JniUtil::handleCount;\n pDbHandle->pTraceTarget.reset(new JavaTraceTarget(javaTrace));\n\n SharedDatabase pDb = Database::newDatabase(\n pCache,\n configMap,\n openMode,\n pDbHandle->pTraceTarget.get());\n\n pDbHandle->pDb = pDb;\n\n pDbHandle->statsTimer.addSource(pDb);\n pDbHandle->statsTimer.start();\n\n if (pDb->isRecoveryRequired()) {\n SegmentAccessor scratchAccessor =\n pDb->getSegmentFactory()->newScratchSegment(pDb->getCache());\n FtrsTableWriterFactory recoveryFactory(\n pDb,\n pDb->getCache(),\n pDb->getTypeFactory(),\n scratchAccessor);\n pDb->recover(recoveryFactory);\n }\n setDbHandle(cmd.getResultHandle(),pDbHandle.release());\n}\n \nvoid CmdInterpreter::visit(ProxyCmdCloseDatabase &cmd)\n{\n DbHandle *pDbHandle = getDbHandle(cmd.getDbHandle());\n deleteAndNullify(pDbHandle);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCheckpoint &cmd)\n{\n DbHandle *pDbHandle = getDbHandle(cmd.getDbHandle());\n\n pDbHandle->pDb->requestCheckpoint(\n cmd.isFuzzy() ? CHECKPOINT_FLUSH_FUZZY : CHECKPOINT_FLUSH_ALL,\n cmd.isAsync());\n}\n \nvoid CmdInterpreter::getBTreeForIndexCmd(\n ProxyIndexCmd &cmd,PageId rootPageId,BTreeDescriptor &treeDescriptor)\n{\n SharedDatabase pDatabase = getDbHandle(cmd.getDbHandle())->pDb;\n \n readTupleDescriptor(\n treeDescriptor.tupleDescriptor,\n *(cmd.getTupleDesc()),pDatabase->getTypeFactory());\n \n CmdInterpreter::readTupleProjection(\n treeDescriptor.keyProjection,cmd.getKeyProj());\n\n treeDescriptor.pageOwnerId = PageOwnerId(cmd.getIndexId());\n treeDescriptor.segmentId = SegmentId(cmd.getSegmentId());\n treeDescriptor.segmentAccessor.pSegment =\n pDatabase->getSegmentById(treeDescriptor.segmentId);\n treeDescriptor.segmentAccessor.pCacheAccessor = pDatabase->getCache();\n treeDescriptor.rootPageId = rootPageId;\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,NULL_PAGE_ID,treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.createEmptyRoot();\n resultHandle = opaqueToInt(builder.getRootPageId());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdTruncateIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,PageId(cmd.getRootPageId()),treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.truncate(false);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdDropIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,PageId(cmd.getRootPageId()),treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.truncate(true);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdBeginTxn &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n\n std::auto_ptr pTxnHandle(newTxnHandle());\n ++JniUtil::handleCount;\n pTxnHandle->pDb = pDb;\n \/\/ TODO: CacheAccessor factory\n pTxnHandle->pTxn = pDb->getTxnLog()->newLogicalTxn(pDb->getCache());\n \n \/\/ NOTE: use a null scratchAccessor; individual ExecStreamGraphs\n \/\/ will have their own\n SegmentAccessor scratchAccessor;\n \n pTxnHandle->pFtrsTableWriterFactory = SharedFtrsTableWriterFactory(\n new FtrsTableWriterFactory(\n pDb,\n pDb->getCache(),\n pDb->getTypeFactory(),\n scratchAccessor));\n setTxnHandle(cmd.getResultHandle(),pTxnHandle.release());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdSavepoint &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n \n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n setSvptHandle(\n cmd.getResultHandle(),\n pTxnHandle->pTxn->createSavepoint());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCommit &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n\n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n if (cmd.getSvptHandle()) {\n SavepointId svptId = getSavepointId(cmd.getSvptHandle());\n pTxnHandle->pTxn->commitSavepoint(svptId);\n } else {\n pTxnHandle->pTxn->commit();\n deleteAndNullify(pTxnHandle);\n }\n}\n\nvoid CmdInterpreter::visit(ProxyCmdRollback &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n\n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n if (cmd.getSvptHandle()) {\n SavepointId svptId = getSavepointId(cmd.getSvptHandle());\n pTxnHandle->pTxn->rollback(&svptId);\n } else {\n pTxnHandle->pTxn->rollback();\n deleteAndNullify(pTxnHandle);\n }\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateExecutionStreamGraph &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n SharedExecStreamGraph pGraph =\n ExecStreamGraph::newExecStreamGraph();\n pGraph->setTxn(pTxnHandle->pTxn);\n std::auto_ptr pStreamGraphHandle(\n new StreamGraphHandle());\n ++JniUtil::handleCount;\n pStreamGraphHandle->pTxnHandle = pTxnHandle;\n pStreamGraphHandle->pExecStreamGraph = pGraph;\n pStreamGraphHandle->pExecStreamFactory.reset(\n new ExecStreamFactory(\n pTxnHandle->pDb,\n pTxnHandle->pFtrsTableWriterFactory,\n pStreamGraphHandle.get()));\n setStreamGraphHandle(\n cmd.getResultHandle(),\n pStreamGraphHandle.release());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdPrepareExecutionStreamGraph &cmd)\n{\n StreamGraphHandle *pStreamGraphHandle = getStreamGraphHandle(\n cmd.getStreamGraphHandle());\n TxnHandle *pTxnHandle = pStreamGraphHandle->pTxnHandle;\n \/\/ NOTE: sequence is important here\n SharedExecStreamScheduler pScheduler(\n new DfsTreeExecStreamScheduler(\n &(pTxnHandle->pDb->getTraceTarget()),\n \"xo.scheduler\"));\n ExecStreamGraphEmbryo graphEmbryo(\n pStreamGraphHandle->pExecStreamGraph,\n pScheduler,\n pTxnHandle->pDb->getCache(),\n pTxnHandle->pDb->getSegmentFactory(), \n pStreamGraphHandle->pExecStreamFactory->shouldEnforceCacheQuotas());\n pStreamGraphHandle->pExecStreamFactory->setGraphEmbryo(graphEmbryo);\n ExecStreamBuilder streamBuilder(\n graphEmbryo, \n *(pStreamGraphHandle->pExecStreamFactory));\n streamBuilder.buildStreamGraph(cmd, true);\n pStreamGraphHandle->pExecStreamFactory.reset();\n pStreamGraphHandle->pScheduler = pScheduler;\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateStreamHandle &cmd)\n{\n StreamGraphHandle *pStreamGraphHandle = getStreamGraphHandle(\n cmd.getStreamGraphHandle());\n SharedExecStream pStream =\n pStreamGraphHandle->pExecStreamGraph->findLastStream(\n cmd.getStreamName(), 0);\n setExecStreamHandle(\n cmd.getResultHandle(),\n pStream.get());\n}\n\nPageId CmdInterpreter::StreamGraphHandle::getRoot(PageOwnerId pageOwnerId)\n{\n JniEnvAutoRef pEnv;\n jlong x = opaqueToInt(pageOwnerId);\n x = pEnv->CallLongMethod(\n javaRuntimeContext,JniUtil::methGetIndexRoot,x);\n return PageId(x);\n}\n\nvoid CmdInterpreter::readTupleDescriptor(\n TupleDescriptor &tupleDesc,\n ProxyTupleDescriptor &javaTupleDesc,\n StoredTypeDescriptorFactory const &typeFactory)\n{\n tupleDesc.clear();\n SharedProxyTupleAttrDescriptor pAttr = javaTupleDesc.getAttrDescriptor();\n for (; pAttr; ++pAttr) {\n StoredTypeDescriptor const &typeDescriptor = \n typeFactory.newDataType(pAttr->getTypeOrdinal());\n tupleDesc.push_back(\n TupleAttributeDescriptor(\n typeDescriptor,pAttr->isNullable(),pAttr->getByteLength()));\n }\n}\n\nvoid CmdInterpreter::readTupleProjection(\n TupleProjection &tupleProj,\n SharedProxyTupleProjection pJavaTupleProj)\n{\n tupleProj.clear();\n SharedProxyTupleAttrProjection pAttr = pJavaTupleProj->getAttrProjection();\n for (; pAttr; ++pAttr) {\n tupleProj.push_back(pAttr->getAttributeIndex());\n }\n}\n\nFENNEL_END_CPPFILE(\"$Id$\");\n\n\/\/ End CmdInterpreter.cpp\nFARRAGO: initialize javaRuntimeContext just in case; should be in a constructor instead\/*\n\/\/ $Id$\n\/\/ Fennel is a library of data storage and processing components.\n\/\/ Copyright (C) 2005-2005 The Eigenbase Project\n\/\/ Copyright (C) 2003-2005 Disruptive Tech\n\/\/ Copyright (C) 2005-2005 LucidEra, Inc.\n\/\/ Portions Copyright (C) 1999-2005 John V. Sichi\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify it\n\/\/ under the terms of the GNU General Public License as published by the Free\n\/\/ Software Foundation; either version 2 of the License, or (at your option)\n\/\/ any later version approved by The Eigenbase Project.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\/\n\n#include \"fennel\/common\/CommonPreamble.h\"\n#include \"fennel\/farrago\/CmdInterpreter.h\"\n#include \"fennel\/farrago\/JavaTraceTarget.h\"\n#include \"fennel\/exec\/ExecStreamGraphEmbryo.h\"\n#include \"fennel\/farrago\/ExecStreamBuilder.h\"\n#include \"fennel\/cache\/CacheParams.h\"\n#include \"fennel\/common\/ConfigMap.h\"\n#include \"fennel\/common\/FennelExcn.h\"\n#include \"fennel\/btree\/BTreeBuilder.h\"\n#include \"fennel\/db\/Database.h\"\n#include \"fennel\/db\/CheckpointThread.h\"\n#include \"fennel\/txn\/LogicalTxn.h\"\n#include \"fennel\/txn\/LogicalTxnLog.h\"\n#include \"fennel\/tuple\/StoredTypeDescriptorFactory.h\"\n#include \"fennel\/segment\/SegmentFactory.h\"\n#include \"fennel\/exec\/DfsTreeExecStreamScheduler.h\"\n#include \"fennel\/exec\/ExecStreamGraph.h\"\n#include \"fennel\/farrago\/ExecStreamFactory.h\"\n#include \"fennel\/ftrs\/FtrsTableWriterFactory.h\"\n\nFENNEL_BEGIN_CPPFILE(\"$Id$\");\n\nint64_t CmdInterpreter::executeCommand(\n ProxyCmd &cmd)\n{\n resultHandle = 0;\n \/\/ dispatch based on polymorphic command type\n FemVisitor::visitTbl.accept(*this,cmd);\n return resultHandle;\n}\n\nCmdInterpreter::DbHandle *CmdInterpreter::getDbHandle(\n SharedProxyDbHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nCmdInterpreter::TxnHandle *CmdInterpreter::getTxnHandle(\n SharedProxyTxnHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nCmdInterpreter::StreamGraphHandle *CmdInterpreter::getStreamGraphHandle(\n SharedProxyStreamGraphHandle pHandle)\n{\n return reinterpret_cast(pHandle->getLongHandle());\n}\n\nSavepointId CmdInterpreter::getSavepointId(SharedProxySvptHandle pHandle)\n{\n return SavepointId(pHandle->getLongHandle());\n}\n\nvoid CmdInterpreter::setDbHandle(\n SharedProxyDbHandle,DbHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setTxnHandle(\n SharedProxyTxnHandle,TxnHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setStreamGraphHandle(\n SharedProxyStreamGraphHandle,StreamGraphHandle *pHandle)\n{\n resultHandle = reinterpret_cast(pHandle);\n}\n\nvoid CmdInterpreter::setExecStreamHandle(\n SharedProxyStreamHandle,ExecStream *pStream)\n{\n resultHandle = reinterpret_cast(pStream);\n}\n\nvoid CmdInterpreter::setSvptHandle(\n SharedProxySvptHandle,SavepointId svptId)\n{\n resultHandle = opaqueToInt(svptId);\n}\n\nCmdInterpreter::DbHandle* CmdInterpreter::newDbHandle()\n{\n return new DbHandle();\n}\n\nCmdInterpreter::TxnHandle* CmdInterpreter::newTxnHandle()\n{\n return new TxnHandle();\n}\n\nCmdInterpreter::DbHandle::~DbHandle()\n{\n statsTimer.stop();\n \n \/\/ close database before trace\n pDb->close();\n --JniUtil::handleCount;\n}\n \nCmdInterpreter::TxnHandle::~TxnHandle()\n{\n --JniUtil::handleCount;\n}\n \nCmdInterpreter::StreamGraphHandle::~StreamGraphHandle()\n{\n if (javaRuntimeContext) {\n JniEnvAutoRef pEnv;\n pEnv->DeleteGlobalRef(javaRuntimeContext);\n }\n --JniUtil::handleCount;\n}\n \nvoid CmdInterpreter::visit(ProxyCmdOpenDatabase &cmd)\n{\n ConfigMap configMap;\n\n SharedProxyDatabaseParam pParam = cmd.getParams();\n for (; pParam; ++pParam) {\n configMap.setStringParam(pParam->getName(),pParam->getValue());\n }\n\n CacheParams cacheParams;\n cacheParams.readConfig(configMap);\n SharedCache pCache = Cache::newCache(cacheParams);\n\n DeviceMode openMode = cmd.isCreateDatabase()\n ? DeviceMode::createNew\n : DeviceMode::load;\n \n jobject javaTrace = getObjectFromLong(cmd.getJavaTraceHandle());\n\n std::auto_ptr pDbHandle(newDbHandle());\n ++JniUtil::handleCount;\n pDbHandle->pTraceTarget.reset(new JavaTraceTarget(javaTrace));\n\n SharedDatabase pDb = Database::newDatabase(\n pCache,\n configMap,\n openMode,\n pDbHandle->pTraceTarget.get());\n\n pDbHandle->pDb = pDb;\n\n pDbHandle->statsTimer.addSource(pDb);\n pDbHandle->statsTimer.start();\n\n if (pDb->isRecoveryRequired()) {\n SegmentAccessor scratchAccessor =\n pDb->getSegmentFactory()->newScratchSegment(pDb->getCache());\n FtrsTableWriterFactory recoveryFactory(\n pDb,\n pDb->getCache(),\n pDb->getTypeFactory(),\n scratchAccessor);\n pDb->recover(recoveryFactory);\n }\n setDbHandle(cmd.getResultHandle(),pDbHandle.release());\n}\n \nvoid CmdInterpreter::visit(ProxyCmdCloseDatabase &cmd)\n{\n DbHandle *pDbHandle = getDbHandle(cmd.getDbHandle());\n deleteAndNullify(pDbHandle);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCheckpoint &cmd)\n{\n DbHandle *pDbHandle = getDbHandle(cmd.getDbHandle());\n\n pDbHandle->pDb->requestCheckpoint(\n cmd.isFuzzy() ? CHECKPOINT_FLUSH_FUZZY : CHECKPOINT_FLUSH_ALL,\n cmd.isAsync());\n}\n \nvoid CmdInterpreter::getBTreeForIndexCmd(\n ProxyIndexCmd &cmd,PageId rootPageId,BTreeDescriptor &treeDescriptor)\n{\n SharedDatabase pDatabase = getDbHandle(cmd.getDbHandle())->pDb;\n \n readTupleDescriptor(\n treeDescriptor.tupleDescriptor,\n *(cmd.getTupleDesc()),pDatabase->getTypeFactory());\n \n CmdInterpreter::readTupleProjection(\n treeDescriptor.keyProjection,cmd.getKeyProj());\n\n treeDescriptor.pageOwnerId = PageOwnerId(cmd.getIndexId());\n treeDescriptor.segmentId = SegmentId(cmd.getSegmentId());\n treeDescriptor.segmentAccessor.pSegment =\n pDatabase->getSegmentById(treeDescriptor.segmentId);\n treeDescriptor.segmentAccessor.pCacheAccessor = pDatabase->getCache();\n treeDescriptor.rootPageId = rootPageId;\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,NULL_PAGE_ID,treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.createEmptyRoot();\n resultHandle = opaqueToInt(builder.getRootPageId());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdTruncateIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,PageId(cmd.getRootPageId()),treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.truncate(false);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdDropIndex &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n \n BTreeDescriptor treeDescriptor;\n getBTreeForIndexCmd(cmd,PageId(cmd.getRootPageId()),treeDescriptor);\n BTreeBuilder builder(treeDescriptor);\n builder.truncate(true);\n}\n\nvoid CmdInterpreter::visit(ProxyCmdBeginTxn &cmd)\n{\n \/\/ block checkpoints\n SharedDatabase pDb = getDbHandle(cmd.getDbHandle())->pDb;\n SXMutexSharedGuard actionMutexGuard(\n pDb->getCheckpointThread()->getActionMutex());\n\n std::auto_ptr pTxnHandle(newTxnHandle());\n ++JniUtil::handleCount;\n pTxnHandle->pDb = pDb;\n \/\/ TODO: CacheAccessor factory\n pTxnHandle->pTxn = pDb->getTxnLog()->newLogicalTxn(pDb->getCache());\n \n \/\/ NOTE: use a null scratchAccessor; individual ExecStreamGraphs\n \/\/ will have their own\n SegmentAccessor scratchAccessor;\n \n pTxnHandle->pFtrsTableWriterFactory = SharedFtrsTableWriterFactory(\n new FtrsTableWriterFactory(\n pDb,\n pDb->getCache(),\n pDb->getTypeFactory(),\n scratchAccessor));\n setTxnHandle(cmd.getResultHandle(),pTxnHandle.release());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdSavepoint &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n \n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n setSvptHandle(\n cmd.getResultHandle(),\n pTxnHandle->pTxn->createSavepoint());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCommit &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n\n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n if (cmd.getSvptHandle()) {\n SavepointId svptId = getSavepointId(cmd.getSvptHandle());\n pTxnHandle->pTxn->commitSavepoint(svptId);\n } else {\n pTxnHandle->pTxn->commit();\n deleteAndNullify(pTxnHandle);\n }\n}\n\nvoid CmdInterpreter::visit(ProxyCmdRollback &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n\n \/\/ block checkpoints\n SXMutexSharedGuard actionMutexGuard(\n pTxnHandle->pDb->getCheckpointThread()->getActionMutex());\n \n if (cmd.getSvptHandle()) {\n SavepointId svptId = getSavepointId(cmd.getSvptHandle());\n pTxnHandle->pTxn->rollback(&svptId);\n } else {\n pTxnHandle->pTxn->rollback();\n deleteAndNullify(pTxnHandle);\n }\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateExecutionStreamGraph &cmd)\n{\n TxnHandle *pTxnHandle = getTxnHandle(cmd.getTxnHandle());\n SharedExecStreamGraph pGraph =\n ExecStreamGraph::newExecStreamGraph();\n pGraph->setTxn(pTxnHandle->pTxn);\n std::auto_ptr pStreamGraphHandle(\n new StreamGraphHandle());\n ++JniUtil::handleCount;\n pStreamGraphHandle->javaRuntimeContext = NULL;\n pStreamGraphHandle->pTxnHandle = pTxnHandle;\n pStreamGraphHandle->pExecStreamGraph = pGraph;\n pStreamGraphHandle->pExecStreamFactory.reset(\n new ExecStreamFactory(\n pTxnHandle->pDb,\n pTxnHandle->pFtrsTableWriterFactory,\n pStreamGraphHandle.get()));\n setStreamGraphHandle(\n cmd.getResultHandle(),\n pStreamGraphHandle.release());\n}\n\nvoid CmdInterpreter::visit(ProxyCmdPrepareExecutionStreamGraph &cmd)\n{\n StreamGraphHandle *pStreamGraphHandle = getStreamGraphHandle(\n cmd.getStreamGraphHandle());\n TxnHandle *pTxnHandle = pStreamGraphHandle->pTxnHandle;\n \/\/ NOTE: sequence is important here\n SharedExecStreamScheduler pScheduler(\n new DfsTreeExecStreamScheduler(\n &(pTxnHandle->pDb->getTraceTarget()),\n \"xo.scheduler\"));\n ExecStreamGraphEmbryo graphEmbryo(\n pStreamGraphHandle->pExecStreamGraph,\n pScheduler,\n pTxnHandle->pDb->getCache(),\n pTxnHandle->pDb->getSegmentFactory(), \n pStreamGraphHandle->pExecStreamFactory->shouldEnforceCacheQuotas());\n pStreamGraphHandle->pExecStreamFactory->setGraphEmbryo(graphEmbryo);\n ExecStreamBuilder streamBuilder(\n graphEmbryo, \n *(pStreamGraphHandle->pExecStreamFactory));\n streamBuilder.buildStreamGraph(cmd, true);\n pStreamGraphHandle->pExecStreamFactory.reset();\n pStreamGraphHandle->pScheduler = pScheduler;\n}\n\nvoid CmdInterpreter::visit(ProxyCmdCreateStreamHandle &cmd)\n{\n StreamGraphHandle *pStreamGraphHandle = getStreamGraphHandle(\n cmd.getStreamGraphHandle());\n SharedExecStream pStream =\n pStreamGraphHandle->pExecStreamGraph->findLastStream(\n cmd.getStreamName(), 0);\n setExecStreamHandle(\n cmd.getResultHandle(),\n pStream.get());\n}\n\nPageId CmdInterpreter::StreamGraphHandle::getRoot(PageOwnerId pageOwnerId)\n{\n JniEnvAutoRef pEnv;\n jlong x = opaqueToInt(pageOwnerId);\n x = pEnv->CallLongMethod(\n javaRuntimeContext,JniUtil::methGetIndexRoot,x);\n return PageId(x);\n}\n\nvoid CmdInterpreter::readTupleDescriptor(\n TupleDescriptor &tupleDesc,\n ProxyTupleDescriptor &javaTupleDesc,\n StoredTypeDescriptorFactory const &typeFactory)\n{\n tupleDesc.clear();\n SharedProxyTupleAttrDescriptor pAttr = javaTupleDesc.getAttrDescriptor();\n for (; pAttr; ++pAttr) {\n StoredTypeDescriptor const &typeDescriptor = \n typeFactory.newDataType(pAttr->getTypeOrdinal());\n tupleDesc.push_back(\n TupleAttributeDescriptor(\n typeDescriptor,pAttr->isNullable(),pAttr->getByteLength()));\n }\n}\n\nvoid CmdInterpreter::readTupleProjection(\n TupleProjection &tupleProj,\n SharedProxyTupleProjection pJavaTupleProj)\n{\n tupleProj.clear();\n SharedProxyTupleAttrProjection pAttr = pJavaTupleProj->getAttrProjection();\n for (; pAttr; ++pAttr) {\n tupleProj.push_back(pAttr->getAttributeIndex());\n }\n}\n\nFENNEL_END_CPPFILE(\"$Id$\");\n\n\/\/ End CmdInterpreter.cpp\n<|endoftext|>"} {"text":"\/*\n * Advent of Code 2016\n * Day 3 (part 2)\n *\n * Command: clang++ --std=c++14 day03b.cpp\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int MAX_LINE_LENGTH = 2000;\n\nclass Triangle {\n\tpublic:\n\t\tTriangle(int, int, int);\n\t\tTriangle(std::string, std::string, std::string);\n\t\tint a;\n\t\tint b;\n\t\tint c;\n\t\tbool valid();\n};\n\nTriangle::Triangle(int a, int b, int c) {\n\tthis->a = a;\n\tthis->b = b;\n\tthis->c = c;\n}\n\nTriangle::Triangle(std::string a, std::string b, std::string c) {\n\tthis->a = atoi(a.c_str());\n\tthis->b = atoi(b.c_str());\n\tthis->c = atoi(c.c_str());\n}\n\nbool Triangle::valid() {\n\treturn ((this->a + this->b > this->c) && (this->a + this->c > this->b) && (this->b + this->c > this->a));\n}\n\nvoid split(const std::string &s, char delim, std::vector &elems) {\n\tstd::stringstream ss;\n\tss.str(s);\n\tstd::string item;\n\twhile (std::getline(ss, item, delim)) {\n\t\telems.push_back(item);\n\t}\n}\n\nstd::vector split(const std::string &s, char delim) {\n\tstd::vector elems;\n\tsplit(s, delim, elems);\n\treturn elems;\n}\n\nint main(void) {\n\t\/\/ Open the input file\n\tstd::ifstream fin(\"input03.txt\");\n\tif (!fin) {\n\t\tstd::cerr << \"Error reading input file input03.txt\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::vector candidates;\n\n\t\/\/ Read the input\n\tstd::vector input;\n\tstd::vector partsA, partsB, partsC;\n\tint parts = 0;\n\tchar cInput[MAX_LINE_LENGTH];\n\twhile (fin.getline(cInput, MAX_LINE_LENGTH)) {\n\t\tusing namespace std;\n\t\tusing namespace boost;\n\n\t\tvector bits;\n\t\tstring input(cInput);\n\t\ttokenizer<> tokenizer(input);\n\n\t\tfor (auto token : tokenizer) {\n\t\t\tbits.push_back(token);\n\t\t}\n\n\t\tpartsA.push_back(bits.at(0));\n\t\tpartsB.push_back(bits.at(1));\n\t\tpartsC.push_back(bits.at(2));\n\t\tparts++;\n\n\t\tif (parts == 3) {\n\t\t\tTriangle t1(partsA.at(0), partsA.at(1), partsA.at(2));\n\t\t\tTriangle t2(partsB.at(0), partsB.at(1), partsB.at(2));\n\t\t\tTriangle t3(partsC.at(0), partsC.at(1), partsC.at(2));\n\n\t\t\t\/*\n\t\t\tvector> theParts;\n\t\t\ttheParts.push_back(partsA); theParts.push_back(partsB); theParts.push_back(partsC);\n\t\t\tfor (auto v : theParts) {\n\t\t\t\tcout << \"{ \";\n\t\t\t\tfor (auto p : v) {\n\t\t\t\t\tcout << p << \" \";\n\t\t\t\t}\n\t\t\t\tcout << \"}\" << endl;\n\t\t\t}\n\t\t\t*\/\n\n\t\t\tpartsA.clear();\n\t\t\tpartsB.clear();\n\t\t\tpartsC.clear();\n\n\t\t\tcandidates.push_back(t1);\n\t\t\tcandidates.push_back(t2);\n\t\t\tcandidates.push_back(t3);\n\t\t\tparts = 0;\n\t\t}\n\t}\n\tfin.close();\n\n\t\/\/ Solve the problem\n\tint triangles = 0; int other = 0;\n\tfor (auto t : candidates) {\n\t\tif (t.valid()) {\n\t\t\ttriangles++;\n\t\t} else {\n\t\t\tother++;\n\t\t}\n\t}\n\n\tstd::cout << \"Triangles: \" << triangles << std::endl << \"Non-triangles: \" << other << std::endl;\n\n\treturn 0;\n}\n\nCleanup\/*\n * Advent of Code 2016\n * Day 3 (part 2)\n *\n * Command: clang++ --std=c++14 day03b.cpp\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int MAX_LINE_LENGTH = 2000;\n\nclass Triangle {\n\tpublic:\n\t\tTriangle(int, int, int);\n\t\tTriangle(std::string, std::string, std::string);\n\t\tint a;\n\t\tint b;\n\t\tint c;\n\t\tbool valid();\n};\n\nTriangle::Triangle(int a, int b, int c) {\n\tthis->a = a;\n\tthis->b = b;\n\tthis->c = c;\n}\n\nTriangle::Triangle(std::string a, std::string b, std::string c) {\n\tthis->a = atoi(a.c_str());\n\tthis->b = atoi(b.c_str());\n\tthis->c = atoi(c.c_str());\n}\n\nbool Triangle::valid() {\n\treturn ((this->a + this->b > this->c) && (this->a + this->c > this->b) && (this->b + this->c > this->a));\n}\n\nvoid split(const std::string &s, char delim, std::vector &elems) {\n\tstd::stringstream ss;\n\tss.str(s);\n\tstd::string item;\n\twhile (std::getline(ss, item, delim)) {\n\t\telems.push_back(item);\n\t}\n}\n\nstd::vector split(const std::string &s, char delim) {\n\tstd::vector elems;\n\tsplit(s, delim, elems);\n\treturn elems;\n}\n\nint main(void) {\n\t\/\/ Open the input file\n\tstd::ifstream fin(\"input03.txt\");\n\tif (!fin) {\n\t\tstd::cerr << \"Error reading input file input03.txt\" << std::endl;\n\t\treturn -1;\n\t}\n\n\tstd::vector candidates;\n\n\t\/\/ Read the input\n\tstd::vector input;\n\tstd::vector partsA, partsB, partsC;\n\tint parts = 0;\n\tchar cInput[MAX_LINE_LENGTH];\n\twhile (fin.getline(cInput, MAX_LINE_LENGTH)) {\n\t\tusing namespace std;\n\t\tusing namespace boost;\n\n\t\tvector bits;\n\t\tstring input(cInput);\n\t\ttokenizer<> tokenizer(input);\n\n\t\tfor (auto token : tokenizer) {\n\t\t\tbits.push_back(token);\n\t\t}\n\n\t\tpartsA.push_back(bits.at(0));\n\t\tpartsB.push_back(bits.at(1));\n\t\tpartsC.push_back(bits.at(2));\n\t\tparts++;\n\n\t\tif (parts == 3) {\n\t\t\tTriangle t1(partsA.at(0), partsA.at(1), partsA.at(2));\n\t\t\tTriangle t2(partsB.at(0), partsB.at(1), partsB.at(2));\n\t\t\tTriangle t3(partsC.at(0), partsC.at(1), partsC.at(2));\n\n\t\t\tpartsA.clear();\n\t\t\tpartsB.clear();\n\t\t\tpartsC.clear();\n\n\t\t\tcandidates.push_back(t1);\n\t\t\tcandidates.push_back(t2);\n\t\t\tcandidates.push_back(t3);\n\t\t\tparts = 0;\n\t\t}\n\t}\n\tfin.close();\n\n\t\/\/ Solve the problem\n\tint triangles = 0; int other = 0;\n\tfor (auto t : candidates) {\n\t\tif (t.valid()) {\n\t\t\ttriangles++;\n\t\t} else {\n\t\t\tother++;\n\t\t}\n\t}\n\n\tstd::cout << \"Triangles: \" << triangles << std::endl << \"Non-triangles: \" << other << std::endl;\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2018 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#include \n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace DO::Sara;\n\n\nGRAPHICS_MAIN()\n{\n auto image = Image{};\n imread(image, \"\/home\/david\/GitHub\/DO-CV\/sara\/data\/sunflowerField.jpg\");\n\n auto kernel = Image{10, 10};\n kernel.matrix() = MatrixXf::Ones(10, 10) \/ 100.f;\n\n create_window(image.sizes());\n display(image);\n get_key();\n close_window();\n\n return EXIT_SUCCESS;\n}\nMAINT: sketch API.\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2018 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nusing namespace std;\nusing namespace DO::Sara;\n\n\nGRAPHICS_MAIN()\n{\n auto image = Image{};\n imread(image, \"\/home\/david\/GitHub\/DO-CV\/sara\/data\/sunflowerField.jpg\");\n\n auto kernel = Image{10, 10};\n kernel.matrix() = MatrixXf::Ones(10, 10) \/ 100.f;\n\n auto y = Image{image.sizes()};\n gemm_convolve(tensor_view(y), tensor_view(image), tensor_view(kernel));\n\n\n create_window(image.sizes());\n display(image);\n get_key();\n close_window();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"net\/disk_cache\/disk_cache_test_util.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_handle.h\"\n#include \"net\/disk_cache\/backend_impl.h\"\n\nstd::string GenerateKey(bool same_length) {\n char key[200];\n CacheTestFillBuffer(key, sizeof(key), same_length);\n\n key[199] = '\\0';\n return std::string(key);\n}\n\nvoid CacheTestFillBuffer(char* buffer, size_t len, bool no_nulls) {\n static bool called = false;\n if (!called) {\n called = true;\n int seed = static_cast(Time::Now().ToInternalValue());\n srand(seed);\n }\n\n for (size_t i = 0; i < len; i++) {\n buffer[i] = static_cast(rand());\n if (!buffer[i] && no_nulls)\n buffer[i] = 'g';\n }\n if (len && !buffer[0])\n buffer[0] = 'g';\n}\n\nstd::wstring GetCachePath() {\n std::wstring path;\n PathService::Get(base::DIR_TEMP, &path);\n file_util::AppendToPath(&path, L\"cache_test\");\n if (!file_util::PathExists(path))\n file_util::CreateDirectory(path);\n\n return path;\n}\n\nbool CreateCacheTestFile(const wchar_t* name) {\n ScopedHandle file(CreateFile(name, GENERIC_READ | GENERIC_WRITE,\n FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,\n CREATE_ALWAYS, 0, NULL));\n if (!file.IsValid())\n return false;\n\n SetFilePointer(file, 4 * 1024 * 1024, 0, FILE_BEGIN);\n SetEndOfFile(file);\n return true;\n}\n\nbool DeleteCache(const wchar_t* path) {\n std::wstring my_path(path);\n file_util::AppendToPath(&my_path, L\"*.*\");\n return file_util::Delete(my_path, false);\n}\n\nbool CheckCacheIntegrity(const std::wstring& path) {\n scoped_ptr cache(new disk_cache::BackendImpl(path));\n if (!cache.get())\n return false;\n if (!cache->Init())\n return false;\n return cache->SelfCheck() >= 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint g_cache_tests_max_id = 0;\nvolatile int g_cache_tests_received = 0;\nvolatile bool g_cache_tests_error = 0;\n\n\/\/ On the actual callback, increase the number of tests received and check for\n\/\/ errors (an unexpected test received)\nvoid CallbackTest::RunWithParams(const Tuple1& params) {\n if (id_ > g_cache_tests_max_id) {\n NOTREACHED();\n g_cache_tests_error = true;\n } else if (reuse_) {\n DCHECK(1 == reuse_);\n if (2 == reuse_)\n g_cache_tests_error = true;\n reuse_++;\n }\n\n g_cache_tests_received++;\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ Quits the message loop when all callbacks are called or we've been waiting\n\/\/ too long for them (2 secs without a callback).\nvoid TimerTask::Run() {\n if (g_cache_tests_received > num_callbacks_) {\n NOTREACHED();\n } else if (g_cache_tests_received == num_callbacks_) {\n completed_ = true;\n MessageLoop::current()->Quit();\n } else {\n \/\/ Not finished yet. See if we have to abort.\n if (last_ == g_cache_tests_received)\n num_iterations_++;\n else\n last_ = g_cache_tests_received;\n if (40 == num_iterations_)\n MessageLoop::current()->Quit();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nMessageLoopHelper::MessageLoopHelper() {\n message_loop_ = MessageLoop::current();\n \/\/ Create a recurrent timer of 50 mS.\n timer_ = message_loop_->timer_manager()->StartTimer(50, &timer_task_, true);\n}\n\nMessageLoopHelper::~MessageLoopHelper() {\n message_loop_->timer_manager()->StopTimer(timer_);\n delete timer_;\n}\n\nbool MessageLoopHelper::WaitUntilCacheIoFinished(int num_callbacks) {\n if (num_callbacks == g_cache_tests_received)\n return true;\n\n timer_task_.ExpectCallbacks(num_callbacks);\n message_loop_->Run();\n return timer_task_.GetSate();\n}\n\nMake the disk cache unit tests use some common code from the disk cache.\/\/ Copyright 2008, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"net\/disk_cache\/disk_cache_test_util.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"net\/disk_cache\/backend_impl.h\"\n#include \"net\/disk_cache\/cache_util.h\"\n#include \"net\/disk_cache\/file.h\"\n\nstd::string GenerateKey(bool same_length) {\n char key[200];\n CacheTestFillBuffer(key, sizeof(key), same_length);\n\n key[199] = '\\0';\n return std::string(key);\n}\n\nvoid CacheTestFillBuffer(char* buffer, size_t len, bool no_nulls) {\n static bool called = false;\n if (!called) {\n called = true;\n int seed = static_cast(Time::Now().ToInternalValue());\n srand(seed);\n }\n\n for (size_t i = 0; i < len; i++) {\n buffer[i] = static_cast(rand());\n if (!buffer[i] && no_nulls)\n buffer[i] = 'g';\n }\n if (len && !buffer[0])\n buffer[0] = 'g';\n}\n\nstd::wstring GetCachePath() {\n std::wstring path;\n PathService::Get(base::DIR_TEMP, &path);\n file_util::AppendToPath(&path, L\"cache_test\");\n if (!file_util::PathExists(path))\n file_util::CreateDirectory(path);\n\n return path;\n}\n\nbool CreateCacheTestFile(const wchar_t* name) {\n using namespace disk_cache;\n int flags = OS_FILE_CREATE_ALWAYS | OS_FILE_READ | OS_FILE_WRITE |\n OS_FILE_SHARE_READ | OS_FILE_SHARE_WRITE;\n\n scoped_refptr file(new File(CreateOSFile(name, flags, NULL)));\n if (!file->IsValid())\n return false;\n\n file->SetLength(4 * 1024 * 1024);\n return true;\n}\n\nbool DeleteCache(const wchar_t* path) {\n disk_cache::DeleteCache(path, false);\n return true;\n}\n\nbool CheckCacheIntegrity(const std::wstring& path) {\n scoped_ptr cache(new disk_cache::BackendImpl(path));\n if (!cache.get())\n return false;\n if (!cache->Init())\n return false;\n return cache->SelfCheck() >= 0;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nint g_cache_tests_max_id = 0;\nvolatile int g_cache_tests_received = 0;\nvolatile bool g_cache_tests_error = 0;\n\n\/\/ On the actual callback, increase the number of tests received and check for\n\/\/ errors (an unexpected test received)\nvoid CallbackTest::RunWithParams(const Tuple1& params) {\n if (id_ > g_cache_tests_max_id) {\n NOTREACHED();\n g_cache_tests_error = true;\n } else if (reuse_) {\n DCHECK(1 == reuse_);\n if (2 == reuse_)\n g_cache_tests_error = true;\n reuse_++;\n }\n\n g_cache_tests_received++;\n}\n\n\/\/ -----------------------------------------------------------------------\n\n\/\/ Quits the message loop when all callbacks are called or we've been waiting\n\/\/ too long for them (2 secs without a callback).\nvoid TimerTask::Run() {\n if (g_cache_tests_received > num_callbacks_) {\n NOTREACHED();\n } else if (g_cache_tests_received == num_callbacks_) {\n completed_ = true;\n MessageLoop::current()->Quit();\n } else {\n \/\/ Not finished yet. See if we have to abort.\n if (last_ == g_cache_tests_received)\n num_iterations_++;\n else\n last_ = g_cache_tests_received;\n if (40 == num_iterations_)\n MessageLoop::current()->Quit();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nMessageLoopHelper::MessageLoopHelper() {\n message_loop_ = MessageLoop::current();\n \/\/ Create a recurrent timer of 50 mS.\n timer_ = message_loop_->timer_manager()->StartTimer(50, &timer_task_, true);\n}\n\nMessageLoopHelper::~MessageLoopHelper() {\n message_loop_->timer_manager()->StopTimer(timer_);\n delete timer_;\n}\n\nbool MessageLoopHelper::WaitUntilCacheIoFinished(int num_callbacks) {\n if (num_callbacks == g_cache_tests_received)\n return true;\n\n timer_task_.ExpectCallbacks(num_callbacks);\n message_loop_->Run();\n return timer_task_.GetSate();\n}\n\n<|endoftext|>"} {"text":"reload_config does log levels now too.<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Reaper\n\/\/\/\n\/\/\/ Copyright (c) 2015-2019 Thibault Schueller\n\/\/\/ This file is distributed under the MIT License\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RenderDoc.h\"\n\n#if defined(REAPER_USE_RENDERDOC)\n\n# include \"common\/DebugLog.h\"\n# include \"common\/ReaperRoot.h\"\n\n# include \"core\/DynamicLibrary.h\"\n# include \"core\/Profile.h\"\n\n# if defined(REAPER_PLATFORM_LINUX) || defined(REAPER_PLATFORM_MACOSX)\n# include \n# elif defined(REAPER_PLATFORM_WINDOWS)\n# include \n# endif\n\nnamespace Reaper::RenderDoc\n{\nnamespace\n{\n constexpr RENDERDOC_Version RenderDocVersion = eRENDERDOC_API_Version_1_4_0;\n using RenderDocAPI = RENDERDOC_API_1_4_0;\n\n LibHandle g_renderDocLib = nullptr;\n RenderDocAPI* g_renderDocAPI = nullptr;\n} \/\/ namespace\n\nvoid start_integration(ReaperRoot& root)\n{\n REAPER_PROFILE_SCOPE(\"RenderDoc\", MP_GREEN1);\n\n log_info(root, \"renderdoc: starting integration\");\n\n Assert(g_renderDocLib == nullptr);\n\n log_info(root, \"renderdoc: loading {}\", REAPER_RENDERDOC_LIB_NAME);\n \/\/ FIXME Documentation recommends RTLD_NOW | RTLD_NOLOAD on linux\n g_renderDocLib = dynlib::load(REAPER_RENDERDOC_LIB_NAME);\n\n pRENDERDOC_GetAPI pfn_RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dynlib::getSymbol(g_renderDocLib, \"RENDERDOC_GetAPI\");\n\n Assert(pfn_RENDERDOC_GetAPI(RenderDocVersion, (void**)&g_renderDocAPI) == 1);\n\n int major, minor, patch;\n g_renderDocAPI->GetAPIVersion(&major, &minor, &patch);\n log_info(root, \"renderdoc: API version {}.{}.{}\", major, minor, patch);\n\n Assert(g_renderDocAPI->SetCaptureOptionU32(eRENDERDOC_Option_DebugOutputMute, 0) == 1);\n log_info(root, \"renderdoc: disable debug output muting\");\n}\n\nvoid stop_integration(ReaperRoot& root)\n{\n REAPER_PROFILE_SCOPE(\"RenderDoc\", MP_GREEN1);\n\n log_info(root, \"renderdoc: stopping integration\");\n\n Assert(g_renderDocLib != nullptr);\n\n \/\/ We are not supposed to unload RenderDoc lib manually ever.\n \/\/ See also: https:\/\/github.com\/bkaradzic\/bgfx\/issues\/1192\n \/\/ log_info(root, \"renderdoc: unloading {}\", REAPER_RENDERDOC_LIB_NAME);\n \/\/ dynlib::close(g_renderDocLib);\n \/\/ g_renderDocLib = nullptr;\n}\n} \/\/ namespace Reaper::RenderDoc\n\n#else\n\nnamespace Reaper::RenderDoc\n{\nvoid start_integration(ReaperRoot& \/*root*\/)\n{\n AssertUnreachable();\n}\n\nvoid stop_integration(ReaperRoot& \/*root*\/)\n{\n AssertUnreachable();\n}\n} \/\/ namespace Reaper::RenderDoc\n\n#endif\nrenderdoc: let renderdoc mute validation ouput.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Reaper\n\/\/\/\n\/\/\/ Copyright (c) 2015-2019 Thibault Schueller\n\/\/\/ This file is distributed under the MIT License\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"RenderDoc.h\"\n\n#if defined(REAPER_USE_RENDERDOC)\n\n# include \"common\/DebugLog.h\"\n# include \"common\/ReaperRoot.h\"\n\n# include \"core\/DynamicLibrary.h\"\n# include \"core\/Profile.h\"\n\n# if defined(REAPER_PLATFORM_LINUX) || defined(REAPER_PLATFORM_MACOSX)\n# include \n# elif defined(REAPER_PLATFORM_WINDOWS)\n# include \n# endif\n\nnamespace Reaper::RenderDoc\n{\nnamespace\n{\n constexpr RENDERDOC_Version RenderDocVersion = eRENDERDOC_API_Version_1_4_0;\n using RenderDocAPI = RENDERDOC_API_1_4_0;\n\n LibHandle g_renderDocLib = nullptr;\n RenderDocAPI* g_renderDocAPI = nullptr;\n} \/\/ namespace\n\nvoid start_integration(ReaperRoot& root)\n{\n REAPER_PROFILE_SCOPE(\"RenderDoc\", MP_GREEN1);\n\n log_info(root, \"renderdoc: starting integration\");\n\n Assert(g_renderDocLib == nullptr);\n\n log_info(root, \"renderdoc: loading {}\", REAPER_RENDERDOC_LIB_NAME);\n \/\/ FIXME Documentation recommends RTLD_NOW | RTLD_NOLOAD on linux\n g_renderDocLib = dynlib::load(REAPER_RENDERDOC_LIB_NAME);\n\n pRENDERDOC_GetAPI pfn_RENDERDOC_GetAPI = (pRENDERDOC_GetAPI)dynlib::getSymbol(g_renderDocLib, \"RENDERDOC_GetAPI\");\n\n Assert(pfn_RENDERDOC_GetAPI(RenderDocVersion, (void**)&g_renderDocAPI) == 1);\n\n int major, minor, patch;\n g_renderDocAPI->GetAPIVersion(&major, &minor, &patch);\n log_info(root, \"renderdoc: API version {}.{}.{}\", major, minor, patch);\n}\n\nvoid stop_integration(ReaperRoot& root)\n{\n REAPER_PROFILE_SCOPE(\"RenderDoc\", MP_GREEN1);\n\n log_info(root, \"renderdoc: stopping integration\");\n\n Assert(g_renderDocLib != nullptr);\n\n \/\/ We are not supposed to unload RenderDoc lib manually ever.\n \/\/ See also: https:\/\/github.com\/bkaradzic\/bgfx\/issues\/1192\n \/\/ log_info(root, \"renderdoc: unloading {}\", REAPER_RENDERDOC_LIB_NAME);\n \/\/ dynlib::close(g_renderDocLib);\n \/\/ g_renderDocLib = nullptr;\n}\n} \/\/ namespace Reaper::RenderDoc\n\n#else\n\nnamespace Reaper::RenderDoc\n{\nvoid start_integration(ReaperRoot& \/*root*\/)\n{\n AssertUnreachable();\n}\n\nvoid stop_integration(ReaperRoot& \/*root*\/)\n{\n AssertUnreachable();\n}\n} \/\/ namespace Reaper::RenderDoc\n\n#endif\n<|endoftext|>"} {"text":"#include \"MainVisitor.hpp\"\n\n#include \n#include \n#include \"Event.hpp\"\n#include \"typedefs.hpp\"\n\n#include \"MainModule.hpp\"\n\n#include \"events\/Terminate.hpp\"\n#include \"events\/CmdResponseReceived.hpp\"\n#include \"events\/WebClientRequestReceived.hpp\"\n#include \"..\/..\/utils\/Machine.hpp\"\n\n#include \"..\/..\/network\/websocket\/typedefs.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageBroadcastRequest.hpp\"\n\nnamespace events = tin::controllers::main::events;\nnamespace main = tin::controllers::main;\nusing nlohmann::json;\n\ntin::controllers::main::MainVisitor::MainVisitor(tin::controllers::main::MainModule& controller):\ncontroller(controller)\n{}\n\nvoid tin::controllers::main::MainVisitor::visit(events::Terminate &evt)\n{\n this->controller.terminate();\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::CmdResponseReceived &evt)\n{\n std::cout << \"[Supervisor] [MainCtrl] Received response: \" << evt.jsonPtr->dump() << std::endl;\n std::cout << \" Source: \" << evt.ip << \":\" << evt.port << std::endl;\n \n\n auto it = std::make_pair(evt.ip, evt.port);\n std::map, int>::iterator ipPortIdMapIt;\n std::map::iterator idMachineMapIt;\n ipPortIdMapIt = controller.ipPortIdMap.find(it);\n idMachineMapIt = controller.idMachineMap.find(ipPortIdMapIt->second);\n utils::Machine& m = idMachineMapIt->second;\n\n json& temp = *(evt.jsonPtr);\n\n if (temp.find(\"error\") != temp.end() && temp[\"error\"].is_string())\n {\n if(temp.find(\"notConnected\") != temp.end())\n {\n bool error = temp[\"error\"][\"notConnected\"]; \n if(error == true)\n \t m.status = \"offline\";\n }\n std::cout << \"[Supervisor][MainCtrl] Error received\" << std::endl;\n return;\n }\n\n if(temp.find(\"cmd\") != temp.end() && temp[\"cmd\"].is_string())\n {\n const std::string cmd = temp[\"cmd\"];\n\n if (cmd == \"sync\")\n {\n auto ms = std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n m.lastSynchronization = ms.count();\n }\n\n else if (cmd == \"ping\")\n {\n if(temp.find(\"response\") != temp.end())\n {\n const std::string response = temp[\"error\"][\"response\"]; \n if(response == \"sniffing\")\n m.status.assign(\"sniffing\");\n if(response == \"stand-by\")\n m.status.assign(\"stand-by\");\n }\n \n }\n\n else if (cmd == \"change_filter\")\n {\n \tconst std::string expr = temp[\"expression\"];\n \tm.filter = expr;\n \tm.status = \"sniffing\";\n }\n }\n\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::WebClientRequestReceived &evt)\n{\n std::cout << \"[Supervisor] WebClient Request Received, processing\" << std::endl;\n\n json& temp = *(evt.jsonPtr);\n\n if(temp.find(\"route\") == temp.end() || temp.find(\"type\") == temp.end() ||\n !temp[\"route\"].is_string() || !temp[\"type\"].is_string())\n {\n std::cout << \"[Supervisor] Bad WebClient request\" << std::endl;\n return;\n }\n\n std::string route = temp[\"route\"];\n std::string type = temp[\"type\"];\n\n if (route == \"machines\" && type == \"GET\")\n {\n json jsonObj;\n jsonObj[\"data\"] = {\n { \"machines\", {} }\n };\n \n for(auto& it: this->controller.idMachineMap)\n {\n jsonObj[\"data\"][\"machines\"][jsonObj[\"data\"][\"machines\"].size()] = {\n { \"id\", it.second.id},\n { \"name\", it.second.name },\n { \"ip\", it.second.ip },\n { \"port\", it.second.port },\n { \"status\", it.second.status },\n { \"lastSync\", it.second.lastSynchronization }\n };\n }\n }\n\n else if(route == \"machines\" && type == \"POST\")\n {\n if(temp.find(\"data\") == temp.end())\n {\n std::cout << \"[Supervisor] No data in POST\" << std::endl;\n return;\n }\n\n const std::string ip = temp[\"data\"][\"ip\"];\n const std::string name = temp[\"data\"][\"name\"];\n unsigned port = temp[\"data\"][\"port\"];\n\n utils::Machine m = utils::Machine(ip, name, port);\n\n this->controller.ipPortIdMap.insert(\n std::pair, int>\n (std::make_pair(ip, port), m.id));\n this->controller.idMachineMap.insert(std::pair(m.id, m));\n\n }\n\n}handling webclient request event#include \"MainVisitor.hpp\"\n\n#include \n#include \n#include \"Event.hpp\"\n#include \"typedefs.hpp\"\n\n#include \"MainModule.hpp\"\n\n#include \"events\/Terminate.hpp\"\n#include \"events\/CmdResponseReceived.hpp\"\n#include \"events\/WebClientRequestReceived.hpp\"\n#include \"..\/..\/utils\/Machine.hpp\"\n\n#include \"..\/..\/network\/websocket\/typedefs.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageSendRequest.hpp\"\n#include \"..\/..\/network\/websocket\/events\/MessageBroadcastRequest.hpp\"\n\nnamespace events = tin::controllers::main::events;\nnamespace main = tin::controllers::main;\nusing nlohmann::json;\n\ntin::controllers::main::MainVisitor::MainVisitor(tin::controllers::main::MainModule& controller):\ncontroller(controller)\n{}\n\nvoid tin::controllers::main::MainVisitor::visit(events::Terminate &evt)\n{\n this->controller.terminate();\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::CmdResponseReceived &evt)\n{\n std::cout << \"[Supervisor] [MainCtrl] Received response: \" << evt.jsonPtr->dump() << std::endl;\n std::cout << \" Source: \" << evt.ip << \":\" << evt.port << std::endl;\n \n\n auto it = std::make_pair(evt.ip, evt.port);\n std::map, int>::iterator ipPortIdMapIt;\n std::map::iterator idMachineMapIt;\n ipPortIdMapIt = controller.ipPortIdMap.find(it);\n idMachineMapIt = controller.idMachineMap.find(ipPortIdMapIt->second);\n utils::Machine& m = idMachineMapIt->second;\n\n json& temp = *(evt.jsonPtr);\n\n if (temp.find(\"error\") != temp.end() && temp[\"error\"].is_string())\n {\n if(temp.find(\"notConnected\") != temp.end())\n {\n bool error = temp[\"error\"][\"notConnected\"]; \n if(error == true)\n \t m.status = \"offline\";\n }\n std::cout << \"[Supervisor][MainCtrl] Error received\" << std::endl;\n return;\n }\n\n if(temp.find(\"cmd\") != temp.end() && temp[\"cmd\"].is_string())\n {\n const std::string cmd = temp[\"cmd\"];\n\n if (cmd == \"sync\")\n {\n auto ms = std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch());\n m.lastSynchronization = ms.count();\n }\n\n else if (cmd == \"ping\")\n {\n if(temp.find(\"response\") != temp.end())\n {\n const std::string response = temp[\"error\"][\"response\"]; \n if(response == \"sniffing\")\n m.status.assign(\"sniffing\");\n if(response == \"stand-by\")\n m.status.assign(\"stand-by\");\n }\n \n }\n\n else if (cmd == \"change_filter\")\n {\n \tconst std::string expr = temp[\"expression\"];\n \tm.filter = expr;\n \tm.status = \"sniffing\";\n }\n }\n\n}\n\nvoid tin::controllers::main::MainVisitor::visit(events::WebClientRequestReceived &evt)\n{\n std::cout << \"[Supervisor] WebClient Request Received, processing\" << std::endl;\n\n json& temp = *(evt.jsonPtr);\n\n if(temp.find(\"route\") == temp.end() || temp.find(\"type\") == temp.end() ||\n !temp[\"route\"].is_string() || !temp[\"type\"].is_string())\n {\n std::cout << \"[Supervisor] Bad WebClient request\" << std::endl;\n return;\n }\n\n std::string route = temp[\"route\"];\n std::string type = temp[\"type\"];\n\n if (route == \"machines\" && type == \"GET\")\n {\n json jsonObj;\n jsonObj[\"data\"] = {\n { \"machines\", {} }\n };\n \n for(auto& it: this->controller.idMachineMap)\n {\n jsonObj[\"data\"][\"machines\"][jsonObj[\"data\"][\"machines\"].size()] = {\n { \"id\", it.second.id},\n { \"name\", it.second.name },\n { \"ip\", it.second.ip },\n { \"port\", it.second.port },\n { \"status\", it.second.status },\n { \"lastSync\", it.second.lastSynchronization }\n };\n }\n }\n\n\n if(route == \"machines\" && type == \"POST\")\n {\n if(temp.find(\"data\") == temp.end())\n {\n std::cout << \"[Supervisor] No data in POST\" << std::endl;\n return;\n }\n\n const std::string ip = temp[\"data\"][\"ip\"];\n const std::string name = temp[\"data\"][\"name\"];\n unsigned port = temp[\"data\"][\"port\"];\n\n utils::Machine m = utils::Machine(ip, name, port);\n\n this->controller.ipPortIdMap.insert(\n std::pair, int>\n (std::make_pair(ip, port), m.id));\n this->controller.idMachineMap.insert(std::pair(m.id, m));\n\n }\n\n\n if (route.substr(0, 8) == \"machine\/\")\n {\n auto routeRest = route.substr(8);\n auto action = std::string(\"\");\n if (routeRest.find(\"\/\") != std::string::npos)\n {\n action = routeRest.substr(routeRest.find(\"\/\") + 1);\n routeRest = routeRest.substr(0, routeRest.find(\"\/\"));\n }\n\n try\n {\n int machineID = static_cast(std::stoul(routeRest));\n\n utils::Machine& machine = this->controller.idMachineMap.at(machineID);\n\n if (action == \"\" && type == \"GET\")\n {\n temp[\"data\"] = {\n { \"id\", machineID },\n { \"name\", machine.name },\n { \"ip\", machine.ip },\n { \"port\", machine.port },\n { \"status\", machine.status },\n { \"lastSync\", machine.lastSynchronization }};\n \n }\n else if (action == \"\" && type == \"PATCH\")\n {\n\n std::string name = temp[\"data\"][\"name\"];\n std::string ip = temp[\"data\"][\"ip\"];\n unsigned int port = temp[\"data\"][\"port\"];\n\n \n machine.name = name;\n machine.ip = ip;\n machine.port = port;\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"\" && type == \"DELETE\")\n {\n \n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"sync\" && type == \"POST\")\n {\n auto ms = std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch()\n );\n\n machine.lastSynchronization = ms.count();\n\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (action == \"toggle-sniffer\" && type == \"POST\")\n {\n \n if (machine.status == \"sniffing\")\n {\n machine.status = \"stand-by\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else if (machine.status == \"stand-by\")\n {\n machine.status = \"sniffing\";\n temp[\"data\"] = {{ \"success\", true }};\n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { {\"status\", machine.status} } }};\n } \n }\n else\n {\n temp[\"error\"] = {{ \"invalid\", { {\"action\", action} } }};\n }\n }\n catch (std::invalid_argument& e)\n {\n temp[\"error\"] = {{ \"invalid\", { {\"routeID\", true} } }};\n }\n }\n\n\n}<|endoftext|>"} {"text":"\/*\n * This file is part of qasmtools.\n *\n * Copyright (c) 2019 - 2021 softwareQ Inc. All rights reserved.\n *\n * MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Adapted from Bruno Schmitt's Tweedledee library\n *\/\n\n\/**\n * \\file qasmtools\/parser\/lexer.hpp\n * \\brief Lexical analysis\n *\/\n\n#pragma once\n\n#include \"token.hpp\"\n\n#include \n#include \n\nnamespace qasmtools {\nnamespace parser {\n\n\/**\n * \\class qasmtools::parser::Lexer\n * \\brief openPARSER lexer class\n *\n * The Lexer reads from (a shared_ptr to) an istream object given during\n * initialization. Rather than lex the entire buffer at once, tokens are\n * lexed and returned on-demand\n *\/\nclass Lexer {\n public:\n Lexer(const Lexer&) = delete;\n Lexer& operator=(const Lexer&) = delete;\n\n Lexer(std::shared_ptr buffer, const std::string& fname = \"\")\n : pos_(fname, 1, 1), buf_(buffer) {}\n\n \/**\n * \\brief Lex and return the next token\n *\n * \\note Advances the buffer to the position after the consumed token\n *\n * \\return The token that was lexed\n *\/\n Token next_token() { return lex(); }\n\n private:\n Position pos_; \/\/\/< current position in the source stream\n std::shared_ptr buf_; \/\/\/< stream buffer being lexed\n\n \/**\n * \\brief Skips the specified number of characters\n *\n * \\param n The number of characters to skip ahead (optional, default is 1)\n *\/\n void skip_char(int n = 1) {\n buf_->ignore(n);\n pos_.advance_column(n);\n }\n\n \/**\n * \\brief Skips over whitespace\n *\n * \\return True if and only if whitespace was actually consumed\n *\/\n bool skip_whitespace() {\n int consumed = 0;\n\n while (buf_->peek() == ' ' || buf_->peek() == '\\t') {\n buf_->ignore();\n ++consumed;\n }\n\n pos_.advance_column(consumed);\n if (consumed != 0)\n return true;\n else\n return false;\n }\n\n \/**\n * \\brief Skips the rest of the line\n *\/\n void skip_line_comment() {\n int consumed = 0;\n\n char c = buf_->peek();\n while (c != 0 && c != '\\n' && c != '\\r' && c != EOF) {\n buf_->ignore();\n ++consumed;\n c = buf_->peek();\n }\n\n pos_.advance_column(consumed);\n }\n\n \/**\n * \\brief Lex a numeric constant\n *\n * \\note [0-9]+(.[0-9]*)([eE][+-][0-9]+)?\n *\n * \\param tok_start The position of the beginning of the token\n * \\return An integer or real type token\n *\/\n Token lex_numeric_constant(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n bool integral = true;\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n \/\/ lex decimal\n if (buf_->peek() == '.') {\n integral = false;\n str.push_back(buf_->peek());\n skip_char();\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n }\n\n \/\/ lex exponent\n if (buf_->peek() == 'e' || buf_->peek() == 'E') {\n integral = false;\n str.push_back(buf_->peek());\n skip_char();\n\n if (buf_->peek() == '-' || buf_->peek() == '+') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n }\n\n if (integral) {\n return Token(tok_start, Token::Kind::nninteger, str,\n std::stoi(str));\n } else {\n return Token(tok_start, Token::Kind::real, str, std::stof(str));\n }\n }\n\n \/**\n * \\brief Lex an identifier\n *\n * \\note [A-Za-z][_A-Za-z0-9]*\n *\n * \\param tok_start The position of the beginning of the token\n * \\return An identifier type token\n *\/\n Token lex_identifier(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n\n while (std::isalpha(buf_->peek()) || std::isdigit(buf_->peek()) ||\n buf_->peek() == '_') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n \/\/ Check if the identifier is a known keyword\n auto keyword = keywords.find(str);\n if (keyword != keywords.end()) {\n return Token(tok_start, keyword->second, str);\n }\n\n return Token(tok_start, Token::Kind::identifier, str, str);\n }\n\n \/**\n * \\brief Lex a string literal\n *\n * \\note \"[.]*\"\n *\n * \\param tok_start The position of the beginning of the token\n * \\return A string type token\n *\/\n Token lex_string(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n\n while (buf_->peek() != '\"' && buf_->peek() != '\\n' &&\n buf_->peek() != '\\r') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n if (buf_->peek() != '\"') {\n std::cerr << \"Lexical error at \" << tok_start << \": unmatched \\\"\\n\";\n return Token(tok_start, Token::Kind::error, str);\n }\n\n skip_char();\n return Token(tok_start, Token::Kind::string, str, str);\n }\n\n \/**\n * \\brief Lex a token\n *\n * \\note See arXiv:1707.03429 for the full grammar\n *\n * \\return The lexed token\n *\/\n Token lex() {\n Position tok_start = pos_;\n skip_whitespace();\n\n switch (buf_->peek()) {\n case EOF:\n skip_char();\n return Token(tok_start, Token::Kind::eof, \"\");\n\n case '\\r':\n skip_char();\n if (buf_->peek() != '\\n') {\n buf_->ignore();\n pos_.advance_line();\n return lex();\n }\n \/\/ FALLTHROUGH\n case '\\n':\n buf_->ignore();\n pos_.advance_line();\n return lex();\n\n case '\/':\n skip_char();\n if (buf_->peek() == '\/') {\n skip_line_comment();\n return lex();\n }\n return Token(tok_start, Token::Kind::slash, \"\/\");\n\n \/\/ clang-format off\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n case '.':\n return lex_numeric_constant(tok_start);\n \/\/ clang-format on\n\n case 'C':\n skip_char();\n if (buf_->peek() == 'X') {\n skip_char();\n return Token(tok_start, Token::Kind::kw_cx, \"CX\");\n }\n\n skip_char();\n std::cerr\n << \"Lexical error at \" << tok_start\n << \": identifiers must start with lowercase letters\\n\";\n return Token(tok_start, Token::Kind::error,\n std::string({'C', (char) buf_->get()}));\n\n case 'U':\n skip_char();\n return Token(tok_start, Token::Kind::kw_u, \"U\");\n\n \/\/ clang-format off\n case 'O':\n case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':\n case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':\n case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':\n case 'v': case 'w': case 'x': case 'y': case 'z':\n return lex_identifier(tok_start);\n \/\/ clang-format on\n\n case '[':\n skip_char();\n return Token(tok_start, Token::Kind::l_square, \"[\");\n\n case ']':\n skip_char();\n return Token(tok_start, Token::Kind::r_square, \"]\");\n\n case '(':\n skip_char();\n return Token(tok_start, Token::Kind::l_paren, \"(\");\n\n case ')':\n skip_char();\n return Token(tok_start, Token::Kind::r_paren, \")\");\n\n case '{':\n skip_char();\n return Token(tok_start, Token::Kind::l_brace, \"{\");\n\n case '}':\n skip_char();\n return Token(tok_start, Token::Kind::r_brace, \"}\");\n\n case '*':\n skip_char();\n return Token(tok_start, Token::Kind::star, \"*\");\n\n case '+':\n skip_char();\n return Token(tok_start, Token::Kind::plus, \"+\");\n\n case '-':\n skip_char();\n\n if (buf_->peek() == '>') {\n skip_char();\n return Token(tok_start, Token::Kind::arrow, \"->\");\n }\n\n return Token(tok_start, Token::Kind::minus, \"-\");\n\n case '^':\n skip_char();\n return Token(tok_start, Token::Kind::caret, \"^\");\n\n case ';':\n skip_char();\n return Token(tok_start, Token::Kind::semicolon, \";\");\n\n case '=':\n skip_char();\n if (buf_->peek() == '=') {\n skip_char();\n return Token(tok_start, Token::Kind::equalequal, \"==\");\n }\n\n skip_char();\n std::cerr << \"Lexical error at \" << tok_start\n << \": expected \\\"=\\\" after \\\"=\\\"\\n\";\n return Token(tok_start, Token::Kind::error,\n std::string({'=', (char) buf_->get()}));\n\n case ',':\n skip_char();\n return Token(tok_start, Token::Kind::comma, \";\");\n\n case '\"':\n skip_char();\n return lex_string(tok_start);\n\n default:\n skip_char();\n return Token(tok_start, Token::Kind::error,\n std::string({(char) buf_->get()}));\n }\n }\n};\n\n} \/\/ namespace parser\n} \/\/ namespace qasmtools\nFixed bug in lexer.hpp\/*\n * This file is part of qasmtools.\n *\n * Copyright (c) 2019 - 2021 softwareQ Inc. All rights reserved.\n *\n * MIT License\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Adapted from Bruno Schmitt's Tweedledee library\n *\/\n\n\/**\n * \\file qasmtools\/parser\/lexer.hpp\n * \\brief Lexical analysis\n *\/\n\n#pragma once\n\n#include \"token.hpp\"\n\n#include \n#include \n\nnamespace qasmtools {\nnamespace parser {\n\n\/**\n * \\class qasmtools::parser::Lexer\n * \\brief openPARSER lexer class\n *\n * The Lexer reads from (a shared_ptr to) an istream object given during\n * initialization. Rather than lex the entire buffer at once, tokens are\n * lexed and returned on-demand\n *\/\nclass Lexer {\n public:\n Lexer(const Lexer&) = delete;\n Lexer& operator=(const Lexer&) = delete;\n\n Lexer(std::shared_ptr buffer, const std::string& fname = \"\")\n : pos_(fname, 1, 1), buf_(buffer) {}\n\n \/**\n * \\brief Lex and return the next token\n *\n * \\note Advances the buffer to the position after the consumed token\n *\n * \\return The token that was lexed\n *\/\n Token next_token() { return lex(); }\n\n private:\n Position pos_; \/\/\/< current position in the source stream\n std::shared_ptr buf_; \/\/\/< stream buffer being lexed\n\n \/**\n * \\brief Skips the specified number of characters\n *\n * \\param n The number of characters to skip ahead (optional, default is 1)\n *\/\n void skip_char(int n = 1) {\n buf_->ignore(n);\n pos_.advance_column(n);\n }\n\n \/**\n * \\brief Skips over whitespace\n *\n * \\return True if and only if whitespace was actually consumed\n *\/\n bool skip_whitespace() {\n int consumed = 0;\n\n while (buf_->peek() == ' ' || buf_->peek() == '\\t') {\n buf_->ignore();\n ++consumed;\n }\n\n pos_.advance_column(consumed);\n if (consumed != 0)\n return true;\n else\n return false;\n }\n\n \/**\n * \\brief Skips the rest of the line\n *\/\n void skip_line_comment() {\n int consumed = 0;\n\n int c = buf_->peek();\n while (c != 0 && c != '\\n' && c != '\\r' && c != EOF) {\n buf_->ignore();\n ++consumed;\n c = buf_->peek();\n }\n\n pos_.advance_column(consumed);\n }\n\n \/**\n * \\brief Lex a numeric constant\n *\n * \\note [0-9]+(.[0-9]*)([eE][+-][0-9]+)?\n *\n * \\param tok_start The position of the beginning of the token\n * \\return An integer or real type token\n *\/\n Token lex_numeric_constant(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n bool integral = true;\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n \/\/ lex decimal\n if (buf_->peek() == '.') {\n integral = false;\n str.push_back(buf_->peek());\n skip_char();\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n }\n\n \/\/ lex exponent\n if (buf_->peek() == 'e' || buf_->peek() == 'E') {\n integral = false;\n str.push_back(buf_->peek());\n skip_char();\n\n if (buf_->peek() == '-' || buf_->peek() == '+') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n while (std::isdigit(buf_->peek())) {\n str.push_back(buf_->peek());\n skip_char();\n }\n }\n\n if (integral) {\n return Token(tok_start, Token::Kind::nninteger, str,\n std::stoi(str));\n } else {\n return Token(tok_start, Token::Kind::real, str, std::stof(str));\n }\n }\n\n \/**\n * \\brief Lex an identifier\n *\n * \\note [A-Za-z][_A-Za-z0-9]*\n *\n * \\param tok_start The position of the beginning of the token\n * \\return An identifier type token\n *\/\n Token lex_identifier(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n\n while (std::isalpha(buf_->peek()) || std::isdigit(buf_->peek()) ||\n buf_->peek() == '_') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n \/\/ Check if the identifier is a known keyword\n auto keyword = keywords.find(str);\n if (keyword != keywords.end()) {\n return Token(tok_start, keyword->second, str);\n }\n\n return Token(tok_start, Token::Kind::identifier, str, str);\n }\n\n \/**\n * \\brief Lex a string literal\n *\n * \\note \"[.]*\"\n *\n * \\param tok_start The position of the beginning of the token\n * \\return A string type token\n *\/\n Token lex_string(Position tok_start) {\n std::string str;\n str.reserve(64); \/\/ Reserve space to avoid reallocation\n\n while (buf_->peek() != '\"' && buf_->peek() != '\\n' &&\n buf_->peek() != '\\r') {\n str.push_back(buf_->peek());\n skip_char();\n }\n\n if (buf_->peek() != '\"') {\n std::cerr << \"Lexical error at \" << tok_start << \": unmatched \\\"\\n\";\n return Token(tok_start, Token::Kind::error, str);\n }\n\n skip_char();\n return Token(tok_start, Token::Kind::string, str, str);\n }\n\n \/**\n * \\brief Lex a token\n *\n * \\note See arXiv:1707.03429 for the full grammar\n *\n * \\return The lexed token\n *\/\n Token lex() {\n Position tok_start = pos_;\n skip_whitespace();\n\n switch (buf_->peek()) {\n case EOF:\n skip_char();\n return Token(tok_start, Token::Kind::eof, \"\");\n\n case '\\r':\n skip_char();\n if (buf_->peek() != '\\n') {\n buf_->ignore();\n pos_.advance_line();\n return lex();\n }\n \/\/ FALLTHROUGH\n case '\\n':\n buf_->ignore();\n pos_.advance_line();\n return lex();\n\n case '\/':\n skip_char();\n if (buf_->peek() == '\/') {\n skip_line_comment();\n return lex();\n }\n return Token(tok_start, Token::Kind::slash, \"\/\");\n\n \/\/ clang-format off\n case '0': case '1': case '2': case '3': case '4':\n case '5': case '6': case '7': case '8': case '9':\n case '.':\n return lex_numeric_constant(tok_start);\n \/\/ clang-format on\n\n case 'C':\n skip_char();\n if (buf_->peek() == 'X') {\n skip_char();\n return Token(tok_start, Token::Kind::kw_cx, \"CX\");\n }\n\n skip_char();\n std::cerr\n << \"Lexical error at \" << tok_start\n << \": identifiers must start with lowercase letters\\n\";\n return Token(tok_start, Token::Kind::error,\n std::string({'C', (char) buf_->get()}));\n\n case 'U':\n skip_char();\n return Token(tok_start, Token::Kind::kw_u, \"U\");\n\n \/\/ clang-format off\n case 'O':\n case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':\n case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':\n case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':\n case 'v': case 'w': case 'x': case 'y': case 'z':\n return lex_identifier(tok_start);\n \/\/ clang-format on\n\n case '[':\n skip_char();\n return Token(tok_start, Token::Kind::l_square, \"[\");\n\n case ']':\n skip_char();\n return Token(tok_start, Token::Kind::r_square, \"]\");\n\n case '(':\n skip_char();\n return Token(tok_start, Token::Kind::l_paren, \"(\");\n\n case ')':\n skip_char();\n return Token(tok_start, Token::Kind::r_paren, \")\");\n\n case '{':\n skip_char();\n return Token(tok_start, Token::Kind::l_brace, \"{\");\n\n case '}':\n skip_char();\n return Token(tok_start, Token::Kind::r_brace, \"}\");\n\n case '*':\n skip_char();\n return Token(tok_start, Token::Kind::star, \"*\");\n\n case '+':\n skip_char();\n return Token(tok_start, Token::Kind::plus, \"+\");\n\n case '-':\n skip_char();\n\n if (buf_->peek() == '>') {\n skip_char();\n return Token(tok_start, Token::Kind::arrow, \"->\");\n }\n\n return Token(tok_start, Token::Kind::minus, \"-\");\n\n case '^':\n skip_char();\n return Token(tok_start, Token::Kind::caret, \"^\");\n\n case ';':\n skip_char();\n return Token(tok_start, Token::Kind::semicolon, \";\");\n\n case '=':\n skip_char();\n if (buf_->peek() == '=') {\n skip_char();\n return Token(tok_start, Token::Kind::equalequal, \"==\");\n }\n\n skip_char();\n std::cerr << \"Lexical error at \" << tok_start\n << \": expected \\\"=\\\" after \\\"=\\\"\\n\";\n return Token(tok_start, Token::Kind::error,\n std::string({'=', (char) buf_->get()}));\n\n case ',':\n skip_char();\n return Token(tok_start, Token::Kind::comma, \";\");\n\n case '\"':\n skip_char();\n return lex_string(tok_start);\n\n default:\n skip_char();\n return Token(tok_start, Token::Kind::error,\n std::string({(char) buf_->get()}));\n }\n }\n};\n\n} \/\/ namespace parser\n} \/\/ namespace qasmtools\n<|endoftext|>"} {"text":"\/**\n * @file examples\/megasync.cpp\n * @brief sample daemon, which synchronizes local and remote folders\n *\n * (c) 2013 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n#include \"megacli.h\"\n\nstruct SyncApp : public MegaApp\n{\n void nodes_updated(Node**, int);\n void debug_log(const char*);\n void login_result(error e);\n\n void request_error(error e);\n};\n\n\/\/ simple Waiter class\nstruct TestWaiter : public Waiter\n{\n dstime getdstime();\n\n void init(dstime);\n int wait();\n};\n\n\/\/ globals\nMegaClient* client;\nstatic handle cwd = UNDEF;\nbool mega::debug;\n\nvoid TestWaiter ::init(dstime ds)\n{\n maxds = ds;\n}\n\n\/\/ update monotonously increasing timestamp in deciseconds\ndstime TestWaiter::getdstime()\n{\n timespec ts;\n\n clock_gettime(CLOCK_MONOTONIC,&ts);\n\n return ds = ts.tv_sec*10+ts.tv_nsec\/100000000;\n}\n\n\/\/ return at once, as we don't have to wait for any custom events\nint TestWaiter ::wait()\n{\n \/\/ sleep for a tiny amount of time\n usleep (200);\n return NEEDEXEC;\n}\n\n\/\/ this callback function is called when nodes have been updated\n\/\/ save root node handle\nvoid SyncApp::nodes_updated(Node** n, int count)\n{\n if (ISUNDEF(cwd)) cwd = client->rootnodes[0];\n}\n\n\/\/ callback for displaying debug logs\nvoid SyncApp::debug_log(const char* message)\n{\n cout << \"DEBUG: \" << message << endl;\n}\n\n\/\/ this callback function is called when we have login result (success or error)\n\/\/ TODO: check for errors\nvoid SyncApp::login_result(error e)\n{\n \/\/ get the list of nodes\n client->fetchnodes();\n}\n\n\/\/ this callback function is called when request-level error occurred\nvoid SyncApp::request_error(error e)\n{\n cout << \"FATAL: Request failed exiting\" << endl;\n exit(0);\n}\n\n\/\/ returns node pointer determined by path relative to cwd\n\/\/ Path naming conventions:\n\/\/ path is relative to cwd\n\/\/ \/path is relative to ROOT\n\/\/ \/\/in is in INBOX\n\/\/ \/\/bin is in RUBBISH\n\/\/ X: is user X's INBOX\n\/\/ X:SHARE is share SHARE from user X\n\/\/ : and \/ filename components, as well as the \\, must be escaped by \\.\n\/\/ (correct UTF-8 encoding is assumed)\n\/\/ returns NULL if path malformed or not found\nstatic Node* nodebypath(const char* ptr, string* user = NULL, string* namepart = NULL)\n{\n\tvector c;\n\tstring s;\n\tint l = 0;\n\tconst char* bptr = ptr;\n\tint remote = 0;\n\tNode* n;\n\tNode* nn;\n\n\t\/\/ split path by \/ or :\n\tdo {\n\t\tif (!l)\n\t\t{\n\t\t\tif (*ptr >= 0)\n\t\t\t{\n\t\t\t\tif (*ptr == '\\\\')\n\t\t\t\t{\n\t\t\t\t\tif (ptr > bptr) s.append(bptr,ptr-bptr);\n\t\t\t\t\tbptr = ++ptr;\n\n\t\t\t\t\tif (*bptr == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tc.push_back(s);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (*ptr == '\/' || *ptr == ':' || !*ptr)\n\t\t\t\t{\n\t\t\t\t\tif (*ptr == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (c.size()) return NULL;\n\t\t\t\t\t\tremote = 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ptr > bptr) s.append(bptr,ptr-bptr);\n\n\t\t\t\t\tbptr = ptr+1;\n\n\t\t\t\t\tc.push_back(s);\n\n\t\t\t\t\ts.erase();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ((*ptr & 0xf0) == 0xe0) l = 1;\n\t\t\telse if ((*ptr & 0xf8) == 0xf0) l = 2;\n\t\t\telse if ((*ptr & 0xfc) == 0xf8) l = 3;\n\t\t\telse if ((*ptr & 0xfe) == 0xfc) l = 4;\n\t\t}\n\t\telse l--;\n\t} while (*ptr++);\n\n\tif (l) return NULL;\n\n\tif (remote)\n\t{\n\t\t\/\/ target: user inbox - record username\/email and return NULL\n\t\tif (c.size() == 2 && !c[1].size())\n\t\t{\n\t\t\tif (user) *user = c[0];\n\t\t\treturn NULL;\n\t\t}\n\n\t\tUser* u;\n\n\t\tif ((u = client->finduser(c[0].c_str())))\n\t\t{\n\t\t\t\/\/ locate matching share from this user\n\t\t\thandle_set::iterator sit;\n\n\t\t\tfor (sit = u->sharing.begin(); sit != u->sharing.end(); sit++)\n\t\t\t{\n\t\t\t\tif ((n = client->nodebyhandle(*sit)))\n\t\t\t\t{\n\t\t\t\t\tif (!strcmp(c[1].c_str(),n->displayname()))\n\t\t\t\t\t{\n\t\t\t\t\t\tl = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (l) break;\n\t\t\t}\n\t\t}\n\n\t\tif (!l) return NULL;\n\t}\n\telse\n\t{\n\t\t\/\/ path starting with \/\n\t\tif (c.size() > 1 && !c[0].size())\n\t\t{\n\t\t\t\/\/ path starting with \/\/\n\t\t\tif (c.size() > 2 && !c[1].size())\n\t\t\t{\n\t\t\t\tif (c[2] == \"in\") n = client->nodebyhandle(client->rootnodes[1]);\n\t\t\t\telse if (c[2] == \"bin\") n = client->nodebyhandle(client->rootnodes[2]);\n\t\t\t\telse if (c[2] == \"mail\") n = client->nodebyhandle(client->rootnodes[3]);\n\t\t\t\telse return NULL;\n\n\t\t\t\tl = 3;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn = client->nodebyhandle(client->rootnodes[0]);\n\n\t\t\t\tl = 1;\n\t\t\t}\n\t\t}\n\t\telse n = client->nodebyhandle(cwd);\n\t}\n\n\t\/\/ parse relative path\n\twhile (n && l < (int)c.size())\n\t{\n\t\tif (c[l] != \".\")\n\t\t{\n\t\t\tif (c[l] == \"..\")\n\t\t\t{\n\t\t\t\tif (n->parent) n = n->parent;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ locate child node (explicit ambiguity resolution: not implemented)\n\t\t\t\tif (c[l].size())\n\t\t\t\t{\n\t\t\t\t\tnn = client->childnodebyname(n,c[l].c_str());\n\n\t\t\t\t\tif (!nn)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ mv command target? return name part of not found\n\t\t\t\t\t\tif (namepart && l == (int)c.size()-1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t*namepart = c[l];\n\t\t\t\t\t\t\treturn n;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\tn = nn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tl++;\n\t}\n\n\treturn n;\n}\n\n\/\/\nint main (int argc, char *argv[])\n{\n static byte pwkey[SymmCipher::KEYLENGTH];\n bool is_active = true;\n string folder_local;\n\n\n if (argc < 3) {\n cout << \"Usage: \" << argv[0] << \" [local folder] [remote folder]\" << endl;\n return 1;\n }\n folder_local = argv[1];\n\n if (!getenv (\"MEGA_EMAIL\") || !getenv (\"MEGA_PWD\")) {\n cout << \"Please set both MEGA_EMAIL and MEGA_PWD env variables!\" << endl;\n return 1;\n }\n\n \/\/ if MEGA_DEBUG env variable is set\n if (getenv (\"MEGA_DEBUG\"))\n mega::debug = true;\n\n \/\/ create MegaClient, providing our custom MegaApp and Waiter classes\n client = new MegaClient(new SyncApp, new TestWaiter, new HTTPIO_CLASS, new FSACCESS_CLASS,\n#ifdef DBACCESS_CLASS\n\tnew DBACCESS_CLASS,\n#else\n\tNULL,\n#endif\n \"megasync\");\n\n \/\/ get values from env\n client->pw_key (getenv (\"MEGA_PWD\"), pwkey);\n client->login (getenv (\"MEGA_EMAIL\"), pwkey);\n\n \/\/ loop while we are not logged in\n while (! client->loggedin ()) {\n client->wait();\n client->exec();\n }\n\n Node* n = nodebypath(argv[2]);\n if (client->checkaccess(n, FULL))\n {\n string localname;\n\n client->fsaccess->path2local(&folder_local, &localname);\n\n if (!n) cout << argv[2] << \": Not found.\" << endl;\n else if (n->type == FILENODE) cout << argv[2] << \": Remote sync root must be folder.\" << endl;\n else new Sync(client,&localname,n);\n }\n else cout << argv[2] << \": Syncing requires full access to path.\" << endl;\n\n while (is_active) {\n\t\tclient->wait();\n\t \/\/ pass the CPU to the engine (nonblocking)\n\t\tclient->exec();\n }\n\n return 0;\n}\nfix Waiter on Windows platform\/**\n * @file examples\/megasync.cpp\n * @brief sample daemon, which synchronizes local and remote folders\n *\n * (c) 2013 by Mega Limited, Wellsford, New Zealand\n *\n * This file is part of the MEGA SDK - Client Access Engine.\n *\n * Applications using the MEGA API must present a valid application key\n * and comply with the the rules set forth in the Terms of Service.\n *\n * The MEGA SDK is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n * @copyright Simplified (2-clause) BSD License.\n *\n * You should have received a copy of the license along with this\n * program.\n *\/\n\n#include \"mega.h\"\n#include \"megacli.h\"\n\nstruct SyncApp : public MegaApp\n{\n void nodes_updated(Node**, int);\n void debug_log(const char*);\n void login_result(error e);\n\n void request_error(error e);\n};\n\n\/\/ simple Waiter class\nstruct TestWaiter : public Waiter\n{\n dstime getdstime();\n#ifdef _WIN32\n PGTC pGTC;\n\tULONGLONG tickhigh;\n\tDWORD prevt;\n#endif\n\n void init(dstime);\n int wait();\n};\n\n\/\/ globals\nMegaClient* client;\nstatic handle cwd = UNDEF;\nbool mega::debug;\n\nvoid TestWaiter ::init(dstime ds)\n{\n maxds = ds;\n#ifdef _WIN32\n\tpGTC = (PGTC)GetProcAddress(GetModuleHandle(TEXT(\"kernel32.dll\")),\"GetTickCount64\");\n if (!pGTC) {\n tickhigh = 0;\n\t prevt = 0;\n }\n#endif\n}\n\n\/\/ update monotonously increasing timestamp in deciseconds\ndstime TestWaiter::getdstime()\n{\n#ifdef _WIN32\n\tif (pGTC) return ds = pGTC()\/100;\n\telse\n\t{\n\t\t\/\/ emulate GetTickCount64() on XP\n\t\tDWORD t = GetTickCount();\n\n\t\tif (t < prevt) tickhigh += 0x100000000;\n\t\tprevt = t;\n\n\t\treturn ds = (t+tickhigh)\/100;\n\t}\n#else\n timespec ts;\n clock_gettime(CLOCK_MONOTONIC,&ts);\n\n return ds = ts.tv_sec*10+ts.tv_nsec\/100000000;\n\n#endif\n}\n\n\/\/ return at once, as we don't have to wait for any custom events\nint TestWaiter ::wait()\n{\n \/\/ sleep for a tiny amount of time\n usleep (200);\n return NEEDEXEC;\n}\n\n\/\/ this callback function is called when nodes have been updated\n\/\/ save root node handle\nvoid SyncApp::nodes_updated(Node** n, int count)\n{\n if (ISUNDEF(cwd)) cwd = client->rootnodes[0];\n}\n\n\/\/ callback for displaying debug logs\nvoid SyncApp::debug_log(const char* message)\n{\n cout << \"DEBUG: \" << message << endl;\n}\n\n\/\/ this callback function is called when we have login result (success or error)\n\/\/ TODO: check for errors\nvoid SyncApp::login_result(error e)\n{\n \/\/ get the list of nodes\n client->fetchnodes();\n}\n\n\/\/ this callback function is called when request-level error occurred\nvoid SyncApp::request_error(error e)\n{\n cout << \"FATAL: Request failed exiting\" << endl;\n exit(0);\n}\n\n\/\/ returns node pointer determined by path relative to cwd\n\/\/ Path naming conventions:\n\/\/ path is relative to cwd\n\/\/ \/path is relative to ROOT\n\/\/ \/\/in is in INBOX\n\/\/ \/\/bin is in RUBBISH\n\/\/ X: is user X's INBOX\n\/\/ X:SHARE is share SHARE from user X\n\/\/ : and \/ filename components, as well as the \\, must be escaped by \\.\n\/\/ (correct UTF-8 encoding is assumed)\n\/\/ returns NULL if path malformed or not found\nstatic Node* nodebypath(const char* ptr, string* user = NULL, string* namepart = NULL)\n{\n\tvector c;\n\tstring s;\n\tint l = 0;\n\tconst char* bptr = ptr;\n\tint remote = 0;\n\tNode* n;\n\tNode* nn;\n\n\t\/\/ split path by \/ or :\n\tdo {\n\t\tif (!l)\n\t\t{\n\t\t\tif (*ptr >= 0)\n\t\t\t{\n\t\t\t\tif (*ptr == '\\\\')\n\t\t\t\t{\n\t\t\t\t\tif (ptr > bptr) s.append(bptr,ptr-bptr);\n\t\t\t\t\tbptr = ++ptr;\n\n\t\t\t\t\tif (*bptr == 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tc.push_back(s);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tptr++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (*ptr == '\/' || *ptr == ':' || !*ptr)\n\t\t\t\t{\n\t\t\t\t\tif (*ptr == ':')\n\t\t\t\t\t{\n\t\t\t\t\t\tif (c.size()) return NULL;\n\t\t\t\t\t\tremote = 1;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (ptr > bptr) s.append(bptr,ptr-bptr);\n\n\t\t\t\t\tbptr = ptr+1;\n\n\t\t\t\t\tc.push_back(s);\n\n\t\t\t\t\ts.erase();\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if ((*ptr & 0xf0) == 0xe0) l = 1;\n\t\t\telse if ((*ptr & 0xf8) == 0xf0) l = 2;\n\t\t\telse if ((*ptr & 0xfc) == 0xf8) l = 3;\n\t\t\telse if ((*ptr & 0xfe) == 0xfc) l = 4;\n\t\t}\n\t\telse l--;\n\t} while (*ptr++);\n\n\tif (l) return NULL;\n\n\tif (remote)\n\t{\n\t\t\/\/ target: user inbox - record username\/email and return NULL\n\t\tif (c.size() == 2 && !c[1].size())\n\t\t{\n\t\t\tif (user) *user = c[0];\n\t\t\treturn NULL;\n\t\t}\n\n\t\tUser* u;\n\n\t\tif ((u = client->finduser(c[0].c_str())))\n\t\t{\n\t\t\t\/\/ locate matching share from this user\n\t\t\thandle_set::iterator sit;\n\n\t\t\tfor (sit = u->sharing.begin(); sit != u->sharing.end(); sit++)\n\t\t\t{\n\t\t\t\tif ((n = client->nodebyhandle(*sit)))\n\t\t\t\t{\n\t\t\t\t\tif (!strcmp(c[1].c_str(),n->displayname()))\n\t\t\t\t\t{\n\t\t\t\t\t\tl = 2;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (l) break;\n\t\t\t}\n\t\t}\n\n\t\tif (!l) return NULL;\n\t}\n\telse\n\t{\n\t\t\/\/ path starting with \/\n\t\tif (c.size() > 1 && !c[0].size())\n\t\t{\n\t\t\t\/\/ path starting with \/\/\n\t\t\tif (c.size() > 2 && !c[1].size())\n\t\t\t{\n\t\t\t\tif (c[2] == \"in\") n = client->nodebyhandle(client->rootnodes[1]);\n\t\t\t\telse if (c[2] == \"bin\") n = client->nodebyhandle(client->rootnodes[2]);\n\t\t\t\telse if (c[2] == \"mail\") n = client->nodebyhandle(client->rootnodes[3]);\n\t\t\t\telse return NULL;\n\n\t\t\t\tl = 3;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tn = client->nodebyhandle(client->rootnodes[0]);\n\n\t\t\t\tl = 1;\n\t\t\t}\n\t\t}\n\t\telse n = client->nodebyhandle(cwd);\n\t}\n\n\t\/\/ parse relative path\n\twhile (n && l < (int)c.size())\n\t{\n\t\tif (c[l] != \".\")\n\t\t{\n\t\t\tif (c[l] == \"..\")\n\t\t\t{\n\t\t\t\tif (n->parent) n = n->parent;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ locate child node (explicit ambiguity resolution: not implemented)\n\t\t\t\tif (c[l].size())\n\t\t\t\t{\n\t\t\t\t\tnn = client->childnodebyname(n,c[l].c_str());\n\n\t\t\t\t\tif (!nn)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ mv command target? return name part of not found\n\t\t\t\t\t\tif (namepart && l == (int)c.size()-1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t*namepart = c[l];\n\t\t\t\t\t\t\treturn n;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn NULL;\n\t\t\t\t\t}\n\n\t\t\t\t\tn = nn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tl++;\n\t}\n\n\treturn n;\n}\n\n\/\/\nint main (int argc, char *argv[])\n{\n static byte pwkey[SymmCipher::KEYLENGTH];\n bool is_active = true;\n string folder_local;\n\n\n if (argc < 3) {\n cout << \"Usage: \" << argv[0] << \" [local folder] [remote folder]\" << endl;\n return 1;\n }\n folder_local = argv[1];\n\n if (!getenv (\"MEGA_EMAIL\") || !getenv (\"MEGA_PWD\")) {\n cout << \"Please set both MEGA_EMAIL and MEGA_PWD env variables!\" << endl;\n return 1;\n }\n\n \/\/ if MEGA_DEBUG env variable is set\n if (getenv (\"MEGA_DEBUG\"))\n mega::debug = true;\n\n \/\/ create MegaClient, providing our custom MegaApp and Waiter classes\n client = new MegaClient(new SyncApp, new TestWaiter, new HTTPIO_CLASS, new FSACCESS_CLASS,\n#ifdef DBACCESS_CLASS\n\tnew DBACCESS_CLASS,\n#else\n\tNULL,\n#endif\n \"megasync\");\n\n \/\/ get values from env\n client->pw_key (getenv (\"MEGA_PWD\"), pwkey);\n client->login (getenv (\"MEGA_EMAIL\"), pwkey);\n\n \/\/ loop while we are not logged in\n while (! client->loggedin ()) {\n client->wait();\n client->exec();\n }\n\n Node* n = nodebypath(argv[2]);\n if (client->checkaccess(n, FULL))\n {\n string localname;\n\n client->fsaccess->path2local(&folder_local, &localname);\n\n if (!n) cout << argv[2] << \": Not found.\" << endl;\n else if (n->type == FILENODE) cout << argv[2] << \": Remote sync root must be folder.\" << endl;\n else new Sync(client,&localname,n);\n }\n else cout << argv[2] << \": Syncing requires full access to path.\" << endl;\n\n while (is_active) {\n\t\tclient->wait();\n\t \/\/ pass the CPU to the engine (nonblocking)\n\t\tclient->exec();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: Array.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 01:32:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _CONNECTIVITY_JAVA_SQL_ARRAY_HXX_\n#include \"java\/sql\/Array.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_SQL_RESULTSET_HXX_\n#include \"java\/sql\/ResultSet.hxx\"\n#endif\n\nusing namespace connectivity;\n\/\/**************************************************************\n\/\/************ Class: java.sql.Array\n\/\/**************************************************************\n\njclass java_sql_Array::theClass = 0;\n\njava_sql_Array::~java_sql_Array()\n{}\n\njclass java_sql_Array::getMyClass()\n{\n \/\/ die Klasse muss nur einmal geholt werden, daher statisch\n if( !theClass ){\n SDBThreadAttach t;\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass( \"java\/sql\/Array\" );\n jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n saveClassRef( globClass );\n }\n return theClass;\n}\n\nvoid java_sql_Array::saveClassRef( jclass pClass )\n{\n if( pClass==NULL )\n return;\n \/\/ der uebergebe Klassen-Handle ist schon global, daher einfach speichern\n theClass = pClass;\n}\n::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n ::rtl::OUString aStr;\n if( t.pEnv ){\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(I)Ljava\/lang\/String;\";\n static const char * cMethodName = \"getBaseTypeName\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);\n ThrowSQLException(t.pEnv,*this);\n aStr = JavaString2String(t.pEnv,out);\n \/\/ und aufraeumen\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n return aStr;\n}\n\nsal_Int32 SAL_CALL java_sql_Array::getBaseType( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jint out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"()I\";\n static const char * cMethodName = \"getBaseType\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallIntMethod( object, mID );\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n } \/\/mID\n } \/\/t.pEnv\n return (sal_Int32)out;\n}\n\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobjectArray out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n static const char * cSignature = \"(Ljava\/util\/Map;)[Ljava\/lang\/Object;\";\n static const char * cMethodName = \"getArray\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();\/\/copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);\n}\n\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobjectArray out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n static const char * cSignature = \"(IILjava\/util\/Map;)[Ljava\/lang\/Object;\";\n static const char * cMethodName = \"getArray\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();\/\/copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);\n}\n\n::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobject out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv ){\n \/\/ Parameter konvertieren\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(Ljava\/util\/Map;)Ljava\/sql\/ResultSet;\";\n static const char * cMethodName = \"getResultSet\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallObjectMethod( object, mID, obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n \/\/ return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );\n return NULL;\n}\n\n::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobject out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv ){\n \/\/ Parameter konvertieren\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(Ljava\/util\/Map;)Ljava\/sql\/ResultSet;\";\n static const char * cMethodName = \"getResultSetAtIndex\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallObjectMethod( object, mID, index,count,obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n \/\/ return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );\n return NULL;\n}\n\n\n\nINTEGRATION: CWS pchfix02 (1.8.60); FILE MERGED 2006\/09\/01 17:22:18 kaib 1.8.60.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: Array.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 02:44:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n#ifndef _CONNECTIVITY_JAVA_SQL_ARRAY_HXX_\n#include \"java\/sql\/Array.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_\n#include \"java\/tools.hxx\"\n#endif\n#ifndef _CONNECTIVITY_JAVA_SQL_RESULTSET_HXX_\n#include \"java\/sql\/ResultSet.hxx\"\n#endif\n\nusing namespace connectivity;\n\/\/**************************************************************\n\/\/************ Class: java.sql.Array\n\/\/**************************************************************\n\njclass java_sql_Array::theClass = 0;\n\njava_sql_Array::~java_sql_Array()\n{}\n\njclass java_sql_Array::getMyClass()\n{\n \/\/ die Klasse muss nur einmal geholt werden, daher statisch\n if( !theClass ){\n SDBThreadAttach t;\n if( !t.pEnv ) return (jclass)NULL;\n jclass tempClass = t.pEnv->FindClass( \"java\/sql\/Array\" );\n jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );\n t.pEnv->DeleteLocalRef( tempClass );\n saveClassRef( globClass );\n }\n return theClass;\n}\n\nvoid java_sql_Array::saveClassRef( jclass pClass )\n{\n if( pClass==NULL )\n return;\n \/\/ der uebergebe Klassen-Handle ist schon global, daher einfach speichern\n theClass = pClass;\n}\n::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n ::rtl::OUString aStr;\n if( t.pEnv ){\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(I)Ljava\/lang\/String;\";\n static const char * cMethodName = \"getBaseTypeName\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);\n ThrowSQLException(t.pEnv,*this);\n aStr = JavaString2String(t.pEnv,out);\n \/\/ und aufraeumen\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n return aStr;\n}\n\nsal_Int32 SAL_CALL java_sql_Array::getBaseType( ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jint out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"()I\";\n static const char * cMethodName = \"getBaseType\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallIntMethod( object, mID );\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n } \/\/mID\n } \/\/t.pEnv\n return (sal_Int32)out;\n}\n\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobjectArray out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n static const char * cSignature = \"(Ljava\/util\/Map;)[Ljava\/lang\/Object;\";\n static const char * cMethodName = \"getArray\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();\/\/copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);\n}\n\n::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobjectArray out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv )\n {\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n static const char * cSignature = \"(IILjava\/util\/Map;)[Ljava\/lang\/Object;\";\n static const char * cMethodName = \"getArray\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();\/\/copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);\n}\n\n::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobject out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv ){\n \/\/ Parameter konvertieren\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(Ljava\/util\/Map;)Ljava\/sql\/ResultSet;\";\n static const char * cMethodName = \"getResultSet\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallObjectMethod( object, mID, obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n \/\/ return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );\n return NULL;\n}\n\n::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)\n{\n jobject out(0);\n SDBThreadAttach t; OSL_ENSURE(t.pEnv,\"Java Enviroment geloescht worden!\");\n if( t.pEnv ){\n \/\/ Parameter konvertieren\n jobject obj = convertTypeMapToJavaMap(t.pEnv,typeMap);\n \/\/ temporaere Variable initialisieren\n static const char * cSignature = \"(Ljava\/util\/Map;)Ljava\/sql\/ResultSet;\";\n static const char * cMethodName = \"getResultSetAtIndex\";\n \/\/ Java-Call absetzen\n static jmethodID mID = NULL;\n if ( !mID )\n mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );\n if( mID ){\n out = t.pEnv->CallObjectMethod( object, mID, index,count,obj);\n ThrowSQLException(t.pEnv,*this);\n \/\/ und aufraeumen\n t.pEnv->DeleteLocalRef(obj);\n } \/\/mID\n } \/\/t.pEnv\n \/\/ ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!\n \/\/ return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );\n return NULL;\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: HDriver.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-11-09 12:15:44 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_HSQLDB_DRIVER_HXX\n#define CONNECTIVITY_HSQLDB_DRIVER_HXX\n\n#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_COMPBASE5_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n class OMetaConnection;\n\n namespace hsqldb\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );\n\n typedef ::cppu::WeakComponentImplHelper5< ::com::sun::star::sdbc::XDriver\n ,::com::sun::star::sdbcx::XDataDefinitionSupplier\n , ::com::sun::star::lang::XServiceInfo\n , ::com::sun::star::lang::XEventListener\n ,::com::sun::star::sdbcx::XCreateCatalog\n > ODriverDelegator_BASE;\n\n typedef ::std::pair< ::rtl::OUString ,OMetaConnection*> TWeakConnectionPair;\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;\n typedef ::std::vector< TWeakPair > TWeakPairVector;\n\n\n \/** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.\n\n *\/\n class ODriverDelegator : public ::comphelper::OBaseMutex\n ,public ODriverDelegator_BASE\n {\n TWeakPairVector m_aConnections; \/\/ vector containing a list\n \/\/ of all the Connection objects\n \/\/ for this Driver\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > m_xDriver;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n\n \/** load the driver we want to delegate.\n The m_xDriver<\/member> may be if the driver could not be loaded.\n @return\n The driver which was currently selected.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( );\n\n public:\n \/** creates a new delegator for a HSQLDB driver\n *\/\n ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDriver\n 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);\n virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n 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);\n virtual sal_Int32 SAL_CALL getMajorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMinorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDataDefinitionSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( 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);\n\n \/\/ XCreateCatalog\n virtual void SAL_CALL createCatalog( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n protected:\n \/\/\/ dtor\n virtual ~ODriverDelegator();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n };\n }\n\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_HSQLDB_DRIVER_HXX\n\nINTEGRATION: CWS dba22 (1.2.16); FILE MERGED 2005\/01\/04 12:14:22 oj 1.2.16.1: #i39671# new method for terminate listener\/*************************************************************************\n *\n * $RCSfile: HDriver.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2005-01-21 16:43:38 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): Ocke Janssen\n *\n *\n ************************************************************************\/\n#ifndef CONNECTIVITY_HSQLDB_DRIVER_HXX\n#define CONNECTIVITY_HSQLDB_DRIVER_HXX\n\n#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_COMPBASE5_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_STLTYPES_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_BROADCASTHELPER_HXX_\n#include \n#endif\n#ifndef _CONNECTIVITY_COMMONTOOLS_HXX_\n#include \"connectivity\/CommonTools.hxx\"\n#endif\n\n\/\/........................................................................\nnamespace connectivity\n{\n\/\/........................................................................\n\n class OMetaConnection;\n\n namespace hsqldb\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriverDelegator_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );\n\n typedef ::cppu::WeakComponentImplHelper5< ::com::sun::star::sdbc::XDriver\n ,::com::sun::star::sdbcx::XDataDefinitionSupplier\n , ::com::sun::star::lang::XServiceInfo\n , ::com::sun::star::lang::XEventListener\n ,::com::sun::star::sdbcx::XCreateCatalog\n > ODriverDelegator_BASE;\n\n typedef ::std::pair< ::rtl::OUString ,OMetaConnection*> TWeakConnectionPair;\n typedef ::std::pair< ::com::sun::star::uno::WeakReferenceHelper,TWeakConnectionPair> TWeakPair;\n typedef ::std::vector< TWeakPair > TWeakPairVector;\n\n\n \/** delegates all calls to the orignal driver and extend the existing one with the SDBCX layer.\n\n *\/\n class ODriverDelegator : public ::comphelper::OBaseMutex\n ,public ODriverDelegator_BASE\n {\n TWeakPairVector m_aConnections; \/\/ vector containing a list\n \/\/ of all the Connection objects\n \/\/ for this Driver\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > m_xDriver;\n ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xFactory;\n\n \/** load the driver we want to delegate.\n The m_xDriver<\/member> may be if the driver could not be loaded.\n @return\n The driver which was currently selected.\n *\/\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDriver > loadDriver( );\n\n public:\n \/** creates a new delegator for a HSQLDB driver\n *\/\n ODriverDelegator(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);\n\n \/\/ XServiceInfo\n DECLARE_SERVICE_INFO();\n static ::rtl::OUString getImplementationName_Static( ) throw(::com::sun::star::uno::RuntimeException);\n static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDriver\n 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);\n virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n 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);\n virtual sal_Int32 SAL_CALL getMajorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n virtual sal_Int32 SAL_CALL getMinorVersion( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XDataDefinitionSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( 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);\n\n \/\/ XCreateCatalog\n virtual void SAL_CALL createCatalog( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n\n \/\/ XEventListener\n virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);\n\n void shutdownConnections();\n protected:\n \/\/\/ dtor\n virtual ~ODriverDelegator();\n \/\/ OComponentHelper\n virtual void SAL_CALL disposing(void);\n };\n }\n\n\/\/........................................................................\n} \/\/ namespace connectivity\n\/\/........................................................................\n#endif \/\/ CONNECTIVITY_HSQLDB_DRIVER_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: wrap_sqlflex.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 02:09:25 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#if defined _MSC_VER\n #pragma warning(disable:4505)\n#endif\n\n#include \"sqlflex.cxx\"\nINTEGRATION: CWS pchfix02 (1.2.60); FILE MERGED 2006\/09\/01 17:22:35 kaib 1.2.60.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: wrap_sqlflex.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 03:10:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#if defined _MSC_VER\n #pragma warning(disable:4505)\n#endif\n\n#include \"sqlflex.cxx\"\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: forms_module.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: hr $ $Date: 2004-04-13 11:17:26 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef FORMS_MODULE_INCLUDE_CONTEXT\n #error \"not to be included directly! use 'foo_module.hxx instead'!\"\n#endif\n\n#ifndef FORMS_MODULE_NAMESPACE\n #error \"set FORMS_MODULE_NAMESPACE to your namespace identifier!\"\n#endif\n\n#ifndef _OSL_MUTEX_HXX_\n#include \n#endif\n#ifndef _TOOLS_RESID_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \n#endif\n#ifndef _RTL_STRING_HXX_\n#include \n#endif\n\n\/\/.........................................................................\nnamespace FORMS_MODULE_NAMESPACE\n{\n\/\/.........................................................................\n\n typedef ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > (SAL_CALL *FactoryInstantiation)\n (\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rServiceManager,\n const ::rtl::OUString & _rComponentName,\n ::cppu::ComponentInstantiation _pCreateFunction,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString > & _rServiceNames,\n rtl_ModuleCount* _pModuleCounter\n );\n\n \/\/=========================================================================\n \/\/= OFormsModule\n \/\/=========================================================================\n class OFormsModule\n {\n private:\n OFormsModule();\n \/\/ not implemented. OFormsModule is a static class\n\n protected:\n \/\/ auto registration administration\n static ::com::sun::star::uno::Sequence< ::rtl::OUString >*\n s_pImplementationNames;\n static ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::rtl::OUString > >*\n s_pSupportedServices;\n static ::com::sun::star::uno::Sequence< sal_Int64 >*\n s_pCreationFunctionPointers;\n static ::com::sun::star::uno::Sequence< sal_Int64 >*\n s_pFactoryFunctionPointers;\n\n public:\n \/** register a component implementing a service with the given data.\n @param _rImplementationName\n the implementation name of the component\n @param _rServiceNames\n the services the component supports\n @param _pCreateFunction\n a function for creating an instance of the component\n @param _pFactoryFunction\n a function for creating a factory for that component\n @see revokeComponent\n *\/\n static void registerComponent(\n const ::rtl::OUString& _rImplementationName,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rServiceNames,\n ::cppu::ComponentInstantiation _pCreateFunction,\n FactoryInstantiation _pFactoryFunction);\n\n \/** revoke the registration for the specified component\n @param _rImplementationName\n the implementation name of the component\n *\/\n static void revokeComponent(\n const ::rtl::OUString& _rImplementationName);\n\n \/** write the registration information of all known components\n

writes the registration information of all components which are currently registered into the\n specified registry.\n

Usually used from within component_writeInfo.\n @param _rxServiceManager\n the service manager\n @param _rRootKey\n the registry key under which the information will be stored\n @return\n sal_True if the registration of all implementations was successfull, sal_False otherwise\n *\/\n static sal_Bool writeComponentInfos(\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager,\n const ::com::sun::star::uno::Reference< ::com::sun::star::registry::XRegistryKey >& _rRootKey);\n\n \/** creates a Factory for the component with the given implementation name.\n

Usually used from within component_getFactory.\n @param _rxServiceManager\n a pointer to an XMultiServiceFactory interface as got in component_getFactory\n @param _pImplementationName\n the implementation name of the component\n @return\n the XInterface access to a factory for the component\n *\/\n static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getComponentFactory(\n const ::rtl::OUString& _rImplementationName,\n const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxServiceManager\n );\n\n private:\n \/** ensure that the impl class exists\n @precond m_aMutex is guarded when this method gets called\n *\/\n static void ensureImpl();\n };\n\n \/\/==========================================================================\n \/\/= OMultiInstanceAutoRegistration\n \/\/==========================================================================\n template \n class OMultiInstanceAutoRegistration\n {\n public:\n \/** automatically registeres a multi instance component\n

Assumed that the template argument has the three methods\n