text
stringlengths
54
60.6k
<commit_before>// // Copyright (c) 2015-2016 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_geometry_data_hpp__ #define __se3_python_geometry_data_hpp__ #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/python/se3.hpp" #include "pinocchio/python/eigen_container.hpp" #include "pinocchio/python/handler.hpp" #include "pinocchio/python/data.hpp" #include "pinocchio/python/geometry-model.hpp" namespace se3 { namespace python { namespace bp = boost::python; struct CollisionPairPythonVisitor : public boost::python::def_visitor<CollisionPairPythonVisitor> { typedef CollisionPair::Index Index; static void expose() { bp::class_<CollisionPair> ("CollisionPair", "Pair of ordered index defining a pair of collisions", bp::init<const Index &, const Index &> (bp::args("co1 (index)", "co2 (index)"), "Initializer of collision pair")) .def("__str__",&CollisionPairPythonVisitor::toString); bp::class_< std::vector<CollisionPair> >("StdVec_CollisionPair") .def(bp::vector_indexing_suite< std::vector<CollisionPair> >()); } static std::string toString(const CollisionPair & cp) { std::ostringstream s; s << cp; return s.str(); } }; // struct CollisionPairPythonVisitor typedef Handler<GeometryData> GeometryDataHandler; struct GeometryDataPythonVisitor : public boost::python::def_visitor< GeometryDataPythonVisitor > { typedef GeometryData::Index Index; typedef GeometryData::CollisionPair_t CollisionPair_t; typedef se3::DistanceResult DistanceResult; typedef eigenpy::UnalignedEquivalent<SE3>::type SE3_fx; /* --- Convert From C++ to Python ------------------------------------- */ // static PyObject* convert(Model const& modelConstRef) // { // Model * ptr = const_cast<Model*>(&modelConstRef); // return boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr()); // } static PyObject* convert(GeometryDataHandler::SmartPtr_t const& ptr) { return boost::python::incref(boost::python::object(GeometryDataHandler(ptr)).ptr()); } /* --- Exposing C++ API to python through the handler ----------------- */ template<class PyClass> void visit(PyClass& cl) const { cl .def("__init__", bp::make_constructor(&GeometryDataPythonVisitor::makeDefault, bp::default_call_policies(), (bp::arg("data"),bp::arg("geometry_model"))), "Initialize from data and the geometry model.") .add_property("nCollisionPairs", &GeometryDataPythonVisitor::nCollisionPairs) .add_property("oMg", bp::make_function(&GeometryDataPythonVisitor::oMg, bp::return_internal_reference<>()), "Vector of collision objects placement relative to the world.") .add_property("collision_pairs", bp::make_function(&GeometryDataPythonVisitor::collision_pairs, bp::return_internal_reference<>()), "Vector of collision pairs.") .add_property("distance_results", bp::make_function(&GeometryDataPythonVisitor::distance_results, bp::return_internal_reference<>()), "Vector of distance results computed in ") .add_property("collision_results", bp::make_function(&GeometryDataPythonVisitor::collision_results, bp::return_internal_reference<>()) ) .def("addCollisionPair",&GeometryDataPythonVisitor::addCollisionPair, bp::args("co1 (index)","co2 (index)"), "Add a collision pair given by the index of the two collision objects." " Remark: co1 < co2") .def("addAllCollisionPairs",&GeometryDataPythonVisitor::addAllCollisionPairs, "Add all collision pairs.") .def("removeCollisionPair",&GeometryDataPythonVisitor::removeCollisionPair, bp::args("co1 (index)","co2 (index)"), "Remove a collision pair given by the index of the two collision objects." " Remark: co1 < co2") .def("removeAllCollisionPairs",&GeometryDataPythonVisitor::removeAllCollisionPairs, "Remove all collision pairs.") .def("existCollisionPair",&GeometryDataPythonVisitor::existCollisionPair, bp::args("co1 (index)","co2 (index)"), "Check if a collision pair given by the index of the two collision objects exists or not." " Remark: co1 < co2") .def("findCollisionPair", &GeometryDataPythonVisitor::findCollisionPair, bp::args("co1 (index)","co2 (index)"), "Return the index of a collision pair given by the index of the two collision objects exists or not." " Remark: co1 < co2") .def("computeCollision",&GeometryDataPythonVisitor::computeCollision, bp::args("co1 (index)","co2 (index)"), "Check if the two collision objects of a collision pair are in collision." "The collision pair is given by the two index of the collision objects.") .def("__str__",&GeometryDataPythonVisitor::toString) ; } static GeometryDataHandler* makeDefault(const DataHandler & data, const GeometryModelHandler & geometry_model) { return new GeometryDataHandler(new GeometryData(*data, *geometry_model), true); } static Index nCollisionPairs(const GeometryDataHandler & m ) { return m->nCollisionPairs; } static std::vector<SE3> & oMg(GeometryDataHandler & m) { return m->oMg; } static std::vector<CollisionPair_t> & collision_pairs( GeometryDataHandler & m ) { return m->collision_pairs; } static std::vector<DistanceResult> & distance_results( GeometryDataHandler & m ) { return m->distance_results; } static std::vector<bool> & collision_results( GeometryDataHandler & m ) { return m->collision_results; } static void addCollisionPair (GeometryDataHandler & m, const Index co1, const Index co2) { m->addCollisionPair(co1, co2); } static void addAllCollisionPairs (GeometryDataHandler & m) { m->addAllCollisionPairs(); } static void removeCollisionPair (GeometryDataHandler & m, const Index co1, const Index co2) { m->removeCollisionPair(co1, co2); } static void removeAllCollisionPairs (GeometryDataHandler & m) { m->removeAllCollisionPairs(); } static bool existCollisionPair (const GeometryDataHandler & m, const Index co1, const Index co2) { return m->existCollisionPair(co1, co2); } static GeometryData::Index findCollisionPair (const GeometryDataHandler & m, const Index co1, const Index co2) { return m->findCollisionPair(co1, co2); } static bool computeCollision(const GeometryDataHandler & m, const Index co1, const Index co2) { return m->computeCollision(co1, co2); } static bool isColliding(const GeometryDataHandler & m) { return m->isColliding(); } static void computeAllCollisions(GeometryDataHandler & m) { m->computeAllCollisions(); } static DistanceResult computeDistance(const GeometryDataHandler & m, const Index co1, const Index co2) { return m->computeDistance(co1, co2); } static void computeAllDistances(GeometryDataHandler & m) { m->computeAllDistances(); } static std::string toString(const GeometryDataHandler& m) { std::ostringstream s; s << *m; return s.str(); } /* --- Expose --------------------------------------------------------- */ static void expose() { bp::class_< std::vector<DistanceResult> >("StdVec_DistanceResult") .def(bp::vector_indexing_suite< std::vector<DistanceResult> >()); bp::class_<GeometryDataHandler>("GeometryData", "Geometry data linked to a geometry model", bp::no_init) .def(GeometryDataPythonVisitor()); bp::to_python_converter< GeometryDataHandler::SmartPtr_t,GeometryDataPythonVisitor >(); } }; }} // namespace se3::python #endif // ifndef __se3_python_geometry_data_hpp__ <commit_msg>[Python] Complete exposure of Geometry class<commit_after>// // Copyright (c) 2015-2016 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_geometry_data_hpp__ #define __se3_python_geometry_data_hpp__ #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/python/se3.hpp" #include "pinocchio/python/eigen_container.hpp" #include "pinocchio/python/handler.hpp" #include "pinocchio/python/data.hpp" #include "pinocchio/python/geometry-model.hpp" namespace se3 { namespace python { namespace bp = boost::python; struct CollisionPairPythonVisitor : public boost::python::def_visitor<CollisionPairPythonVisitor> { typedef CollisionPair::Index Index; static void expose() { bp::class_<CollisionPair> ("CollisionPair", "Pair of ordered index defining a pair of collisions", bp::init<const Index &, const Index &> (bp::args("co1 (index)", "co2 (index)"), "Initializer of collision pair")) .def("__str__",&CollisionPairPythonVisitor::toString) .def_readwrite("first",&CollisionPair::first) .def_readwrite("second",&CollisionPair::second); bp::class_< std::vector<CollisionPair> >("StdVec_CollisionPair") .def(bp::vector_indexing_suite< std::vector<CollisionPair> >()); } static std::string toString(const CollisionPair & cp) { std::ostringstream s; s << cp; return s.str(); } }; // struct CollisionPairPythonVisitor typedef Handler<GeometryData> GeometryDataHandler; struct GeometryDataPythonVisitor : public boost::python::def_visitor< GeometryDataPythonVisitor > { typedef GeometryData::Index Index; typedef GeometryData::CollisionPair_t CollisionPair_t; typedef se3::DistanceResult DistanceResult; typedef eigenpy::UnalignedEquivalent<SE3>::type SE3_fx; /* --- Convert From C++ to Python ------------------------------------- */ // static PyObject* convert(Model const& modelConstRef) // { // Model * ptr = const_cast<Model*>(&modelConstRef); // return boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr()); // } static PyObject* convert(GeometryDataHandler::SmartPtr_t const& ptr) { return boost::python::incref(boost::python::object(GeometryDataHandler(ptr)).ptr()); } /* --- Exposing C++ API to python through the handler ----------------- */ template<class PyClass> void visit(PyClass& cl) const { cl .def("__init__", bp::make_constructor(&GeometryDataPythonVisitor::makeDefault, bp::default_call_policies(), (bp::arg("data"),bp::arg("geometry_model"))), "Initialize from data and the geometry model.") .add_property("nCollisionPairs", &GeometryDataPythonVisitor::nCollisionPairs) .add_property("oMg", bp::make_function(&GeometryDataPythonVisitor::oMg, bp::return_internal_reference<>()), "Vector of collision objects placement relative to the world.") .add_property("collision_pairs", bp::make_function(&GeometryDataPythonVisitor::collision_pairs, bp::return_internal_reference<>()), "Vector of collision pairs.") .add_property("distance_results", bp::make_function(&GeometryDataPythonVisitor::distance_results, bp::return_internal_reference<>()), "Vector of distance results computed in ") .add_property("collision_results", bp::make_function(&GeometryDataPythonVisitor::collision_results, bp::return_internal_reference<>()) ) .def("addCollisionPair",&GeometryDataPythonVisitor::addCollisionPair, bp::args("co1 (index)","co2 (index)"), "Add a collision pair given by the index of the two collision objects." " Remark: co1 < co2") .def("addAllCollisionPairs",&GeometryDataPythonVisitor::addAllCollisionPairs, "Add all collision pairs.") .def("removeCollisionPair",&GeometryDataPythonVisitor::removeCollisionPair, bp::args("co1 (index)","co2 (index)"), "Remove a collision pair given by the index of the two collision objects." " Remark: co1 < co2") .def("removeAllCollisionPairs",&GeometryDataPythonVisitor::removeAllCollisionPairs, "Remove all collision pairs.") .def("existCollisionPair",&GeometryDataPythonVisitor::existCollisionPair, bp::args("co1 (index)","co2 (index)"), "Check if a collision pair given by the index of the two collision objects exists or not." " Remark: co1 < co2") .def("findCollisionPair", &GeometryDataPythonVisitor::findCollisionPair, bp::args("co1 (index)","co2 (index)"), "Return the index of a collision pair given by the index of the two collision objects exists or not." " Remark: co1 < co2") .def("computeCollision",&GeometryDataPythonVisitor::computeCollision, bp::args("co1 (index)","co2 (index)"), "Check if the two collision objects of a collision pair are in collision." "The collision pair is given by the two index of the collision objects.") .def("computeAllCollisions",&GeometryDataPythonVisitor::computeAllCollisions, "Same as computeCollision. It applies computeCollision to all collision pairs contained collision_pairs." "The results are stored in collision_results.") .def("isColliding",&GeometryDataPythonVisitor::isColliding, "Check if at least one of the collision pairs is in collision.") .def("computeDistance",&GeometryDataPythonVisitor::computeDistance, bp::args("co1 (index)","co2 (index)"), "Compute the distance result between two collision objects of a collision pair." "The collision pair is given by the two index of the collision objects.") .def("computeAllDistances",&GeometryDataPythonVisitor::computeAllDistances, "Same as computeDistance. It applies computeDistance to all collision pairs contained collision_pairs." "The results are stored in collision_distances.") .def("__str__",&GeometryDataPythonVisitor::toString) ; } static GeometryDataHandler* makeDefault(const DataHandler & data, const GeometryModelHandler & geometry_model) { return new GeometryDataHandler(new GeometryData(*data, *geometry_model), true); } static Index nCollisionPairs(const GeometryDataHandler & m ) { return m->nCollisionPairs; } static std::vector<SE3> & oMg(GeometryDataHandler & m) { return m->oMg; } static std::vector<CollisionPair_t> & collision_pairs( GeometryDataHandler & m ) { return m->collision_pairs; } static std::vector<DistanceResult> & distance_results( GeometryDataHandler & m ) { return m->distance_results; } static std::vector<bool> & collision_results( GeometryDataHandler & m ) { return m->collision_results; } static void addCollisionPair (GeometryDataHandler & m, const Index co1, const Index co2) { m->addCollisionPair(co1, co2); } static void addAllCollisionPairs (GeometryDataHandler & m) { m->addAllCollisionPairs(); } static void removeCollisionPair (GeometryDataHandler & m, const Index co1, const Index co2) { m->removeCollisionPair(co1, co2); } static void removeAllCollisionPairs (GeometryDataHandler & m) { m->removeAllCollisionPairs(); } static bool existCollisionPair (const GeometryDataHandler & m, const Index co1, const Index co2) { return m->existCollisionPair(co1, co2); } static GeometryData::Index findCollisionPair (const GeometryDataHandler & m, const Index co1, const Index co2) { return m->findCollisionPair(co1, co2); } static bool computeCollision(const GeometryDataHandler & m, const Index co1, const Index co2) { return m->computeCollision(co1, co2); } static bool isColliding(const GeometryDataHandler & m) { return m->isColliding(); } static void computeAllCollisions(GeometryDataHandler & m) { m->computeAllCollisions(); } static DistanceResult computeDistance(const GeometryDataHandler & m, const Index co1, const Index co2) { return m->computeDistance(co1, co2); } static void computeAllDistances(GeometryDataHandler & m) { m->computeAllDistances(); } static std::string toString(const GeometryDataHandler& m) { std::ostringstream s; s << *m; return s.str(); } /* --- Expose --------------------------------------------------------- */ static void expose() { bp::class_< std::vector<DistanceResult> >("StdVec_DistanceResult") .def(bp::vector_indexing_suite< std::vector<DistanceResult> >()); bp::class_<GeometryDataHandler>("GeometryData", "Geometry data linked to a geometry model", bp::no_init) .def(GeometryDataPythonVisitor()); bp::to_python_converter< GeometryDataHandler::SmartPtr_t,GeometryDataPythonVisitor >(); } }; }} // namespace se3::python #endif // ifndef __se3_python_geometry_data_hpp__ <|endoftext|>
<commit_before>/* Copyright 2009 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include "py_oiio.h" namespace PyOpenImageIO { using namespace boost::python; using namespace std; template <typename BaseType> object ParamValue_convert(const TypeDesc& t, int n, const BaseType* data) { switch (t.aggregate) { case TypeDesc::SCALAR: return object(data[n]); case TypeDesc::VEC2: return make_tuple(data[n*2], data[n*2+1]); case TypeDesc::VEC3: return make_tuple(data[n*3], data[n*3+1], data[n*3+2]); case TypeDesc::VEC4: return make_tuple(data[n*4], data[n*4+1], data[n*4+2], data[n*4+3]); // Bypass the make_tuple argument list size limit by making two // tuples and adding them. Inefficient, but not likely to be a bottleneck. // If it turns out we need efficient access to this stuff we should look // at an array/ctypes interface. case TypeDesc::MATRIX44: return make_tuple( data[n*16+0], data[n*16+1], data[n*16+2], data[n*16+3], data[n*16+4], data[n*16+5], data[n*16+6], data[n*16+7]) + make_tuple(data[n*16+8], data[n*16+9], data[n*16+10], data[n*16+11], data[n*16+12], data[n*16+13], data[n*16+14], data[n*16+15]); default: PyErr_SetString(PyExc_TypeError, "Unable to convert ParamValue with unknown TypeDesc"); throw_error_already_set(); } return object(); } object ParamValue_getitem(const ParamValue& self, int n) { if (n >= self.nvalues()) { PyErr_SetString(PyExc_IndexError, "ParamValue index out of range"); throw_error_already_set(); } TypeDesc t = self.type(); #define ParamValue_convert_dispatch(TYPE) \ case TypeDesc::TYPE: \ return ParamValue_convert(t,n,(CType<TypeDesc::TYPE>::type*)self.data()); switch (t.basetype) { ParamValue_convert_dispatch(UCHAR) ParamValue_convert_dispatch(CHAR) ParamValue_convert_dispatch(USHORT) ParamValue_convert_dispatch(SHORT) ParamValue_convert_dispatch(UINT) ParamValue_convert_dispatch(INT) ParamValue_convert_dispatch(ULONGLONG) ParamValue_convert_dispatch(LONGLONG) #ifdef _HALF_H_ ParamValue_convert_dispatch(HALF) #endif ParamValue_convert_dispatch(FLOAT) ParamValue_convert_dispatch(DOUBLE) case TypeDesc::STRING: return ParamValue_convert(t, n, (ustring*)self.data()); default: return object(); } #undef ParamValue_convert_dispatch } ustring ParamValue_name(const ParamValue& self) { return self.name(); } ParamValue& ParamValueList_getitem(ParamValueList& self, int i) { return self[i]; } void declare_paramvalue() { enum_<ParamValue::Interp>("Interp") .value("INTERP_CONSTANT", ParamValue::INTERP_CONSTANT) .value("INTERP_PERPIECE", ParamValue::INTERP_PERPIECE) .value("INTERP_LINEAR", ParamValue::INTERP_LINEAR) .value("INTERP_VERTEX", ParamValue::INTERP_VERTEX) ; class_<ParamValue>("ParamValue") .add_property("name", &ParamValue_name) .add_property("type", &ParamValue::type) .def("__getitem__", &ParamValue_getitem) .def("__len__", &ParamValue::nvalues) ; class_<ParamValueList>("ParamValueList") .def("__getitem__", &ParamValueList_getitem, return_internal_reference<>()) .def("__len__", &ParamValueList::size) .def("grow", &ParamValueList::grow, return_internal_reference<>()) .def("append", &ParamValueList::push_back) .def("clear", &ParamValueList::clear) .def("free", &ParamValueList::free) .def("resize", &ParamValueList::resize) ; } } <commit_msg>fixes OIIO issue 518, extra_attribs properly responds to iterator calls<commit_after>/* Copyright 2009 Larry Gritz and the other authors and contributors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the software's owners nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (This is the Modified BSD License) */ #include "py_oiio.h" namespace PyOpenImageIO { using namespace boost::python; using namespace std; template <typename BaseType> object ParamValue_convert(const TypeDesc& t, int n, const BaseType* data) { switch (t.aggregate) { case TypeDesc::SCALAR: return object(data[n]); case TypeDesc::VEC2: return make_tuple(data[n*2], data[n*2+1]); case TypeDesc::VEC3: return make_tuple(data[n*3], data[n*3+1], data[n*3+2]); case TypeDesc::VEC4: return make_tuple(data[n*4], data[n*4+1], data[n*4+2], data[n*4+3]); // Bypass the make_tuple argument list size limit by making two // tuples and adding them. Inefficient, but not likely to be a bottleneck. // If it turns out we need efficient access to this stuff we should look // at an array/ctypes interface. case TypeDesc::MATRIX44: return make_tuple( data[n*16+0], data[n*16+1], data[n*16+2], data[n*16+3], data[n*16+4], data[n*16+5], data[n*16+6], data[n*16+7]) + make_tuple(data[n*16+8], data[n*16+9], data[n*16+10], data[n*16+11], data[n*16+12], data[n*16+13], data[n*16+14], data[n*16+15]); default: PyErr_SetString(PyExc_TypeError, "Unable to convert ParamValue with unknown TypeDesc"); throw_error_already_set(); } return object(); } object ParamValue_getitem(const ParamValue& self, int n) { if (n >= self.nvalues()) { PyErr_SetString(PyExc_IndexError, "ParamValue index out of range"); throw_error_already_set(); } TypeDesc t = self.type(); #define ParamValue_convert_dispatch(TYPE) \ case TypeDesc::TYPE: \ return ParamValue_convert(t,n,(CType<TypeDesc::TYPE>::type*)self.data()); switch (t.basetype) { ParamValue_convert_dispatch(UCHAR) ParamValue_convert_dispatch(CHAR) ParamValue_convert_dispatch(USHORT) ParamValue_convert_dispatch(SHORT) ParamValue_convert_dispatch(UINT) ParamValue_convert_dispatch(INT) ParamValue_convert_dispatch(ULONGLONG) ParamValue_convert_dispatch(LONGLONG) #ifdef _HALF_H_ ParamValue_convert_dispatch(HALF) #endif ParamValue_convert_dispatch(FLOAT) ParamValue_convert_dispatch(DOUBLE) case TypeDesc::STRING: return ParamValue_convert(t, n, (ustring*)self.data()); default: return object(); } #undef ParamValue_convert_dispatch } ustring ParamValue_name(const ParamValue& self) { return self.name(); } ParamValue& ParamValueList_getitem(ParamValueList& self, int i) { return self[i]; } void declare_paramvalue() { enum_<ParamValue::Interp>("Interp") .value("INTERP_CONSTANT", ParamValue::INTERP_CONSTANT) .value("INTERP_PERPIECE", ParamValue::INTERP_PERPIECE) .value("INTERP_LINEAR", ParamValue::INTERP_LINEAR) .value("INTERP_VERTEX", ParamValue::INTERP_VERTEX) ; class_<ParamValue>("ParamValue") .add_property("name", &ParamValue_name) .add_property("type", &ParamValue::type) .def("__getitem__", &ParamValue_getitem) .def("__len__", &ParamValue::nvalues) ; class_<ParamValueList>("ParamValueList") .def("__getitem__", &ParamValueList_getitem, return_internal_reference<>()) .def("__iter__", boost::python::iterator<ParamValueList>()) .def("__len__", &ParamValueList::size) .def("grow", &ParamValueList::grow, return_internal_reference<>()) .def("append", &ParamValueList::push_back) .def("clear", &ParamValueList::clear) .def("free", &ParamValueList::free) .def("resize", &ParamValueList::resize) ; } } <|endoftext|>
<commit_before>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/tools/tokenizer.h> #include "readxml.h" void ReadXML::Initialize(QMTopology* top, Property* options) { _filename = options->get("options.readxml.file").as<string>(); } bool ReadXML::EvaluateFrame(QMTopology *top) { _top = top; _parser.NextHandler(this, &ReadXML::ParseRoot); _parser.Open(_filename); } void ReadXML::EndEvaluate(QMTopology *top) { } void ReadXML::ParseRoot(const string &el, map<string, string> &attr) { if(el != "qmtop") throw std::runtime_error("Wrong root node in xml. Must be qmtop."); _parser.NextHandler(this, &ReadXML::ParseBody); } void ReadXML::ParseBody(const string &el, map<string, string> &attr) { if(el == "frame") { _parser.NextHandler(this, &ReadXML::ParseFrame); } else throw std::runtime_error("error, unknown node: " + el); } void ReadXML::ParseFrame(const string &el, map<string, string> &attr) { if(el == "clear_nblist") { _top->nblist().Cleanup(); } else if(el == "pair") { int first = lexical_cast<int>(attr["first"]) - 1; int second = lexical_cast<int>(attr["second"]) - 1; QMCrgUnit *crg1 = _top->GetCrgUnit(first); QMCrgUnit *crg2 = _top->GetCrgUnit(second); if(crg1->getId() > crg2->getId()) swap(crg1, crg2); if(_top->nblist().FindPair(crg1, crg2)) throw std::runtime_error("multiple definitions of pair (" + lexical_cast<string>(first+1) + ", " + lexical_cast<string>(second+1) + ")"); QMPair *pair = new QMPair(crg1, crg2, _top); map<string,string>::iterator iter; for(iter=attr.begin(); iter!=attr.end(); ++iter) { if(iter->first == "J") { Tokenizer tok(iter->second, " "); tok.ConvertToVector<double>(pair->Js()); } else if(iter->first == "rate12") { pair->setRate12(lexical_cast<double>(iter->second)); } else if(iter->first == "rate21") { pair->setRate21(lexical_cast<double>(iter->second)); } else if(iter->first == "first" || iter->first == "second") { } else if(iter->first == "lambda_out") { pair->setLambdaOuter(lexical_cast<double>(iter->second)); } else throw std::runtime_error("undefined property in pair: \"" + iter->first + "\""); } _top->nblist().AddPair(pair); } else if (el == "site" ) { int site_number = lexical_cast<int>(attr["number"]) - 1; CrgUnit *crg = _top->GetCrgUnit(site_number); map<string,string>::iterator iter; for(iter=attr.begin(); iter!=attr.end(); ++iter) { if(iter->first == "energy") { crg->setEnergy(lexical_cast<double>(iter->second)); } } } else throw std::runtime_error("unknown node: " + el); _parser.IgnoreChilds(); } <commit_msg>modification including lambda outer sphere<commit_after>/* * Copyright 2009 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <votca/tools/tokenizer.h> #include "readxml.h" void ReadXML::Initialize(QMTopology* top, Property* options) { _filename = options->get("options.readxml.file").as<string>(); } bool ReadXML::EvaluateFrame(QMTopology *top) { _top = top; _parser.NextHandler(this, &ReadXML::ParseRoot); _parser.Open(_filename); } void ReadXML::EndEvaluate(QMTopology *top) { } void ReadXML::ParseRoot(const string &el, map<string, string> &attr) { if(el != "qmtop") throw std::runtime_error("Wrong root node in xml. Must be qmtop."); _parser.NextHandler(this, &ReadXML::ParseBody); } void ReadXML::ParseBody(const string &el, map<string, string> &attr) { if(el == "frame") { _parser.NextHandler(this, &ReadXML::ParseFrame); } else throw std::runtime_error("error, unknown node: " + el); } void ReadXML::ParseFrame(const string &el, map<string, string> &attr) { if(el == "clear_nblist") { _top->nblist().Cleanup(); } else if(el == "pair") { int first = lexical_cast<int>(attr["first"]) - 1; int second = lexical_cast<int>(attr["second"]) - 1; QMCrgUnit *crg1 = _top->GetCrgUnit(first); QMCrgUnit *crg2 = _top->GetCrgUnit(second); if(crg1->getId() > crg2->getId()) swap(crg1, crg2); if(_top->nblist().FindPair(crg1, crg2)) throw std::runtime_error("multiple definitions of pair (" + lexical_cast<string>(first+1) + ", " + lexical_cast<string>(second+1) + ")"); QMPair *pair = new QMPair(crg1, crg2, _top); map<string,string>::iterator iter; for(iter=attr.begin(); iter!=attr.end(); ++iter) { //cout << iter->first <<endl; if(iter->first == "J") { Tokenizer tok(iter->second, " "); tok.ConvertToVector<double>(pair->Js()); } else if(iter->first == "rate12") { pair->setRate12(lexical_cast<double>(iter->second)); } else if(iter->first == "rate21") { pair->setRate21(lexical_cast<double>(iter->second)); } else if(iter->first == "dist" || iter->first == "Jeff" ||iter->first == "rij" ) { } else if(iter->first == "lambdaout") { pair->setLambdaOuter(lexical_cast<double>(iter->second)); } else if(iter->first == "first" || iter->first == "second") { } else throw std::runtime_error("undefined property in pair: \"" + iter->first + "\""); } _top->nblist().AddPair(pair); } else if (el == "site" ) { int site_number = lexical_cast<int>(attr["number"]) - 1; CrgUnit *crg = _top->GetCrgUnit(site_number); map<string,string>::iterator iter; for(iter=attr.begin(); iter!=attr.end(); ++iter) { if(iter->first == "energy") { crg->setEnergy(lexical_cast<double>(iter->second)); } } } else throw std::runtime_error("unknown node: " + el); _parser.IgnoreChilds(); } <|endoftext|>
<commit_before>// Copyright (c) 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/logging/logging.h" #include "libmv/detector/detector.h" #include "libmv/correspondence/feature.h" #include "libmv/image/image.h" #include "libmv/image/surf.h" namespace libmv { namespace detector { class SurfDetector : public Detector { public: virtual ~SurfDetector() {} SurfDetector(int num_octaves, int num_intervals) :num_octaves_(num_octaves), num_intervals_(num_intervals) {} virtual void Detect(const Image &image, vector<Feature *> *features, DetectorData **data) { int num_corners = 0; ByteImage *byte_image = image.AsArray3Du(); //TODO(pmoulon) Assert that byte_image is valid. Matu integral_image; IntegralImage(*byte_image, &integral_image); libmv::vector<PointFeature> detections; MultiscaleDetectFeatures(integral_image, num_octaves_, num_intervals_, &detections); for (int i = 0; i < detections.size(); ++i) { PointFeature *f = new PointFeature(detections[i].x(), detections[i].y()); f->scale = detections[i].scale; f->orientation = detections[i].orientation; features->push_back(f); } //data can contain the integral image that can be use for descriptor computation if (data) { *data = NULL; } } private: int num_octaves_; int num_intervals_; }; Detector *CreateSURFDetector(int num_octaves, int num_intervals) { return new SurfDetector(num_octaves, num_intervals); } } // namespace detector } // namespace libmv <commit_msg>remove unused variable.<commit_after>// Copyright (c) 2009 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #include "libmv/logging/logging.h" #include "libmv/detector/detector.h" #include "libmv/correspondence/feature.h" #include "libmv/image/image.h" #include "libmv/image/surf.h" namespace libmv { namespace detector { class SurfDetector : public Detector { public: virtual ~SurfDetector() {} SurfDetector(int num_octaves, int num_intervals) :num_octaves_(num_octaves), num_intervals_(num_intervals) {} virtual void Detect(const Image &image, vector<Feature *> *features, DetectorData **data) { ByteImage *byte_image = image.AsArray3Du(); //TODO(pmoulon) Assert that byte_image is valid. Matu integral_image; IntegralImage(*byte_image, &integral_image); libmv::vector<PointFeature> detections; MultiscaleDetectFeatures(integral_image, num_octaves_, num_intervals_, &detections); for (int i = 0; i < detections.size(); ++i) { PointFeature *f = new PointFeature(detections[i].x(), detections[i].y()); f->scale = detections[i].scale; f->orientation = detections[i].orientation; features->push_back(f); } //data can contain the integral image that can be use for descriptor computation if (data) { *data = NULL; } } private: int num_octaves_; int num_intervals_; }; Detector *CreateSURFDetector(int num_octaves, int num_intervals) { return new SurfDetector(num_octaves, num_intervals); } } // namespace detector } // namespace libmv <|endoftext|>
<commit_before>/** * The database populated by the importer uses TIMESTAMP columns to * represent times and dates. This class formats them according to section * 8.5.1.3 of the postgres docs: * http://www.postgresql.org/docs/9.1/static/datatype-datetime.html */ #ifndef IMPORTER_TIMESTAMP_HPP #define IMPORTER_TIMESTAMP_HPP /** * Formats timestamps according to the postgres docs */ class Timestamp { private: /** * length of ISO timestamp string yyyy-mm-ddThh:mm:ssZ\0 */ static const int timestamp_length = 20 + 1; /** * The timestamp format for OSM timestamps in strftime(3) format. * This is the ISO-Format yyyy-mm-ddThh:mm:ssZ */ static const char *timestamp_format() { static const char f[] = "%Y-%m-%dT%H:%M:%SZ"; return f; } public: /** * Format the timestamp */ static std::string format(const time_t time) { struct tm *tm = gmtime(&time); std::string s(timestamp_length, '\0'); /* This const_cast is ok, because we know we have enough space in the string for the format we are using (well at least until the year will have 5 digits). And by setting the size afterwards from the result of strftime we make sure thats set right, too. */ s.resize(strftime(const_cast<char *>(s.c_str()), timestamp_length, timestamp_format(), tm)); return s; } static std::string formatDb(const time_t time) { if(time == 0) { return "\\N"; } return format(time); } }; #endif // IMPORTER_TIMESTAMP_HPP <commit_msg>document new timestamp format method<commit_after>/** * The database populated by the importer uses TIMESTAMP columns to * represent times and dates. This class formats them according to section * 8.5.1.3 of the postgres docs: * http://www.postgresql.org/docs/9.1/static/datatype-datetime.html */ #ifndef IMPORTER_TIMESTAMP_HPP #define IMPORTER_TIMESTAMP_HPP /** * Formats timestamps according to the postgres docs */ class Timestamp { private: /** * length of ISO timestamp string yyyy-mm-ddThh:mm:ssZ\0 */ static const int timestamp_length = 20 + 1; /** * The timestamp format for OSM timestamps in strftime(3) format. * This is the ISO-Format yyyy-mm-ddThh:mm:ssZ */ static const char *timestamp_format() { static const char f[] = "%Y-%m-%dT%H:%M:%SZ"; return f; } public: /** * Format the timestamp */ static std::string format(const time_t time) { struct tm *tm = gmtime(&time); std::string s(timestamp_length, '\0'); /* * This const_cast is ok, because we know we have enough space * in the string for the format we are using (well at least until * the year will have 5 digits). And by setting the size * afterwards from the result of strftime we make sure thats set * right, too. */ s.resize(strftime(const_cast<char *>(s.c_str()), timestamp_length, timestamp_format(), tm)); return s; } /** * the timestamp 0 has a special meaning in the context of osm data. * in 1970 there was no osm. For a valid_to value, where this method * is used for, a timestamp of 0 is identical to "never" (as in: at * least valid untill today) which is in the database represented as * NULL. In the copy pipe used to fill the database, this NULL is * represented as \N which is returned by this method for a timestamp * of 0. In any other cast, the result is identical to the result of * the format(const time_t) method. */ static std::string formatDb(const time_t time) { // return special string indicating a value of NULL in a postgres // copy pipe for a timestamp of 0 if(time == 0) { return "\\N"; } // return the formatted timestamp return format(time); } }; #endif // IMPORTER_TIMESTAMP_HPP <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> using namespace std; template<typename T> struct Node { T x; Node<T> * left; Node<T> * right; Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {} }; template<typename T> class Tree { private: Node<T> * root; public: Tree() { root = nullptr; } ~Tree() { deleteNode(root); } void deleteNode(Node<T> * node) { if (node == nullptr) return; deleteNode(node->left); deleteNode(node->right); delete node; } T x_() const { return root->x; } T left_() const { return root->left->x; } T right_() const { return root->right->x; } Node<T> * root_() const { return root; } void insert(const T& value) { insert(root, value); } void insert(Node<T>* & node, const T& value) { if (node) { if (value < node->x) { insert(node->left, value); } else if (value > node->x) { insert(node->right, value); } else { return; } } else { node = new Node<T>(value); } } Node<T> * search(const T& x)const { Node<T> * curEl = root; while (curEl != nullptr) { if (curEl->x == x) break; else { if (x > curEl->x) curEl = curEl->right; else curEl = curEl->left; } } return curEl; } bool check_search(const T& x) { Node<T> * node; node = search(x); if (node != nullptr) return true; else return false; } void fIn(const string filename) { ifstream fin; unsigned int k; fin.open(filename); if (!fin.is_open()) cout << "The file isn't find" << endl; else { deleteNode(root); if (fin.eof()) return; else { fin >> k; T newEl; for (unsigned int i = 0; i < k; ++i) { fin >> newEl; insert(newEl); } } fin.close(); } } unsigned int size(Node<T> * node)const { unsigned int size_ = 0; if (node != nullptr) size_ = size(node->left) + 1 + size(node->right); return size_; } void out_to_file(const string filename)const { ofstream fout; fout.open(filename); if (!fout.is_open()) cout << "The file isn't find" << endl; else { unsigned int size_ = size(root); if (size_ == 0) return; fout << size_ << "\t"; fOut(root, fout); fout.close(); } } void fOut(Node<T> * node, ostream&stream)const { if (node != nullptr) { fOut(node->left, stream); stream << node->x << " "; fOut(node->right, stream); } } void out(ostream & stream)const { Out(root, stream, 0); } void Out(Node<T> * node, ostream&stream, size_t level)const { Node<T> * curEl = node; if (curEl != nullptr) { Out(curEl->right, stream, level + 1); for (unsigned int i = 0; i < level; ++i) stream << '-'; stream << curEl->x << endl; Out(curEl->left, stream, level + 1); } } }; <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> using namespace std; template<typename T> struct Node { T x; Node<T> * left; Node<T> * right; Node(T const& value) : x{ value }, left{ nullptr }, right{ nullptr } {} }; template<typename T> class Tree { private: Node<T> * root; public: Tree() { root = nullptr; } ~Tree() { deleteNode(root); } void deleteNode(Node<T> * node) { if (node == nullptr) return; deleteNode(node->left); deleteNode(node->right); delete node; } T x_() const { return root->x; } Node<T> * left_() const { return root->left; } Node<T> * right_() const { return root->right; } Node<T> * root_() const { return root; } void insert(const T& value) { insert(root, value); } void insert(Node<T>* & node, const T& value) { if (node) { if (value < node->x) { insert(node->left, value); } else if (value > node->x) { insert(node->right, value); } else { return; } } else { node = new Node<T>(value); } } Node<T> * search(const T& x)const { Node<T> * curEl = root; while (curEl != nullptr) { if (curEl->x == x) break; else { if (x > curEl->x) curEl = curEl->right; else curEl = curEl->left; } } return curEl; } bool check_search(const T& x) { Node<T> * node; node = search(x); if (node != nullptr) return true; else return false; } void fIn(const string filename) { ifstream fin; unsigned int k; fin.open(filename); if (!fin.is_open()) cout << "The file isn't find" << endl; else { deleteNode(root); if (fin.eof()) return; else { fin >> k; T newEl; for (unsigned int i = 0; i < k; ++i) { fin >> newEl; insert(newEl); } } fin.close(); } } unsigned int size(Node<T> * node)const { unsigned int size_ = 0; if (node != nullptr) size_ = size(node->left) + 1 + size(node->right); return size_; } void out_to_file(const string filename)const { ofstream fout; fout.open(filename); if (!fout.is_open()) cout << "The file isn't find" << endl; else { unsigned int size_ = size(root); if (size_ == 0) return; fout << size_ << "\t"; fOut(root, fout); fout.close(); } } void fOut(Node<T> * node, ostream&stream)const { if (node != nullptr) { fOut(node->left, stream); stream << node->x << " "; fOut(node->right, stream); } } void out(ostream & stream)const { Out(root, stream, 0); } void Out(Node<T> * node, ostream&stream, size_t level)const { Node<T> * curEl = node; if (curEl != nullptr) { Out(curEl->right, stream, level + 1); for (unsigned int i = 0; i < level; ++i) stream << '-'; stream << curEl->x << endl; Out(curEl->left, stream, level + 1); } } }; <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree { private: Node<T>* root; int CountElements = 0; public: BinaryTree(); ~BinaryTree(); BinaryTree(const std::initializer_list<T>&); void _deleteElements(Node<T>*); unsigned int count() const; void BinaryTree<T>::insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; Node<T>*root_(); void BinaryTree<T>::deleteNode(Node<T>* temp); void BinaryTree<T>::writing(const std::string& filename)const; void output(std::ostream& ost, const Node<T>* temp); friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template <typename T> void BinaryTree<T>::_deleteElements(Node<T>* temp) { if (!temp) { throw "error"; } _deleteElements(temp->left); _deleteElements(temp->right); delete node; } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { throw "error"; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void output(std::ostream& ost, const Node<T>* temp) { if (temp == nullptr) { throw "error"; return; } else { ost << temp->data << " "; output(ost, temp->left); output(ost, temp->right); } } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& show(std::ostream& os, const Node<T>* node, unsigned int level) { if (!node) return os; show(os, node->right, level + 1); for (unsigned int i = 0; i < level; i++) os << "\t"; os << node->data << std::endl; show(os, node->left, level + 1); return os; } template <typename T> std::ostream& operator<<(std::ostream& os, const BinaryTree<T>& temp) { if (!temp.root) throw "error"; show(os, temp.root, 0); return os; } <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree { private: Node<T>* root; int CountElements = 0; public: BinaryTree(); ~BinaryTree(); BinaryTree(const std::initializer_list<T>&); void _deleteElements(Node<T>*); unsigned int count() const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; Node<T>*root_(); void deleteNode(Node<T>* temp); void writing(const std::string& filename)const; void output(std::ostream& ost, const Node<T>* temp); friend std::ostream& operator<< <> (std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template <typename T> void BinaryTree<T>::_deleteElements(Node<T>* temp) { if (!temp) { throw "error"; } _deleteElements(temp->left); _deleteElements(temp->right); delete node; } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { if (!temp) { throw "error"; } if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::output(std::ostream& ost, const Node<T>* temp) { if (temp == nullptr) { throw "error"; return; } else { ost << temp->data << " "; output(ost, temp->left); output(ost, temp->right); } } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& show(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; show(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; show(ost, node->left, level + 1); return ost; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& bst) { if (!bst.root) throw "error"; show(ost, bst.root, 0); return ost; } int main() { BinaryTree<int>tree; tree.insert_node(2); tree.insert_node(3); tree.insert_node(4); tree.insert_node(11); cout << tree; system ("pause"); } <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <fstream> #include <exception> #include <string> #include <limits> #include <cctype> #include <CImg.h> #include <ArgumentList.hpp> #include <ColorMap.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { bool gray = false; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; float minSNR = std::numeric_limits< float >::max(); float maxSNR = std::numeric_limits< float >::min(); float snrSpaceDim = 0.0f; float * snrSpace = 0; std::string outFilename; std::ifstream searchFile; isa::utils::ArgumentList args(argc, argv); try { gray = args.getSwitch("-gray"); outFilename = args.getSwitchArgument< std::string >("-output"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } snrSpace = new float [nrDMs * nrPeriods]; try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); if ( snr > maxSNR ) { maxSNR = snr; } if ( snr < minSNR ) { minSNR = snr; } snrSpace[(period * nrDMs) + DM] = snr; } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { snrSpaceDim = maxSNR - minSNR; } cimg_library::CImg< unsigned char > searchImage; AstroData::Color * colorMap; if ( gray ) { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1); } else { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3); colorMap = AstroData::getColorMap(); } for ( unsigned int period = 0; period < nrPeriods; period++ ) { for ( unsigned int DM = 0; DM < nrDMs; DM++ ) { float snr = snrSpace[(period * nrDMs) + DM]; if ( gray ) { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = static_cast< unsigned char >(((snr - minSNR) * 255.0) / snrSpaceDim); } else { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR(); searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG(); searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB(); } } } searchImage.save(outFilename.c_str()); delete [] snrSpace; return 0; } <commit_msg>Inverting the colors of the gray image.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <fstream> #include <exception> #include <string> #include <limits> #include <cctype> #include <CImg.h> #include <ArgumentList.hpp> #include <ColorMap.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { bool gray = false; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; float minSNR = std::numeric_limits< float >::max(); float maxSNR = std::numeric_limits< float >::min(); float snrSpaceDim = 0.0f; float * snrSpace = 0; std::string outFilename; std::ifstream searchFile; isa::utils::ArgumentList args(argc, argv); try { gray = args.getSwitch("-gray"); outFilename = args.getSwitchArgument< std::string >("-output"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-gray] -output ... -dms ... -periods ... input" << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } snrSpace = new float [nrDMs * nrPeriods]; try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); if ( snr > maxSNR ) { maxSNR = snr; } if ( snr < minSNR ) { minSNR = snr; } snrSpace[(period * nrDMs) + DM] = snr; } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { snrSpaceDim = maxSNR - minSNR; } cimg_library::CImg< unsigned char > searchImage; AstroData::Color * colorMap; if ( gray ) { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 1); } else { searchImage = cimg_library::CImg< unsigned char >(nrDMs, nrPeriods, 1, 3); colorMap = AstroData::getColorMap(); } for ( unsigned int period = 0; period < nrPeriods; period++ ) { for ( unsigned int DM = 0; DM < nrDMs; DM++ ) { float snr = snrSpace[(period * nrDMs) + DM]; if ( gray ) { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = 255 - static_cast< unsigned char >(((snr - minSNR) * 255.0) / snrSpaceDim); } else { searchImage(DM, (nrPeriods - 1) - period, 0, 0) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getR(); searchImage(DM, (nrPeriods - 1) - period, 0, 1) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getG(); searchImage(DM, (nrPeriods - 1) - period, 0, 2) = (colorMap[static_cast< unsigned int >(((snr - minSNR) * 256.0) / snrSpaceDim)]).getB(); } } } searchImage.save(outFilename.c_str()); delete [] snrSpace; return 0; } <|endoftext|>
<commit_before>/* * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fs.hpp" #include <filesystem> #include <regex> #include <string> #include <system_error> #include <vector> namespace ipmi_flash { namespace fs = std::filesystem; std::vector<std::string> GetJsonList(const std::string& directory) { std::vector<std::string> output; try { for (const auto& p : fs::recursive_directory_iterator(directory)) { auto ps = p.path().string(); /** TODO: openbmc/phosphor-ipmi-blobs/blob/de8a16e2e8/fs.cpp#L27 is * nicer, may be worth finding a way to make this into a util. */ if (std::regex_match(ps, std::regex(".+.json$"))) { output.push_back(ps); } } } catch (const fs::filesystem_error& e) { // Ignore missing directories and just return an empty list if (e.code() == std::error_code(ENOENT, std::generic_category())) { return output; } throw; } return output; } } // namespace ipmi_flash <commit_msg>bmc/fs: Replace regex with fs functions<commit_after>/* * Copyright 2019 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "fs.hpp" #include <filesystem> #include <string> #include <system_error> #include <vector> namespace ipmi_flash { namespace fs = std::filesystem; std::vector<std::string> GetJsonList(const std::string& directory) { std::vector<std::string> output; try { for (const auto& p : fs::recursive_directory_iterator(directory)) { auto path = p.path(); if (path.extension().string() == ".json") { output.push_back(path.string()); } } } catch (const fs::filesystem_error& e) { // Ignore missing directories and just return an empty list if (e.code() == std::error_code(ENOENT, std::generic_category())) { return output; } throw; } return output; } } // namespace ipmi_flash <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "liblocationwrapper_p.h" using namespace std; QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine) LiblocationWrapper *LiblocationWrapper::instance() { return LocationEngine(); } LiblocationWrapper::~LiblocationWrapper() { if (locationDevice) g_object_unref(locationDevice); if (locationControl) g_object_unref(locationControl); } bool LiblocationWrapper::inited() { int retval = false; if (!(locationState & LiblocationWrapper::Inited)) { g_type_init(); locationControl = location_gpsd_control_get_default(); if (locationControl) { g_object_set(G_OBJECT(locationControl), "preferred-method", LOCATION_METHOD_USER_SELECTED, "preferred-interval", LOCATION_INTERVAL_1S, NULL); locationDevice = (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, NULL); if (locationDevice) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); locationState = LiblocationWrapper::Inited; retval = true; startcounter = 0; } } } else { retval = true; } return retval; } void LiblocationWrapper::locationError(LocationGPSDevice *device, gint errorCode, gpointer data) { Q_UNUSED(device); QString locationError; switch (errorCode) { case LOCATION_ERROR_USER_REJECTED_DIALOG: locationError = "User didn't enable requested methods"; break; case LOCATION_ERROR_USER_REJECTED_SETTINGS: locationError = "User changed settings, which disabled location."; break; case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE: locationError = "Problems with BT GPS"; break; case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE: locationError = "Requested method is not allowed in offline mode"; break; case LOCATION_ERROR_SYSTEM: locationError = "System error."; break; default: locationError = "Unknown error."; } qDebug() << "Location error:" << locationError; LiblocationWrapper *object; object = (LiblocationWrapper *)data; emit object->error(); } void LiblocationWrapper::locationChanged(LocationGPSDevice *device, gpointer data) { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; QGeoSatelliteInfo satInfo; int satellitesInUseCount = 0; LiblocationWrapper *object; if (!data || !device) { return; } object = (LiblocationWrapper *)data; if (device) { if (device->fix) { if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) { posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time)); } if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) { coordinate.setLatitude(device->fix->latitude); coordinate.setLongitude(device->fix->longitude); posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy, device->fix->eph / 100.0); posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy, device->fix->epv); } if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) { coordinate.setAltitude(device->fix->altitude); } if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, device->fix->speed); } if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, device->fix->climb); } if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) { posInfo.setAttribute(QGeoPositionInfo::Direction, device->fix->track); } } if (device->satellites_in_view) { QList<QGeoSatelliteInfo> satsInView; QList<QGeoSatelliteInfo> satsInUse; unsigned int i; for (i=0;i<device->satellites->len;i++) { LocationGPSDeviceSatellite *satData = (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites, i); satInfo.setSignalStrength(satData->signal_strength); satInfo.setPrnNumber(satData->prn); satInfo.setAttribute(QGeoSatelliteInfo::Elevation, satData->elevation); satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, satData->azimuth); satsInView.append(satInfo); if (satData->in_use) { satellitesInUseCount++; satsInUse.append(satInfo); } } if (!satsInView.isEmpty()) object->satellitesInViewUpdated(satsInView); if (!satsInUse.isEmpty()) object->satellitesInUseUpdated(satsInUse); } } posInfo.setCoordinate(coordinate); if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET || posInfo.attribute(QGeoPositionInfo::HorizontalAccuracy) >= 0) && ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) { object->setLocation(posInfo, true); } else { object->setLocation(posInfo, false); } } void LiblocationWrapper::setLocation(const QGeoPositionInfo &update, bool locationValid) { validLastSatUpdate = locationValid; lastSatUpdate = update; } QGeoPositionInfo LiblocationWrapper::position() { return lastSatUpdate; } bool LiblocationWrapper::fixIsValid() { return validLastSatUpdate; } QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; double time; double latitude; double longitude; double altitude; double speed; double track; double climb; GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time"); GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude"); GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude"); GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude"); GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed"); GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track"); GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb"); if (validLastSatUpdate) return lastSatUpdate; if (!fromSatellitePositioningMethodsOnly) if (validLastUpdate) return lastUpdate; time = lastKnownPositionTime.value().toDouble(); latitude = lastKnownPositionLatitude.value().toDouble(); longitude = lastKnownPositionLongitude.value().toDouble(); altitude = lastKnownPositionAltitude.value().toDouble(); speed = lastKnownPositionSpeed.value().toDouble(); track = lastKnownPositionTrack.value().toDouble(); climb = lastKnownPositionClimb.value().toDouble(); if (longitude && latitude) { coordinate.setLongitude(longitude); coordinate.setLatitude(latitude); if (altitude) { coordinate.setAltitude(altitude); } posInfo.setCoordinate(coordinate); } if (speed) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed); } if (track) { posInfo.setAttribute(QGeoPositionInfo::Direction, track); } if (climb) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); } // Only positions with time (3D) are provided. if (time) { posInfo.setTimestamp(QDateTime::fromTime_t(time)); return posInfo; } return QGeoPositionInfo(); } void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInView = satellites; } void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInUse = satellites; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView() { return satsInView; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse() { return satsInUse; } void LiblocationWrapper::start() { startcounter++; if ((locationState & LiblocationWrapper::Inited) && !(locationState & LiblocationWrapper::Started)) { if (!errorHandlerId) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); } if (!posChangedId) { posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); } location_gpsd_control_start(locationControl); locationState |= LiblocationWrapper::Started; locationState &= ~LiblocationWrapper::Stopped; } } void LiblocationWrapper::stop() { startcounter--; if (startcounter > 0) return; if ((locationState & (LiblocationWrapper::Started | LiblocationWrapper::Inited)) && !(locationState & LiblocationWrapper::Stopped)) { if (errorHandlerId) g_signal_handler_disconnect(G_OBJECT(locationControl), errorHandlerId); if (posChangedId) g_signal_handler_disconnect(G_OBJECT(locationDevice), posChangedId); errorHandlerId = 0; posChangedId = 0; startcounter = 0; location_gpsd_control_stop(locationControl); locationState &= ~LiblocationWrapper::Started; locationState |= LiblocationWrapper::Stopped; } } bool LiblocationWrapper::isActive() { if (locationState & LiblocationWrapper::Started) return true; else return false; } #include "moc_liblocationwrapper_p.cpp" QTM_END_NAMESPACE <commit_msg>Improved the fix for QTMOBILITY-311<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "liblocationwrapper_p.h" #include <QDateTime> using namespace std; QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(LiblocationWrapper, LocationEngine) LiblocationWrapper *LiblocationWrapper::instance() { return LocationEngine(); } LiblocationWrapper::~LiblocationWrapper() { if (locationDevice) g_object_unref(locationDevice); if (locationControl) g_object_unref(locationControl); } bool LiblocationWrapper::inited() { int retval = false; if (!(locationState & LiblocationWrapper::Inited)) { g_type_init(); locationControl = location_gpsd_control_get_default(); if (locationControl) { g_object_set(G_OBJECT(locationControl), "preferred-method", LOCATION_METHOD_USER_SELECTED, "preferred-interval", LOCATION_INTERVAL_1S, NULL); locationDevice = (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, NULL); if (locationDevice) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); locationState = LiblocationWrapper::Inited; retval = true; startcounter = 0; } } } else { retval = true; } return retval; } void LiblocationWrapper::locationError(LocationGPSDevice *device, gint errorCode, gpointer data) { Q_UNUSED(device); QString locationError; switch (errorCode) { case LOCATION_ERROR_USER_REJECTED_DIALOG: locationError = "User didn't enable requested methods"; break; case LOCATION_ERROR_USER_REJECTED_SETTINGS: locationError = "User changed settings, which disabled location."; break; case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE: locationError = "Problems with BT GPS"; break; case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE: locationError = "Requested method is not allowed in offline mode"; break; case LOCATION_ERROR_SYSTEM: locationError = "System error."; break; default: locationError = "Unknown error."; } qDebug() << "Location error:" << locationError; LiblocationWrapper *object; object = (LiblocationWrapper *)data; emit object->error(); } void LiblocationWrapper::locationChanged(LocationGPSDevice *device, gpointer data) { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; QGeoSatelliteInfo satInfo; int satellitesInUseCount = 0; LiblocationWrapper *object; if (!data || !device) { return; } object = (LiblocationWrapper *)data; if (device) { if (device->fix) { if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) { posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time)); } if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) { coordinate.setLatitude(device->fix->latitude); coordinate.setLongitude(device->fix->longitude); posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy, device->fix->eph / 100.0); posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy, device->fix->epv); } if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) { coordinate.setAltitude(device->fix->altitude); } if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, device->fix->speed); } if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, device->fix->climb); } if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) { posInfo.setAttribute(QGeoPositionInfo::Direction, device->fix->track); } } if (device->satellites_in_view) { QList<QGeoSatelliteInfo> satsInView; QList<QGeoSatelliteInfo> satsInUse; unsigned int i; for (i=0;i<device->satellites->len;i++) { LocationGPSDeviceSatellite *satData = (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites, i); satInfo.setSignalStrength(satData->signal_strength); satInfo.setPrnNumber(satData->prn); satInfo.setAttribute(QGeoSatelliteInfo::Elevation, satData->elevation); satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, satData->azimuth); satsInView.append(satInfo); if (satData->in_use) { satellitesInUseCount++; satsInUse.append(satInfo); } } if (!satsInView.isEmpty()) object->satellitesInViewUpdated(satsInView); if (!satsInUse.isEmpty()) object->satellitesInUseUpdated(satsInUse); } } posInfo.setCoordinate(coordinate); /* Invalid fixes have NaN for horizontal accuracy regardless of whether they come from satellite or non-satellite position methods. After the inital fix, satellite methods will always have LOCATION_GPS_DEVICE_TIME_SET. If this is not set and we have a numeric value for horizontal accuracy then we are dealing with a non-satellite based positioning method. Since QGeoPositionInfo instances are only considered valid if they have a valid coordinate and a valid timestamp, we use the current date and time as the timestamp for the network based positioning. This will help in the case where someone wants to reply a journey from a log file. Based on some logging it looks like satellite and non-satellite methods can be distinguished (after the initial fix) by whether the time has been set and / or whether the horizontal accuracy is above or below around 500 metres. Using the timestamp appears to be more definitive than using the accuracy. */ if ((posInfo.attribute(QGeoPositionInfo::HorizontalAccuracy) >= 0) && ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) { if (!(device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET)) posInfo.setTimestamp(QDateTime::currentDateTime()); object->setLocation(posInfo, true); } else { object->setLocation(posInfo, false); } } void LiblocationWrapper::setLocation(const QGeoPositionInfo &update, bool locationValid) { validLastSatUpdate = locationValid; lastSatUpdate = update; } QGeoPositionInfo LiblocationWrapper::position() { return lastSatUpdate; } bool LiblocationWrapper::fixIsValid() { return validLastSatUpdate; } QGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const { QGeoPositionInfo posInfo; QGeoCoordinate coordinate; double time; double latitude; double longitude; double altitude; double speed; double track; double climb; GConfItem lastKnownPositionTime("/system/nokia/location/lastknown/time"); GConfItem lastKnownPositionLatitude("/system/nokia/location/lastknown/latitude"); GConfItem lastKnownPositionLongitude("/system/nokia/location/lastknown/longitude"); GConfItem lastKnownPositionAltitude("/system/nokia/location/lastknown/altitude"); GConfItem lastKnownPositionSpeed("/system/nokia/location/lastknown/speed"); GConfItem lastKnownPositionTrack("/system/nokia/location/lastknown/track"); GConfItem lastKnownPositionClimb("/system/nokia/location/lastknown/climb"); if (validLastSatUpdate) return lastSatUpdate; if (!fromSatellitePositioningMethodsOnly) if (validLastUpdate) return lastUpdate; time = lastKnownPositionTime.value().toDouble(); latitude = lastKnownPositionLatitude.value().toDouble(); longitude = lastKnownPositionLongitude.value().toDouble(); altitude = lastKnownPositionAltitude.value().toDouble(); speed = lastKnownPositionSpeed.value().toDouble(); track = lastKnownPositionTrack.value().toDouble(); climb = lastKnownPositionClimb.value().toDouble(); if (longitude && latitude) { coordinate.setLongitude(longitude); coordinate.setLatitude(latitude); if (altitude) { coordinate.setAltitude(altitude); } posInfo.setCoordinate(coordinate); } if (speed) { posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed); } if (track) { posInfo.setAttribute(QGeoPositionInfo::Direction, track); } if (climb) { posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); } // Only positions with time (3D) are provided. if (time) { posInfo.setTimestamp(QDateTime::fromTime_t(time)); return posInfo; } return QGeoPositionInfo(); } void LiblocationWrapper::satellitesInViewUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInView = satellites; } void LiblocationWrapper::satellitesInUseUpdated(const QList<QGeoSatelliteInfo> &satellites) { satsInUse = satellites; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInView() { return satsInView; } QList<QGeoSatelliteInfo> LiblocationWrapper::satellitesInUse() { return satsInUse; } void LiblocationWrapper::start() { startcounter++; if ((locationState & LiblocationWrapper::Inited) && !(locationState & LiblocationWrapper::Started)) { if (!errorHandlerId) { errorHandlerId = g_signal_connect(G_OBJECT(locationControl), "error-verbose", G_CALLBACK(&locationError), static_cast<void*>(this)); } if (!posChangedId) { posChangedId = g_signal_connect(G_OBJECT(locationDevice), "changed", G_CALLBACK(&locationChanged), static_cast<void*>(this)); } location_gpsd_control_start(locationControl); locationState |= LiblocationWrapper::Started; locationState &= ~LiblocationWrapper::Stopped; } } void LiblocationWrapper::stop() { startcounter--; if (startcounter > 0) return; if ((locationState & (LiblocationWrapper::Started | LiblocationWrapper::Inited)) && !(locationState & LiblocationWrapper::Stopped)) { if (errorHandlerId) g_signal_handler_disconnect(G_OBJECT(locationControl), errorHandlerId); if (posChangedId) g_signal_handler_disconnect(G_OBJECT(locationDevice), posChangedId); errorHandlerId = 0; posChangedId = 0; startcounter = 0; location_gpsd_control_stop(locationControl); locationState &= ~LiblocationWrapper::Started; locationState |= LiblocationWrapper::Stopped; } } bool LiblocationWrapper::isActive() { if (locationState & LiblocationWrapper::Started) return true; else return false; } #include "moc_liblocationwrapper_p.cpp" QTM_END_NAMESPACE <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: lorn.potter@jollamobile.com ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "qofonosmartmessaging.h" #include "dbus/ofonosmartmessaging.h" class QOfonoSmartMessagingPrivate { public: QOfonoSmartMessagingPrivate(); QString modemPath; OfonoSmartMessaging *smartMessaging; }; QOfonoSmartMessagingPrivate::QOfonoSmartMessagingPrivate() : modemPath(QString()) , smartMessaging(0) { } QOfonoSmartMessaging::QOfonoSmartMessaging(QObject *parent) : QObject(parent) , d_ptr(new QOfonoSmartMessagingPrivate) { } QOfonoSmartMessaging::~QOfonoSmartMessaging() { delete d_ptr; } void QOfonoSmartMessaging::setModemPath(const QString &path) { if (path == d_ptr->modemPath || path.isEmpty()) return; if (path != modemPath()) { if (d_ptr->smartMessaging) { delete d_ptr->smartMessaging; d_ptr->smartMessaging - 0; } d_ptr->smartMessaging = new OfonoSmartMessaging("org.ofono", path, QDBusConnection::systemBus(),this); if (d_ptr->smartMessaging->isValid()) { d_ptr->modemPath = path; Q_EMIT modemPathChanged(path); } } } QString QOfonoSmartMessaging::modemPath() const { return d_ptr->modemPath; } QDBusObjectPath QOfonoSmartMessaging::sendAppointment(const QString &toPhoneNumber, const QByteArray &appointment) { if (d_ptr->smartMessaging) { QDBusPendingReply<QDBusObjectPath> returnPath = d_ptr->smartMessaging->SendAppointment(toPhoneNumber, appointment); return returnPath; } return QDBusObjectPath(); } QDBusObjectPath QOfonoSmartMessaging::sendBusinessCard(const QString &toPhoneNumber, const QByteArray &card) { if (d_ptr->smartMessaging) { QDBusPendingReply<QDBusObjectPath> returnPath = d_ptr->smartMessaging->SendBusinessCard(toPhoneNumber,card); return returnPath; } return QDBusObjectPath(); } void QOfonoSmartMessaging::registerAgent(const QString &objectPath) { if (d_ptr->smartMessaging) d_ptr->smartMessaging->RegisterAgent(QDBusObjectPath(objectPath)); } void QOfonoSmartMessaging::unregisterAgent(const QString &objectPath) { if (d_ptr->smartMessaging) d_ptr->smartMessaging->UnregisterAgent(QDBusObjectPath(objectPath)); } bool QOfonoSmartMessaging::isValid() const { return d_ptr->smartMessaging->isValid(); } <commit_msg>Fixed apparent typo<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Jolla Ltd. ** Contact: lorn.potter@jollamobile.com ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include "qofonosmartmessaging.h" #include "dbus/ofonosmartmessaging.h" class QOfonoSmartMessagingPrivate { public: QOfonoSmartMessagingPrivate(); QString modemPath; OfonoSmartMessaging *smartMessaging; }; QOfonoSmartMessagingPrivate::QOfonoSmartMessagingPrivate() : modemPath(QString()) , smartMessaging(0) { } QOfonoSmartMessaging::QOfonoSmartMessaging(QObject *parent) : QObject(parent) , d_ptr(new QOfonoSmartMessagingPrivate) { } QOfonoSmartMessaging::~QOfonoSmartMessaging() { delete d_ptr; } void QOfonoSmartMessaging::setModemPath(const QString &path) { if (path == d_ptr->modemPath || path.isEmpty()) return; if (path != modemPath()) { if (d_ptr->smartMessaging) { delete d_ptr->smartMessaging; d_ptr->smartMessaging = 0; } d_ptr->smartMessaging = new OfonoSmartMessaging("org.ofono", path, QDBusConnection::systemBus(),this); if (d_ptr->smartMessaging->isValid()) { d_ptr->modemPath = path; Q_EMIT modemPathChanged(path); } } } QString QOfonoSmartMessaging::modemPath() const { return d_ptr->modemPath; } QDBusObjectPath QOfonoSmartMessaging::sendAppointment(const QString &toPhoneNumber, const QByteArray &appointment) { if (d_ptr->smartMessaging) { QDBusPendingReply<QDBusObjectPath> returnPath = d_ptr->smartMessaging->SendAppointment(toPhoneNumber, appointment); return returnPath; } return QDBusObjectPath(); } QDBusObjectPath QOfonoSmartMessaging::sendBusinessCard(const QString &toPhoneNumber, const QByteArray &card) { if (d_ptr->smartMessaging) { QDBusPendingReply<QDBusObjectPath> returnPath = d_ptr->smartMessaging->SendBusinessCard(toPhoneNumber,card); return returnPath; } return QDBusObjectPath(); } void QOfonoSmartMessaging::registerAgent(const QString &objectPath) { if (d_ptr->smartMessaging) d_ptr->smartMessaging->RegisterAgent(QDBusObjectPath(objectPath)); } void QOfonoSmartMessaging::unregisterAgent(const QString &objectPath) { if (d_ptr->smartMessaging) d_ptr->smartMessaging->UnregisterAgent(QDBusObjectPath(objectPath)); } bool QOfonoSmartMessaging::isValid() const { return d_ptr->smartMessaging->isValid(); } <|endoftext|>
<commit_before>//===-- PipePosix.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/posix/PipePosix.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostInfo.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) #define _GLIBCXX_USE_NANOSLEEP #endif #include <functional> #include <thread> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> using namespace lldb; using namespace lldb_private; int PipePosix::kInvalidDescriptor = -1; enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE // pipe2 is supported by Linux, FreeBSD v10 and higher. // TODO: Add more platforms that support pipe2. #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10) #define PIPE2_SUPPORTED 1 #else #define PIPE2_SUPPORTED 0 #endif namespace { constexpr auto OPEN_WRITER_SLEEP_TIMEOUT_MSECS = 100; #if defined(FD_CLOEXEC) && !PIPE2_SUPPORTED bool SetCloexecFlag(int fd) { int flags = ::fcntl(fd, F_GETFD); if (flags == -1) return false; return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); } #endif std::chrono::time_point<std::chrono::steady_clock> Now() { return std::chrono::steady_clock::now(); } Error SelectIO(int handle, bool is_read, const std::function<Error(bool&)> &io_handler, const std::chrono::microseconds &timeout) { Error error; fd_set fds; bool done = false; using namespace std::chrono; const auto finish_time = Now() + timeout; while (!done) { struct timeval tv = {0, 0}; if (timeout != microseconds::zero()) { const auto remaining_dur = duration_cast<microseconds>(finish_time - Now()); if (remaining_dur.count() <= 0) { error.SetErrorString("timeout exceeded"); break; } const auto dur_secs = duration_cast<seconds>(remaining_dur); const auto dur_usecs = remaining_dur % seconds(1); tv.tv_sec = dur_secs.count(); tv.tv_usec = dur_usecs.count(); } else tv.tv_sec = 1; FD_ZERO(&fds); FD_SET(handle, &fds); const auto retval = ::select(handle + 1, (is_read) ? &fds : nullptr, (is_read) ? nullptr : &fds, nullptr, &tv); if (retval == -1) { if (errno == EINTR) continue; error.SetErrorToErrno(); break; } if (retval == 0) { error.SetErrorString("timeout exceeded"); break; } if (!FD_ISSET(handle, &fds)) { error.SetErrorString("invalid state"); break; } error = io_handler(done); if (error.Fail()) { if (error.GetError() == EINTR) continue; break; } } return error; } } PipePosix::PipePosix() : m_fds{ PipePosix::kInvalidDescriptor, PipePosix::kInvalidDescriptor } {} PipePosix::PipePosix(int read_fd, int write_fd) : m_fds{read_fd, write_fd} {} PipePosix::PipePosix(PipePosix &&pipe_posix) : PipeBase{std::move(pipe_posix)}, m_fds{ pipe_posix.ReleaseReadFileDescriptor(), pipe_posix.ReleaseWriteFileDescriptor() } {} PipePosix &PipePosix::operator=(PipePosix &&pipe_posix) { PipeBase::operator=(std::move(pipe_posix)); m_fds[READ] = pipe_posix.ReleaseReadFileDescriptor(); m_fds[WRITE] = pipe_posix.ReleaseWriteFileDescriptor(); return *this; } PipePosix::~PipePosix() { Close(); } Error PipePosix::CreateNew(bool child_processes_inherit) { if (CanRead() || CanWrite()) return Error(EINVAL, eErrorTypePOSIX); Error error; #if PIPE2_SUPPORTED if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0) return error; #else if (::pipe(m_fds) == 0) { #ifdef FD_CLOEXEC if (!child_processes_inherit) { if (!SetCloexecFlag(m_fds[0]) || !SetCloexecFlag(m_fds[1])) { error.SetErrorToErrno(); Close(); return error; } } #endif return error; } #endif error.SetErrorToErrno(); m_fds[READ] = PipePosix::kInvalidDescriptor; m_fds[WRITE] = PipePosix::kInvalidDescriptor; return error; } Error PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); Error error; if (::mkfifo(name.data(), 0660) != 0) error.SetErrorToErrno(); return error; } Error PipePosix::CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl<char>& name) { llvm::SmallString<PATH_MAX> named_pipe_path; llvm::SmallString<PATH_MAX> pipe_spec((prefix + ".%%%%%%").str()); FileSpec tmpdir_file_spec; tmpdir_file_spec.Clear(); if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) { tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); } else { tmpdir_file_spec.AppendPathComponent("/tmp"); tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); } // It's possible that another process creates the target path after we've // verified it's available but before we create it, in which case we // should try again. Error error; do { llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), named_pipe_path); error = CreateNew(named_pipe_path, child_process_inherit); } while (error.GetError() == EEXIST); if (error.Success()) name = named_pipe_path; return error; } Error PipePosix::OpenAsReader(llvm::StringRef name, bool child_process_inherit) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); int flags = O_RDONLY | O_NONBLOCK; if (!child_process_inherit) flags |= O_CLOEXEC; Error error; int fd = ::open(name.data(), flags); if (fd != -1) m_fds[READ] = fd; else error.SetErrorToErrno(); return error; } Error PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); int flags = O_WRONLY | O_NONBLOCK; if (!child_process_inherit) flags |= O_CLOEXEC; using namespace std::chrono; const auto finish_time = Now() + timeout; while (!CanWrite()) { if (timeout != microseconds::zero()) { const auto dur = duration_cast<microseconds>(finish_time - Now()).count(); if (dur <= 0) return Error("timeout exceeded - reader hasn't opened so far"); } errno = 0; int fd = ::open(name.data(), flags); if (fd == -1) { const auto errno_copy = errno; // We may get ENXIO if a reader side of the pipe hasn't opened yet. if (errno_copy != ENXIO) return Error(errno_copy, eErrorTypePOSIX); std::this_thread::sleep_for(milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS)); } else { m_fds[WRITE] = fd; } } return Error(); } int PipePosix::GetReadFileDescriptor() const { return m_fds[READ]; } int PipePosix::GetWriteFileDescriptor() const { return m_fds[WRITE]; } int PipePosix::ReleaseReadFileDescriptor() { const int fd = m_fds[READ]; m_fds[READ] = PipePosix::kInvalidDescriptor; return fd; } int PipePosix::ReleaseWriteFileDescriptor() { const int fd = m_fds[WRITE]; m_fds[WRITE] = PipePosix::kInvalidDescriptor; return fd; } void PipePosix::Close() { CloseReadFileDescriptor(); CloseWriteFileDescriptor(); } Error PipePosix::Delete(llvm::StringRef name) { return FileSystem::Unlink(FileSpec{name.data(), true}); } bool PipePosix::CanRead() const { return m_fds[READ] != PipePosix::kInvalidDescriptor; } bool PipePosix::CanWrite() const { return m_fds[WRITE] != PipePosix::kInvalidDescriptor; } void PipePosix::CloseReadFileDescriptor() { if (CanRead()) { close(m_fds[READ]); m_fds[READ] = PipePosix::kInvalidDescriptor; } } void PipePosix::CloseWriteFileDescriptor() { if (CanWrite()) { close(m_fds[WRITE]); m_fds[WRITE] = PipePosix::kInvalidDescriptor; } } Error PipePosix::ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) { bytes_read = 0; if (!CanRead()) return Error(EINVAL, eErrorTypePOSIX); auto handle = GetReadFileDescriptor(); return SelectIO(handle, true, [=, &bytes_read](bool &done) { Error error; auto result = ::read(handle, reinterpret_cast<char*>(buf) + bytes_read, size - bytes_read); if (result != -1) { bytes_read += result; if (bytes_read == size || result == 0) done = true; } else error.SetErrorToErrno(); return error; }, timeout); } Error PipePosix::Write(const void *buf, size_t size, size_t &bytes_written) { bytes_written = 0; if (!CanWrite()) return Error(EINVAL, eErrorTypePOSIX); auto handle = GetWriteFileDescriptor(); return SelectIO(handle, false, [=, &bytes_written](bool &done) { Error error; auto result = ::write(handle, reinterpret_cast<const char*>(buf) + bytes_written, size - bytes_written); if (result != -1) { bytes_written += result; if (bytes_written == size) done = true; } else error.SetErrorToErrno(); return error; }, std::chrono::microseconds::zero()); } <commit_msg>Prevent from a redefinition of _GLIBCXX_USE_NANOSLEEP<commit_after>//===-- PipePosix.cpp -------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/posix/PipePosix.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostInfo.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/FileSystem.h" #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) #ifndef _GLIBCXX_USE_NANOSLEEP #define _GLIBCXX_USE_NANOSLEEP #endif #endif #include <functional> #include <thread> #include <errno.h> #include <fcntl.h> #include <limits.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> using namespace lldb; using namespace lldb_private; int PipePosix::kInvalidDescriptor = -1; enum PIPES { READ, WRITE }; // Constants 0 and 1 for READ and WRITE // pipe2 is supported by Linux, FreeBSD v10 and higher. // TODO: Add more platforms that support pipe2. #if defined(__linux__) || (defined(__FreeBSD__) && __FreeBSD__ >= 10) #define PIPE2_SUPPORTED 1 #else #define PIPE2_SUPPORTED 0 #endif namespace { constexpr auto OPEN_WRITER_SLEEP_TIMEOUT_MSECS = 100; #if defined(FD_CLOEXEC) && !PIPE2_SUPPORTED bool SetCloexecFlag(int fd) { int flags = ::fcntl(fd, F_GETFD); if (flags == -1) return false; return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); } #endif std::chrono::time_point<std::chrono::steady_clock> Now() { return std::chrono::steady_clock::now(); } Error SelectIO(int handle, bool is_read, const std::function<Error(bool&)> &io_handler, const std::chrono::microseconds &timeout) { Error error; fd_set fds; bool done = false; using namespace std::chrono; const auto finish_time = Now() + timeout; while (!done) { struct timeval tv = {0, 0}; if (timeout != microseconds::zero()) { const auto remaining_dur = duration_cast<microseconds>(finish_time - Now()); if (remaining_dur.count() <= 0) { error.SetErrorString("timeout exceeded"); break; } const auto dur_secs = duration_cast<seconds>(remaining_dur); const auto dur_usecs = remaining_dur % seconds(1); tv.tv_sec = dur_secs.count(); tv.tv_usec = dur_usecs.count(); } else tv.tv_sec = 1; FD_ZERO(&fds); FD_SET(handle, &fds); const auto retval = ::select(handle + 1, (is_read) ? &fds : nullptr, (is_read) ? nullptr : &fds, nullptr, &tv); if (retval == -1) { if (errno == EINTR) continue; error.SetErrorToErrno(); break; } if (retval == 0) { error.SetErrorString("timeout exceeded"); break; } if (!FD_ISSET(handle, &fds)) { error.SetErrorString("invalid state"); break; } error = io_handler(done); if (error.Fail()) { if (error.GetError() == EINTR) continue; break; } } return error; } } PipePosix::PipePosix() : m_fds{ PipePosix::kInvalidDescriptor, PipePosix::kInvalidDescriptor } {} PipePosix::PipePosix(int read_fd, int write_fd) : m_fds{read_fd, write_fd} {} PipePosix::PipePosix(PipePosix &&pipe_posix) : PipeBase{std::move(pipe_posix)}, m_fds{ pipe_posix.ReleaseReadFileDescriptor(), pipe_posix.ReleaseWriteFileDescriptor() } {} PipePosix &PipePosix::operator=(PipePosix &&pipe_posix) { PipeBase::operator=(std::move(pipe_posix)); m_fds[READ] = pipe_posix.ReleaseReadFileDescriptor(); m_fds[WRITE] = pipe_posix.ReleaseWriteFileDescriptor(); return *this; } PipePosix::~PipePosix() { Close(); } Error PipePosix::CreateNew(bool child_processes_inherit) { if (CanRead() || CanWrite()) return Error(EINVAL, eErrorTypePOSIX); Error error; #if PIPE2_SUPPORTED if (::pipe2(m_fds, (child_processes_inherit) ? 0 : O_CLOEXEC) == 0) return error; #else if (::pipe(m_fds) == 0) { #ifdef FD_CLOEXEC if (!child_processes_inherit) { if (!SetCloexecFlag(m_fds[0]) || !SetCloexecFlag(m_fds[1])) { error.SetErrorToErrno(); Close(); return error; } } #endif return error; } #endif error.SetErrorToErrno(); m_fds[READ] = PipePosix::kInvalidDescriptor; m_fds[WRITE] = PipePosix::kInvalidDescriptor; return error; } Error PipePosix::CreateNew(llvm::StringRef name, bool child_process_inherit) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); Error error; if (::mkfifo(name.data(), 0660) != 0) error.SetErrorToErrno(); return error; } Error PipePosix::CreateWithUniqueName(llvm::StringRef prefix, bool child_process_inherit, llvm::SmallVectorImpl<char>& name) { llvm::SmallString<PATH_MAX> named_pipe_path; llvm::SmallString<PATH_MAX> pipe_spec((prefix + ".%%%%%%").str()); FileSpec tmpdir_file_spec; tmpdir_file_spec.Clear(); if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) { tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); } else { tmpdir_file_spec.AppendPathComponent("/tmp"); tmpdir_file_spec.AppendPathComponent(pipe_spec.c_str()); } // It's possible that another process creates the target path after we've // verified it's available but before we create it, in which case we // should try again. Error error; do { llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), named_pipe_path); error = CreateNew(named_pipe_path, child_process_inherit); } while (error.GetError() == EEXIST); if (error.Success()) name = named_pipe_path; return error; } Error PipePosix::OpenAsReader(llvm::StringRef name, bool child_process_inherit) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); int flags = O_RDONLY | O_NONBLOCK; if (!child_process_inherit) flags |= O_CLOEXEC; Error error; int fd = ::open(name.data(), flags); if (fd != -1) m_fds[READ] = fd; else error.SetErrorToErrno(); return error; } Error PipePosix::OpenAsWriterWithTimeout(llvm::StringRef name, bool child_process_inherit, const std::chrono::microseconds &timeout) { if (CanRead() || CanWrite()) return Error("Pipe is already opened"); int flags = O_WRONLY | O_NONBLOCK; if (!child_process_inherit) flags |= O_CLOEXEC; using namespace std::chrono; const auto finish_time = Now() + timeout; while (!CanWrite()) { if (timeout != microseconds::zero()) { const auto dur = duration_cast<microseconds>(finish_time - Now()).count(); if (dur <= 0) return Error("timeout exceeded - reader hasn't opened so far"); } errno = 0; int fd = ::open(name.data(), flags); if (fd == -1) { const auto errno_copy = errno; // We may get ENXIO if a reader side of the pipe hasn't opened yet. if (errno_copy != ENXIO) return Error(errno_copy, eErrorTypePOSIX); std::this_thread::sleep_for(milliseconds(OPEN_WRITER_SLEEP_TIMEOUT_MSECS)); } else { m_fds[WRITE] = fd; } } return Error(); } int PipePosix::GetReadFileDescriptor() const { return m_fds[READ]; } int PipePosix::GetWriteFileDescriptor() const { return m_fds[WRITE]; } int PipePosix::ReleaseReadFileDescriptor() { const int fd = m_fds[READ]; m_fds[READ] = PipePosix::kInvalidDescriptor; return fd; } int PipePosix::ReleaseWriteFileDescriptor() { const int fd = m_fds[WRITE]; m_fds[WRITE] = PipePosix::kInvalidDescriptor; return fd; } void PipePosix::Close() { CloseReadFileDescriptor(); CloseWriteFileDescriptor(); } Error PipePosix::Delete(llvm::StringRef name) { return FileSystem::Unlink(FileSpec{name.data(), true}); } bool PipePosix::CanRead() const { return m_fds[READ] != PipePosix::kInvalidDescriptor; } bool PipePosix::CanWrite() const { return m_fds[WRITE] != PipePosix::kInvalidDescriptor; } void PipePosix::CloseReadFileDescriptor() { if (CanRead()) { close(m_fds[READ]); m_fds[READ] = PipePosix::kInvalidDescriptor; } } void PipePosix::CloseWriteFileDescriptor() { if (CanWrite()) { close(m_fds[WRITE]); m_fds[WRITE] = PipePosix::kInvalidDescriptor; } } Error PipePosix::ReadWithTimeout(void *buf, size_t size, const std::chrono::microseconds &timeout, size_t &bytes_read) { bytes_read = 0; if (!CanRead()) return Error(EINVAL, eErrorTypePOSIX); auto handle = GetReadFileDescriptor(); return SelectIO(handle, true, [=, &bytes_read](bool &done) { Error error; auto result = ::read(handle, reinterpret_cast<char*>(buf) + bytes_read, size - bytes_read); if (result != -1) { bytes_read += result; if (bytes_read == size || result == 0) done = true; } else error.SetErrorToErrno(); return error; }, timeout); } Error PipePosix::Write(const void *buf, size_t size, size_t &bytes_written) { bytes_written = 0; if (!CanWrite()) return Error(EINVAL, eErrorTypePOSIX); auto handle = GetWriteFileDescriptor(); return SelectIO(handle, false, [=, &bytes_written](bool &done) { Error error; auto result = ::write(handle, reinterpret_cast<const char*>(buf) + bytes_written, size - bytes_written); if (result != -1) { bytes_written += result; if (bytes_written == size) done = true; } else error.SetErrorToErrno(); return error; }, std::chrono::microseconds::zero()); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet.h" #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *wallet, AddressTableModel *parent): wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_NOW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from Bitcoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <commit_msg>qt: change CT_NOW string to CT_NEW in log message<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet.h" #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type type, const QString &label, const QString &address): type(type), label(label), address(address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *wallet, AddressTableModel *parent): wallet(wallet), parent(parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qDebug() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::bitcoinAddressFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from Bitcoin core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); CBitcoinAddress address_parsed(address.toStdString()); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); } <|endoftext|>
<commit_before>// Copyright (C) 2017 xaizek <xaizek@openmailbox.org> // // This file is part of uncov. // // uncov is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // uncov is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with uncov. If not, see <http://www.gnu.org/licenses/>. #ifndef UNCOV__UTILS__INTEGER_SEQ_HPP__ #define UNCOV__UTILS__INTEGER_SEQ_HPP__ #include <cstddef> template <std::size_t...> struct integer_sequence {}; template <typename... T> struct Idx; template <typename T> struct Idx<T> { using type = integer_sequence<0U>; }; template <typename T> struct Extend; template <std::size_t... Is> struct Extend<integer_sequence<Is...>> { using type = integer_sequence<0U, (Is + 1U)...>; }; template <typename T, typename... Ts> struct Idx<T, Ts...> { using type = typename Extend<typename Idx<Ts...>::type>::type; }; template <typename... T> using index_sequence_for = typename Idx<T...>::type; #endif // UNCOV__UTILS__INTEGER_SEQ_HPP__ <commit_msg>Simplify integer_seq implementation a bit<commit_after>// Copyright (C) 2017 xaizek <xaizek@openmailbox.org> // // This file is part of uncov. // // uncov is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // uncov is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with uncov. If not, see <http://www.gnu.org/licenses/>. #ifndef UNCOV__UTILS__INTEGER_SEQ_HPP__ #define UNCOV__UTILS__INTEGER_SEQ_HPP__ #include <cstddef> template <std::size_t...> struct integer_sequence {}; template <typename... T> struct Idx; template <typename T> struct Idx<T> { using type = integer_sequence<0U>; }; template <typename T> struct Extend; template <std::size_t... Is> struct Extend<integer_sequence<Is...>> { using type = integer_sequence<Is..., sizeof...(Is)>; }; template <typename T, typename... Ts> struct Idx<T, Ts...> { using type = typename Extend<typename Idx<Ts...>::type>::type; }; template <typename... T> using index_sequence_for = typename Idx<T...>::type; #endif // UNCOV__UTILS__INTEGER_SEQ_HPP__ <|endoftext|>
<commit_before>/* Siconos-Kernel, Copyright INRIA 2005-2012. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr */ //#define DEBUG_MESSAGES 1 #include <debug.h> #include "BulletR.hpp" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #pragma clang diagnostic ignored "-Woverloaded-virtual" #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverloaded-virtual" #endif #include <BulletCollision/NarrowPhaseCollision/btManifoldPoint.h> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <btBulletCollisionCommon.h> #if defined(__clang__) #pragma clang diagnostic pop #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic pop #endif #include <Interaction.hpp> BulletR::BulletR(SP::btManifoldPoint point) : NewtonEulerFrom3DLocalFrameR(), _contactPoints(point) { btVector3 posa = _contactPoints->getPositionWorldOnA(); btVector3 posb = _contactPoints->getPositionWorldOnB(); (*pc1())(0) = posa[0]; (*pc1())(1) = posa[1]; (*pc1())(2) = posa[2]; (*pc2())(0) = posb[0]; (*pc2())(1) = posb[1]; (*pc2())(2) = posb[2]; (*nc())(0) = _contactPoints->m_normalWorldOnB[0]; (*nc())(1) = _contactPoints->m_normalWorldOnB[1]; (*nc())(2) = _contactPoints->m_normalWorldOnB[2]; } void BulletR::computeh(double time, BlockVector& q0, SiconosVector& y) { NewtonEulerR::computeh(time, q0, y); DEBUG_PRINT("start of computeh\n"); btVector3 posa = _contactPoints->getPositionWorldOnA(); btVector3 posb = _contactPoints->getPositionWorldOnB(); (*pc1())(0) = posa[0]; (*pc1())(1) = posa[1]; (*pc1())(2) = posa[2]; (*pc2())(0) = posb[0]; (*pc2())(1) = posb[1]; (*pc2())(2) = posb[2]; { y.setValue(0, _contactPoints->getDistance()); (*nc())(0) = _contactPoints->m_normalWorldOnB[0]; (*nc())(1) = _contactPoints->m_normalWorldOnB[1]; (*nc())(2) = _contactPoints->m_normalWorldOnB[2]; } DEBUG_PRINTF("distance : %g\n", y.getValue(0)); DEBUG_PRINTF("position on A : %g,%g,%g\n", posa[0], posa[1], posa[2]); DEBUG_PRINTF("position on B : %g,%g,%g\n", posb[0], posb[1], posb[2]); DEBUG_PRINTF("normal on B : %g,%g,%g\n", (*nc())(0), (*nc())(1), (*nc())(2)); DEBUG_PRINT("end of computeh\n"); } <commit_msg>[mechanics proposed] assert if contact normal is zero.<commit_after>/* Siconos-Kernel, Copyright INRIA 2005-2012. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY, siconos-team@lists.gforge.inria.fr */ //#define DEBUG_MESSAGES 1 #include <debug.h> #include "BulletR.hpp" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" #pragma clang diagnostic ignored "-Woverloaded-virtual" #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Woverloaded-virtual" #endif #include <BulletCollision/NarrowPhaseCollision/btManifoldPoint.h> #include <BulletCollision/CollisionDispatch/btCollisionObject.h> #include <btBulletCollisionCommon.h> #if defined(__clang__) #pragma clang diagnostic pop #elif !(__INTEL_COMPILER || __APPLE__ ) #pragma GCC diagnostic pop #endif #include <Interaction.hpp> BulletR::BulletR(SP::btManifoldPoint point) : NewtonEulerFrom3DLocalFrameR(), _contactPoints(point) { btVector3 posa = _contactPoints->getPositionWorldOnA(); btVector3 posb = _contactPoints->getPositionWorldOnB(); (*pc1())(0) = posa[0]; (*pc1())(1) = posa[1]; (*pc1())(2) = posa[2]; (*pc2())(0) = posb[0]; (*pc2())(1) = posb[1]; (*pc2())(2) = posb[2]; (*nc())(0) = _contactPoints->m_normalWorldOnB[0]; (*nc())(1) = _contactPoints->m_normalWorldOnB[1]; (*nc())(2) = _contactPoints->m_normalWorldOnB[2]; assert(!((*nc())(0)==0 && (*nc())(1)==0 && (*nc())(2)==0) && "nc = 0, problems..\n"); } void BulletR::computeh(double time, BlockVector& q0, SiconosVector& y) { NewtonEulerR::computeh(time, q0, y); DEBUG_PRINT("start of computeh\n"); btVector3 posa = _contactPoints->getPositionWorldOnA(); btVector3 posb = _contactPoints->getPositionWorldOnB(); (*pc1())(0) = posa[0]; (*pc1())(1) = posa[1]; (*pc1())(2) = posa[2]; (*pc2())(0) = posb[0]; (*pc2())(1) = posb[1]; (*pc2())(2) = posb[2]; { y.setValue(0, _contactPoints->getDistance()); (*nc())(0) = _contactPoints->m_normalWorldOnB[0]; (*nc())(1) = _contactPoints->m_normalWorldOnB[1]; (*nc())(2) = _contactPoints->m_normalWorldOnB[2]; } DEBUG_PRINTF("distance : %g\n", y.getValue(0)); DEBUG_PRINTF("position on A : %g,%g,%g\n", posa[0], posa[1], posa[2]); DEBUG_PRINTF("position on B : %g,%g,%g\n", posb[0], posb[1], posb[2]); DEBUG_PRINTF("normal on B : %g,%g,%g\n", (*nc())(0), (*nc())(1), (*nc())(2)); DEBUG_PRINT("end of computeh\n"); } <|endoftext|>
<commit_before>#include "game/temporary_systems/physics_system.h" #include "game/components/fixtures_component.h" #include "game/components/special_physics_component.h" #include "game/transcendental/cosmos.h" #include "game/transcendental/step.h" #include "physics_scripts.h" void physics_system::rechoose_owner_friction_body(entity_handle entity) { auto& physics = entity.get<components::special_physics>(); auto& cosmos = entity.get_cosmos(); // purge of dead entities erase_remove(physics.owner_friction_grounds, [&cosmos](entity_id subject) { return cosmos[subject].dead(); }); auto feasible_grounds = physics.owner_friction_grounds; if (!feasible_grounds.empty()) { // cycle guard // remove friction grounds whom I do own myself erase_remove(feasible_grounds, [this, entity, &cosmos](entity_id subject) { return are_connected_by_friction(cosmos[subject], entity); }); } if (!feasible_grounds.empty()) { std::stable_sort(feasible_grounds.begin(), feasible_grounds.end(), [this, &cosmos](entity_id a, entity_id b) { return are_connected_by_friction(cosmos[a], cosmos[b]); }); physics.owner_friction_ground = feasible_grounds[0]; // make the new owner first in order in case it is later compared to the same ancestor-level parents for (auto& it = physics.owner_friction_grounds.begin(); it != physics.owner_friction_grounds.end(); ++it) { if (*it == physics.owner_friction_ground) { std::swap(physics.owner_friction_grounds[0], *it); } } /// consider friction grounds ONLY from the same ancestor line, and only the descendants /// if the current one is not found within contacting friction grounds, /// prioritize like this: /// firstly, the lowest descendant of the ancestor line of the lost friction ground /// descendant of any other tree with the biggest height, stable-sorted in order of entrance } else { physics.owner_friction_ground.unset(); } } void physics_system::recurential_friction_handler(fixed_step& step, entity_handle entity, entity_handle friction_owner) { if (friction_owner.dead()) return; float dt = static_cast<float>(step.get_delta().in_seconds()); auto& physics = entity.get<components::physics>(); auto& friction_physics = friction_owner.get<components::fixtures>(); auto& friction_entity = friction_physics.get_owner_body(); recurential_friction_handler(step, entity, friction_entity.get_owner_friction_ground()); auto* body = get_rigid_body_cache(entity).body; auto friction_body = get_rigid_body_cache(friction_entity).body; auto fricted_pos = body->GetPosition() + dt* friction_body->GetLinearVelocityFromWorldPoint(body->GetPosition()); body->SetTransform(fricted_pos, body->GetAngle() + dt*friction_body->GetAngularVelocity()); friction_entity.get<components::special_physics>().measured_carried_mass += physics.get_mass() + entity.get<components::special_physics>().measured_carried_mass; } <commit_msg>aesthics<commit_after>#include "game/temporary_systems/physics_system.h" #include "game/components/fixtures_component.h" #include "game/components/special_physics_component.h" #include "game/transcendental/cosmos.h" #include "game/transcendental/step.h" #include "physics_scripts.h" void physics_system::rechoose_owner_friction_body(const entity_handle entity) { auto& physics = entity.get<components::special_physics>(); auto& cosmos = entity.get_cosmos(); // purge of dead entities erase_remove(physics.owner_friction_grounds, [&cosmos](const entity_id subject) { return cosmos[subject].dead(); }); auto feasible_grounds = physics.owner_friction_grounds; if (!feasible_grounds.empty()) { // cycle guard // remove friction grounds whom I do own myself erase_remove(feasible_grounds, [this, entity, &cosmos](entity_id subject) { return are_connected_by_friction(cosmos[subject], entity); }); } if (!feasible_grounds.empty()) { std::stable_sort(feasible_grounds.begin(), feasible_grounds.end(), [this, &cosmos](const entity_id a, const entity_id b) { return are_connected_by_friction(cosmos[a], cosmos[b]); }); physics.owner_friction_ground = feasible_grounds[0]; // make the new owner first in order in case it is later compared to the same ancestor-level parents for (auto& it = physics.owner_friction_grounds.begin(); it != physics.owner_friction_grounds.end(); ++it) { if (*it == physics.owner_friction_ground) { std::swap(physics.owner_friction_grounds[0], *it); } } /// consider friction grounds ONLY from the same ancestor line, and only the descendants /// if the current one is not found within contacting friction grounds, /// prioritize like this: /// firstly, the lowest descendant of the ancestor line of the lost friction ground /// descendant of any other tree with the biggest height, stable-sorted in order of entrance } else { physics.owner_friction_ground.unset(); } } void physics_system::recurential_friction_handler(fixed_step& step, const entity_handle entity, const entity_handle friction_owner) { if (friction_owner.dead()) return; const float dt = static_cast<float>(step.get_delta().in_seconds()); const auto& physics = entity.get<components::physics>(); auto& friction_entity = friction_owner.get_owner_body(); recurential_friction_handler(step, entity, friction_entity.get_owner_friction_ground()); auto* const body = get_rigid_body_cache(entity).body; const auto friction_body = get_rigid_body_cache(friction_entity).body; const auto fricted_pos = body->GetPosition() + dt* friction_body->GetLinearVelocityFromWorldPoint(body->GetPosition()); body->SetTransform(fricted_pos, body->GetAngle() + dt*friction_body->GetAngularVelocity()); friction_entity.get<components::special_physics>().measured_carried_mass += physics.get_mass() + entity.get<components::special_physics>().measured_carried_mass; } <|endoftext|>
<commit_before>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net) Version 0.9.6, packaged on June, 2006. http://glc-lib.sourceforge.net GLC-lib is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLC-lib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_circle.cpp implementation of the GLC_Circle class. #include "glc_circle.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// GLC_Circle::GLC_Circle(const double &dRadius, double Angle, const char *pName, const GLfloat *pColor) :GLC_Geometry(pName, pColor) { //! \todo remade init m_Radius= dRadius; m_nDiscret= GLC_DISCRET; m_dAngle= Angle; } GLC_Circle::~GLC_Circle() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // return the circle bounding box GLC_BoundingBox* GLC_Circle::getBoundingBox(void) const { GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox(); GLC_Vector3d lower(-m_Radius, -m_Radius, -2.0 * EPSILON); GLC_Vector3d upper(m_Radius, m_Radius, 2.0 * EPSILON); pBoundingBox->combine(lower); pBoundingBox->combine(upper); pBoundingBox->transform(m_MatPos); return pBoundingBox; } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Circle Radius bool GLC_Circle::SetRadius(double R) { R = fabs(R); if ( fabs(R - m_Radius) > EPSILON) { // Radius is changing if (R > EPSILON) { m_Radius= R; m_ListIsValid= false; return true; } else return false; // Radius must be > 0 } else return true; // Radius doesn't change //! \todo Add error handler in case of invalid radius } // Set Circle discret void GLC_Circle::SetDiscretion(int TargetDiscret) { TargetDiscret= abs(TargetDiscret); if (TargetDiscret != m_nDiscret) { m_nDiscret= TargetDiscret; if (m_nDiscret < 6) m_nDiscret= 6; m_ListIsValid= false; } } // Set Circle Angle bool GLC_Circle::SetAngle(double AngleRadians) // Angle in Radians { if ( fabs(AngleRadians - m_dAngle) > EPSILON) { // Angle is changing if (AngleRadians > EPSILON) { m_dAngle= AngleRadians; m_ListIsValid= false; return true; } else return false; // Angle must be > 0 } else return true; // Radius doesn't change //! \todo Add error handler in case of invalid angle } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Dessin du Cercle void GLC_Circle::GlDraw(void) { double MyCos; double MySin; GLC_Vector4d Vect; // Affichage du Cercle glBegin(GL_LINE_STRIP); for (int i= 0; i <= m_nDiscret; i++) { MyCos= m_Radius * cos(i * m_dAngle / m_nDiscret); MySin= m_Radius * sin(i * m_dAngle / m_nDiscret); Vect.SetVect(MyCos, MySin, 0); glVertex3dv(Vect.Return_dVect()); } glEnd(); // Fin de l'affichage du cercle } // Fonction dfinissant le proprits de la gomtrie (Couleur, position, epaisseur) void GLC_Circle::GlPropGeom(void) { // Modification de la matrice courante glMultMatrixd(m_MatPos.Return_dMat()); // Proprit Graphique du cercle glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); // Pas de transparence glDisable(GL_BLEND); glColor4fv(GetfRGBA()); // Sa Couleur glLineWidth(GetThickness()); // Son Epaisseur } <commit_msg>Change default constructor initialization. Add a copy constructor<commit_after>/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net) Version 0.9.6, packaged on June, 2006. http://glc-lib.sourceforge.net GLC-lib is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLC-lib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLC-lib; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *****************************************************************************/ //! \file glc_circle.cpp implementation of the GLC_Circle class. #include "glc_circle.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// GLC_Circle::GLC_Circle(const double &dRadius, double Angle, const char *pName, const GLfloat *pColor) :GLC_Geometry(pName, pColor) , m_Radius(dRadius) , m_nDiscret(GLC_DISCRET) , m_dAngle(Angle) { } GLC_Circle::GLC_Circle(const GLC_Circle& sourceCircle) :GLC_Geometry(sourceCircle) , m_Radius(sourceCircle.m_Radius) , m_nDiscret(sourceCircle.m_nDiscret) , m_dAngle(sourceCircle.m_dAngle) { } GLC_Circle::~GLC_Circle() { } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// // return the circle bounding box GLC_BoundingBox* GLC_Circle::getBoundingBox(void) const { GLC_BoundingBox* pBoundingBox= new GLC_BoundingBox(); GLC_Vector3d lower(-m_Radius, -m_Radius, -2.0 * EPSILON); GLC_Vector3d upper(m_Radius, m_Radius, 2.0 * EPSILON); pBoundingBox->combine(lower); pBoundingBox->combine(upper); pBoundingBox->transform(m_MatPos); return pBoundingBox; } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// // Set Circle Radius bool GLC_Circle::SetRadius(double R) { R = fabs(R); if ( fabs(R - m_Radius) > EPSILON) { // Radius is changing if (R > EPSILON) { m_Radius= R; m_ListIsValid= false; return true; } else return false; // Radius must be > 0 } else return true; // Radius doesn't change //! \todo Add error handler in case of invalid radius } // Set Circle discret void GLC_Circle::SetDiscretion(int TargetDiscret) { TargetDiscret= abs(TargetDiscret); if (TargetDiscret != m_nDiscret) { m_nDiscret= TargetDiscret; if (m_nDiscret < 6) m_nDiscret= 6; m_ListIsValid= false; } } // Set Circle Angle bool GLC_Circle::SetAngle(double AngleRadians) // Angle in Radians { if ( fabs(AngleRadians - m_dAngle) > EPSILON) { // Angle is changing if (AngleRadians > EPSILON) { m_dAngle= AngleRadians; m_ListIsValid= false; return true; } else return false; // Angle must be > 0 } else return true; // Radius doesn't change //! \todo Add error handler in case of invalid angle } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// // Dessin du Cercle void GLC_Circle::GlDraw(void) { double MyCos; double MySin; GLC_Vector4d Vect; // Affichage du Cercle glBegin(GL_LINE_STRIP); for (int i= 0; i <= m_nDiscret; i++) { MyCos= m_Radius * cos(i * m_dAngle / m_nDiscret); MySin= m_Radius * sin(i * m_dAngle / m_nDiscret); Vect.SetVect(MyCos, MySin, 0); glVertex3dv(Vect.Return_dVect()); } glEnd(); // Fin de l'affichage du cercle } // Fonction dfinissant le proprits de la gomtrie (Couleur, position, epaisseur) void GLC_Circle::GlPropGeom(void) { // Modification de la matrice courante glMultMatrixd(m_MatPos.Return_dMat()); // Proprit Graphique du cercle glDisable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); // Pas de transparence glDisable(GL_BLEND); glColor4fv(GetfRGBA()); // Sa Couleur glLineWidth(GetThickness()); // Son Epaisseur } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // Description: Implements the Graphite interfaces with access to the // platform's font and graphics systems. // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" // We need this to enable namespace support in libgrengine headers. #define GR_NAMESPACE // Header files // // Standard Library #include <string> #include <cassert> // Libraries #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <i18npool/mslangid.hxx> // Platform #ifndef WNT #include <saldisp.hxx> #include <vcl/salgdi.hxx> #include <freetype/ftsynth.h> // Module #include "gcach_ftyp.hxx" #include <vcl/graphite_features.hxx> #include <vcl/graphite_adaptors.hxx> // Module private type definitions and forward declarations. // using gr::GrResult; namespace { inline float from_hinted(const int x) { return static_cast<float>(x + 32) / 64.0; } typedef std::hash_map<long,bool> SilfMap; SilfMap sSilfMap; } extern FT_Error (*pFTEmbolden)(FT_GlyphSlot); extern FT_Error (*pFTOblique)(FT_GlyphSlot); // class CharacterRenderProperties implentation. // FontProperties::FontProperties(const FreetypeServerFont &font) throw() { clrFore = gr::kclrBlack; clrBack = gr::kclrTransparent; pixHeight = from_hinted(font.GetMetricsFT().height); switch (font.GetFontSelData().meWeight) { case WEIGHT_SEMIBOLD: case WEIGHT_BOLD: case WEIGHT_ULTRABOLD: case WEIGHT_BLACK: fBold = true; break; default : fBold = false; } switch (font.GetFontSelData().meItalic) { case ITALIC_NORMAL: case ITALIC_OBLIQUE: fItalic = true; break; default : fItalic = false; } // Get the font name, but prefix with file name hash in case // there are 2 fonts on the system with the same face name sal_Int32 nHashCode = font.GetFontFileName()->hashCode(); ::rtl::OUStringBuffer nHashFaceName; nHashFaceName.append(nHashCode, 16); const sal_Unicode * name = font.GetFontSelData().maName.GetBuffer(); nHashFaceName.append(name); const size_t name_sz = std::min(sizeof szFaceName/sizeof(wchar_t)-1, static_cast<size_t>(nHashFaceName.getLength())); std::copy(nHashFaceName.getStr(), nHashFaceName.getStr() + name_sz, szFaceName); szFaceName[name_sz] = '\0'; } // class GraphiteFontAdaptor implementaion. // GraphiteFontAdaptor::GraphiteFontAdaptor(ServerFont & sfont, const sal_Int32 dpiX, const sal_Int32 dpiY) : mrFont(static_cast<FreetypeServerFont &>(sfont)), maFontProperties(static_cast<FreetypeServerFont &>(sfont)), mnDpiX(dpiX), mnDpiY(dpiY), mfAscent(from_hinted(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().ascender)), mfDescent(from_hinted(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().descender)), mfEmUnits(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().y_ppem), mpFeatures(NULL) { const rtl::OString aLang = MsLangId::convertLanguageToIsoByteString( sfont.GetFontSelData().meLanguage ); rtl::OString name = rtl::OUStringToOString( sfont.GetFontSelData().maTargetName, RTL_TEXTENCODING_UTF8 ); #ifdef DEBUG printf("GraphiteFontAdaptor %lx %s italic=%u bold=%u\n", (long)this, name.getStr(), maFontProperties.fItalic, maFontProperties.fBold); #endif sal_Int32 nFeat = name.indexOf(grutils::GrFeatureParser::FEAT_PREFIX) + 1; if (nFeat > 0) { rtl::OString aFeat = name.copy(nFeat, name.getLength() - nFeat); mpFeatures = new grutils::GrFeatureParser(*this, aFeat.getStr(), aLang.getStr()); #ifdef DEBUG printf("GraphiteFontAdaptor %s/%s/%s %x language %d features %d errors\n", rtl::OUStringToOString( sfont.GetFontSelData().maName, RTL_TEXTENCODING_UTF8 ).getStr(), rtl::OUStringToOString( sfont.GetFontSelData().maTargetName, RTL_TEXTENCODING_UTF8 ).getStr(), rtl::OUStringToOString( sfont.GetFontSelData().maSearchName, RTL_TEXTENCODING_UTF8 ).getStr(), sfont.GetFontSelData().meLanguage, (int)mpFeatures->getFontFeatures(NULL), mpFeatures->parseErrors()); #endif } else { mpFeatures = new grutils::GrFeatureParser(*this, aLang.getStr()); } } GraphiteFontAdaptor::GraphiteFontAdaptor(const GraphiteFontAdaptor &rhs) throw() : Font(rhs), mrFont (rhs.mrFont), maFontProperties(rhs.maFontProperties), mnDpiX(rhs.mnDpiX), mnDpiY(rhs.mnDpiY), mfAscent(rhs.mfAscent), mfDescent(rhs.mfDescent), mfEmUnits(rhs.mfEmUnits), mpFeatures(NULL) { if (rhs.mpFeatures) mpFeatures = new grutils::GrFeatureParser(*(rhs.mpFeatures)); } GraphiteFontAdaptor::~GraphiteFontAdaptor() throw() { maGlyphMetricMap.clear(); if (mpFeatures) delete mpFeatures; mpFeatures = NULL; } void GraphiteFontAdaptor::UniqueCacheInfo(ext_std::wstring & face_name_out, bool & bold_out, bool & italic_out) { face_name_out = maFontProperties.szFaceName; bold_out = maFontProperties.fBold; italic_out = maFontProperties.fItalic; } bool GraphiteFontAdaptor::IsGraphiteEnabledFont(ServerFont & font) throw() { // NOTE: this assumes that the same FTFace pointer won't be reused, // so FtFontInfo::ReleaseFaceFT must only be called at shutdown. FreetypeServerFont & aFtFont = dynamic_cast<FreetypeServerFont &>(font); FT_Face aFace = reinterpret_cast<FT_FaceRec_*>(aFtFont.GetFtFace()); SilfMap::iterator i = sSilfMap.find(reinterpret_cast<long>(aFace)); if (i != sSilfMap.end()) { #ifdef DEBUG if (static_cast<bool>(aFtFont.GetTable("Silf", 0)) != (*i).second) printf("Silf cache font mismatch\n"); #endif return (*i).second; } bool bHasSilf = aFtFont.GetTable("Silf", 0); sSilfMap[reinterpret_cast<long>(aFace)] = bHasSilf; return bHasSilf; } gr::Font * GraphiteFontAdaptor::copyThis() { return new GraphiteFontAdaptor(*this); } unsigned int GraphiteFontAdaptor::getDPIx() { return mnDpiX; } unsigned int GraphiteFontAdaptor::getDPIy() { return mnDpiY; } float GraphiteFontAdaptor::ascent() { return mfAscent; } float GraphiteFontAdaptor::descent() { return mfDescent; } bool GraphiteFontAdaptor::bold() { return maFontProperties.fBold; } bool GraphiteFontAdaptor::italic() { return maFontProperties.fItalic; } float GraphiteFontAdaptor::height() { return maFontProperties.pixHeight; } void GraphiteFontAdaptor::getFontMetrics(float * ascent_out, float * descent_out, float * em_square_out) { if (ascent_out) *ascent_out = mfAscent; if (descent_out) *descent_out = mfDescent; if (em_square_out) *em_square_out = mfEmUnits; } const void * GraphiteFontAdaptor::getTable(gr::fontTableId32 table_id, size_t * buffer_sz) { char tag_name[5] = {char(table_id >> 24), char(table_id >> 16), char(table_id >> 8), char(table_id), 0}; ULONG temp = *buffer_sz; const void * const tbl_buf = static_cast<FreetypeServerFont &>(mrFont).GetTable(tag_name, &temp); *buffer_sz = temp; return tbl_buf; } #define fix26_6(x) (x >> 6) + (x & 32 ? (x > 0 ? 1 : 0) : (x < 0 ? -1 : 0)) // Return the glyph's metrics in pixels. void GraphiteFontAdaptor::getGlyphMetrics(gr::gid16 nGlyphId, gr::Rect & aBounding, gr::Point & advances) { // There used to be problems when orientation was set however, this no // longer seems to be the case and the Glyph Metric cache in // FreetypeServerFont is more efficient since it lasts between calls to VCL #if 1 const GlyphMetric & metric = mrFont.GetGlyphMetric(nGlyphId); aBounding.right = aBounding.left = metric.GetOffset().X(); aBounding.bottom = aBounding.top = -metric.GetOffset().Y(); aBounding.right += metric.GetSize().Width(); aBounding.bottom -= metric.GetSize().Height(); advances.x = metric.GetDelta().X(); advances.y = -metric.GetDelta().Y(); #else // The problem with the code below is that the cache only lasts // as long as the life time of the GraphiteFontAdaptor, which // is created once per call to X11SalGraphics::GetTextLayout GlyphMetricMap::const_iterator gm_itr = maGlyphMetricMap.find(nGlyphId); if (gm_itr != maGlyphMetricMap.end()) { // We've cached the results from last time. aBounding = gm_itr->second.first; advances = gm_itr->second.second; } else { // We need to look up the glyph. FT_Int nLoadFlags = mrFont.GetLoadFlags(); FT_Face aFace = reinterpret_cast<FT_Face>(mrFont.GetFtFace()); if (!aFace) { aBounding.top = aBounding.bottom = aBounding.left = aBounding.right = 0; advances.x = advances.y = 0; return; } FT_Error aStatus = -1; aStatus = FT_Load_Glyph(aFace, nGlyphId, nLoadFlags); if( aStatus != FT_Err_Ok || (!aFace->glyph)) { aBounding.top = aBounding.bottom = aBounding.left = aBounding.right = 0; advances.x = advances.y = 0; return; } // check whether we need synthetic bold/italic otherwise metric is wrong if (mrFont.NeedsArtificialBold() && pFTEmbolden) (*pFTEmbolden)(aFace->glyph); if (mrFont.NeedsArtificialItalic() && pFTOblique) (*pFTOblique)(aFace->glyph); const FT_Glyph_Metrics &gm = aFace->glyph->metrics; // Fill out the bounding box an advances. aBounding.top = aBounding.bottom = fix26_6(gm.horiBearingY); aBounding.bottom -= fix26_6(gm.height); aBounding.left = aBounding.right = fix26_6(gm.horiBearingX); aBounding.right += fix26_6(gm.width); advances.x = fix26_6(gm.horiAdvance); advances.y = 0; // Now add an entry to our metrics map. maGlyphMetricMap[nGlyphId] = std::make_pair(aBounding, advances); } #endif } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>move global sSilfMap to be a local sSilfMap to defer ctor until first use<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // Description: Implements the Graphite interfaces with access to the // platform's font and graphics systems. // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" // We need this to enable namespace support in libgrengine headers. #define GR_NAMESPACE // Header files // // Standard Library #include <string> #include <cassert> // Libraries #include <rtl/string.hxx> #include <rtl/ustring.hxx> #include <i18npool/mslangid.hxx> // Platform #ifndef WNT #include <saldisp.hxx> #include <vcl/salgdi.hxx> #include <freetype/ftsynth.h> // Module #include "gcach_ftyp.hxx" #include <vcl/graphite_features.hxx> #include <vcl/graphite_adaptors.hxx> // Module private type definitions and forward declarations. // using gr::GrResult; namespace { inline float from_hinted(const int x) { return static_cast<float>(x + 32) / 64.0; } typedef std::hash_map<long,bool> SilfMap; } extern FT_Error (*pFTEmbolden)(FT_GlyphSlot); extern FT_Error (*pFTOblique)(FT_GlyphSlot); // class CharacterRenderProperties implentation. // FontProperties::FontProperties(const FreetypeServerFont &font) throw() { clrFore = gr::kclrBlack; clrBack = gr::kclrTransparent; pixHeight = from_hinted(font.GetMetricsFT().height); switch (font.GetFontSelData().meWeight) { case WEIGHT_SEMIBOLD: case WEIGHT_BOLD: case WEIGHT_ULTRABOLD: case WEIGHT_BLACK: fBold = true; break; default : fBold = false; } switch (font.GetFontSelData().meItalic) { case ITALIC_NORMAL: case ITALIC_OBLIQUE: fItalic = true; break; default : fItalic = false; } // Get the font name, but prefix with file name hash in case // there are 2 fonts on the system with the same face name sal_Int32 nHashCode = font.GetFontFileName()->hashCode(); ::rtl::OUStringBuffer nHashFaceName; nHashFaceName.append(nHashCode, 16); const sal_Unicode * name = font.GetFontSelData().maName.GetBuffer(); nHashFaceName.append(name); const size_t name_sz = std::min(sizeof szFaceName/sizeof(wchar_t)-1, static_cast<size_t>(nHashFaceName.getLength())); std::copy(nHashFaceName.getStr(), nHashFaceName.getStr() + name_sz, szFaceName); szFaceName[name_sz] = '\0'; } // class GraphiteFontAdaptor implementaion. // GraphiteFontAdaptor::GraphiteFontAdaptor(ServerFont & sfont, const sal_Int32 dpiX, const sal_Int32 dpiY) : mrFont(static_cast<FreetypeServerFont &>(sfont)), maFontProperties(static_cast<FreetypeServerFont &>(sfont)), mnDpiX(dpiX), mnDpiY(dpiY), mfAscent(from_hinted(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().ascender)), mfDescent(from_hinted(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().descender)), mfEmUnits(static_cast<FreetypeServerFont &>(sfont).GetMetricsFT().y_ppem), mpFeatures(NULL) { const rtl::OString aLang = MsLangId::convertLanguageToIsoByteString( sfont.GetFontSelData().meLanguage ); rtl::OString name = rtl::OUStringToOString( sfont.GetFontSelData().maTargetName, RTL_TEXTENCODING_UTF8 ); #ifdef DEBUG printf("GraphiteFontAdaptor %lx %s italic=%u bold=%u\n", (long)this, name.getStr(), maFontProperties.fItalic, maFontProperties.fBold); #endif sal_Int32 nFeat = name.indexOf(grutils::GrFeatureParser::FEAT_PREFIX) + 1; if (nFeat > 0) { rtl::OString aFeat = name.copy(nFeat, name.getLength() - nFeat); mpFeatures = new grutils::GrFeatureParser(*this, aFeat.getStr(), aLang.getStr()); #ifdef DEBUG printf("GraphiteFontAdaptor %s/%s/%s %x language %d features %d errors\n", rtl::OUStringToOString( sfont.GetFontSelData().maName, RTL_TEXTENCODING_UTF8 ).getStr(), rtl::OUStringToOString( sfont.GetFontSelData().maTargetName, RTL_TEXTENCODING_UTF8 ).getStr(), rtl::OUStringToOString( sfont.GetFontSelData().maSearchName, RTL_TEXTENCODING_UTF8 ).getStr(), sfont.GetFontSelData().meLanguage, (int)mpFeatures->getFontFeatures(NULL), mpFeatures->parseErrors()); #endif } else { mpFeatures = new grutils::GrFeatureParser(*this, aLang.getStr()); } } GraphiteFontAdaptor::GraphiteFontAdaptor(const GraphiteFontAdaptor &rhs) throw() : Font(rhs), mrFont (rhs.mrFont), maFontProperties(rhs.maFontProperties), mnDpiX(rhs.mnDpiX), mnDpiY(rhs.mnDpiY), mfAscent(rhs.mfAscent), mfDescent(rhs.mfDescent), mfEmUnits(rhs.mfEmUnits), mpFeatures(NULL) { if (rhs.mpFeatures) mpFeatures = new grutils::GrFeatureParser(*(rhs.mpFeatures)); } GraphiteFontAdaptor::~GraphiteFontAdaptor() throw() { maGlyphMetricMap.clear(); if (mpFeatures) delete mpFeatures; mpFeatures = NULL; } void GraphiteFontAdaptor::UniqueCacheInfo(ext_std::wstring & face_name_out, bool & bold_out, bool & italic_out) { face_name_out = maFontProperties.szFaceName; bold_out = maFontProperties.fBold; italic_out = maFontProperties.fItalic; } bool GraphiteFontAdaptor::IsGraphiteEnabledFont(ServerFont & font) throw() { static SilfMap sSilfMap; // NOTE: this assumes that the same FTFace pointer won't be reused, // so FtFontInfo::ReleaseFaceFT must only be called at shutdown. FreetypeServerFont & aFtFont = dynamic_cast<FreetypeServerFont &>(font); FT_Face aFace = reinterpret_cast<FT_FaceRec_*>(aFtFont.GetFtFace()); SilfMap::iterator i = sSilfMap.find(reinterpret_cast<long>(aFace)); if (i != sSilfMap.end()) { #ifdef DEBUG if (static_cast<bool>(aFtFont.GetTable("Silf", 0)) != (*i).second) printf("Silf cache font mismatch\n"); #endif return (*i).second; } bool bHasSilf = aFtFont.GetTable("Silf", 0); sSilfMap[reinterpret_cast<long>(aFace)] = bHasSilf; return bHasSilf; } gr::Font * GraphiteFontAdaptor::copyThis() { return new GraphiteFontAdaptor(*this); } unsigned int GraphiteFontAdaptor::getDPIx() { return mnDpiX; } unsigned int GraphiteFontAdaptor::getDPIy() { return mnDpiY; } float GraphiteFontAdaptor::ascent() { return mfAscent; } float GraphiteFontAdaptor::descent() { return mfDescent; } bool GraphiteFontAdaptor::bold() { return maFontProperties.fBold; } bool GraphiteFontAdaptor::italic() { return maFontProperties.fItalic; } float GraphiteFontAdaptor::height() { return maFontProperties.pixHeight; } void GraphiteFontAdaptor::getFontMetrics(float * ascent_out, float * descent_out, float * em_square_out) { if (ascent_out) *ascent_out = mfAscent; if (descent_out) *descent_out = mfDescent; if (em_square_out) *em_square_out = mfEmUnits; } const void * GraphiteFontAdaptor::getTable(gr::fontTableId32 table_id, size_t * buffer_sz) { char tag_name[5] = {char(table_id >> 24), char(table_id >> 16), char(table_id >> 8), char(table_id), 0}; ULONG temp = *buffer_sz; const void * const tbl_buf = static_cast<FreetypeServerFont &>(mrFont).GetTable(tag_name, &temp); *buffer_sz = temp; return tbl_buf; } #define fix26_6(x) (x >> 6) + (x & 32 ? (x > 0 ? 1 : 0) : (x < 0 ? -1 : 0)) // Return the glyph's metrics in pixels. void GraphiteFontAdaptor::getGlyphMetrics(gr::gid16 nGlyphId, gr::Rect & aBounding, gr::Point & advances) { // There used to be problems when orientation was set however, this no // longer seems to be the case and the Glyph Metric cache in // FreetypeServerFont is more efficient since it lasts between calls to VCL #if 1 const GlyphMetric & metric = mrFont.GetGlyphMetric(nGlyphId); aBounding.right = aBounding.left = metric.GetOffset().X(); aBounding.bottom = aBounding.top = -metric.GetOffset().Y(); aBounding.right += metric.GetSize().Width(); aBounding.bottom -= metric.GetSize().Height(); advances.x = metric.GetDelta().X(); advances.y = -metric.GetDelta().Y(); #else // The problem with the code below is that the cache only lasts // as long as the life time of the GraphiteFontAdaptor, which // is created once per call to X11SalGraphics::GetTextLayout GlyphMetricMap::const_iterator gm_itr = maGlyphMetricMap.find(nGlyphId); if (gm_itr != maGlyphMetricMap.end()) { // We've cached the results from last time. aBounding = gm_itr->second.first; advances = gm_itr->second.second; } else { // We need to look up the glyph. FT_Int nLoadFlags = mrFont.GetLoadFlags(); FT_Face aFace = reinterpret_cast<FT_Face>(mrFont.GetFtFace()); if (!aFace) { aBounding.top = aBounding.bottom = aBounding.left = aBounding.right = 0; advances.x = advances.y = 0; return; } FT_Error aStatus = -1; aStatus = FT_Load_Glyph(aFace, nGlyphId, nLoadFlags); if( aStatus != FT_Err_Ok || (!aFace->glyph)) { aBounding.top = aBounding.bottom = aBounding.left = aBounding.right = 0; advances.x = advances.y = 0; return; } // check whether we need synthetic bold/italic otherwise metric is wrong if (mrFont.NeedsArtificialBold() && pFTEmbolden) (*pFTEmbolden)(aFace->glyph); if (mrFont.NeedsArtificialItalic() && pFTOblique) (*pFTOblique)(aFace->glyph); const FT_Glyph_Metrics &gm = aFace->glyph->metrics; // Fill out the bounding box an advances. aBounding.top = aBounding.bottom = fix26_6(gm.horiBearingY); aBounding.bottom -= fix26_6(gm.height); aBounding.left = aBounding.right = fix26_6(gm.horiBearingX); aBounding.right += fix26_6(gm.width); advances.x = fix26_6(gm.horiAdvance); advances.y = 0; // Now add an entry to our metrics map. maGlyphMetricMap[nGlyphId] = std::make_pair(aBounding, advances); } #endif } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2016 Artur Troian // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <openssl/hmac.h> #include <cstring> #include <josepp/crypto.hpp> #include <josepp/b64.hpp> #include <josepp/tools.hpp> namespace jose { hmac::hmac(jose::alg alg, const std::string &secret) : crypto(alg) , secret_(secret) { if (alg != jose::alg::HS256 && alg != jose::alg::HS384 && alg != jose::alg::HS512) { throw std::invalid_argument("Invalid algorithm"); } if (secret.empty()) { throw std::invalid_argument("Invalid secret"); } } hmac::~hmac() { std::memset(const_cast<char *>(secret_.data()), 0 , secret_.length()); } std::string hmac::sign(const std::string &data) { if (data.empty()) { throw std::invalid_argument("Data is empty"); } const EVP_MD *evp; switch (alg_) { case jose::alg::HS256: evp = EVP_sha256(); break; case jose::alg::HS384: evp = EVP_sha384(); break; case jose::alg::HS512: evp = EVP_sha512(); break; default: // Should never happen throw std::runtime_error("Invalid alg"); } HMAC_CTX *hmac; #if OPENSSL_VERSION_NUMBER < 0x10100000L HMAC_CTX hmac_l; HMAC_CTX_init(&hmac_l); hmac = &hmac_l; #else hmac = HMAC_CTX_new(); #endif HMAC_Init_ex(hmac, secret_.data(), static_cast<int>(secret_.length()), evp, nullptr); HMAC_Update(hmac, reinterpret_cast<const uint8_t *>(data.c_str()), data.size()); std::shared_ptr<uint8_t> res = std::shared_ptr<uint8_t>(new uint8_t[EVP_MD_size(evp)], std::default_delete<uint8_t[]>()); uint32_t size; HMAC_Final(hmac, res.get(), &size); HMAC_CTX_cleanup(hmac); #if OPENSSL_VERSION_NUMBER >= 0x10100000L HMAC_CTX_free(hmac); #endif return std::move(b64::encode_uri(res.get(), size)); } bool hmac::verify(const std::string &data, const std::string &sig) { return sig == sign(data); } } // namespace jose <commit_msg>Ref #5 remove HMAC_CTX_cleanup from openssl 1.1.0 usage<commit_after>// The MIT License (MIT) // // Copyright (c) 2016 Artur Troian // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <openssl/hmac.h> #include <cstring> #include <josepp/crypto.hpp> #include <josepp/b64.hpp> #include <josepp/tools.hpp> namespace jose { hmac::hmac(jose::alg alg, const std::string &secret) : crypto(alg) , secret_(secret) { if (alg != jose::alg::HS256 && alg != jose::alg::HS384 && alg != jose::alg::HS512) { throw std::invalid_argument("Invalid algorithm"); } if (secret.empty()) { throw std::invalid_argument("Invalid secret"); } } hmac::~hmac() { std::memset(const_cast<char *>(secret_.data()), 0 , secret_.length()); } std::string hmac::sign(const std::string &data) { if (data.empty()) { throw std::invalid_argument("Data is empty"); } const EVP_MD *evp; switch (alg_) { case jose::alg::HS256: evp = EVP_sha256(); break; case jose::alg::HS384: evp = EVP_sha384(); break; case jose::alg::HS512: evp = EVP_sha512(); break; default: // Should never happen throw std::runtime_error("Invalid alg"); } HMAC_CTX *hmac; #if OPENSSL_VERSION_NUMBER < 0x10100000L HMAC_CTX hmac_l; HMAC_CTX_init(&hmac_l); hmac = &hmac_l; #else hmac = HMAC_CTX_new(); #endif HMAC_Init_ex(hmac, secret_.data(), static_cast<int>(secret_.length()), evp, nullptr); HMAC_Update(hmac, reinterpret_cast<const uint8_t *>(data.c_str()), data.size()); std::shared_ptr<uint8_t> res = std::shared_ptr<uint8_t>(new uint8_t[EVP_MD_size(evp)], std::default_delete<uint8_t[]>()); uint32_t size; HMAC_Final(hmac, res.get(), &size); #if OPENSSL_VERSION_NUMBER < 0x10100000L HMAC_CTX_cleanup(hmac); #else HMAC_CTX_free(hmac); #endif return std::move(b64::encode_uri(res.get(), size)); } bool hmac::verify(const std::string &data, const std::string &sig) { return sig == sign(data); } } // namespace jose <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (defined(WIN32) || defined(_WIN32)) && !defined(_WIN32_WCE) #include <windows.h> #undef ERROR #include <log4cxx/nt/nteventlogappender.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/level.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include <apr_strings.h> using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::nt; class CCtUserSIDHelper { public: static bool FreeSid(SID * pSid) { return ::HeapFree(GetProcessHeap(), 0, (LPVOID)pSid) != 0; } static bool CopySid(SID * * ppDstSid, SID * pSrcSid) { bool bSuccess = false; DWORD dwLength = ::GetLengthSid(pSrcSid); *ppDstSid = (SID *) ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); if (::CopySid(dwLength, *ppDstSid, pSrcSid)) { bSuccess = true; } else { FreeSid(*ppDstSid); } return bSuccess; } static bool GetCurrentUserSID(SID * * ppSid) { bool bSuccess = false; // Pseudohandle so don't need to close it HANDLE hProcess = ::GetCurrentProcess(); HANDLE hToken = NULL; if (::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { // Get the required size DWORD tusize = 0; GetTokenInformation(hToken, TokenUser, NULL, 0, &tusize); TOKEN_USER* ptu = (TOKEN_USER*)new BYTE[tusize]; if (GetTokenInformation(hToken, TokenUser, (LPVOID)ptu, tusize, &tusize)) { bSuccess = CopySid(ppSid, (SID *)ptu->User.Sid); } CloseHandle(hToken); delete [] ptu; } return bSuccess; } }; IMPLEMENT_LOG4CXX_OBJECT(NTEventLogAppender) NTEventLogAppender::NTEventLogAppender() : hEventLog(NULL), pCurrentUserSID(NULL) { } NTEventLogAppender::NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout) : server(server), log(log), source(source), hEventLog(NULL), pCurrentUserSID(NULL) { this->layout = layout; Pool pool; activateOptions(pool); } NTEventLogAppender::~NTEventLogAppender() { finalize(); } void NTEventLogAppender::close() { if (hEventLog != NULL) { ::DeregisterEventSource(hEventLog); hEventLog = NULL; } if (pCurrentUserSID != NULL) { CCtUserSIDHelper::FreeSid((::SID*) pCurrentUserSID); pCurrentUserSID = NULL; } } void NTEventLogAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SERVER"), LOG4CXX_STR("server"))) { server = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOG"), LOG4CXX_STR("log"))) { log = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SOURCE"), LOG4CXX_STR("source"))) { source = value; } else { AppenderSkeleton::setOption(option, value); } } void NTEventLogAppender::activateOptions(Pool&) { if (source.empty()) { LogLog::warn( ((LogString) LOG4CXX_STR("Source option not set for appender [")) + name + LOG4CXX_STR("].")); return; } if (log.empty()) { log = LOG4CXX_STR("Application"); } close(); // current user security identifier CCtUserSIDHelper::GetCurrentUserSID((::SID**) &pCurrentUserSID); addRegistryInfo(); LOG4CXX_ENCODE_WCHAR(wsource, source); LOG4CXX_ENCODE_WCHAR(wserver, server); hEventLog = ::RegisterEventSourceW( wserver.empty() ? NULL : wserver.c_str(), wsource.c_str()); if (hEventLog == NULL) { LogString msg(LOG4CXX_STR("Cannot register NT EventLog -- server: '")); msg.append(server); msg.append(LOG4CXX_STR("' source: '")); msg.append(source); LogLog::error(msg); LogLog::error(getErrorString(LOG4CXX_STR("RegisterEventSource"))); } } void NTEventLogAppender::append(const LoggingEventPtr& event, Pool& p) { if (hEventLog == NULL) { LogLog::warn(LOG4CXX_STR("NT EventLog not opened.")); return; } LogString oss; layout->format(oss, event, p); wchar_t* msgs = Transcoder::wencode(oss, p); BOOL bSuccess = ::ReportEventW( hEventLog, getEventType(event), getEventCategory(event), 0x1000, pCurrentUserSID, 1, 0, (LPCWSTR*) &msgs, NULL); if (!bSuccess) { LogLog::error(getErrorString(LOG4CXX_STR("ReportEvent"))); } } /* * Add this source with appropriate configuration keys to the registry. */ void NTEventLogAppender::addRegistryInfo() { DWORD disposition = 0; ::HKEY hkey = 0; LogString subkey(LOG4CXX_STR("SYSTEM\\CurrentControlSet\\Services\\EventLog\\")); subkey.append(log); subkey.append(1, (logchar) 0x5C /* '\\' */); subkey.append(source); LOG4CXX_ENCODE_WCHAR(wsubkey, subkey); long stat = RegCreateKeyExW(HKEY_LOCAL_MACHINE, wsubkey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, &disposition); if (stat == ERROR_SUCCESS && disposition == REG_CREATED_NEW_KEY) { HMODULE hmodule = GetModuleHandleW(L"log4cxx"); if (hmodule == NULL) { hmodule = GetModuleHandleW(0); } wchar_t modpath[_MAX_PATH]; DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1); if (modlen > 0) { modpath[modlen] = 0; RegSetValueExW(hkey, L"EventMessageFile", 0, REG_SZ, (LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t)); RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_SZ, (LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t)); DWORD typesSupported = 7; DWORD categoryCount = 6; RegSetValueExW(hkey, L"TypesSupported", 0, REG_DWORD, (LPBYTE)&typesSupported, sizeof(DWORD)); RegSetValueExW(hkey, L"CategoryCount", 0, REG_DWORD, (LPBYTE)&categoryCount, sizeof(DWORD)); } } RegCloseKey(hkey); return; } WORD NTEventLogAppender::getEventType(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD type = EVENTLOG_SUCCESS; if (priority >= Level::INFO_INT) { type = EVENTLOG_INFORMATION_TYPE; if (priority >= Level::WARN_INT) { type = EVENTLOG_WARNING_TYPE; if (priority >= Level::ERROR_INT) { type = EVENTLOG_ERROR_TYPE; } } } return type; } WORD NTEventLogAppender::getEventCategory(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD category = 1; if (priority >= Level::DEBUG_INT) { category = 2; if (priority >= Level::INFO_INT) { category = 3; if (priority >= Level::WARN_INT) { category = 4; if (priority >= Level::ERROR_INT) { category = 5; if (priority >= Level::FATAL_INT) { category = 6; } } } } } return category; } LogString NTEventLogAppender::getErrorString(const LogString& function) { Pool p; enum { MSGSIZE = 5000 }; wchar_t* lpMsgBuf = (wchar_t*) p.palloc(MSGSIZE * sizeof(wchar_t)); DWORD dw = GetLastError(); FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMsgBuf, MSGSIZE, NULL ); LogString msg(function); msg.append(LOG4CXX_STR(" failed with error ")); StringHelper::toString((size_t) dw, p, msg); msg.append(LOG4CXX_STR(": ")); Transcoder::decode(lpMsgBuf, msg); return msg; } #endif // WIN32 <commit_msg>LOGCXX-426<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (defined(WIN32) || defined(_WIN32)) && !defined(_WIN32_WCE) #define _WINSOCKAPI_ #include <windows.h> #undef ERROR #include <log4cxx/nt/nteventlogappender.h> #include <log4cxx/spi/loggingevent.h> #include <log4cxx/helpers/loglog.h> #include <log4cxx/level.h> #include <log4cxx/helpers/stringhelper.h> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/pool.h> #include <apr_strings.h> using namespace log4cxx; using namespace log4cxx::spi; using namespace log4cxx::helpers; using namespace log4cxx::nt; class CCtUserSIDHelper { public: static bool FreeSid(SID * pSid) { return ::HeapFree(GetProcessHeap(), 0, (LPVOID)pSid) != 0; } static bool CopySid(SID * * ppDstSid, SID * pSrcSid) { bool bSuccess = false; DWORD dwLength = ::GetLengthSid(pSrcSid); *ppDstSid = (SID *) ::HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength); if (::CopySid(dwLength, *ppDstSid, pSrcSid)) { bSuccess = true; } else { FreeSid(*ppDstSid); } return bSuccess; } static bool GetCurrentUserSID(SID * * ppSid) { bool bSuccess = false; // Pseudohandle so don't need to close it HANDLE hProcess = ::GetCurrentProcess(); HANDLE hToken = NULL; if (::OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { // Get the required size DWORD tusize = 0; GetTokenInformation(hToken, TokenUser, NULL, 0, &tusize); TOKEN_USER* ptu = (TOKEN_USER*)new BYTE[tusize]; if (GetTokenInformation(hToken, TokenUser, (LPVOID)ptu, tusize, &tusize)) { bSuccess = CopySid(ppSid, (SID *)ptu->User.Sid); } CloseHandle(hToken); delete [] ptu; } return bSuccess; } }; IMPLEMENT_LOG4CXX_OBJECT(NTEventLogAppender) NTEventLogAppender::NTEventLogAppender() : hEventLog(NULL), pCurrentUserSID(NULL) { } NTEventLogAppender::NTEventLogAppender(const LogString& server, const LogString& log, const LogString& source, const LayoutPtr& layout) : server(server), log(log), source(source), hEventLog(NULL), pCurrentUserSID(NULL) { this->layout = layout; Pool pool; activateOptions(pool); } NTEventLogAppender::~NTEventLogAppender() { finalize(); } void NTEventLogAppender::close() { if (hEventLog != NULL) { ::DeregisterEventSource(hEventLog); hEventLog = NULL; } if (pCurrentUserSID != NULL) { CCtUserSIDHelper::FreeSid((::SID*) pCurrentUserSID); pCurrentUserSID = NULL; } } void NTEventLogAppender::setOption(const LogString& option, const LogString& value) { if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SERVER"), LOG4CXX_STR("server"))) { server = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOG"), LOG4CXX_STR("log"))) { log = value; } else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("SOURCE"), LOG4CXX_STR("source"))) { source = value; } else { AppenderSkeleton::setOption(option, value); } } void NTEventLogAppender::activateOptions(Pool&) { if (source.empty()) { LogLog::warn( ((LogString) LOG4CXX_STR("Source option not set for appender [")) + name + LOG4CXX_STR("].")); return; } if (log.empty()) { log = LOG4CXX_STR("Application"); } close(); // current user security identifier CCtUserSIDHelper::GetCurrentUserSID((::SID**) &pCurrentUserSID); addRegistryInfo(); LOG4CXX_ENCODE_WCHAR(wsource, source); LOG4CXX_ENCODE_WCHAR(wserver, server); hEventLog = ::RegisterEventSourceW( wserver.empty() ? NULL : wserver.c_str(), wsource.c_str()); if (hEventLog == NULL) { LogString msg(LOG4CXX_STR("Cannot register NT EventLog -- server: '")); msg.append(server); msg.append(LOG4CXX_STR("' source: '")); msg.append(source); LogLog::error(msg); LogLog::error(getErrorString(LOG4CXX_STR("RegisterEventSource"))); } } void NTEventLogAppender::append(const LoggingEventPtr& event, Pool& p) { if (hEventLog == NULL) { LogLog::warn(LOG4CXX_STR("NT EventLog not opened.")); return; } LogString oss; layout->format(oss, event, p); wchar_t* msgs = Transcoder::wencode(oss, p); BOOL bSuccess = ::ReportEventW( hEventLog, getEventType(event), getEventCategory(event), 0x1000, pCurrentUserSID, 1, 0, (LPCWSTR*) &msgs, NULL); if (!bSuccess) { LogLog::error(getErrorString(LOG4CXX_STR("ReportEvent"))); } } /* * Add this source with appropriate configuration keys to the registry. */ void NTEventLogAppender::addRegistryInfo() { DWORD disposition = 0; ::HKEY hkey = 0; LogString subkey(LOG4CXX_STR("SYSTEM\\CurrentControlSet\\Services\\EventLog\\")); subkey.append(log); subkey.append(1, (logchar) 0x5C /* '\\' */); subkey.append(source); LOG4CXX_ENCODE_WCHAR(wsubkey, subkey); long stat = RegCreateKeyExW(HKEY_LOCAL_MACHINE, wsubkey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hkey, &disposition); if (stat == ERROR_SUCCESS && disposition == REG_CREATED_NEW_KEY) { HMODULE hmodule = GetModuleHandleW(L"log4cxx"); if (hmodule == NULL) { hmodule = GetModuleHandleW(0); } wchar_t modpath[_MAX_PATH]; DWORD modlen = GetModuleFileNameW(hmodule, modpath, _MAX_PATH - 1); if (modlen > 0) { modpath[modlen] = 0; RegSetValueExW(hkey, L"EventMessageFile", 0, REG_SZ, (LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t)); RegSetValueExW(hkey, L"CategoryMessageFile", 0, REG_SZ, (LPBYTE) modpath, wcslen(modpath) * sizeof(wchar_t)); DWORD typesSupported = 7; DWORD categoryCount = 6; RegSetValueExW(hkey, L"TypesSupported", 0, REG_DWORD, (LPBYTE)&typesSupported, sizeof(DWORD)); RegSetValueExW(hkey, L"CategoryCount", 0, REG_DWORD, (LPBYTE)&categoryCount, sizeof(DWORD)); } } RegCloseKey(hkey); return; } WORD NTEventLogAppender::getEventType(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD type = EVENTLOG_SUCCESS; if (priority >= Level::INFO_INT) { type = EVENTLOG_INFORMATION_TYPE; if (priority >= Level::WARN_INT) { type = EVENTLOG_WARNING_TYPE; if (priority >= Level::ERROR_INT) { type = EVENTLOG_ERROR_TYPE; } } } return type; } WORD NTEventLogAppender::getEventCategory(const LoggingEventPtr& event) { int priority = event->getLevel()->toInt(); WORD category = 1; if (priority >= Level::DEBUG_INT) { category = 2; if (priority >= Level::INFO_INT) { category = 3; if (priority >= Level::WARN_INT) { category = 4; if (priority >= Level::ERROR_INT) { category = 5; if (priority >= Level::FATAL_INT) { category = 6; } } } } } return category; } LogString NTEventLogAppender::getErrorString(const LogString& function) { Pool p; enum { MSGSIZE = 5000 }; wchar_t* lpMsgBuf = (wchar_t*) p.palloc(MSGSIZE * sizeof(wchar_t)); DWORD dw = GetLastError(); FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), lpMsgBuf, MSGSIZE, NULL ); LogString msg(function); msg.append(LOG4CXX_STR(" failed with error ")); StringHelper::toString((size_t) dw, p, msg); msg.append(LOG4CXX_STR(": ")); Transcoder::decode(lpMsgBuf, msg); return msg; } #endif // WIN32 <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_load_iop_xram.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_load_iop_xram.H /// @brief Load PCIE firmware to IOP external RAM. /// /// *HWP HW Maintainer: Thi Tran <thi@us.ibm.com> /// *HWP FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com> /// *HWP Consumed by: HB, Cronus /// //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_load_iop_xram.H> #include <p10_pcie_scominit.H> #include <multicast_group_defs.H> #include <p10_ipl_image.H> #include <p10_iop_xram_utils.H> #include <p10_putsram.H> #include <p10_getputsram_utils.H> #include <fapi2_subroutine_executor.H> #include <p10_scom_pec.H> //@TODO: RTC 214852 - Use SCOM accessors, remove workaround code //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ const uint64_t IOPFIRACT0 = 0x0000000000000000ULL; const uint64_t IOPFIRACT1 = 0xABA0000000000000ULL; const uint64_t IOPFIRMASK = 0x0000000000000000ULL; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /// NOTE: doxygen in header fapi2::ReturnCode p10_load_iop_xram( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, void* const i_hw_image) { FAPI_DBG("Start"); fapi2::ReturnCode l_rc; P9XipSection l_section; l_section.iv_offset = 0; l_section.iv_size = 0; uint8_t* l_xramImgPtr = NULL; uint8_t* l_xramFwDataPtr = NULL; uint32_t l_xramFwSize = 0; // Get PEC multicast target auto l_target_mcast = i_target.getMulticast<fapi2::TARGET_TYPE_PEC>(fapi2::MCGROUP_GOOD_PCI); std::vector<fapi2::Target<fapi2::TARGET_TYPE_PEC>> l_pecChiplets = l_target_mcast.getChildren<fapi2::TARGET_TYPE_PEC>(); // Skip load if there are no functional PEC targets on this chip if (l_pecChiplets.size() == 0) { FAPI_INF("p10_load_iop_xram: Skipping load, no functional PEC on chip."); goto fapi_try_exit; } // Validate HW image FAPI_ASSERT(i_hw_image != NULL , fapi2::P10_LOAD_IOP_XRAM_HW_IMG_ERROR() .set_TARGET(i_target) .set_HW_IMAGE(i_hw_image), "p10_load_iop_xram: Invalid HW XIP image"); // Reference the XRAM image (.xram) section in the HW image // This is an XIP image nested in the HW image itself FAPI_INF("p10_load_iop_xram: Calling p9_xip_get_section (HW image)"); FAPI_TRY(p9_xip_get_section(i_hw_image, P9_XIP_SECTION_HW_IOPXRAM, &l_section), "p10_load_iop_xram: Error from p9_xip_get_section (HW image)."); l_xramImgPtr = l_section.iv_offset + (uint8_t*)(i_hw_image); // From the XRAM image, obtain pointers to IOP FW data FAPI_DBG("p10_load_iop_xram: Calling p9_xip_get_section (XRAM image, FW section)"); FAPI_TRY(p9_xip_get_section(l_xramImgPtr, P9_XIP_SECTION_IOPXRAM_IOP_FW, &l_section), "p10_load_iop_xram: Error from p9_xip_get_section (XRAM image, FW section)"); l_xramFwDataPtr = l_section.iv_offset + (uint8_t*)(l_xramImgPtr); l_xramFwSize = l_section.iv_size; FAPI_INF("p10_load_iop_xram: i_hw_image %p, l_xramImgPtr %p, l_xramFwDataPtr %p, l_xramFwSize %u", i_hw_image, l_xramImgPtr, l_xramFwDataPtr, l_xramFwSize); // Validate XRAM image FAPI_ASSERT((l_xramFwDataPtr != NULL) && (l_xramFwSize != 0) && (l_xramFwSize <= MAX_XRAM_IMAGE_SIZE), fapi2::P10_LOAD_IOP_XRAM_IMG_ERROR() .set_TARGET(i_target) .set_HW_IMAGE(i_hw_image) .set_XRAM_IMAGE_PTR(l_xramImgPtr) .set_XRAM_FW_DATA_PTR(l_xramFwDataPtr) .set_XRAM_FW_SIZE(l_xramFwSize) .set_XIP_SECTION(l_section), "p10_load_iop_xram: Invalid XRAM image: l_xramFwDataPtr %p, Size %u", l_xramFwDataPtr, l_xramFwSize); // Write img data to XRAM using PEC multicast FAPI_INF("p10_load_iop_xram: Write XRAM FW data: Ptr %p, size %u.", l_xramFwDataPtr, l_xramFwSize); // Reset PHYs on both PECs FAPI_TRY(doPhyReset(l_target_mcast), "p10_load_iop_xram: doPhyReset returns an error."); // configure IOP FIR error reporting FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRACT0, IOPFIRACT0)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRACT0, IOPFIRACT0)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRACT1, IOPFIRACT1)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRACT1, IOPFIRACT1)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRMASK_RW, IOPFIRMASK)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRMASK_RW, IOPFIRMASK)); // Write CReg overrides through the CR Parallel Interface // This is called here because phy reset has to be deasserted for CReg access // Do this after PHY Reset and preferablly before ext_ld_done. FAPI_TRY(p10_load_iop_override(i_target)); // Use multicast PEC target to load PCIE FW to all PECs // Loop to load to all IOP XRAM (iop_top0/1, phy0/1) for (uint8_t l_top = 0; l_top < NUM_OF_IO_TOPS; l_top++) { for (uint8_t l_phy = 0; l_phy < NUM_OF_PHYS; l_phy++) { FAPI_INF("p10_load_iop_xram: Attemp to write PCIE img to XRAM: iop_top %d, phy %d.", l_top, l_phy); // Encode Top and Phy into mode uint8_t l_mode = 0; if (l_top) { l_mode = MODE_PCIE_TOP_BIT_MASK; } if (l_phy) { l_mode |= MODE_PCIE_PHY_BIT_MASK; } // Load IOP XRAM using putsram chip-op FAPI_CALL_SUBROUTINE(fapi2::current_err, p10_putsram, i_target, PCI0_PERV_CHIPLET_ID, // Set to PCI0 as default for multicast. // p10_putsram will find valid multicast target. true, // Do multicast load l_mode, // Access mode, not used here static_cast<uint64_t>(0), // Load at offset 0 l_xramFwSize, l_xramFwDataPtr); FAPI_TRY(fapi2::current_err, "p10_load_iop_xram: p10_write_xram returns an error: iop_top %d, phy %d."); FAPI_INF("p10_load_iop_xram: Successfully wrote PCIE img to XRAM: iop_top %d, phy %d.", l_top, l_phy); } // Done loading this iop_top, enable XRAM scrubber // Note: do this here because Scrubber bit applies to both PHYs of an io_top FAPI_TRY(enableXramScrubber(l_target_mcast, static_cast<xramIopTopNum_t>(l_top)), "p10_load_iop_xram: enableXramScrubber returns an error."); } FAPI_TRY(p10_load_rtrim_override(i_target)); FAPI_TRY(p10_verify_iop_fw(i_target)); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <commit_msg>p10_load_iop_xram -- skip rtim override in simulation<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_load_iop_xram.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_load_iop_xram.H /// @brief Load PCIE firmware to IOP external RAM. /// /// *HWP HW Maintainer: Thi Tran <thi@us.ibm.com> /// *HWP FW Maintainer: Ilya Smirnov <ismirno@us.ibm.com> /// *HWP Consumed by: HB, Cronus /// //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_load_iop_xram.H> #include <p10_pcie_scominit.H> #include <multicast_group_defs.H> #include <p10_ipl_image.H> #include <p10_iop_xram_utils.H> #include <p10_putsram.H> #include <p10_getputsram_utils.H> #include <fapi2_subroutine_executor.H> #include <p10_scom_pec.H> //@TODO: RTC 214852 - Use SCOM accessors, remove workaround code //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ const uint64_t IOPFIRACT0 = 0x0000000000000000ULL; const uint64_t IOPFIRACT1 = 0xABA0000000000000ULL; const uint64_t IOPFIRMASK = 0x0000000000000000ULL; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /// NOTE: doxygen in header fapi2::ReturnCode p10_load_iop_xram( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, void* const i_hw_image) { FAPI_DBG("Start"); fapi2::ReturnCode l_rc; P9XipSection l_section; l_section.iv_offset = 0; l_section.iv_size = 0; uint8_t* l_xramImgPtr = NULL; uint8_t* l_xramFwDataPtr = NULL; uint32_t l_xramFwSize = 0; // Get PEC multicast target auto l_target_mcast = i_target.getMulticast<fapi2::TARGET_TYPE_PEC>(fapi2::MCGROUP_GOOD_PCI); std::vector<fapi2::Target<fapi2::TARGET_TYPE_PEC>> l_pecChiplets = l_target_mcast.getChildren<fapi2::TARGET_TYPE_PEC>(); fapi2::ATTR_IS_SIMULATION_Type l_attr_is_simulation = 0; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>(), l_attr_is_simulation)); // Skip load if there are no functional PEC targets on this chip if (l_pecChiplets.size() == 0) { FAPI_INF("p10_load_iop_xram: Skipping load, no functional PEC on chip."); goto fapi_try_exit; } // Validate HW image FAPI_ASSERT(i_hw_image != NULL , fapi2::P10_LOAD_IOP_XRAM_HW_IMG_ERROR() .set_TARGET(i_target) .set_HW_IMAGE(i_hw_image), "p10_load_iop_xram: Invalid HW XIP image"); // Reference the XRAM image (.xram) section in the HW image // This is an XIP image nested in the HW image itself FAPI_INF("p10_load_iop_xram: Calling p9_xip_get_section (HW image)"); FAPI_TRY(p9_xip_get_section(i_hw_image, P9_XIP_SECTION_HW_IOPXRAM, &l_section), "p10_load_iop_xram: Error from p9_xip_get_section (HW image)."); l_xramImgPtr = l_section.iv_offset + (uint8_t*)(i_hw_image); // From the XRAM image, obtain pointers to IOP FW data FAPI_DBG("p10_load_iop_xram: Calling p9_xip_get_section (XRAM image, FW section)"); FAPI_TRY(p9_xip_get_section(l_xramImgPtr, P9_XIP_SECTION_IOPXRAM_IOP_FW, &l_section), "p10_load_iop_xram: Error from p9_xip_get_section (XRAM image, FW section)"); l_xramFwDataPtr = l_section.iv_offset + (uint8_t*)(l_xramImgPtr); l_xramFwSize = l_section.iv_size; FAPI_INF("p10_load_iop_xram: i_hw_image %p, l_xramImgPtr %p, l_xramFwDataPtr %p, l_xramFwSize %u", i_hw_image, l_xramImgPtr, l_xramFwDataPtr, l_xramFwSize); // Validate XRAM image FAPI_ASSERT((l_xramFwDataPtr != NULL) && (l_xramFwSize != 0) && (l_xramFwSize <= MAX_XRAM_IMAGE_SIZE), fapi2::P10_LOAD_IOP_XRAM_IMG_ERROR() .set_TARGET(i_target) .set_HW_IMAGE(i_hw_image) .set_XRAM_IMAGE_PTR(l_xramImgPtr) .set_XRAM_FW_DATA_PTR(l_xramFwDataPtr) .set_XRAM_FW_SIZE(l_xramFwSize) .set_XIP_SECTION(l_section), "p10_load_iop_xram: Invalid XRAM image: l_xramFwDataPtr %p, Size %u", l_xramFwDataPtr, l_xramFwSize); // Write img data to XRAM using PEC multicast FAPI_INF("p10_load_iop_xram: Write XRAM FW data: Ptr %p, size %u.", l_xramFwDataPtr, l_xramFwSize); // Reset PHYs on both PECs FAPI_TRY(doPhyReset(l_target_mcast), "p10_load_iop_xram: doPhyReset returns an error."); // configure IOP FIR error reporting FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRACT0, IOPFIRACT0)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRACT0, IOPFIRACT0)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRACT1, IOPFIRACT1)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRACT1, IOPFIRACT1)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP0_IOPFIRMASK_RW, IOPFIRMASK)); FAPI_TRY(fapi2::putScom(l_target_mcast, scomt::pec::TOP1_IOPFIRMASK_RW, IOPFIRMASK)); // Write CReg overrides through the CR Parallel Interface // This is called here because phy reset has to be deasserted for CReg access // Do this after PHY Reset and preferablly before ext_ld_done. FAPI_TRY(p10_load_iop_override(i_target)); // Use multicast PEC target to load PCIE FW to all PECs // Loop to load to all IOP XRAM (iop_top0/1, phy0/1) for (uint8_t l_top = 0; l_top < NUM_OF_IO_TOPS; l_top++) { for (uint8_t l_phy = 0; l_phy < NUM_OF_PHYS; l_phy++) { FAPI_INF("p10_load_iop_xram: Attemp to write PCIE img to XRAM: iop_top %d, phy %d.", l_top, l_phy); // Encode Top and Phy into mode uint8_t l_mode = 0; if (l_top) { l_mode = MODE_PCIE_TOP_BIT_MASK; } if (l_phy) { l_mode |= MODE_PCIE_PHY_BIT_MASK; } // Load IOP XRAM using putsram chip-op FAPI_CALL_SUBROUTINE(fapi2::current_err, p10_putsram, i_target, PCI0_PERV_CHIPLET_ID, // Set to PCI0 as default for multicast. // p10_putsram will find valid multicast target. true, // Do multicast load l_mode, // Access mode, not used here static_cast<uint64_t>(0), // Load at offset 0 l_xramFwSize, l_xramFwDataPtr); FAPI_TRY(fapi2::current_err, "p10_load_iop_xram: p10_write_xram returns an error: iop_top %d, phy %d."); FAPI_INF("p10_load_iop_xram: Successfully wrote PCIE img to XRAM: iop_top %d, phy %d.", l_top, l_phy); } // Done loading this iop_top, enable XRAM scrubber // Note: do this here because Scrubber bit applies to both PHYs of an io_top FAPI_TRY(enableXramScrubber(l_target_mcast, static_cast<xramIopTopNum_t>(l_top)), "p10_load_iop_xram: enableXramScrubber returns an error."); } if (!l_attr_is_simulation) { FAPI_TRY(p10_load_rtrim_override(i_target)); } FAPI_TRY(p10_verify_iop_fw(i_target)); fapi_try_exit: FAPI_DBG("End"); return fapi2::current_err; } <|endoftext|>
<commit_before>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return static_cast<ics::Angle::rawType>((rx[4] << 7) | rx[5]); } static inline ics::Core::value getCmd(const int head, const ics::ID& id) { return head | id.get(); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = getCmd(0x80, id); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()}; Core::Container rx(5); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()}; Core::Container rx(6); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { const Core::Container tx {getCmd(0xA0, id), 0}; Core::Container rx(68); core->communicate(tx, rx); // throw std::runtime_error EepRom::Container romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = getCmd(0xC0, id); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<uint8_t>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <commit_msg>Update type specify with some alias<commit_after>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return (rx[4] << 7) | rx[5]; } static inline ics::Core::value getCmd(const int head, const ics::ID& id) { return head | id.get(); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = getCmd(0x80, id); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()}; Core::Container rx(5); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()}; Core::Container rx(6); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { const Core::Container tx {getCmd(0xA0, id), 0}; Core::Container rx(68); core->communicate(tx, rx); // throw std::runtime_error EepRom::Container romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = getCmd(0xC0, id); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<ID::type>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <|endoftext|>
<commit_before>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return (rx[4] << 7) | rx[5]; } static inline ics::Core::value getCmd(const int head, const ics::ID& id) { return head | id.get(); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const uint16_t send {angle.getRaw()}; tx[0] = getCmd(0x80, id); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()}; Core::Container rx(5); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()}; Core::Container rx(6); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { const Core::Container tx {getCmd(0xA0, id), 0}; Core::Container rx(68); core->communicate(tx, rx); // throw std::runtime_error EepRom::Container romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = getCmd(0xC0, id); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<ID::type>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <commit_msg>Update variable with alias type<commit_after>#include"ics3/ics3.hpp" #include"core.hpp" #include"ics3/eeprom.hpp" #include"ics3/parameter.hpp" #include"ics3/id.hpp" static inline ics::Angle::rawType getReceiveAngle(const ics::Core::Container& rx) noexcept { return (rx[4] << 7) | rx[5]; } static inline ics::Core::value getCmd(const int head, const ics::ID& id) { return head | id.get(); } ics::ICS3::ICS3(const std::string& path, const Baudrate& baudrate) : core {Core::getCore(path, baudrate.getSpeed())} {} ics::Angle ics::ICS3::move(const ID& id, Angle angle) { static Core::Container tx(3), rx(6); // cache for runtime speed const auto send = angle.getRaw(); tx[0] = getCmd(0x80, id); tx[1] = 0x7F & (send >> 7); tx[2] = 0x7F & send; core->communicate(tx, rx); // throw std::runtime_error angle.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return angle; } ics::Angle ics::ICS3::free(const ID& id, Angle unit) { static Core::Container tx(3), rx(6); // cache for runtime speed tx[0] = getCmd(0x80, id); // tx[1] == tx[2] == 0 core->communicate(tx, rx); // throw std::runtime_error unit.rawData = getReceiveAngle(rx); // avoid invalid check. need friend return unit; } ics::Parameter ics::ICS3::get(const ID& id, const Parameter& type) { const Core::Container tx {getCmd(0xA0, id), type.getSubcommand()}; Core::Container rx(5); core->communicate(tx, rx); // throw std::runtime_error return Parameter::newParameter(type, rx[4]); } void ics::ICS3::set(const ID& id, const Parameter& param) { const Core::Container tx {getCmd(0xC0, id), param.getSubcommand(), param.get()}; Core::Container rx(6); core->communicate(tx, rx); // throw std::runtime_error } ics::EepRom ics::ICS3::getRom(const ID& id) { const Core::Container tx {getCmd(0xA0, id), 0}; Core::Container rx(68); core->communicate(tx, rx); // throw std::runtime_error EepRom::Container romData; std::copy(rx.cbegin() + 4, rx.cend(), romData.begin()); return EepRom {romData}; // need friend } void ics::ICS3::setRom(const ID& id, const EepRom& rom) { Core::Container tx(66), rx(68); tx[0] = getCmd(0xC0, id); // tx[1] == 0 rom.write(tx.begin() + 2); core->communicate(tx, rx); // throw std::runtime_error } ics::ID ics::ICS3::getID() { constexpr Core::IDContainerTx tx {0xFF, 0x00, 0x00, 0x00}; Core::IDContainerRx rx; core->communicateID(tx, rx); return ID {static_cast<ID::type>(0x1F & rx[4])}; } void ics::ICS3::setID(const ID& id) { const Core::IDContainerTx tx {getCmd(0xE0, id), 1, 1, 1}; Core::IDContainerRx rx; core->communicateID(tx, rx); } <|endoftext|>
<commit_before> #include "mitkManualSegmentationToSurfaceFilter.h" #include <itksys/SystemTools.hxx> #include "mitkDataTreeNodeFactory.h" #include <mitkSurfaceVtkWriter.h> #include <vtkSTLWriter.h> #include <fstream> int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[]) { if(argc==0) { std::cout<<"no file specified [FAILED]"<<std::endl; return EXIT_FAILURE; } std::string path = argv[1]; itksys::SystemTools::ConvertToUnixSlashes(path); //std::string fileIn = path + "/Pic3DLeber.pic"; //std::string fileOut = path + "/Pic3DLeberSurfaceResult.stl"; std::string fileIn = path + "/Pic3D.pic"; std::string fileOut = path + "/Pic3DSurfaceResult.stl"; fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str()); fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str()); std::cout<<"Eingabe Datei: "<<fileIn<<std::endl; std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl; mitk::Image::Pointer image = NULL; mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New(); try { std::cout << "Loading file: "; factory->SetFileName( fileIn.c_str() ); factory->Update(); if(factory->GetNumberOfOutputs()<1) { std::cout<<"file could not be loaded [FAILED]"<<std::endl; return EXIT_FAILURE; } mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch ( itk::ExceptionObject & ex ) { std::cout << "Exception: " << ex << "[FAILED]" << std::endl; return EXIT_FAILURE; } mitk::ManualSegmentationToSurfaceFilter::Pointer filter; std::cout << "Testing mitk::ManualSegmentationToSurfaceFilter::New(): "; filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } //Wirter instance mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New(); if (filter.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { writer->GlobalWarningDisplayOn(); writer->SetFileName(fileOut.c_str()); writer->GetVtkWriter()->SetFileTypeToBinary(); } std::cout << "Only create surface: "; filter->SetInput(image); writer->SetInput(filter->GetOutput()); writer->Write(); if( writer->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED]"<<std::endl; writer->Delete(); return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Create surface with image preprocessing and smoothing: "; filter->UseMedianFilter3DOn(); filter->SetInterpolationOn(); filter->UseStandardDeviationOn(); //configure ImageToSurfaceFilter filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube filter->SetDecimateOn(); filter->SetSmoothOn(); //filter->Update(); writer->SetInput( filter->GetOutput() ); if( writer->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; writer->Write(); } std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>ENH: work around<commit_after> #include "mitkManualSegmentationToSurfaceFilter.h" #include <itksys/SystemTools.hxx> #include "mitkDataTreeNodeFactory.h" #include <mitkSurfaceVtkWriter.h> #include <vtkSTLWriter.h> #include <fstream> /** * Test class for ManualSegmentationToSurfaceFilter and ImageToSurface * 1. Read an image * 2. Create a surface * 3. Create a Surface with all image processing facillities */ int mitkManualSegmentationToSurfaceFilterTest(int argc, char* argv[]) { if(argc==0) { std::cout<<"no file specified [FAILED]"<<std::endl; return EXIT_FAILURE; } std::string path = argv[1]; itksys::SystemTools::ConvertToUnixSlashes(path); std::string fileIn = path + "/BallBinary30x30x30.pic.gz"; std::string fileOut = path + "/BallBinary30x30x30.stl"; fileIn = itksys::SystemTools::ConvertToOutputPath(fileIn.c_str()); fileOut = itksys::SystemTools::ConvertToOutputPath(fileOut.c_str()); std::cout<<"Eingabe Datei: "<<fileIn<<std::endl; std::cout<<"Ausgabe Datei: "<<fileOut<<std::endl; mitk::Image::Pointer image = NULL; mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New(); try { std::cout << "Loading file: "; factory->SetFileName( fileIn.c_str() ); factory->Update(); if(factory->GetNumberOfOutputs()<1) { std::cout<<"file could not be loaded [FAILED]"<<std::endl; return EXIT_FAILURE; } mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 ); image = dynamic_cast<mitk::Image*>(node->GetData()); if(image.IsNull()) { std::cout<<"file not an image - test will not be applied [PASSED]"<<std::endl; std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } } catch ( itk::ExceptionObject & ex ) { std::cout << "Exception: " << ex << "[FAILED]" << std::endl; return EXIT_FAILURE; } mitk::ManualSegmentationToSurfaceFilter::Pointer filter; std::cout << "Instantiat mitk::ManualSegmentationToSurfaceFilter - implicit: mitk::ImageToSurface: "; filter = mitk::ManualSegmentationToSurfaceFilter::New(); if (filter.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } //Wirter instance mitk::SurfaceVtkWriter<vtkSTLWriter>::Pointer writer = mitk::SurfaceVtkWriter<vtkSTLWriter>::New(); if (filter.IsNull()) { std::cout<<"Instantiat SurfaceVtkWirter: [FAILED]"<<std::endl; return EXIT_FAILURE; } else { writer->GlobalWarningDisplayOn(); writer->SetFileName(fileOut.c_str()); writer->GetVtkWriter()->SetFileTypeToBinary(); } std::cout << "Create surface with default settings: "; filter->SetInput(image); writer->SetInput(filter->GetOutput()); writer->Write(); if( writer->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED]"<<std::endl; writer->Delete(); return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Create surface all optimised settings: "; //configure ImageToSurfaceFilter filter->MedianFilter3DOn(); filter->SetStandardDeviation(1.5); filter->SetInterpolationOn(); filter->UseStandardDeviationOn(); filter->SetThreshold( 1 ); //if( Gauss ) --> TH manipulated for vtkMarchingCube filter->DecimateOn(); filter->SetTargetReduction(0.05f); filter->SmoothOn(); //filter->Update(); writer->SetInput( filter->GetOutput() ); if( writer->GetNumberOfInputs() < 1 ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; writer->Write(); } std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local Includes #include "libmesh/elem.h" #include "libmesh/location_maps.h" #include "libmesh/mesh_base.h" #include "libmesh/node.h" #include "libmesh/parallel.h" // C++ Includes #include <limits> #include <utility> namespace { using libMesh::Real; // 10 bits per coordinate, to work with 32+ bit machines const unsigned int chunkmax = 1024; const Real chunkfloat = 1024.0; } namespace libMesh { template <typename T> void LocationMap<T>::init(MeshBase & mesh) { // This function must be run on all processors at once // for non-serial meshes if (!mesh.is_serial()) libmesh_parallel_only(mesh.comm()); LOG_SCOPE("init()", "LocationMap"); // Clear the old map _map.clear(); // Cache a bounding box _lower_bound.clear(); _lower_bound.resize(LIBMESH_DIM, std::numeric_limits<Real>::max()); _upper_bound.clear(); _upper_bound.resize(LIBMESH_DIM, -std::numeric_limits<Real>::max()); for (auto & node : mesh.nodes_range()) for (unsigned int i=0; i != LIBMESH_DIM; ++i) { // Expand the bounding box if necessary _lower_bound[i] = std::min(_lower_bound[i], (*node)(i)); _upper_bound[i] = std::max(_upper_bound[i], (*node)(i)); } // On a parallel mesh we might not yet have a full bounding box if (!mesh.is_serial()) { mesh.comm().min(_lower_bound); mesh.comm().max(_upper_bound); } this->fill(mesh); } template <typename T> void LocationMap<T>::insert(T & t) { this->_map.insert(std::make_pair(this->key(this->point_of(t)), &t)); } template <> Point LocationMap<Node>::point_of(const Node & node) const { return node; } template <> Point LocationMap<Elem>::point_of(const Elem & elem) const { return elem.centroid(); } template <typename T> T * LocationMap<T>::find(const Point & p, const Real tol) { LOG_SCOPE("find()", "LocationMap"); // Look for a likely key in the multimap unsigned int pointkey = this->key(p); // Look for the exact key first std::pair<typename map_type::iterator, typename map_type::iterator> pos = _map.equal_range(pointkey); while (pos.first != pos.second) if (p.absolute_fuzzy_equals(this->point_of(*(pos.first->second)), tol)) return pos.first->second; else ++pos.first; // Look for neighboring bins' keys next for (int xoffset = -1; xoffset != 2; ++xoffset) { for (int yoffset = -1; yoffset != 2; ++yoffset) { for (int zoffset = -1; zoffset != 2; ++zoffset) { std::pair<typename map_type::iterator, typename map_type::iterator> key_pos = _map.equal_range(pointkey + xoffset*chunkmax*chunkmax + yoffset*chunkmax + zoffset); while (key_pos.first != key_pos.second) if (p.absolute_fuzzy_equals(this->point_of(*(key_pos.first->second)), tol)) return key_pos.first->second; else ++key_pos.first; } } } return libmesh_nullptr; } template <typename T> unsigned int LocationMap<T>::key(const Point & p) { Real xscaled = 0., yscaled = 0., zscaled = 0.; Real deltax = _upper_bound[0] - _lower_bound[0]; if (std::abs(deltax) > TOLERANCE) xscaled = (p(0) - _lower_bound[0])/deltax; // Only check y-coords if libmesh is compiled with LIBMESH_DIM>1 #if LIBMESH_DIM > 1 Real deltay = _upper_bound[1] - _lower_bound[1]; if (std::abs(deltay) > TOLERANCE) yscaled = (p(1) - _lower_bound[1])/deltay; #endif // Only check z-coords if libmesh is compiled with LIBMESH_DIM>2 #if LIBMESH_DIM > 2 Real deltaz = _upper_bound[2] - _lower_bound[2]; if (std::abs(deltaz) > TOLERANCE) zscaled = (p(2) - _lower_bound[2])/deltaz; #endif unsigned int n0 = static_cast<unsigned int> (chunkfloat * xscaled), n1 = static_cast<unsigned int> (chunkfloat * yscaled), n2 = static_cast<unsigned int> (chunkfloat * zscaled); return chunkmax*chunkmax*n0 + chunkmax*n1 + n2; } template <> void LocationMap<Node>::fill(MeshBase & mesh) { // Populate the nodes map MeshBase::node_iterator it = mesh.nodes_begin(), end = mesh.nodes_end(); for (; it != end; ++it) this->insert(**it); } template <> void LocationMap<Elem>::fill(MeshBase & mesh) { // Populate the elem map MeshBase::element_iterator it = mesh.active_elements_begin(), end = mesh.active_elements_end(); for (; it != end; ++it) this->insert(**it); } template class LocationMap<Elem>; template class LocationMap<Node>; } // namespace libMesh <commit_msg>Use rangefor in LocationMap<Node>::fill().<commit_after>// The libMesh Finite Element Library. // Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // Local Includes #include "libmesh/elem.h" #include "libmesh/location_maps.h" #include "libmesh/mesh_base.h" #include "libmesh/node.h" #include "libmesh/parallel.h" // C++ Includes #include <limits> #include <utility> namespace { using libMesh::Real; // 10 bits per coordinate, to work with 32+ bit machines const unsigned int chunkmax = 1024; const Real chunkfloat = 1024.0; } namespace libMesh { template <typename T> void LocationMap<T>::init(MeshBase & mesh) { // This function must be run on all processors at once // for non-serial meshes if (!mesh.is_serial()) libmesh_parallel_only(mesh.comm()); LOG_SCOPE("init()", "LocationMap"); // Clear the old map _map.clear(); // Cache a bounding box _lower_bound.clear(); _lower_bound.resize(LIBMESH_DIM, std::numeric_limits<Real>::max()); _upper_bound.clear(); _upper_bound.resize(LIBMESH_DIM, -std::numeric_limits<Real>::max()); for (auto & node : mesh.nodes_range()) for (unsigned int i=0; i != LIBMESH_DIM; ++i) { // Expand the bounding box if necessary _lower_bound[i] = std::min(_lower_bound[i], (*node)(i)); _upper_bound[i] = std::max(_upper_bound[i], (*node)(i)); } // On a parallel mesh we might not yet have a full bounding box if (!mesh.is_serial()) { mesh.comm().min(_lower_bound); mesh.comm().max(_upper_bound); } this->fill(mesh); } template <typename T> void LocationMap<T>::insert(T & t) { this->_map.insert(std::make_pair(this->key(this->point_of(t)), &t)); } template <> Point LocationMap<Node>::point_of(const Node & node) const { return node; } template <> Point LocationMap<Elem>::point_of(const Elem & elem) const { return elem.centroid(); } template <typename T> T * LocationMap<T>::find(const Point & p, const Real tol) { LOG_SCOPE("find()", "LocationMap"); // Look for a likely key in the multimap unsigned int pointkey = this->key(p); // Look for the exact key first std::pair<typename map_type::iterator, typename map_type::iterator> pos = _map.equal_range(pointkey); while (pos.first != pos.second) if (p.absolute_fuzzy_equals(this->point_of(*(pos.first->second)), tol)) return pos.first->second; else ++pos.first; // Look for neighboring bins' keys next for (int xoffset = -1; xoffset != 2; ++xoffset) { for (int yoffset = -1; yoffset != 2; ++yoffset) { for (int zoffset = -1; zoffset != 2; ++zoffset) { std::pair<typename map_type::iterator, typename map_type::iterator> key_pos = _map.equal_range(pointkey + xoffset*chunkmax*chunkmax + yoffset*chunkmax + zoffset); while (key_pos.first != key_pos.second) if (p.absolute_fuzzy_equals(this->point_of(*(key_pos.first->second)), tol)) return key_pos.first->second; else ++key_pos.first; } } } return libmesh_nullptr; } template <typename T> unsigned int LocationMap<T>::key(const Point & p) { Real xscaled = 0., yscaled = 0., zscaled = 0.; Real deltax = _upper_bound[0] - _lower_bound[0]; if (std::abs(deltax) > TOLERANCE) xscaled = (p(0) - _lower_bound[0])/deltax; // Only check y-coords if libmesh is compiled with LIBMESH_DIM>1 #if LIBMESH_DIM > 1 Real deltay = _upper_bound[1] - _lower_bound[1]; if (std::abs(deltay) > TOLERANCE) yscaled = (p(1) - _lower_bound[1])/deltay; #endif // Only check z-coords if libmesh is compiled with LIBMESH_DIM>2 #if LIBMESH_DIM > 2 Real deltaz = _upper_bound[2] - _lower_bound[2]; if (std::abs(deltaz) > TOLERANCE) zscaled = (p(2) - _lower_bound[2])/deltaz; #endif unsigned int n0 = static_cast<unsigned int> (chunkfloat * xscaled), n1 = static_cast<unsigned int> (chunkfloat * yscaled), n2 = static_cast<unsigned int> (chunkfloat * zscaled); return chunkmax*chunkmax*n0 + chunkmax*n1 + n2; } template <> void LocationMap<Node>::fill(MeshBase & mesh) { // Populate the nodes map for (auto & node : mesh.nodes_range()) this->insert(*node); } template <> void LocationMap<Elem>::fill(MeshBase & mesh) { // Populate the elem map MeshBase::element_iterator it = mesh.active_elements_begin(), end = mesh.active_elements_end(); for (; it != end; ++it) this->insert(**it); } template class LocationMap<Elem>; template class LocationMap<Node>; } // namespace libMesh <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/pathspec.hpp" #include "rdb_protocol/term.hpp" namespace ql { pathspec_t::pathspec_t(const pathspec_t &other) { init_from(other); } pathspec_t& pathspec_t::operator=(const pathspec_t &other) { init_from(other); return *this; } pathspec_t::pathspec_t(const std::string &_str, term_t *_creator) : type(STR), str(new std::string(_str)), creator(_creator) { } pathspec_t::pathspec_t(const std::map<std::string, pathspec_t> &_map, term_t *_creator) : type(MAP), map(new std::map<std::string, pathspec_t>(_map)), creator(_creator) { } pathspec_t::pathspec_t(counted_t<const datum_t> datum, term_t *_creator) : creator(_creator) { if (datum->get_type() == datum_t::R_STR) { type = STR; str = new std::string(datum->as_str()); } else if (datum->get_type() == datum_t::R_ARRAY) { type = VEC; vec = new std::vector<pathspec_t>; for (size_t i = 0; i < datum->size(); ++i) { vec->push_back(pathspec_t(datum->get(i), creator)); } } else if (datum->get_type() == datum_t::R_OBJECT) { scoped_ptr_t<std::vector<pathspec_t> > local_vec(new std::vector<pathspec_t>); scoped_ptr_t<std::map<std::string, pathspec_t> > local_map(new std::map<std::string, pathspec_t>); for (auto it = datum->as_object().begin(); it != datum->as_object().end(); ++it) { if (it->second->get_type() == datum_t::R_BOOL && it->second->as_bool() == true) { local_vec->push_back(pathspec_t(it->first, creator)); } else { local_map->insert(std::make_pair(it->first, pathspec_t(it->second, creator))); } } if (local_vec->empty()) { type = MAP; map = local_map.release(); } else { type = VEC; vec = local_vec.release(); if (!local_map->empty()) { vec->push_back(pathspec_t(*local_map, creator)); } } } else { rfail_target(creator, base_exc_t::GENERIC, "Invalid path argument of `%s` to %s.", datum->print().c_str(), creator->name()); } if (type == VEC && vec->size() == 1) { *this = (*vec)[0]; } } pathspec_t::~pathspec_t() { switch (type) { case STR: delete str; break; case VEC: delete vec; break; case MAP: delete map; break; default: unreachable(); } } void pathspec_t::init_from(const pathspec_t &other) { type = other.type; switch (type) { case STR: str = new std::string(*other.str); break; case VEC: vec = new std::vector<pathspec_t>(*other.vec); break; case MAP: map = new std::map<std::string, pathspec_t>(*other.map); break; default: unreachable(); } creator = other.creator; } /* Limit the datum to only the paths specified by the pathspec. */ counted_t<const datum_t> project(counted_t<const datum_t> datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (datum->get_type() == datum_t::R_ARRAY && recurse == RECURSE) { datum_ptr_t res(datum_t::R_ARRAY); for (size_t i = 0; i < datum->size(); ++i) { res.add(project(datum->get(i), pathspec, DONT_RECURSE)); } return res.to_counted(); } else { datum_ptr_t res(datum_t::R_OBJECT); if (const std::string *str = pathspec.as_str()) { if (counted_t<const datum_t> val = datum->get(*str, NOTHROW)) { // This bool indicates if things were clobbered. We're fine // with things being clobbered so we ignore it. UNUSED bool b = res.add(*str, val, CLOBBER); } } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { counted_t<const datum_t> sub_result = project(datum, *it, recurse); for (auto jt = sub_result->as_object().begin(); jt != sub_result->as_object().end(); ++jt) { UNUSED bool b = res.add(jt->first, jt->second, CLOBBER); } } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = datum->get(it->first, NOTHROW)) { try { counted_t<const datum_t> sub_result = project(val, it->second, RECURSE); // We know we're clobbering, that's the point. UNUSED bool b = res.add(it->first, sub_result, CLOBBER); } catch (const datum_exc_t &e) { // do nothing } } } } else { unreachable(); } return res.to_counted(); } } void unproject_helper(datum_ptr_t *datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (const std::string *str = pathspec.as_str()) { UNUSED bool key_was_deleted = datum->delete_field(*str); } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { unproject_helper(datum, *it, recurse); } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = (*datum)->get(it->first, NOTHROW)) { try { counted_t<const datum_t> sub_result = unproject(val, it->second, RECURSE); /* We know we're clobbering, that's the point. */ UNUSED bool clobbered = datum->add(it->first, sub_result, CLOBBER); } catch (const datum_exc_t &e) { // do nothing } } } } else { unreachable(); } } /* Limit the datum to only the paths not specified by the pathspec. */ counted_t<const datum_t> unproject(counted_t<const datum_t> datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (datum->get_type() == datum_t::R_ARRAY && recurse == RECURSE) { datum_ptr_t res(datum_t::R_ARRAY); for (size_t i = 0; i < datum->size(); ++i) { res.add(unproject(datum->get(i), pathspec, DONT_RECURSE)); } return res.to_counted(); } else { datum_ptr_t res(datum->as_object()); unproject_helper(&res, pathspec, recurse); return res.to_counted(); } } /* Return whether or not ALL of the paths in the pathspec exist in the datum. */ bool contains(counted_t<const datum_t> datum, const pathspec_t &pathspec) { try { bool res = true; if (const std::string *str = pathspec.as_str()) { if (!(res &= (datum->get(*str, NOTHROW).has() && datum->get(*str)->get_type() != datum_t::R_NULL))) { return res; } } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { if (!(res &= contains(datum, *it))) { return res; } } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = datum->get(it->first, NOTHROW)) { if (!(res &= contains(val, it->second))) { return res; } } else { return false; } } } else { unreachable(); } return res; } catch (const datum_exc_t &e) { return false; } } } // namespace ql <commit_msg>Removed the part of the "Invalid path argument" error message which refers to the creating term. Because many terms internally create sub-terms, that part of the message was confusing to the user.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "rdb_protocol/pathspec.hpp" #include "rdb_protocol/term.hpp" namespace ql { pathspec_t::pathspec_t(const pathspec_t &other) { init_from(other); } pathspec_t& pathspec_t::operator=(const pathspec_t &other) { init_from(other); return *this; } pathspec_t::pathspec_t(const std::string &_str, term_t *_creator) : type(STR), str(new std::string(_str)), creator(_creator) { } pathspec_t::pathspec_t(const std::map<std::string, pathspec_t> &_map, term_t *_creator) : type(MAP), map(new std::map<std::string, pathspec_t>(_map)), creator(_creator) { } pathspec_t::pathspec_t(counted_t<const datum_t> datum, term_t *_creator) : creator(_creator) { if (datum->get_type() == datum_t::R_STR) { type = STR; str = new std::string(datum->as_str()); } else if (datum->get_type() == datum_t::R_ARRAY) { type = VEC; vec = new std::vector<pathspec_t>; for (size_t i = 0; i < datum->size(); ++i) { vec->push_back(pathspec_t(datum->get(i), creator)); } } else if (datum->get_type() == datum_t::R_OBJECT) { scoped_ptr_t<std::vector<pathspec_t> > local_vec(new std::vector<pathspec_t>); scoped_ptr_t<std::map<std::string, pathspec_t> > local_map(new std::map<std::string, pathspec_t>); for (auto it = datum->as_object().begin(); it != datum->as_object().end(); ++it) { if (it->second->get_type() == datum_t::R_BOOL && it->second->as_bool() == true) { local_vec->push_back(pathspec_t(it->first, creator)); } else { local_map->insert(std::make_pair(it->first, pathspec_t(it->second, creator))); } } if (local_vec->empty()) { type = MAP; map = local_map.release(); } else { type = VEC; vec = local_vec.release(); if (!local_map->empty()) { vec->push_back(pathspec_t(*local_map, creator)); } } } else { rfail_target(creator, base_exc_t::GENERIC, "Invalid path argument `%s`.", datum->print().c_str()); } if (type == VEC && vec->size() == 1) { *this = (*vec)[0]; } } pathspec_t::~pathspec_t() { switch (type) { case STR: delete str; break; case VEC: delete vec; break; case MAP: delete map; break; default: unreachable(); } } void pathspec_t::init_from(const pathspec_t &other) { type = other.type; switch (type) { case STR: str = new std::string(*other.str); break; case VEC: vec = new std::vector<pathspec_t>(*other.vec); break; case MAP: map = new std::map<std::string, pathspec_t>(*other.map); break; default: unreachable(); } creator = other.creator; } /* Limit the datum to only the paths specified by the pathspec. */ counted_t<const datum_t> project(counted_t<const datum_t> datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (datum->get_type() == datum_t::R_ARRAY && recurse == RECURSE) { datum_ptr_t res(datum_t::R_ARRAY); for (size_t i = 0; i < datum->size(); ++i) { res.add(project(datum->get(i), pathspec, DONT_RECURSE)); } return res.to_counted(); } else { datum_ptr_t res(datum_t::R_OBJECT); if (const std::string *str = pathspec.as_str()) { if (counted_t<const datum_t> val = datum->get(*str, NOTHROW)) { // This bool indicates if things were clobbered. We're fine // with things being clobbered so we ignore it. UNUSED bool b = res.add(*str, val, CLOBBER); } } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { counted_t<const datum_t> sub_result = project(datum, *it, recurse); for (auto jt = sub_result->as_object().begin(); jt != sub_result->as_object().end(); ++jt) { UNUSED bool b = res.add(jt->first, jt->second, CLOBBER); } } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = datum->get(it->first, NOTHROW)) { try { counted_t<const datum_t> sub_result = project(val, it->second, RECURSE); // We know we're clobbering, that's the point. UNUSED bool b = res.add(it->first, sub_result, CLOBBER); } catch (const datum_exc_t &e) { // do nothing } } } } else { unreachable(); } return res.to_counted(); } } void unproject_helper(datum_ptr_t *datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (const std::string *str = pathspec.as_str()) { UNUSED bool key_was_deleted = datum->delete_field(*str); } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { unproject_helper(datum, *it, recurse); } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = (*datum)->get(it->first, NOTHROW)) { try { counted_t<const datum_t> sub_result = unproject(val, it->second, RECURSE); /* We know we're clobbering, that's the point. */ UNUSED bool clobbered = datum->add(it->first, sub_result, CLOBBER); } catch (const datum_exc_t &e) { // do nothing } } } } else { unreachable(); } } /* Limit the datum to only the paths not specified by the pathspec. */ counted_t<const datum_t> unproject(counted_t<const datum_t> datum, const pathspec_t &pathspec, recurse_flag_t recurse) { if (datum->get_type() == datum_t::R_ARRAY && recurse == RECURSE) { datum_ptr_t res(datum_t::R_ARRAY); for (size_t i = 0; i < datum->size(); ++i) { res.add(unproject(datum->get(i), pathspec, DONT_RECURSE)); } return res.to_counted(); } else { datum_ptr_t res(datum->as_object()); unproject_helper(&res, pathspec, recurse); return res.to_counted(); } } /* Return whether or not ALL of the paths in the pathspec exist in the datum. */ bool contains(counted_t<const datum_t> datum, const pathspec_t &pathspec) { try { bool res = true; if (const std::string *str = pathspec.as_str()) { if (!(res &= (datum->get(*str, NOTHROW).has() && datum->get(*str)->get_type() != datum_t::R_NULL))) { return res; } } else if (const std::vector<pathspec_t> *vec = pathspec.as_vec()) { for (auto it = vec->begin(); it != vec->end(); ++it) { if (!(res &= contains(datum, *it))) { return res; } } } else if (const std::map<std::string, pathspec_t> *map = pathspec.as_map()) { for (auto it = map->begin(); it != map->end(); ++it) { if (counted_t<const datum_t> val = datum->get(it->first, NOTHROW)) { if (!(res &= contains(val, it->second))) { return res; } } else { return false; } } } else { unreachable(); } return res; } catch (const datum_exc_t &e) { return false; } } } // namespace ql <|endoftext|>
<commit_before>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <windows.h> #include <objbase.h> #include <Wininet.h> #include <vector> #include <iostream> #include <fstream> #include "Progress.h" #include "Resource.h" #define DISTRIBUTION_UUID L"7F7FA377-E695-4280-9F1F-96126F3D2C2A" #define RUNTIME_UUID L"A2AC5CB5-8C52-456C-9525-601A5B0725DA" #define MODULE_UUID L"1ACE5D3A-2B52-43FB-A136-007BD166CFD0" std::wstring ParseQueryParam(std::wstring uri, std::wstring name) { std::wstring key = name; key+=L"="; size_t pos = uri.find(key); if (pos!=std::wstring::npos) { std::wstring p = uri.substr(pos + key.length()); pos = p.find(L"&"); if (pos!=std::wstring::npos) { p = p.substr(0,pos); } // decode WCHAR szOut[INTERNET_MAX_URL_LENGTH]; DWORD cchDecodedUrl = INTERNET_MAX_URL_LENGTH; CoInternetParseUrl(p.c_str(), PARSE_UNESCAPE, 0, szOut, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); p.assign(szOut); return p; } return L""; } bool DownloadURL(Progress *p, HINTERNET hINet, std::wstring url, std::wstring outFilename) { WCHAR szDecodedUrl[INTERNET_MAX_URL_LENGTH]; DWORD cchDecodedUrl = INTERNET_MAX_URL_LENGTH; WCHAR szDomainName[INTERNET_MAX_URL_LENGTH]; bool failed = false; // parse the URL HRESULT hr = CoInternetParseUrl(url.c_str(), PARSE_DECODE, URL_ENCODING_NONE, szDecodedUrl, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); if (hr != S_OK) { //TODO failed = true; } // figure out the domain/hostname hr = CoInternetParseUrl(szDecodedUrl, PARSE_DOMAIN, 0, szDomainName, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); if (hr != S_OK) { //TODO failed = true; } // TODO - how to cancel download if user presses the Cancel button // start the HTTP fetch HINTERNET hConnection = InternetConnectW( hINet, szDomainName, 80, L" ", L" ", INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { failed = true; } HINTERNET hRequest = HttpOpenRequestW( hConnection, L"GET", L"", NULL, NULL, NULL, INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI|INTERNET_FLAG_IGNORE_CERT_CN_INVALID|INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, 0 ); if ( !hRequest ) { InternetCloseHandle(hConnection); failed = true; } // now stream the resulting HTTP into a file std::ofstream ostr; ostr.open(outFilename.c_str(), std::ios_base::binary | std::ios_base::trunc); CHAR buffer[2048]; DWORD dwRead; DWORD total = 0; wchar_t msg[255]; HttpSendRequest( hRequest, NULL, 0, NULL, 0); while( InternetReadFile( hRequest, buffer, 2047, &dwRead ) ) { if ( dwRead == 0) { break; } if (p->IsCancelled()) { failed = true; break; } buffer[dwRead] = 0; total+=dwRead; ostr << buffer; wsprintfW(msg,L"Downloaded %d bytes",total); p->SetLineText(2,msg,true); } ostr.close(); InternetCloseHandle(hConnection); InternetCloseHandle(hRequest); return ! failed; } bool UnzipFile(std::wstring unzipper, std::wstring zipFile, std::wstring destdir) { // now we're going to invoke back into the boot to unzip our file and install STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); ZeroMemory( &pi, sizeof(pi) ); si.cb = sizeof(si); std::wstring cmdline = L"\""; cmdline+=unzipper; cmdline+=L"\" --tiunzip \""; cmdline+=zipFile; cmdline+=L"\" \""; cmdline+=destdir; cmdline+=L"\""; // in win32, we just invoke back the same process and let him unzip if (!CreateProcessW(NULL,(LPWSTR)cmdline.c_str(),NULL,NULL,FALSE,NULL,NULL,NULL,&si,&pi)) { return false; } // wait for the process to finish unzipping WaitForSingleObject(pi.hProcess,INFINITE); return true; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { //TODO: set the icon for this app and dialogs // HICON icon = LoadIcon(hInstance,MAKEINTRESOURCE(IDR_MAINFRAME)); // SendMessage(NULL, WM_SETICON, (WPARAM)true, (LPARAM)icon); // get the command line LPWSTR cmdline = GetCommandLineW(); int argcount = 0; LPWSTR *args = CommandLineToArgvW(cmdline,&argcount); // we must have at least the mandatory args + 1 URL if (argcount < 8) { MessageBoxW(GetDesktopWindow(),L"Invalid arguments passed to Installer",L"Application Error",MB_OK|MB_SYSTEMMODAL|MB_ICONEXCLAMATION); return 1; } std::wstring appname = args[1]; std::wstring title = args[2]; std::wstring message = args[3]; std::wstring appTitle = appname + L" Installer"; std::wstring tempdir = args[4]; std::wstring installdir = args[5]; std::wstring unzipper = args[6]; // verify the installation if (IDOK != MessageBoxW(GetDesktopWindow(),message.c_str(),title.c_str(),MB_ICONINFORMATION|MB_OKCANCEL)) { MessageBoxW(GetDesktopWindow(),L"Installation Aborted. To install later, re-run the application again.", title.c_str(), MB_OK|MB_ICONWARNING); return 1; } int count = argcount - 7; int startAt = 7; CoInitialize(NULL); // create our progress indicator class Progress *p = new Progress; p->SetTitle(appTitle.c_str()); p->SetCancelMessage(L"Cancelling, one moment..."); wchar_t buf[255]; wsprintfW(buf,L"Preparing to download %d file%s", count, (count > 1 ? L"s" : L"")); p->SetLineText(1,std::wstring(buf),true); p->Show(); p->Update(0,count); // initialize interent DLL HINTERNET hINet = InternetOpenW(L"Mozilla/5.0 (compatible; Titanium_Downloader/0.1; Win32)", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); // for each URL, fetch the URL and then unzip it bool failed = false; DWORD x = 0; for (int c=startAt;c<argcount;c++) { p->Update(x++,count); std::wstring url = args[c]; std::wstring uuid = ParseQueryParam(url,L"uuid"); std::wstring name = ParseQueryParam(url,L"name"); std::wstring version = ParseQueryParam(url,L"version"); std::wstring filename = name; filename+=L"-"; filename+=version; filename+=L".zip"; // figure out the path and destination std::wstring path = tempdir + L"\\" + filename; std::wstring destdir; if (RUNTIME_UUID == uuid) { destdir = installdir + L"\\runtime\\win32\\" + version; } else if (MODULE_UUID == uuid) { destdir = installdir + L"\\modules\\win32\\" + name + L"\\" + version; } else { continue; } bool downloaded = DownloadURL(p, hINet, url, path); if(downloaded) { wchar_t msg[255]; wsprintfW(msg, L"Installing %s/%s ...",name.c_str(),version.c_str()); p->SetLineText(2,msg,true); UnzipFile(unzipper, path, destdir); } } // done with iNet - so close it InternetCloseHandle(hINet); if (p->IsCancelled()) { failed = true; } // cleanup delete p; CoUninitialize(); return (failed) ? 1 : 0; } <commit_msg>add 2nd method to download resources<commit_after>/** * Appcelerator Titanium - licensed under the Apache Public License 2 * see LICENSE in the root folder for details on the license. * Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved. */ #include <windows.h> #include <objbase.h> #include <Wininet.h> #include <vector> #include <iostream> #include <fstream> #include "Progress.h" #include "Resource.h" #define DISTRIBUTION_UUID L"7F7FA377-E695-4280-9F1F-96126F3D2C2A" #define RUNTIME_UUID L"A2AC5CB5-8C52-456C-9525-601A5B0725DA" #define MODULE_UUID L"1ACE5D3A-2B52-43FB-A136-007BD166CFD0" std::wstring ParseQueryParam(std::wstring uri, std::wstring name) { std::wstring key = name; key+=L"="; size_t pos = uri.find(key); if (pos!=std::wstring::npos) { std::wstring p = uri.substr(pos + key.length()); pos = p.find(L"&"); if (pos!=std::wstring::npos) { p = p.substr(0,pos); } // decode WCHAR szOut[INTERNET_MAX_URL_LENGTH]; DWORD cchDecodedUrl = INTERNET_MAX_URL_LENGTH; CoInternetParseUrl(p.c_str(), PARSE_UNESCAPE, 0, szOut, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); p.assign(szOut); return p; } return L""; } bool DownloadURL(Progress *p, HINTERNET hINet, std::wstring url, std::wstring outFilename) { WCHAR szDecodedUrl[INTERNET_MAX_URL_LENGTH]; DWORD cchDecodedUrl = INTERNET_MAX_URL_LENGTH; WCHAR szDomainName[INTERNET_MAX_URL_LENGTH]; bool failed = false; // parse the URL HRESULT hr = CoInternetParseUrl(url.c_str(), PARSE_DECODE, URL_ENCODING_NONE, szDecodedUrl, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); if (hr != S_OK) { //TODO failed = true; } // figure out the domain/hostname hr = CoInternetParseUrl(szDecodedUrl, PARSE_DOMAIN, 0, szDomainName, INTERNET_MAX_URL_LENGTH, &cchDecodedUrl, 0); if (hr != S_OK) { //TODO failed = true; } // TODO - how to cancel download if user presses the Cancel button // start the HTTP fetch HINTERNET hConnection = InternetConnectW( hINet, szDomainName, 80, L" ", L" ", INTERNET_SERVICE_HTTP, 0, 0 ); if ( !hConnection ) { failed = true; } HINTERNET hRequest = HttpOpenRequestW( hConnection, L"GET", L"", NULL, NULL, NULL, INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE|INTERNET_FLAG_NO_COOKIES|INTERNET_FLAG_NO_UI|INTERNET_FLAG_IGNORE_CERT_CN_INVALID|INTERNET_FLAG_IGNORE_CERT_DATE_INVALID, 0 ); if ( !hRequest ) { InternetCloseHandle(hConnection); failed = true; } // now stream the resulting HTTP into a file std::ofstream ostr; ostr.open(outFilename.c_str(), std::ios_base::binary | std::ios_base::trunc); CHAR buffer[2048]; DWORD dwRead; DWORD total = 0; wchar_t msg[255]; HttpSendRequest( hRequest, NULL, 0, NULL, 0); while( InternetReadFile( hRequest, buffer, 2047, &dwRead ) ) { if ( dwRead == 0) { break; } if (p->IsCancelled()) { failed = true; break; } buffer[dwRead] = 0; total+=dwRead; ostr << buffer; wsprintfW(msg,L"Downloaded %d bytes",total); p->SetLineText(2,msg,true); } ostr.close(); InternetCloseHandle(hConnection); InternetCloseHandle(hRequest); return ! failed; } bool DownloadURL2(Progress *p, HINTERNET hINet, std::wstring url, std::wstring outFilename) { // TODO - how to cancel download if user presses the Cancel button //url = L"http://www.google.com"; // start the HTTP fetch HINTERNET urlConn = InternetOpenUrl(hINet, url.c_str(), NULL, 0, 0, 0); if ( !urlConn ) { MessageBox(GetDesktopWindow(), L"didn't get a good url connection?", L"Download no good", MB_OK); return false; } bool failed = false; // now stream the resulting HTTP into a file std::ofstream ostr; ostr.open(outFilename.c_str(), std::ios_base::binary | std::ios_base::trunc); CHAR buffer[2048]; DWORD dwRead; DWORD total = 0; TCHAR msg[255]; while( InternetReadFile(urlConn, buffer, 2047, &dwRead ) ) { if ( dwRead == 0) { break; } if (p->IsCancelled()) { failed = true; break; } buffer[dwRead] = 0; total+=dwRead; ostr << buffer; wsprintf(msg,L"Downloaded %d bytes",total); p->SetLineText(2,msg,true); } ostr.close(); InternetCloseHandle(urlConn); MessageBox(GetDesktopWindow(), url.c_str(), L"URL Downloaded", MB_OK); MessageBox(GetDesktopWindow(), outFilename.c_str(), L"File Downloaded", MB_OK); return ! failed; } bool UnzipFile(std::wstring unzipper, std::wstring zipFile, std::wstring destdir) { // now we're going to invoke back into the boot to unzip our file and install STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); ZeroMemory( &pi, sizeof(pi) ); si.cb = sizeof(si); std::wstring cmdline = L"\""; cmdline+=unzipper; cmdline+=L"\" --tiunzip \""; cmdline+=zipFile; cmdline+=L"\" \""; cmdline+=destdir; cmdline+=L"\""; // in win32, we just invoke back the same process and let him unzip if (!CreateProcessW(NULL,(LPWSTR)cmdline.c_str(),NULL,NULL,FALSE,NULL,NULL,NULL,&si,&pi)) { return false; } // wait for the process to finish unzipping WaitForSingleObject(pi.hProcess,INFINITE); return true; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { //TODO: set the icon for this app and dialogs // HICON icon = LoadIcon(hInstance,MAKEINTRESOURCE(IDR_MAINFRAME)); // SendMessage(NULL, WM_SETICON, (WPARAM)true, (LPARAM)icon); // get the command line LPWSTR cmdline = GetCommandLineW(); int argcount = 0; LPWSTR *args = CommandLineToArgvW(cmdline,&argcount); // we must have at least the mandatory args + 1 URL if (argcount < 8) { MessageBoxW(GetDesktopWindow(),L"Invalid arguments passed to Installer",L"Application Error",MB_OK|MB_SYSTEMMODAL|MB_ICONEXCLAMATION); return 1; } std::wstring appname = args[1]; std::wstring title = args[2]; std::wstring message = args[3]; std::wstring appTitle = appname + L" Installer"; std::wstring tempdir = args[4]; std::wstring installdir = args[5]; std::wstring unzipper = args[6]; // verify the installation if (IDOK != MessageBoxW(GetDesktopWindow(),message.c_str(),title.c_str(),MB_ICONINFORMATION|MB_OKCANCEL)) { MessageBoxW(GetDesktopWindow(),L"Installation Aborted. To install later, re-run the application again.", title.c_str(), MB_OK|MB_ICONWARNING); return 1; } int count = argcount - 7; int startAt = 7; CoInitialize(NULL); // create our progress indicator class Progress *p = new Progress; p->SetTitle(appTitle.c_str()); p->SetCancelMessage(L"Cancelling, one moment..."); wchar_t buf[255]; wsprintfW(buf,L"Preparing to download %d file%s", count, (count > 1 ? L"s" : L"")); p->SetLineText(1,std::wstring(buf),true); p->Show(); p->Update(0,count); // initialize interent DLL HINTERNET hINet = InternetOpenW(L"Mozilla/5.0 (compatible; Titanium_Downloader/0.1; Win32)", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); // for each URL, fetch the URL and then unzip it bool failed = false; DWORD x = 0; for (int c=startAt;c<argcount;c++) { p->Update(x++,count); std::wstring url = args[c]; std::wstring uuid = ParseQueryParam(url,L"uuid"); std::wstring name = ParseQueryParam(url,L"name"); std::wstring version = ParseQueryParam(url,L"version"); std::wstring filename = name; filename+=L"-"; filename+=version; filename+=L".zip"; // figure out the path and destination std::wstring path = tempdir + L"\\" + filename; std::wstring destdir; if (RUNTIME_UUID == uuid) { destdir = installdir + L"\\runtime\\win32\\" + version; } else if (MODULE_UUID == uuid) { destdir = installdir + L"\\modules\\win32\\" + name + L"\\" + version; } else { continue; } bool downloaded = DownloadURL(p, hINet, url, path); if(downloaded) { wchar_t msg[255]; wsprintfW(msg, L"Installing %s/%s ...",name.c_str(),version.c_str()); p->SetLineText(2,msg,true); UnzipFile(unzipper, path, destdir); } } // done with iNet - so close it InternetCloseHandle(hINet); if (p->IsCancelled()) { failed = true; } // cleanup delete p; CoUninitialize(); return (failed) ? 1 : 0; } <|endoftext|>
<commit_before>#include <node.h> #include <v8.h> #include <git2.h> #include <map> #include <algorithm> #include <set> #include <openssl/crypto.h> #include "../include/init_ssh2.h" #include "../include/lock_master.h" #include "../include/nodegit.h" #include "../include/wrapper.h" #include "../include/promise_completion.h" #include "../include/functions/copy.h" {% each %} {% if type != "enum" %} #include "../include/{{ filename }}.h" {% endif %} {% endeach %} #include "../include/convenient_patch.h" #include "../include/convenient_hunk.h" #include "../include/filter_registry.h" #if (NODE_MODULE_VERSION > 48) v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, key); v8::Local<v8::Value> value; v8::Maybe<bool> result = object->HasPrivate(context, privateKey); if (!(result.IsJust() && result.FromJust())) return v8::Local<v8::Value>(); if (object->GetPrivate(context, privateKey).ToLocal(&value)) return value; return v8::Local<v8::Value>(); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { if (value.IsEmpty()) return; v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, key); object->SetPrivate(context, privateKey, value); } #else v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { return object->GetHiddenValue(key); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { object->SetHiddenValue(key, value); } #endif void LockMasterEnable(const FunctionCallbackInfo<Value>& info) { LockMaster::Enable(); } void LockMasterSetStatus(const FunctionCallbackInfo<Value>& info) { Nan::HandleScope scope; // convert the first argument to Status if(info.Length() >= 0 && info[0]->IsNumber()) { v8::Local<v8::Int32> value = info[0]->ToInt32(v8::Isolate::GetCurrent()); LockMaster::Status status = static_cast<LockMaster::Status>(value->Value()); if(status >= LockMaster::Disabled && status <= LockMaster::Enabled) { LockMaster::SetStatus(status); return; } } // argument error Nan::ThrowError("Argument must be one 0, 1 or 2"); } void LockMasterGetStatus(const FunctionCallbackInfo<Value>& info) { info.GetReturnValue().Set(Nan::New(LockMaster::GetStatus())); } void LockMasterGetDiagnostics(const FunctionCallbackInfo<Value>& info) { LockMaster::Diagnostics diagnostics(LockMaster::GetDiagnostics()); // return a plain JS object with properties v8::Local<v8::Object> result = Nan::New<v8::Object>(); result->Set(Nan::New("storedMutexesCount").ToLocalChecked(), Nan::New(diagnostics.storedMutexesCount)); info.GetReturnValue().Set(result); } static uv_mutex_t *opensslMutexes; void OpenSSL_LockingCallback(int mode, int type, const char *, int) { if (mode & CRYPTO_LOCK) { uv_mutex_lock(&opensslMutexes[type]); } else { uv_mutex_unlock(&opensslMutexes[type]); } } unsigned long OpenSSL_IDCallback() { return (unsigned long)uv_thread_self(); } void OpenSSL_ThreadSetup() { opensslMutexes=(uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t)); for (int i=0; i<CRYPTO_num_locks(); i++) { uv_mutex_init(&opensslMutexes[i]); } CRYPTO_set_locking_callback(OpenSSL_LockingCallback); CRYPTO_set_id_callback(OpenSSL_IDCallback); } ThreadPool libgit2ThreadPool(10, uv_default_loop()); extern "C" void init(v8::Local<v8::Object> target) { // Initialize thread safety in openssl and libssh2 OpenSSL_ThreadSetup(); init_ssh2(); // Initialize libgit2. git_libgit2_init(); Nan::HandleScope scope; Wrapper::InitializeComponent(target); PromiseCompletion::InitializeComponent(); {% each %} {% if type != "enum" %} {{ cppClassName }}::InitializeComponent(target); {% endif %} {% endeach %} ConvenientHunk::InitializeComponent(target); ConvenientPatch::InitializeComponent(target); GitFilterRegistry::InitializeComponent(target); NODE_SET_METHOD(target, "enableThreadSafety", LockMasterEnable); NODE_SET_METHOD(target, "setThreadSafetyStatus", LockMasterSetStatus); NODE_SET_METHOD(target, "getThreadSafetyStatus", LockMasterGetStatus); NODE_SET_METHOD(target, "getThreadSafetyDiagnostics", LockMasterGetDiagnostics); v8::Local<v8::Object> threadSafety = Nan::New<v8::Object>(); threadSafety->Set(Nan::New("DISABLED").ToLocalChecked(), Nan::New((int)LockMaster::Disabled)); threadSafety->Set(Nan::New("ENABLED_FOR_ASYNC_ONLY").ToLocalChecked(), Nan::New((int)LockMaster::EnabledForAsyncOnly)); threadSafety->Set(Nan::New("ENABLED").ToLocalChecked(), Nan::New((int)LockMaster::Enabled)); target->Set(Nan::New("THREAD_SAFETY").ToLocalChecked(), threadSafety); LockMaster::Initialize(); } NODE_MODULE(nodegit, init) <commit_msg>Use proper callback for setting thread ID in OpenSSL<commit_after>#include <node.h> #include <v8.h> #include <git2.h> #include <map> #include <algorithm> #include <set> #include <openssl/crypto.h> #include "../include/init_ssh2.h" #include "../include/lock_master.h" #include "../include/nodegit.h" #include "../include/wrapper.h" #include "../include/promise_completion.h" #include "../include/functions/copy.h" {% each %} {% if type != "enum" %} #include "../include/{{ filename }}.h" {% endif %} {% endeach %} #include "../include/convenient_patch.h" #include "../include/convenient_hunk.h" #include "../include/filter_registry.h" #if (NODE_MODULE_VERSION > 48) v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, key); v8::Local<v8::Value> value; v8::Maybe<bool> result = object->HasPrivate(context, privateKey); if (!(result.IsJust() && result.FromJust())) return v8::Local<v8::Value>(); if (object->GetPrivate(context, privateKey).ToLocal(&value)) return value; return v8::Local<v8::Value>(); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { if (value.IsEmpty()) return; v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Local<v8::Context> context = isolate->GetCurrentContext(); v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate, key); object->SetPrivate(context, privateKey, value); } #else v8::Local<v8::Value> GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { return object->GetHiddenValue(key); } void SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value) { object->SetHiddenValue(key, value); } #endif void LockMasterEnable(const FunctionCallbackInfo<Value>& info) { LockMaster::Enable(); } void LockMasterSetStatus(const FunctionCallbackInfo<Value>& info) { Nan::HandleScope scope; // convert the first argument to Status if(info.Length() >= 0 && info[0]->IsNumber()) { v8::Local<v8::Int32> value = info[0]->ToInt32(v8::Isolate::GetCurrent()); LockMaster::Status status = static_cast<LockMaster::Status>(value->Value()); if(status >= LockMaster::Disabled && status <= LockMaster::Enabled) { LockMaster::SetStatus(status); return; } } // argument error Nan::ThrowError("Argument must be one 0, 1 or 2"); } void LockMasterGetStatus(const FunctionCallbackInfo<Value>& info) { info.GetReturnValue().Set(Nan::New(LockMaster::GetStatus())); } void LockMasterGetDiagnostics(const FunctionCallbackInfo<Value>& info) { LockMaster::Diagnostics diagnostics(LockMaster::GetDiagnostics()); // return a plain JS object with properties v8::Local<v8::Object> result = Nan::New<v8::Object>(); result->Set(Nan::New("storedMutexesCount").ToLocalChecked(), Nan::New(diagnostics.storedMutexesCount)); info.GetReturnValue().Set(result); } static uv_mutex_t *opensslMutexes; void OpenSSL_LockingCallback(int mode, int type, const char *, int) { if (mode & CRYPTO_LOCK) { uv_mutex_lock(&opensslMutexes[type]); } else { uv_mutex_unlock(&opensslMutexes[type]); } } void OpenSSL_IDCallback(CRYPTO_THREADID *id) { CRYPTO_THREADID_set_numeric(id, (unsigned long)uv_thread_self()); } void OpenSSL_ThreadSetup() { opensslMutexes=(uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t)); for (int i=0; i<CRYPTO_num_locks(); i++) { uv_mutex_init(&opensslMutexes[i]); } CRYPTO_set_locking_callback(OpenSSL_LockingCallback); CRYPTO_THREADID_set_callback(OpenSSL_IDCallback); } ThreadPool libgit2ThreadPool(10, uv_default_loop()); extern "C" void init(v8::Local<v8::Object> target) { // Initialize thread safety in openssl and libssh2 OpenSSL_ThreadSetup(); init_ssh2(); // Initialize libgit2. git_libgit2_init(); Nan::HandleScope scope; Wrapper::InitializeComponent(target); PromiseCompletion::InitializeComponent(); {% each %} {% if type != "enum" %} {{ cppClassName }}::InitializeComponent(target); {% endif %} {% endeach %} ConvenientHunk::InitializeComponent(target); ConvenientPatch::InitializeComponent(target); GitFilterRegistry::InitializeComponent(target); NODE_SET_METHOD(target, "enableThreadSafety", LockMasterEnable); NODE_SET_METHOD(target, "setThreadSafetyStatus", LockMasterSetStatus); NODE_SET_METHOD(target, "getThreadSafetyStatus", LockMasterGetStatus); NODE_SET_METHOD(target, "getThreadSafetyDiagnostics", LockMasterGetDiagnostics); v8::Local<v8::Object> threadSafety = Nan::New<v8::Object>(); threadSafety->Set(Nan::New("DISABLED").ToLocalChecked(), Nan::New((int)LockMaster::Disabled)); threadSafety->Set(Nan::New("ENABLED_FOR_ASYNC_ONLY").ToLocalChecked(), Nan::New((int)LockMaster::EnabledForAsyncOnly)); threadSafety->Set(Nan::New("ENABLED").ToLocalChecked(), Nan::New((int)LockMaster::Enabled)); target->Set(Nan::New("THREAD_SAFETY").ToLocalChecked(), threadSafety); LockMaster::Initialize(); } NODE_MODULE(nodegit, init) <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_COMMON_TMP_STORAGE_HH #define DUNE_STUFF_COMMON_TMP_STORAGE_HH #include <vector> #include <dune/stuff/common/disable_warnings.hh> # include <dune/common/dynmatrix.hh> #include <dune/stuff/common/reenable_warnings.hh> #include <dune/common/dynvector.hh> #include <dune/stuff/common/parallel/threadmanager.hh> namespace Dune { namespace Stuff { namespace Common { template< class FieldType = double > class TmpMatricesStorage { public: typedef DynamicMatrix< FieldType > LocalMatrixType; protected: typedef std::vector< std::vector< LocalMatrixType > > LocalMatrixContainerType; public: TmpMatricesStorage(const std::vector< size_t >& num_tmp_objects, const size_t max_rows, const size_t max_cols) : matrices_(LocalMatrixContainerType({std::vector< LocalMatrixType >(num_tmp_objects.at(0), LocalMatrixType(max_rows, max_cols, FieldType(0))) , std::vector< LocalMatrixType >(num_tmp_objects.at(1), LocalMatrixType(max_rows, max_cols, FieldType(0))) } )) , indices_(4, Dune::DynamicVector< size_t >(std::max(max_rows, max_cols))) {} virtual ~TmpMatricesStorage() {} std::vector< std::vector< LocalMatrixType > >& matrices() { return *matrices_; } std::vector< Dune::DynamicVector< size_t > >& indices() { return *indices_; } protected: PerThreadValue< LocalMatrixContainerType > matrices_; PerThreadValue< std::vector< DynamicVector< size_t > > > indices_; }; // class Matrices template< class FieldType = double > class TmpVectorsStorage { public: typedef DynamicVector< FieldType > LocalVectorType; protected: typedef std::vector< std::vector< LocalVectorType > > LocalVectorContainerType; TmpVectorsStorage(const std::vector< size_t >& num_tmp_objects, const size_t max_size) : vectors_(LocalVectorContainerType({ std::vector< LocalVectorType >(num_tmp_objects.at(0), LocalVectorType(max_size, FieldType(0))) , std::vector< LocalVectorType >(num_tmp_objects.at(1), LocalVectorType(max_size, FieldType(0))) } )) , indices_(max_size) {} virtual ~TmpVectorsStorage() {} std::vector< std::vector< LocalVectorType > >& vectors() { return *vectors_; } Dune::DynamicVector< size_t >& indices() { return *indices_; } protected: PerThreadValue< std::vector< std::vector< LocalVectorType > > > vectors_; PerThreadValue< Dune::DynamicVector< size_t > > indices_; }; // class Vectors } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_COMMON_TMP_STORAGE_HH <commit_msg>[common.tmp-storage] added documentation, removed warning guards<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_COMMON_TMP_STORAGE_HH #define DUNE_STUFF_COMMON_TMP_STORAGE_HH #include <vector> #include <dune/common/dynmatrix.hh> #include <dune/common/dynvector.hh> #include <dune/stuff/common/parallel/threadmanager.hh> namespace Dune { namespace Stuff { namespace Common { template< class FieldType = double > class TmpMatricesStorage { public: typedef DynamicMatrix< FieldType > LocalMatrixType; protected: typedef std::vector< std::vector< LocalMatrixType > > LocalMatrixContainerType; public: /** * \brief constructs the appropriate amount of matrix and indices storage * * We construct 4 indices vectors since this is the maximum amount needed for discretizations (at least that * we know of atm), namely one for each entity/neighbor and ansatz/test combination. */ TmpMatricesStorage(const std::vector< size_t >& num_tmp_objects, const size_t max_rows, const size_t max_cols) : matrices_(LocalMatrixContainerType({std::vector< LocalMatrixType >(num_tmp_objects.at(0), LocalMatrixType(max_rows, max_cols, FieldType(0))) , std::vector< LocalMatrixType >(num_tmp_objects.at(1), LocalMatrixType(max_rows, max_cols, FieldType(0))) } )) , indices_(4, Dune::DynamicVector< size_t >(std::max(max_rows, max_cols))) {} virtual ~TmpMatricesStorage() {} std::vector< std::vector< LocalMatrixType > >& matrices() { return *matrices_; } std::vector< Dune::DynamicVector< size_t > >& indices() { return *indices_; } protected: PerThreadValue< LocalMatrixContainerType > matrices_; PerThreadValue< std::vector< DynamicVector< size_t > > > indices_; }; // class Matrices template< class FieldType = double > class TmpVectorsStorage { public: typedef DynamicVector< FieldType > LocalVectorType; protected: typedef std::vector< std::vector< LocalVectorType > > LocalVectorContainerType; TmpVectorsStorage(const std::vector< size_t >& num_tmp_objects, const size_t max_size) : vectors_(LocalVectorContainerType({ std::vector< LocalVectorType >(num_tmp_objects.at(0), LocalVectorType(max_size, FieldType(0))) , std::vector< LocalVectorType >(num_tmp_objects.at(1), LocalVectorType(max_size, FieldType(0))) } )) , indices_(max_size) {} virtual ~TmpVectorsStorage() {} std::vector< std::vector< LocalVectorType > >& vectors() { return *vectors_; } Dune::DynamicVector< size_t >& indices() { return *indices_; } protected: PerThreadValue< std::vector< std::vector< LocalVectorType > > > vectors_; PerThreadValue< Dune::DynamicVector< size_t > > indices_; }; // class Vectors } // namespace Common } // namespace Stuff } // namespace Dune #endif // DUNE_STUFF_COMMON_TMP_STORAGE_HH <|endoftext|>
<commit_before>#ifndef _vector_hpp_1337420 #define _vector_hpp_1337420 #include <cstdlib> #include <new> #include <utility> #include <memory> #include <type_traits> #include <iterator> #include "../ztl_base.hpp" __ztl_namespace_start template <class T> class vector { public: typedef T value_type; typedef T& reference; typedef T* iterator; typedef const T* const_iterator; typedef __stl::random_access_iterator_tag iterator_category; typedef __stl::reverse_iterator<const_iterator> const_reverse_iterator; typedef __stl::reverse_iterator<iterator> reverse_iterator; typedef __stl::size_t size_type; typedef __stl::ptrdiff_t difference_type; private: iterator p_begin; iterator p_last; iterator p_end; inline void enlarge() { enlarge((p_end - p_begin + 1) * 2); } inline void enlarge(int size) { int n = p_last - p_begin; p_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size); p_end = p_begin + size - 1; p_last = p_begin + n; } public: vector() { p_begin = p_end = (iterator)malloc(sizeof(value_type)); p_last = p_begin - 1; } vector(size_type starting_size) { p_begin = (iterator)malloc(sizeof(value_type) * starting_size); p_end = p_begin + starting_size - 1; p_last = p_begin - 1; } ~vector() { if (!__stl::is_trivially_destructible<value_type>::value) { ++p_last; while (--p_last >= p_begin) { (p_last)->~T(); } } free(p_begin); } template<class... Args> inline void emplace_back(Args&&... args) { if (p_last == p_end) enlarge(); new (++p_last) T(__stl::forward<Args>(args)...); } inline void push_back(const T& other) { if (p_last == p_end) enlarge(); new (++p_last) T(other); } /* Access elements */ inline reference at(unsigned int id) { if (!(id < size())) throw __stl::out_of_range("Index out of range"); return p_begin[id]; } inline const reference at(unsigned int id) const { if (!(id < size())) throw __stl::out_of_range("Index out of range"); return p_begin[id]; } inline reference operator[](unsigned int id) { return p_begin[id]; } inline const reference operator[](unsigned int id) const { return p_begin[id]; } /* Iterators */ inline iterator begin() { return p_begin; } inline iterator end() { return p_end; } inline const_iterator cbegin() const { return p_begin; } inline const_iterator cend() const { return p_end; } inline reverse_iterator rbegin() { return reverse_iterator(p_end); } inline reverse_iterator rend() { return reverse_iterator(p_begin); } inline const_reverse_iterator crbegin() const { return const_reverse_iterator(p_end); } inline const_reverse_iterator crend() const { return const_reverse_iterator(p_begin); } inline reference first() { return *p_begin; } inline const reference first() const { return *p_begin; } inline reference last() { return *p_last; } inline const reference last() const { return *p_last; } /* Size / Allocation */ inline bool empty() const { return size() == 0; } inline size_type size() const { return p_last - p_begin + 1; } inline size_type reserved() const { return p_end - p_begin + 1; } inline void reserve(size_type num) { enlarge(num); } inline void clear() { erase(p_begin, p_last); } inline void erase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); } inline void erase(iterator pa, iterator pb) { if (!__stl::is_trivially_destructible<value_type>::value) { iterator a = pa - 1; while (a < pb) (++a)->~T(); } memmove(pa, pb + 1, sizeof(value_type) * (p_last - pb)); p_last = pa + (p_last - pb) - 1; } }; __ztl_namespace_end #endif /* _vector_hpp_1337420 */ <commit_msg>Code formatting<commit_after>#ifndef _vector_hpp_1337420 #define _vector_hpp_1337420 #include <cstdlib> #include <new> #include <utility> #include <memory> #include <type_traits> #include <iterator> #include "../ztl_base.hpp" __ztl_namespace_start template <class T> class vector { public: typedef T value_type; typedef T& reference; typedef T* iterator; typedef const T* const_iterator; typedef __stl::random_access_iterator_tag iterator_category; typedef __stl::reverse_iterator<const_iterator> const_reverse_iterator; typedef __stl::reverse_iterator<iterator> reverse_iterator; typedef __stl::size_t size_type; typedef __stl::ptrdiff_t difference_type; private: iterator p_begin; iterator p_last; iterator p_end; inline void enlarge() { enlarge((p_end - p_begin + 1) * 2); } inline void enlarge(int size) { int n = p_last - p_begin; p_begin = (iterator)realloc((void*)p_begin, sizeof(value_type) * size); p_end = p_begin + size - 1; p_last = p_begin + n; } public: vector() { p_begin = p_end = (iterator)malloc(sizeof(value_type)); p_last = p_begin - 1; } vector(size_type starting_size) { p_begin = (iterator)malloc(sizeof(value_type) * starting_size); p_end = p_begin + starting_size - 1; p_last = p_begin - 1; } ~vector() { if (!__stl::is_trivially_destructible<value_type>::value) { ++p_last; while (--p_last >= p_begin) { (p_last)->~T(); } } free(p_begin); } template<class... Args> inline void emplace_back(Args&&... args) { if (p_last == p_end) enlarge(); new (++p_last) T(__stl::forward<Args>(args)...); } inline void push_back(const T& other) { if (p_last == p_end) enlarge(); new (++p_last) T(other); } /* Access elements */ inline reference at(unsigned int id) { if (!(id < size())) throw __stl::out_of_range("Index out of range"); return p_begin[id]; } inline const reference at(unsigned int id) const { if (!(id < size())) throw __stl::out_of_range("Index out of range"); return p_begin[id]; } inline reference operator[](unsigned int id) { return p_begin[id]; } inline const reference operator[](unsigned int id) const { return p_begin[id]; } /* Iterators */ inline iterator begin() { return p_begin; } inline iterator end() { return p_end; } inline const_iterator cbegin() const { return p_begin; } inline const_iterator cend() const { return p_end; } inline reverse_iterator rbegin() { return reverse_iterator(p_end); } inline reverse_iterator rend() { return reverse_iterator(p_begin); } inline const_reverse_iterator crbegin() const { return const_reverse_iterator(p_end); } inline const_reverse_iterator crend() const { return const_reverse_iterator(p_begin); } inline reference first() { return *p_begin; } inline const reference first() const { return *p_begin; } inline reference last() { return *p_last; } inline const reference last() const { return *p_last; } /* Size / Allocation */ inline bool empty() const { return size() == 0; } inline size_type size() const { return p_last - p_begin + 1; } inline size_type reserved() const { return p_end - p_begin + 1; } inline void reserve(size_type num) { enlarge(num); } inline void clear() { erase(p_begin, p_last); } inline void erase(size_type a, size_type b) { erase(p_begin + a, p_begin + b); } inline void erase(iterator pa, iterator pb) { if (!__stl::is_trivially_destructible<value_type>::value) { iterator a = pa - 1; while (a < pb) (++a)->~T(); } memmove(pa, pb + 1, sizeof(value_type) * (p_last - pb)); p_last = pa + (p_last - pb) - 1; } }; __ztl_namespace_end #endif /* _vector_hpp_1337420 */ <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file pc_merge.cc /// /// A simple tool to merge multiple point cloud files into a single file. The clouds /// can have 1 channel (plain raster images) or 3 to 6 channels. #include <asp/Core/Macros.h> #include <asp/Core/Common.h> #include <asp/Core/PointUtils.h> #include <asp/Core/OrthoRasterizer.h> #include <vw/Core/Stopwatch.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/FileIO/DiskImageUtils.h> #include <vw/Cartography/PointImageManipulation.h> #include <limits> using namespace vw; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; // Allows FileIO to correctly read/write these pixel types namespace vw { typedef Vector<float64,4> Vector4; typedef Vector<float64,6> Vector6; template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; }; template<> struct PixelFormatID<Vector3f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; }; template<> struct PixelFormatID<Vector4> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; }; template<> struct PixelFormatID<Vector4f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; }; template<> struct PixelFormatID<Vector6> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; }; } struct Options : asp::BaseOptions { // Input std::vector<std::string> pointcloud_files; // Settings bool write_double; ///< If true, output file is double instead of float // Output std::string out_file; Options() : write_double(false) {} }; void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("General Options"); general_options.add_options() ("output-file,o", po::value(&opt.out_file)->default_value(""), "Specify the output file.") ("write-double,d", po::value(&opt.write_double)->default_value(false), "Write a double precision output file."); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-files", po::value< std::vector<std::string> >(), "Input files"); po::positional_options_description positional_desc; positional_desc.add("input-files", -1); std::string usage("[options] <point-clouds> "); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered ); if (vm.count("input-files") == 0) vw_throw( ArgumentErr() << "Missing input point clouds.\n" << usage << general_options ); opt.pointcloud_files = vm["input-files"].as< std::vector<std::string> >(); if (opt.out_file == "") vw_throw( ArgumentErr() << "The output file must be specified!\n" << usage << general_options ); vw::create_out_dir(opt.out_file); } /// Throws if the input point clouds do not have the same number of channels. /// - Returns the number of channels. int check_num_channels(std::vector<std::string> const& pc_files){ VW_ASSERT(pc_files.size() >= 1, ArgumentErr() << "Expecting at least one file.\n"); int target_num = get_num_channels(pc_files[0]); for (int i = 1; i < (int)pc_files.size(); ++i){ int num_channels = get_num_channels(pc_files[i]); if (num_channels != target_num) vw_throw( ArgumentErr() << "Input point clouds must all have the same number of channels!.\n" ); } return target_num; } /// Determine the common shift value to use for the output files Vector3 determine_output_shift(std::vector<std::string> const& pc_files, Options const& opt){ // If writing to double format, no shift is needed. if (opt.write_double) return Vector3(0,0,0); // As an approximation, compute the mean shift vector of the input files. // - If none of the input files have a shift, the output file will be written as a double. vw::Vector3 shift(0,0,0), shiftIn; double shift_count = 0; for (size_t i=0; i<pc_files.size(); ++i) { // Read in the shift from each cloud and accumulate them std::string shift_str; boost::shared_ptr<vw::DiskImageResource> rsrc( new vw::DiskImageResourceGDAL(pc_files[i]) ); if (vw::cartography::read_header_string(*rsrc.get(), asp::ASP_POINT_OFFSET_TAG_STR, shift_str)){ //std::cout << "shift string = " << shift_str << std::endl; shift += asp::str_to_vec<vw::Vector3>(shift_str); shift_count += 1.0; } } if (shift_count < 0.9) // If no shifts read, don't use a shift. return Vector3(0,0,0); // Compute the mean shift // - It would be more accurate to weight the shift according to the number of input points shift /= shift_count; return shift; } // Do the actual work of loading, merging, and saving the point clouds // Case 1: Single-channel cloud. template <class PixelT> typename boost::enable_if<boost::is_same<PixelT, vw::PixelGray<float> >, void >::type do_work(Vector3 const& shift, Options const& opt) { // The spacing is selected to be compatible with the point2dem convention. const int spacing = asp::OrthoRasterizerView::max_subblock_size(); ImageViewRef<PixelT> merged_cloud = asp::form_point_cloud_composite<PixelT>(opt.pointcloud_files, spacing); vw_out() << "Writing image: " << opt.out_file << "\n"; bool has_georef = false; bool has_nodata = false; double nodata; GeoReference georef; asp::block_write_gdal_image(opt.out_file, merged_cloud, has_georef, georef, has_nodata, nodata, opt, TerminalProgressCallback("asp", "\t--> Merging: ")); } // Case 2: Multi-channel cloud. template <class PixelT> typename boost::disable_if<boost::is_same<PixelT, vw::PixelGray<float> >, void >::type do_work(Vector3 const& shift, Options const& opt) { // The spacing is selected to be compatible with the point2dem convention. const int spacing = asp::OrthoRasterizerView::max_subblock_size(); ImageViewRef<PixelT> merged_cloud = asp::form_point_cloud_composite<PixelT>(opt.pointcloud_files, spacing); // See if we can pull a georeference from somewhere. Of course it will be wrong // when applied to the merged cloud, but it will at least have the correct datum // and projection. bool has_georef = false; cartography::GeoReference georef; for (size_t i = 0; i < opt.pointcloud_files.size(); i++){ cartography::GeoReference local_georef; if (read_georeference(local_georef, opt.pointcloud_files[i])){ georef = local_georef; has_georef = true; } } bool has_nodata = false; double nodata = -std::numeric_limits<float>::max(); // smallest float vw_out() << "Writing point cloud: " << opt.out_file << "\n"; // If shift != zero then this will cast the output data to type float. // Otherwise it will keep its data type. double point_cloud_rounding_error = 0.0; asp::block_write_approx_gdal_image ( opt.out_file, shift, point_cloud_rounding_error, merged_cloud, has_georef, georef, has_nodata, nodata, opt, TerminalProgressCallback("asp", "\t--> Merging: ")); } //----------------------------------------------------------------------------------- int main( int argc, char *argv[] ) { Options opt; //try { handle_arguments( argc, argv, opt ); // Determine the number of channels int num_channels = check_num_channels(opt.pointcloud_files); // Determine the output shift (if any) Vector3 shift = determine_output_shift(opt.pointcloud_files, opt); // The code has to branch here depending on the number of channels switch (num_channels) { // The input point clouds have their shift incorporated and are stored as doubles. // If the output file is stored as float, it needs to have a single shift value applied. case 1: do_work< vw::PixelGray<float> >(shift, opt); break; case 3: do_work<Vector3>(shift, opt); break; case 4: do_work<Vector4>(shift, opt); break; case 6: do_work<Vector6>(shift, opt); break; default: vw_throw( ArgumentErr() << "Unsupported number of channels!.\n" ); } //} ASP_STANDARD_CATCHES; return 0; } <commit_msg>pc_merge: initialize nodata<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is licensed under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance with the // License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // __END_LICENSE__ /// \file pc_merge.cc /// /// A simple tool to merge multiple point cloud files into a single file. The clouds /// can have 1 channel (plain raster images) or 3 to 6 channels. #include <asp/Core/Macros.h> #include <asp/Core/Common.h> #include <asp/Core/PointUtils.h> #include <asp/Core/OrthoRasterizer.h> #include <vw/Core/Stopwatch.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/FileIO/DiskImageUtils.h> #include <vw/Cartography/PointImageManipulation.h> #include <limits> using namespace vw; using namespace vw::cartography; namespace po = boost::program_options; namespace fs = boost::filesystem; // Allows FileIO to correctly read/write these pixel types namespace vw { typedef Vector<float64,4> Vector4; typedef Vector<float64,6> Vector6; template<> struct PixelFormatID<Vector3> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; }; template<> struct PixelFormatID<Vector3f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; }; template<> struct PixelFormatID<Vector4> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; }; template<> struct PixelFormatID<Vector4f> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_4_CHANNEL; }; template<> struct PixelFormatID<Vector6> { static const PixelFormatEnum value = VW_PIXEL_GENERIC_6_CHANNEL; }; } struct Options : asp::BaseOptions { // Input std::vector<std::string> pointcloud_files; // Settings bool write_double; ///< If true, output file is double instead of float // Output std::string out_file; Options() : write_double(false) {} }; void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("General Options"); general_options.add_options() ("output-file,o", po::value(&opt.out_file)->default_value(""), "Specify the output file.") ("write-double,d", po::value(&opt.write_double)->default_value(false), "Write a double precision output file."); general_options.add( asp::BaseOptionsDescription(opt) ); po::options_description positional(""); positional.add_options() ("input-files", po::value< std::vector<std::string> >(), "Input files"); po::positional_options_description positional_desc; positional_desc.add("input-files", -1); std::string usage("[options] <point-clouds> "); bool allow_unregistered = false; std::vector<std::string> unregistered; po::variables_map vm = asp::check_command_line( argc, argv, opt, general_options, general_options, positional, positional_desc, usage, allow_unregistered, unregistered ); if (vm.count("input-files") == 0) vw_throw( ArgumentErr() << "Missing input point clouds.\n" << usage << general_options ); opt.pointcloud_files = vm["input-files"].as< std::vector<std::string> >(); if (opt.out_file == "") vw_throw( ArgumentErr() << "The output file must be specified!\n" << usage << general_options ); vw::create_out_dir(opt.out_file); } /// Throws if the input point clouds do not have the same number of channels. /// - Returns the number of channels. int check_num_channels(std::vector<std::string> const& pc_files){ VW_ASSERT(pc_files.size() >= 1, ArgumentErr() << "Expecting at least one file.\n"); int target_num = get_num_channels(pc_files[0]); for (int i = 1; i < (int)pc_files.size(); ++i){ int num_channels = get_num_channels(pc_files[i]); if (num_channels != target_num) vw_throw( ArgumentErr() << "Input point clouds must all have the same number of channels!.\n" ); } return target_num; } /// Determine the common shift value to use for the output files Vector3 determine_output_shift(std::vector<std::string> const& pc_files, Options const& opt){ // If writing to double format, no shift is needed. if (opt.write_double) return Vector3(0,0,0); // As an approximation, compute the mean shift vector of the input files. // - If none of the input files have a shift, the output file will be written as a double. vw::Vector3 shift(0,0,0), shiftIn; double shift_count = 0; for (size_t i=0; i<pc_files.size(); ++i) { // Read in the shift from each cloud and accumulate them std::string shift_str; boost::shared_ptr<vw::DiskImageResource> rsrc( new vw::DiskImageResourceGDAL(pc_files[i]) ); if (vw::cartography::read_header_string(*rsrc.get(), asp::ASP_POINT_OFFSET_TAG_STR, shift_str)){ //std::cout << "shift string = " << shift_str << std::endl; shift += asp::str_to_vec<vw::Vector3>(shift_str); shift_count += 1.0; } } if (shift_count < 0.9) // If no shifts read, don't use a shift. return Vector3(0,0,0); // Compute the mean shift // - It would be more accurate to weight the shift according to the number of input points shift /= shift_count; return shift; } // Do the actual work of loading, merging, and saving the point clouds // Case 1: Single-channel cloud. template <class PixelT> typename boost::enable_if<boost::is_same<PixelT, vw::PixelGray<float> >, void >::type do_work(Vector3 const& shift, Options const& opt) { // The spacing is selected to be compatible with the point2dem convention. const int spacing = asp::OrthoRasterizerView::max_subblock_size(); ImageViewRef<PixelT> merged_cloud = asp::form_point_cloud_composite<PixelT>(opt.pointcloud_files, spacing); vw_out() << "Writing image: " << opt.out_file << "\n"; bool has_georef = false; bool has_nodata = false; double nodata = -std::numeric_limits<float>::max(); // smallest float GeoReference georef; asp::block_write_gdal_image(opt.out_file, merged_cloud, has_georef, georef, has_nodata, nodata, opt, TerminalProgressCallback("asp", "\t--> Merging: ")); } // Case 2: Multi-channel cloud. template <class PixelT> typename boost::disable_if<boost::is_same<PixelT, vw::PixelGray<float> >, void >::type do_work(Vector3 const& shift, Options const& opt) { // The spacing is selected to be compatible with the point2dem convention. const int spacing = asp::OrthoRasterizerView::max_subblock_size(); ImageViewRef<PixelT> merged_cloud = asp::form_point_cloud_composite<PixelT>(opt.pointcloud_files, spacing); // See if we can pull a georeference from somewhere. Of course it will be wrong // when applied to the merged cloud, but it will at least have the correct datum // and projection. bool has_georef = false; cartography::GeoReference georef; for (size_t i = 0; i < opt.pointcloud_files.size(); i++){ cartography::GeoReference local_georef; if (read_georeference(local_georef, opt.pointcloud_files[i])){ georef = local_georef; has_georef = true; } } bool has_nodata = false; double nodata = -std::numeric_limits<float>::max(); // smallest float vw_out() << "Writing point cloud: " << opt.out_file << "\n"; // If shift != zero then this will cast the output data to type float. // Otherwise it will keep its data type. double point_cloud_rounding_error = 0.0; asp::block_write_approx_gdal_image ( opt.out_file, shift, point_cloud_rounding_error, merged_cloud, has_georef, georef, has_nodata, nodata, opt, TerminalProgressCallback("asp", "\t--> Merging: ")); } //----------------------------------------------------------------------------------- int main( int argc, char *argv[] ) { Options opt; //try { handle_arguments( argc, argv, opt ); // Determine the number of channels int num_channels = check_num_channels(opt.pointcloud_files); // Determine the output shift (if any) Vector3 shift = determine_output_shift(opt.pointcloud_files, opt); // The code has to branch here depending on the number of channels switch (num_channels) { // The input point clouds have their shift incorporated and are stored as doubles. // If the output file is stored as float, it needs to have a single shift value applied. case 1: do_work< vw::PixelGray<float> >(shift, opt); break; case 3: do_work<Vector3>(shift, opt); break; case 4: do_work<Vector4>(shift, opt); break; case 6: do_work<Vector6>(shift, opt); break; default: vw_throw( ArgumentErr() << "Unsupported number of channels!.\n" ); } //} ASP_STANDARD_CATCHES; return 0; } <|endoftext|>
<commit_before>#include "AnimSymLoader.h" #include "FilepathHelper.h" #include "EasyAnimLoader.h" #include "SpineAnimLoader.h" #include "ExtendSymFile.h" #include "BodymovinAnimLoader.h" #include <sprite2/AnimSymbol.h> #include <json/json.h> #include <fstream> #include <string.h> namespace gum { AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym, const SymbolLoader* sym_loader, const SpriteLoader* spr_loader) : m_sym(sym) , m_spr_loader(spr_loader) , m_sym_loader(sym_loader) { if (m_sym) { m_sym->AddReference(); } } AnimSymLoader::~AnimSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AnimSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } std::string dir = FilepathHelper::Dir(filepath); Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); int type = ExtendSymFile::GetType(val); switch (type) { case SYM_SPINE: { SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir, filepath); } break; case SYM_BODYMOVIN: { BodymovinAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir); } break; case SYM_UNKNOWN: { EasyAnimLoader loader(m_sym, m_spr_loader); loader.LoadJson(val, dir); } break; } m_sym->LoadCopy(); m_sym->BuildCurr(); } void AnimSymLoader::LoadBin(const simp::NodeAnimation* node) { EasyAnimLoader loader(m_sym, m_spr_loader); loader.LoadBin(node); m_sym->LoadCopy(); m_sym->BuildCurr(); } }<commit_msg>up s2<commit_after>#include "AnimSymLoader.h" #include "FilepathHelper.h" #include "EasyAnimLoader.h" #include "SpineAnimLoader.h" #include "ExtendSymFile.h" #include "BodymovinAnimLoader.h" #include <sprite2/AnimSymbol.h> #include <json/json.h> #include <fstream> #include <string.h> namespace gum { AnimSymLoader::AnimSymLoader(s2::AnimSymbol* sym, const SymbolLoader* sym_loader, const SpriteLoader* spr_loader) : m_sym(sym) , m_spr_loader(spr_loader) , m_sym_loader(sym_loader) { if (m_sym) { m_sym->AddReference(); } } AnimSymLoader::~AnimSymLoader() { if (m_sym) { m_sym->RemoveReference(); } } void AnimSymLoader::LoadJson(const std::string& filepath) { if (!m_sym) { return; } std::string dir = FilepathHelper::Dir(filepath); Json::Value val; Json::Reader reader; std::locale::global(std::locale("")); std::ifstream fin(filepath.c_str()); std::locale::global(std::locale("C")); reader.parse(fin, val); fin.close(); int type = ExtendSymFile::GetType(val); switch (type) { case SYM_SPINE: { SpineAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir, filepath); } break; case SYM_BODYMOVIN: { BodymovinAnimLoader loader(m_sym, m_sym_loader, m_spr_loader); loader.LoadJson(val, dir); } break; case SYM_UNKNOWN: { EasyAnimLoader loader(m_sym, m_spr_loader); loader.LoadJson(val, dir); } break; } m_sym->LoadCopy(); } void AnimSymLoader::LoadBin(const simp::NodeAnimation* node) { EasyAnimLoader loader(m_sym, m_spr_loader); loader.LoadBin(node); m_sym->LoadCopy(); } }<|endoftext|>
<commit_before>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include <iostream> #include <string> #include <votca/csg/topology.h> #include "gmxtopologyreader.h" #include <gromacs/fileio/tpxio.h> #include <gromacs/mdtypes/inputrec.h> #include <gromacs/topology/atoms.h> #include <gromacs/topology/topology.h> #include <gromacs/version.h> // this one is needed because of bool is defined in one of the headers included // by gmx #undef bool namespace votca { namespace csg { bool GMXTopologyReader::ReadTopology(std::string file, Topology &top) { gmx_mtop_t mtop; int natoms; // cleanup topology to store new data top.Cleanup(); t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(), &ir, gbox, &natoms, nullptr, nullptr, &mtop); size_t ifirstatom = 0; #if GMX_VERSION >= 20190000 size_t nmolblock = mtop.molblock.size(); #else size_t nmolblock = mtop.nmolblock; #endif for (size_t iblock = 0; iblock < nmolblock; ++iblock) { gmx_moltype_t *mol = &(mtop.moltype[mtop.molblock[iblock].type]); std::string molname = *(mol->name); Index res_offset = top.ResidueCount(); t_atoms *atoms = &(mol->atoms); for (Index i = 0; i < atoms->nres; i++) { top.CreateResidue(*(atoms->resinfo[i].name)); } for (Index imol = 0; imol < mtop.molblock[iblock].nmol; ++imol) { Molecule *mi = top.CreateMolecule(molname); #if GMX_VERSION >= 20190000 size_t natoms_mol = mtop.moltype[mtop.molblock[iblock].type].atoms.nr; #else size_t natoms_mol = mtop.molblock[iblock].natoms_mol; #endif // read the atoms for (size_t iatom = 0; iatom < natoms_mol; iatom++) { t_atom *a = &(atoms->atom[iatom]); std::string bead_type = *(atoms->atomtype[iatom]); if (!top.BeadTypeExist(bead_type)) { top.RegisterBeadType(bead_type); } Bead *bead = top.CreateBead(Bead::spherical, *(atoms->atomname[iatom]), bead_type, a->resind + res_offset, a->m, a->q); std::stringstream nm; nm << bead->getResnr() + 1 - res_offset << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } // add exclusions for (size_t iatom = 0; iatom < natoms_mol; iatom++) { // read exclusions t_blocka *excl = &(mol->excls); // insert exclusions std::list<Bead *> excl_list; for (Index k = excl->index[iatom]; k < excl->index[iatom + 1]; k++) { excl_list.push_back(top.getBead(excl->a[k] + ifirstatom)); } top.InsertExclusion(top.getBead(iatom + ifirstatom), excl_list); } ifirstatom += natoms_mol; } } Eigen::Matrix3d m; for (Index i = 0; i < 3; i++) { for (Index j = 0; j < 3; j++) { m(i, j) = gbox[j][i]; } } top.setBox(m); return true; } } // namespace csg } // namespace votca <commit_msg>gmxtopologyreader: compile fixes for gmx2021<commit_after>/* * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include <iostream> #include <string> #include <votca/csg/topology.h> #include "gmxtopologyreader.h" #include <gromacs/fileio/tpxio.h> #include <gromacs/mdtypes/inputrec.h> #include <gromacs/topology/atoms.h> #include <gromacs/topology/topology.h> #include <gromacs/version.h> // this one is needed because of bool is defined in one of the headers included // by gmx #undef bool namespace votca { namespace csg { bool GMXTopologyReader::ReadTopology(std::string file, Topology &top) { gmx_mtop_t mtop; int natoms; // cleanup topology to store new data top.Cleanup(); t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(), &ir, gbox, &natoms, nullptr, nullptr, &mtop); size_t ifirstatom = 0; #if GMX_VERSION >= 20190000 size_t nmolblock = mtop.molblock.size(); #else size_t nmolblock = mtop.nmolblock; #endif for (size_t iblock = 0; iblock < nmolblock; ++iblock) { gmx_moltype_t *mol = &(mtop.moltype[mtop.molblock[iblock].type]); std::string molname = *(mol->name); Index res_offset = top.ResidueCount(); t_atoms *atoms = &(mol->atoms); for (Index i = 0; i < atoms->nres; i++) { top.CreateResidue(*(atoms->resinfo[i].name)); } for (Index imol = 0; imol < mtop.molblock[iblock].nmol; ++imol) { Molecule *mi = top.CreateMolecule(molname); #if GMX_VERSION >= 20190000 size_t natoms_mol = mtop.moltype[mtop.molblock[iblock].type].atoms.nr; #else size_t natoms_mol = mtop.molblock[iblock].natoms_mol; #endif // read the atoms for (size_t iatom = 0; iatom < natoms_mol; iatom++) { t_atom *a = &(atoms->atom[iatom]); std::string bead_type = *(atoms->atomtype[iatom]); if (!top.BeadTypeExist(bead_type)) { top.RegisterBeadType(bead_type); } Bead *bead = top.CreateBead(Bead::spherical, *(atoms->atomname[iatom]), bead_type, a->resind + res_offset, a->m, a->q); std::stringstream nm; nm << bead->getResnr() + 1 - res_offset << ":" << top.getResidue(bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } // add exclusions for (size_t iatom = 0; iatom < natoms_mol; iatom++) { std::list<Bead *> excl_list; #if GMX_VERSION >= 20210000 gmx::ListOfLists<int> &excl = mol->excls; for (const Index k : excl[iatom]) { excl_list.push_back(top.getBead(k + ifirstatom)); } #else t_blocka *excl = &(mol->excls); for (Index k = excl->index[iatom]; k < excl->index[iatom + 1]; k++) { excl_list.push_back(top.getBead(excl->a[k] + ifirstatom)); } #endif top.InsertExclusion(top.getBead(iatom + ifirstatom), excl_list); } ifirstatom += natoms_mol; } } Eigen::Matrix3d m; for (Index i = 0; i < 3; i++) { for (Index j = 0; j < 3; j++) { m(i, j) = gbox[j][i]; } } top.setBox(m); return true; } } // namespace csg } // namespace votca <|endoftext|>
<commit_before>/** * \file * \brief ThreadCommon class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-11-13 */ #include "distortos/ThreadCommon.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include "distortos/synchronization/SignalsReceiverControlBlock.hpp" #include <cerrno> namespace distortos { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ ThreadCommon::ThreadCommon(StackStorageUniquePointer&& stackStorageUniquePointer, const size_t size, const uint8_t priority, const SchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) : ThreadCommon{{std::move(stackStorageUniquePointer), size, threadRunner, *this}, priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver} { } ThreadCommon::ThreadCommon(architecture::Stack&& stack, const uint8_t priority, const SchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) : threadControlBlock_{std::move(stack), priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver, *this}, joinSemaphore_{0} { } ThreadCommon::~ThreadCommon() { } int ThreadCommon::generateSignal(const uint8_t signalNumber) { auto& threadControlBlock = getThreadControlBlock(); const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return ENOTSUP; return signalsReceiverControlBlock->generateSignal(signalNumber, threadControlBlock); } uint8_t ThreadCommon::getEffectivePriority() const { return getThreadControlBlock().getEffectivePriority(); } SignalSet ThreadCommon::getPendingSignalSet() const { const auto signalsReceiverControlBlock = getThreadControlBlock().getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return SignalSet{SignalSet::empty}; architecture::InterruptMaskingLock interruptMaskingLock; return signalsReceiverControlBlock->getPendingSignalSet(); } uint8_t ThreadCommon::getPriority() const { return getThreadControlBlock().getPriority(); } SchedulingPolicy ThreadCommon::getSchedulingPolicy() const { return getThreadControlBlock().getSchedulingPolicy(); } ThreadState ThreadCommon::getState() const { return getThreadControlBlock().getState(); } int ThreadCommon::join() { if (&getThreadControlBlock() == &scheduler::getScheduler().getCurrentThreadControlBlock()) return EDEADLK; int ret; while ((ret = joinSemaphore_.wait()) == EINTR); return ret; } int ThreadCommon::queueSignal(const uint8_t signalNumber, const sigval value) { auto& threadControlBlock = getThreadControlBlock(); const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return ENOTSUP; return signalsReceiverControlBlock->queueSignal(signalNumber, value, threadControlBlock); } void ThreadCommon::setPriority(const uint8_t priority, const bool alwaysBehind) { getThreadControlBlock().setPriority(priority, alwaysBehind); } void ThreadCommon::setSchedulingPolicy(const SchedulingPolicy schedulingPolicy) { getThreadControlBlock().setSchedulingPolicy(schedulingPolicy); } int ThreadCommon::start() { if (getState() != ThreadState::New) return EINVAL; return scheduler::getScheduler().add(getThreadControlBlock()); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void ThreadCommon::terminationHook() { joinSemaphore_.post(); getThreadControlBlock().setList(nullptr); } } // namespace distortos <commit_msg>ThreadCommon::terminationHook(): don't clear list of control block<commit_after>/** * \file * \brief ThreadCommon class header * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-11-26 */ #include "distortos/ThreadCommon.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include "distortos/synchronization/SignalsReceiverControlBlock.hpp" #include <cerrno> namespace distortos { /*---------------------------------------------------------------------------------------------------------------------+ | public functions +---------------------------------------------------------------------------------------------------------------------*/ ThreadCommon::ThreadCommon(StackStorageUniquePointer&& stackStorageUniquePointer, const size_t size, const uint8_t priority, const SchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) : ThreadCommon{{std::move(stackStorageUniquePointer), size, threadRunner, *this}, priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver} { } ThreadCommon::ThreadCommon(architecture::Stack&& stack, const uint8_t priority, const SchedulingPolicy schedulingPolicy, scheduler::ThreadGroupControlBlock* const threadGroupControlBlock, SignalsReceiver* const signalsReceiver) : threadControlBlock_{std::move(stack), priority, schedulingPolicy, threadGroupControlBlock, signalsReceiver, *this}, joinSemaphore_{0} { } ThreadCommon::~ThreadCommon() { } int ThreadCommon::generateSignal(const uint8_t signalNumber) { auto& threadControlBlock = getThreadControlBlock(); const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return ENOTSUP; return signalsReceiverControlBlock->generateSignal(signalNumber, threadControlBlock); } uint8_t ThreadCommon::getEffectivePriority() const { return getThreadControlBlock().getEffectivePriority(); } SignalSet ThreadCommon::getPendingSignalSet() const { const auto signalsReceiverControlBlock = getThreadControlBlock().getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return SignalSet{SignalSet::empty}; architecture::InterruptMaskingLock interruptMaskingLock; return signalsReceiverControlBlock->getPendingSignalSet(); } uint8_t ThreadCommon::getPriority() const { return getThreadControlBlock().getPriority(); } SchedulingPolicy ThreadCommon::getSchedulingPolicy() const { return getThreadControlBlock().getSchedulingPolicy(); } ThreadState ThreadCommon::getState() const { return getThreadControlBlock().getState(); } int ThreadCommon::join() { if (&getThreadControlBlock() == &scheduler::getScheduler().getCurrentThreadControlBlock()) return EDEADLK; int ret; while ((ret = joinSemaphore_.wait()) == EINTR); return ret; } int ThreadCommon::queueSignal(const uint8_t signalNumber, const sigval value) { auto& threadControlBlock = getThreadControlBlock(); const auto signalsReceiverControlBlock = threadControlBlock.getSignalsReceiverControlBlock(); if (signalsReceiverControlBlock == nullptr) return ENOTSUP; return signalsReceiverControlBlock->queueSignal(signalNumber, value, threadControlBlock); } void ThreadCommon::setPriority(const uint8_t priority, const bool alwaysBehind) { getThreadControlBlock().setPriority(priority, alwaysBehind); } void ThreadCommon::setSchedulingPolicy(const SchedulingPolicy schedulingPolicy) { getThreadControlBlock().setSchedulingPolicy(schedulingPolicy); } int ThreadCommon::start() { if (getState() != ThreadState::New) return EINVAL; return scheduler::getScheduler().add(getThreadControlBlock()); } /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ void ThreadCommon::terminationHook() { joinSemaphore_.post(); } } // namespace distortos <|endoftext|>
<commit_before>#ifndef CAFFE_BLOB_HPP_ #define CAFFE_BLOB_HPP_ #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/syncedmem.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> class Blob { public: Blob() : data_(), diff_(), num_(0), channels_(0), height_(0), width_(0), count_(0) {} explicit Blob(const int num, const int channels, const int height, const int width); void Reshape(const int num, const int channels, const int height, const int width); void ReshapeLike(const Blob& other); inline int num() const { return num_; } inline int channels() const { return channels_; } inline int height() const { return height_; } inline int width() const { return width_; } inline int count() const { return count_; } inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0) const { CHECK_GE(n, 0); CHECK_LE(n, num_); CHECK_GE(channels_, 0); CHECK_LE(c, channels_); CHECK_GE(height_, 0); CHECK_LE(h, height_); CHECK_GE(width_, 0); CHECK_LE(w, width_); return ((n * channels_ + c) * height_ + h) * width_ + w; } // Copy from source. If copy_diff is false, we copy the data; if copy_diff // is true, we copy the diff. void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false, bool reshape = false); inline Dtype data_at(const int n, const int c, const int h, const int w) const { return *(cpu_data() + offset(n, c, h, w)); } inline Dtype diff_at(const int n, const int c, const int h, const int w) const { return *(cpu_diff() + offset(n, c, h, w)); } inline const shared_ptr<SyncedMemory>& data() const { CHECK(data_); return data_; } inline const shared_ptr<SyncedMemory>& diff() const { CHECK(diff_); return diff_; } const Dtype* cpu_data() const; void set_cpu_data(Dtype* data); const Dtype* gpu_data() const; const Dtype* cpu_diff() const; const Dtype* gpu_diff() const; Dtype* mutable_cpu_data(); Dtype* mutable_gpu_data(); Dtype* mutable_cpu_diff(); Dtype* mutable_gpu_diff(); void Update(); void FromProto(const BlobProto& proto); void ToProto(BlobProto* proto, bool write_diff = false) const; // Compute the sum of absolute values (L1 norm) of the data or diff. Dtype asum_data() const; Dtype asum_diff() const; // Set the data_/diff_ shared_ptr to point to the SyncedMemory holding the // data_/diff_ of Blob other -- useful in layers which simply perform a copy // in their forward or backward pass. // This deallocates the SyncedMemory holding this blob's data/diff, as // shared_ptr calls its destructor when reset with the = operator. void ShareData(const Blob& other); void ShareDiff(const Blob& other); protected: shared_ptr<SyncedMemory> data_; shared_ptr<SyncedMemory> diff_; int num_; int channels_; int height_; int width_; int count_; DISABLE_COPY_AND_ASSIGN(Blob); }; // class Blob } // namespace caffe #endif // CAFFE_BLOB_HPP_ <commit_msg>blob.hpp: a little Doxygen-style documentation<commit_after>#ifndef CAFFE_BLOB_HPP_ #define CAFFE_BLOB_HPP_ #include "caffe/common.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/syncedmem.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { /** * @brief A wrapper around SyncedMemory holders serving as the basic * computational unit through which Layer%s, Net%s, and Solver%s * interact. * * TODO(dox): more thorough description. */ template <typename Dtype> class Blob { public: Blob() : data_(), diff_(), num_(0), channels_(0), height_(0), width_(0), count_(0) {} explicit Blob(const int num, const int channels, const int height, const int width); void Reshape(const int num, const int channels, const int height, const int width); void ReshapeLike(const Blob& other); inline int num() const { return num_; } inline int channels() const { return channels_; } inline int height() const { return height_; } inline int width() const { return width_; } inline int count() const { return count_; } inline int offset(const int n, const int c = 0, const int h = 0, const int w = 0) const { CHECK_GE(n, 0); CHECK_LE(n, num_); CHECK_GE(channels_, 0); CHECK_LE(c, channels_); CHECK_GE(height_, 0); CHECK_LE(h, height_); CHECK_GE(width_, 0); CHECK_LE(w, width_); return ((n * channels_ + c) * height_ + h) * width_ + w; } /** * @brief Copy from a source Blob. * * @param source the Blob to copy from * @param copy_diff if false, copy the data; if true, copy the diff * @param reshape if false, require this Blob to be pre-shaped to the shape * of other (and die otherwise); if true, Reshape this Blob to other's * shape if necessary */ void CopyFrom(const Blob<Dtype>& source, bool copy_diff = false, bool reshape = false); inline Dtype data_at(const int n, const int c, const int h, const int w) const { return *(cpu_data() + offset(n, c, h, w)); } inline Dtype diff_at(const int n, const int c, const int h, const int w) const { return *(cpu_diff() + offset(n, c, h, w)); } inline const shared_ptr<SyncedMemory>& data() const { CHECK(data_); return data_; } inline const shared_ptr<SyncedMemory>& diff() const { CHECK(diff_); return diff_; } const Dtype* cpu_data() const; void set_cpu_data(Dtype* data); const Dtype* gpu_data() const; const Dtype* cpu_diff() const; const Dtype* gpu_diff() const; Dtype* mutable_cpu_data(); Dtype* mutable_gpu_data(); Dtype* mutable_cpu_diff(); Dtype* mutable_gpu_diff(); void Update(); void FromProto(const BlobProto& proto); void ToProto(BlobProto* proto, bool write_diff = false) const; /// @brief Compute the sum of absolute values (L1 norm) of the data. Dtype asum_data() const; /// @brief Compute the sum of absolute values (L1 norm) of the diff. Dtype asum_diff() const; /** * @brief Set the data_ shared_ptr to point to the SyncedMemory holding the * data_ of Blob other -- useful in Layer&s which simply perform a copy * in their Forward pass. * * This deallocates the SyncedMemory holding this Blob's data_, as * shared_ptr calls its destructor when reset with the "=" operator. */ void ShareData(const Blob& other); /** * @brief Set the diff_ shared_ptr to point to the SyncedMemory holding the * diff_ of Blob other -- useful in Layer&s which simply perform a copy * in their Forward pass. * * This deallocates the SyncedMemory holding this Blob's diff_, as * shared_ptr calls its destructor when reset with the "=" operator. */ void ShareDiff(const Blob& other); protected: shared_ptr<SyncedMemory> data_; shared_ptr<SyncedMemory> diff_; int num_; int channels_; int height_; int width_; int count_; DISABLE_COPY_AND_ASSIGN(Blob); }; // class Blob } // namespace caffe #endif // CAFFE_BLOB_HPP_ <|endoftext|>
<commit_before>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" #define W SkIntToScalar(80) #define H SkIntToScalar(60) typedef void (*PaintProc)(SkPaint*); static void identity_paintproc(SkPaint* paint) {} static void gradient_paintproc(SkPaint* paint) { const SkColor colors[] = { SK_ColorGREEN, SK_ColorBLUE }; const SkPoint pts[] = { { 0, 0 }, { W, H } }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode); paint->setShader(s)->unref(); } typedef void (*Proc)(SkCanvas*, const SkPaint&); static void draw_hair(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(0); canvas->drawLine(0, 0, W, H, p); } static void draw_thick(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(H/5); canvas->drawLine(0, 0, W, H, p); } static void draw_rect(SkCanvas* canvas, const SkPaint& paint) { canvas->drawRect(SkRect::MakeWH(W, H), paint); } static void draw_oval(SkCanvas* canvas, const SkPaint& paint) { canvas->drawOval(SkRect::MakeWH(W, H), paint); } static void draw_text(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setTextSize(H/4); canvas->drawText("Hamburge", 8, 0, H*2/3, p); } class SrcModeGM : public skiagm::GM { SkPath fPath; public: SrcModeGM() { this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("srcmode"); } virtual SkISize onISize() { return SkISize::Make(640, 760); } virtual void onDraw(SkCanvas* canvas) { canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); SkPaint paint; paint.setColor(0x80FF0000); const Proc procs[] = { draw_hair, draw_thick, draw_rect, draw_oval, draw_text }; const SkXfermode::Mode modes[] = { SkXfermode::kSrcOver_Mode, SkXfermode::kSrc_Mode, SkXfermode::kClear_Mode }; const PaintProc paintProcs[] = { identity_paintproc, gradient_paintproc }; for (int aa = 0; aa <= 1; ++aa) { paint.setAntiAlias(SkToBool(aa)); canvas->save(); for (size_t i = 0; i < SK_ARRAY_COUNT(paintProcs); ++i) { paintProcs[i](&paint); for (size_t x = 0; x < SK_ARRAY_COUNT(modes); ++x) { paint.setXfermodeMode(modes[x]); canvas->save(); for (size_t y = 0; y < SK_ARRAY_COUNT(procs); ++y) { procs[y](canvas, paint); canvas->translate(0, H * 5 / 4); } canvas->restore(); canvas->translate(W * 5 / 4, 0); } } canvas->restore(); canvas->translate(0, (H * 5 / 4) * SK_ARRAY_COUNT(procs)); } } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM(return new SrcModeGM;) <commit_msg>draw offscreen so we can see the alpha-channel we are writing todo: know when to use a gpu-surface<commit_after>/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkGradientShader.h" #include "SkSurface.h" #define W SkIntToScalar(80) #define H SkIntToScalar(60) typedef void (*PaintProc)(SkPaint*); static void identity_paintproc(SkPaint* paint) {} static void gradient_paintproc(SkPaint* paint) { const SkColor colors[] = { SK_ColorGREEN, SK_ColorBLUE }; const SkPoint pts[] = { { 0, 0 }, { W, H } }; SkShader* s = SkGradientShader::CreateLinear(pts, colors, NULL, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode); paint->setShader(s)->unref(); } typedef void (*Proc)(SkCanvas*, const SkPaint&); static void draw_hair(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(0); canvas->drawLine(0, 0, W, H, p); } static void draw_thick(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setStrokeWidth(H/5); canvas->drawLine(0, 0, W, H, p); } static void draw_rect(SkCanvas* canvas, const SkPaint& paint) { canvas->drawRect(SkRect::MakeWH(W, H), paint); } static void draw_oval(SkCanvas* canvas, const SkPaint& paint) { canvas->drawOval(SkRect::MakeWH(W, H), paint); } static void draw_text(SkCanvas* canvas, const SkPaint& paint) { SkPaint p(paint); p.setTextSize(H/4); canvas->drawText("Hamburge", 8, 0, H*2/3, p); } class SrcModeGM : public skiagm::GM { SkPath fPath; public: SrcModeGM() { this->setBGColor(SK_ColorBLACK); } protected: virtual SkString onShortName() { return SkString("srcmode"); } virtual SkISize onISize() { return SkISize::Make(640, 760); } void drawContent(SkCanvas* canvas) { canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); SkPaint paint; paint.setColor(0x80FF0000); const Proc procs[] = { draw_hair, draw_thick, draw_rect, draw_oval, draw_text }; const SkXfermode::Mode modes[] = { SkXfermode::kSrcOver_Mode, SkXfermode::kSrc_Mode, SkXfermode::kClear_Mode }; const PaintProc paintProcs[] = { identity_paintproc, gradient_paintproc }; for (int aa = 0; aa <= 1; ++aa) { paint.setAntiAlias(SkToBool(aa)); canvas->save(); for (size_t i = 0; i < SK_ARRAY_COUNT(paintProcs); ++i) { paintProcs[i](&paint); for (size_t x = 0; x < SK_ARRAY_COUNT(modes); ++x) { paint.setXfermodeMode(modes[x]); canvas->save(); for (size_t y = 0; y < SK_ARRAY_COUNT(procs); ++y) { procs[y](canvas, paint); canvas->translate(0, H * 5 / 4); } canvas->restore(); canvas->translate(W * 5 / 4, 0); } } canvas->restore(); canvas->translate(0, (H * 5 / 4) * SK_ARRAY_COUNT(procs)); } } static SkSurface* compat_surface(SkCanvas* canvas, const SkISize& size) { SkImage::Info info = { size.width(), size.height(), SkImage::kPMColor_ColorType, SkImage::kPremul_AlphaType }; return SkSurface::NewRaster(info); } virtual void onDraw(SkCanvas* canvas) { SkAutoTUnref<SkSurface> surf(compat_surface(canvas, this->getISize())); surf->getCanvas()->drawColor(SK_ColorWHITE); this->drawContent(surf->getCanvas()); surf->draw(canvas, 0, 0, NULL); } private: typedef skiagm::GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// DEF_GM(return new SrcModeGM;) <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <activemq/connector/openwire/utils/BooleanStream.h> using namespace std; using namespace activemq; using namespace activemq::io; using namespace activemq::exceptions; using namespace activemq::connector; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::utils; /////////////////////////////////////////////////////////////////////////////// BooleanStream::BooleanStream() { this->arrayLimit = 0; this->arrayPos = 0; this->bytePos = 0; // Reserve 1K this->data.resize( 1000, 0 ); } /////////////////////////////////////////////////////////////////////////////// BooleanStream::~BooleanStream() {} /////////////////////////////////////////////////////////////////////////////// bool BooleanStream::readBoolean() throw ( IOException ) { try { //assert arrayPos <= arrayLimit; unsigned char b = data[arrayPos]; bool rc = ( ( b >> bytePos ) & 0x01 ) != 0; bytePos++; if( bytePos >= 8 ) { bytePos = 0; arrayPos++; } return rc; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::writeBoolean( bool value ) throw ( IOException ) { try{ if( bytePos == 0 ) { arrayLimit++; if( (size_t)arrayLimit >= data.capacity() ) { // re-grow the array if necessary data.resize( data.size() * 2 ); } } if( value ) { data[arrayPos] |= ( 0x01 << bytePos ); } bytePos++; // Wrap around when we hit the next byte if( bytePos >= 8 ) { bytePos=0; arrayPos++; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::marshal( DataOutputStream* dataOut ) throw ( IOException ) { try { if( arrayLimit < 64 ) { dataOut->writeByte( (unsigned char)arrayLimit ); } else if( arrayLimit < 256 ) { // max value of unsigned char dataOut->writeByte( 0xC0 ); dataOut->writeByte( (unsigned char)arrayLimit ); } else { dataOut->writeByte( 0x80 ); dataOut->writeShort( arrayLimit ); } // Dump the payload dataOut->write( &data[0], arrayLimit ); clear(); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::marshal( std::vector< unsigned char >& dataOut ) { try{ if( arrayLimit < 64 ) { dataOut.push_back( ( unsigned char ) arrayLimit ); } else if( arrayLimit < 256 ) { // max value of unsigned byte dataOut.push_back( ( unsigned char ) 0xC0 ); dataOut.push_back( ( unsigned char ) arrayLimit ); } else { dataOut.push_back( ( unsigned char ) 0x80 ); dataOut.push_back( arrayLimit >> 8 ); // High Byte dataOut.push_back( arrayLimit & 0xFF ); // Low Byte } // Insert all data from data into the passed buffer dataOut.insert( dataOut.begin(), &data[0], &data[arrayLimit-1] ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::unmarshal( DataInputStream* dataIn ) throw ( IOException ) { try{ arrayLimit = (short)( dataIn->readByte() & 0xFF ); if ( arrayLimit == 0xC0 ) { arrayLimit = (short)( dataIn->readByte() & 0xFF ); } else if( arrayLimit == 0x80 ) { arrayLimit = dataIn->readShort(); } // Reserve space all at once if needed. if( data.capacity() < (size_t)arrayLimit ) { data.reserve( arrayLimit ); } // Make sure we can accomodate all the data. data.resize( arrayLimit ); // Make sure we get all the data we are expecting dataIn->readFully( &data[0], 0, arrayLimit ); clear(); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::clear() { arrayPos = 0; bytePos = 0; } /////////////////////////////////////////////////////////////////////////////// int BooleanStream::marshalledSize() { if( arrayLimit < 64 ) { return 1 + arrayLimit; } else if( arrayLimit < 256 ) { return 2 + arrayLimit; } else { return 3 + arrayLimit; } } <commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-93<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <activemq/connector/openwire/utils/BooleanStream.h> using namespace std; using namespace activemq; using namespace activemq::io; using namespace activemq::exceptions; using namespace activemq::connector; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::utils; /////////////////////////////////////////////////////////////////////////////// BooleanStream::BooleanStream() { this->arrayLimit = 0; this->arrayPos = 0; this->bytePos = 0; // Reserve 1K this->data.resize( 1000, 0 ); } /////////////////////////////////////////////////////////////////////////////// BooleanStream::~BooleanStream() {} /////////////////////////////////////////////////////////////////////////////// bool BooleanStream::readBoolean() throw ( IOException ) { try { //assert arrayPos <= arrayLimit; unsigned char b = data[arrayPos]; bool rc = ( ( b >> bytePos ) & 0x01 ) != 0; bytePos++; if( bytePos >= 8 ) { bytePos = 0; arrayPos++; } return rc; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::writeBoolean( bool value ) throw ( IOException ) { try{ if( bytePos == 0 ) { arrayLimit++; if( (size_t)arrayLimit >= data.capacity() ) { // re-grow the array if necessary data.resize( data.size() * 2 ); } } if( value ) { data[arrayPos] |= ( 0x01 << bytePos ); } bytePos++; // Wrap around when we hit the next byte if( bytePos >= 8 ) { bytePos=0; arrayPos++; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::marshal( DataOutputStream* dataOut ) throw ( IOException ) { try { if( arrayLimit < 64 ) { dataOut->writeByte( (unsigned char)arrayLimit ); } else if( arrayLimit < 256 ) { // max value of unsigned char dataOut->writeByte( 0xC0 ); dataOut->writeByte( (unsigned char)arrayLimit ); } else { dataOut->writeByte( 0x80 ); dataOut->writeShort( arrayLimit ); } // Dump the payload dataOut->write( &data[0], arrayLimit ); clear(); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::marshal( std::vector< unsigned char >& dataOut ) { try{ if( arrayLimit < 64 ) { dataOut.push_back( ( unsigned char ) arrayLimit ); } else if( arrayLimit < 256 ) { // max value of unsigned byte dataOut.push_back( ( unsigned char ) 0xC0 ); dataOut.push_back( ( unsigned char ) arrayLimit ); } else { dataOut.push_back( ( unsigned char ) 0x80 ); dataOut.push_back( arrayLimit >> 8 ); // High Byte dataOut.push_back( arrayLimit & 0xFF ); // Low Byte } // Insert all data from data into the passed buffer std::back_insert_iterator< std::vector<unsigned char> > iter( dataOut ); std::copy( &data[0], &data[arrayLimit-1], iter ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::unmarshal( DataInputStream* dataIn ) throw ( IOException ) { try{ arrayLimit = (short)( dataIn->readByte() & 0xFF ); if ( arrayLimit == 0xC0 ) { arrayLimit = (short)( dataIn->readByte() & 0xFF ); } else if( arrayLimit == 0x80 ) { arrayLimit = dataIn->readShort(); } // Make sure we can accomodate all the data. data.resize( arrayLimit ); // Make sure we get all the data we are expecting dataIn->readFully( &data[0], 0, arrayLimit ); clear(); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } /////////////////////////////////////////////////////////////////////////////// void BooleanStream::clear() { arrayPos = 0; bytePos = 0; } /////////////////////////////////////////////////////////////////////////////// int BooleanStream::marshalledSize() { if( arrayLimit < 64 ) { return 1 + arrayLimit; } else if( arrayLimit < 256 ) { return 2 + arrayLimit; } else { return 3 + arrayLimit; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsScrollBarManager.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2008-04-03 14:35:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_SLIDESORTER_SLIDE_SORTER_SCROLL_BAR_MANAGER_HXX #define SD_SLIDESORTER_SLIDE_SORTER_SCROLL_BAR_MANAGER_HXX #include <tools/link.hxx> #include <tools/gen.hxx> #include <vcl/timer.hxx> #include <boost/shared_ptr.hpp> class Point; class Rectangle; class ScrollBar; class ScrollBarBox; class Window; namespace sd { class Window; } namespace sd { namespace slidesorter { class SlideSorter; } } namespace sd { namespace slidesorter { namespace controller { /** Manage the horizontal and vertical scroll bars. Listen for events, set their sizes, place them in the window, determine their visibilities. <p>Handle auto scrolling, i.e. the scrolling of the window when the mouse comes near the window border while dragging a selection.</p> <p>In order to make the slide sorter be used in the task pane with its own vertical scrollbars the vertical scrollbar of the use of the slide sorter is optional. When using it the available area in a window is used and the vertical scrollbar is displayed when that area is not large enough. When the vertical scrollbar is not used then the available area is assumed to be modifiable. In that case the PlaceScrollBars() method may return an area larger than the one given.<p> */ class ScrollBarManager { public: /** Create a new scroll bar manager that manages three controls: the horizontal scroll bar, the vertical scroll bar, and the little window that fills the gap at the bottom right corner that is left between the two scroll bars. Call LateInitialization() after constructing a new object. */ ScrollBarManager (SlideSorter& rSlideSorter); ~ScrollBarManager (void); /** Call this method after constructing a new object of this class. */ void LateInitialization (void); /** Register listeners at the scroll bars. This method is called after startup of a new slide sorter object or after a reactivation of a slide sorter that for example is taken from a cache. */ void Connect (void); /** Remove listeners from the scroll bars. This method is called whent the slide sorter is destroyed or when it is suspended, e.g. put into a cache for later reuse. */ void Disconnect (void); /** Set up the scroll bar, i.e. thumb size and position. Call this method when the content of the browser window changed, i.e. pages were inserted or deleted, the layout or the zoom factor has changed. @param bResetThumbPosition When <TRUE/> then set the thumb position to position 0. This is done when e.g. switching between master page mode and draw mode. @param bScrollToCurrentPosition When <TRUE/> then scroll the window to the new offset that is defined by the scroll bars. Otherwise the new offset is simply set and the whole window is repainted. */ void UpdateScrollBars ( bool bResetThumbPosition = false, bool bScrollToCurrentPosition = true); /** Place the scroll bars inside the given area. When the available area is not large enough for the content to display the resulting behaviour depends on the mbUseVerticalScrollBar flag. When it is set to true then a vertical scroll bar is shown. Otherwise the height of the returned area is enlarged so that the content fits into it. @param rAvailableArea The scroll bars will be placed inside this rectangle. It is expected to be given in pixel relative to its parent. @return Returns the space that remains after the scroll bars are placed. When the mbUseVerticalScrollBar flag is false then the returned rectangle may be larger than the given one. */ Rectangle PlaceScrollBars (const Rectangle& rAvailableArea); /** Update the vertical scroll bar so that the visible area has the given top value. */ void SetTop (const sal_Int32 nTop); /** Update the horizontal scroll bar so that the visible area has the given left value. */ void SetLeft (const sal_Int32 nLeft); /** Return the width of the vertical scroll bar, which--when shown--should be fixed in contrast to its height. @return Returns 0 when the vertical scroll bar is not shown or does not exist, otherwise its width in pixel is returned. */ int GetVerticalScrollBarWidth (void) const; /** Return the height of the horizontal scroll bar, which--when shown--should be fixed in contrast to its width. @return Returns 0 when the vertical scroll bar is not shown or does not exist, otherwise its height in pixel is returned. */ int GetHorizontalScrollBarHeight (void) const; /** Call this method to scroll a window while the mouse is in dragging a selection. If the mouse is near the window border or is outside the window then scroll the window accordingly. @return When the window is scrolled then this method returns <TRUE/>. When the window is not changed then <FALSE/> is returned. */ bool AutoScroll (const Point& rMouseWindowPosition); void StopAutoScroll (void); private: SlideSorter& mrSlideSorter; /** The horizontal scroll bar. Note that is used but not owned by objects of this class. It is given to the constructor. */ ::boost::shared_ptr<ScrollBar> mpHorizontalScrollBar; /** The vertical scroll bar. Note that is used but not owned by objects of this class. It is given to the constructor. */ ::boost::shared_ptr<ScrollBar> mpVerticalScrollBar; /// Relative horizontal position of the visible area in the view. double mnHorizontalPosition; /// Relative vertical position of the visible area in the view. double mnVerticalPosition; /** The width and height of the border at the inside of the window which when entered while in drag mode leads to a scrolling of the window. */ Size maScrollBorder; double mnHorizontalScrollFactor; double mnVerticalScrollFactor; /** The only task of this little window is to paint the little square at the bottom right corner left by the two scroll bars (when both are visible). */ ::boost::shared_ptr<ScrollBarBox> mpScrollBarFiller; /** The auto scroll timer is used for keep scrolling the window when the mouse reaches its border while dragging a selection. When the mouse is not moved the timer issues events to keep scrolling. */ Timer maAutoScrollTimer; Size maAutoScrollOffset; /** The content window is the one whose view port is controlled by the scroll bars. */ ::boost::shared_ptr<sd::Window> mpContentWindow; void SetWindowOrigin ( double nHorizontalPosition, double nVerticalPosition); /** Determine the visibility of the scroll bars so that the window content is not clipped in any dimension without showing a scroll bar. @param rAvailableArea The area in which the scroll bars, the scroll bar filler, and the SlideSorterView will be placed. @return The area that is enclosed by the scroll bars is returned. It will be filled with the SlideSorterView. */ Rectangle DetermineScrollBarVisibilities (const Rectangle& rAvailableArea); /** Typically called by DetermineScrollBarVisibilities() this method tests a specific configuration of the two scroll bars being visible or hidden. @return When the window content can be shown with only being clipped in an orientation where the scroll bar would be shown then <TRUE/> is returned. */ bool TestScrollBarVisibilities ( bool bHorizontalScrollBarVisible, bool bVerticalScrollBarVisible, const Rectangle& rAvailableArea); void CalcAutoScrollOffset (const Point& rMouseWindowPosition); bool RepeatAutoScroll (void); DECL_LINK(HorizontalScrollBarHandler, ScrollBar*); DECL_LINK(VerticalScrollBarHandler, ScrollBar*); DECL_LINK(AutoScrollTimeoutHandler, Timer*); void PlaceHorizontalScrollBar (const Rectangle& aArea); void PlaceVerticalScrollBar (const Rectangle& aArea); void PlaceFiller (const Rectangle& aArea); /** Make the height of the content window larger or smaller, so that the content size fits exactly in. This is achieved by changing the size of the parent window and rely on the resulting resize. */ void AdaptWindowSize (const Rectangle& rArea); }; } } } // end of namespace ::sd::slidesorter::controller #endif <commit_msg>INTEGRATION: CWS changefileheader (1.6.136); FILE MERGED 2008/03/31 13:58:49 rt 1.6.136.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlsScrollBarManager.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SD_SLIDESORTER_SLIDE_SORTER_SCROLL_BAR_MANAGER_HXX #define SD_SLIDESORTER_SLIDE_SORTER_SCROLL_BAR_MANAGER_HXX #include <tools/link.hxx> #include <tools/gen.hxx> #include <vcl/timer.hxx> #include <boost/shared_ptr.hpp> class Point; class Rectangle; class ScrollBar; class ScrollBarBox; class Window; namespace sd { class Window; } namespace sd { namespace slidesorter { class SlideSorter; } } namespace sd { namespace slidesorter { namespace controller { /** Manage the horizontal and vertical scroll bars. Listen for events, set their sizes, place them in the window, determine their visibilities. <p>Handle auto scrolling, i.e. the scrolling of the window when the mouse comes near the window border while dragging a selection.</p> <p>In order to make the slide sorter be used in the task pane with its own vertical scrollbars the vertical scrollbar of the use of the slide sorter is optional. When using it the available area in a window is used and the vertical scrollbar is displayed when that area is not large enough. When the vertical scrollbar is not used then the available area is assumed to be modifiable. In that case the PlaceScrollBars() method may return an area larger than the one given.<p> */ class ScrollBarManager { public: /** Create a new scroll bar manager that manages three controls: the horizontal scroll bar, the vertical scroll bar, and the little window that fills the gap at the bottom right corner that is left between the two scroll bars. Call LateInitialization() after constructing a new object. */ ScrollBarManager (SlideSorter& rSlideSorter); ~ScrollBarManager (void); /** Call this method after constructing a new object of this class. */ void LateInitialization (void); /** Register listeners at the scroll bars. This method is called after startup of a new slide sorter object or after a reactivation of a slide sorter that for example is taken from a cache. */ void Connect (void); /** Remove listeners from the scroll bars. This method is called whent the slide sorter is destroyed or when it is suspended, e.g. put into a cache for later reuse. */ void Disconnect (void); /** Set up the scroll bar, i.e. thumb size and position. Call this method when the content of the browser window changed, i.e. pages were inserted or deleted, the layout or the zoom factor has changed. @param bResetThumbPosition When <TRUE/> then set the thumb position to position 0. This is done when e.g. switching between master page mode and draw mode. @param bScrollToCurrentPosition When <TRUE/> then scroll the window to the new offset that is defined by the scroll bars. Otherwise the new offset is simply set and the whole window is repainted. */ void UpdateScrollBars ( bool bResetThumbPosition = false, bool bScrollToCurrentPosition = true); /** Place the scroll bars inside the given area. When the available area is not large enough for the content to display the resulting behaviour depends on the mbUseVerticalScrollBar flag. When it is set to true then a vertical scroll bar is shown. Otherwise the height of the returned area is enlarged so that the content fits into it. @param rAvailableArea The scroll bars will be placed inside this rectangle. It is expected to be given in pixel relative to its parent. @return Returns the space that remains after the scroll bars are placed. When the mbUseVerticalScrollBar flag is false then the returned rectangle may be larger than the given one. */ Rectangle PlaceScrollBars (const Rectangle& rAvailableArea); /** Update the vertical scroll bar so that the visible area has the given top value. */ void SetTop (const sal_Int32 nTop); /** Update the horizontal scroll bar so that the visible area has the given left value. */ void SetLeft (const sal_Int32 nLeft); /** Return the width of the vertical scroll bar, which--when shown--should be fixed in contrast to its height. @return Returns 0 when the vertical scroll bar is not shown or does not exist, otherwise its width in pixel is returned. */ int GetVerticalScrollBarWidth (void) const; /** Return the height of the horizontal scroll bar, which--when shown--should be fixed in contrast to its width. @return Returns 0 when the vertical scroll bar is not shown or does not exist, otherwise its height in pixel is returned. */ int GetHorizontalScrollBarHeight (void) const; /** Call this method to scroll a window while the mouse is in dragging a selection. If the mouse is near the window border or is outside the window then scroll the window accordingly. @return When the window is scrolled then this method returns <TRUE/>. When the window is not changed then <FALSE/> is returned. */ bool AutoScroll (const Point& rMouseWindowPosition); void StopAutoScroll (void); private: SlideSorter& mrSlideSorter; /** The horizontal scroll bar. Note that is used but not owned by objects of this class. It is given to the constructor. */ ::boost::shared_ptr<ScrollBar> mpHorizontalScrollBar; /** The vertical scroll bar. Note that is used but not owned by objects of this class. It is given to the constructor. */ ::boost::shared_ptr<ScrollBar> mpVerticalScrollBar; /// Relative horizontal position of the visible area in the view. double mnHorizontalPosition; /// Relative vertical position of the visible area in the view. double mnVerticalPosition; /** The width and height of the border at the inside of the window which when entered while in drag mode leads to a scrolling of the window. */ Size maScrollBorder; double mnHorizontalScrollFactor; double mnVerticalScrollFactor; /** The only task of this little window is to paint the little square at the bottom right corner left by the two scroll bars (when both are visible). */ ::boost::shared_ptr<ScrollBarBox> mpScrollBarFiller; /** The auto scroll timer is used for keep scrolling the window when the mouse reaches its border while dragging a selection. When the mouse is not moved the timer issues events to keep scrolling. */ Timer maAutoScrollTimer; Size maAutoScrollOffset; /** The content window is the one whose view port is controlled by the scroll bars. */ ::boost::shared_ptr<sd::Window> mpContentWindow; void SetWindowOrigin ( double nHorizontalPosition, double nVerticalPosition); /** Determine the visibility of the scroll bars so that the window content is not clipped in any dimension without showing a scroll bar. @param rAvailableArea The area in which the scroll bars, the scroll bar filler, and the SlideSorterView will be placed. @return The area that is enclosed by the scroll bars is returned. It will be filled with the SlideSorterView. */ Rectangle DetermineScrollBarVisibilities (const Rectangle& rAvailableArea); /** Typically called by DetermineScrollBarVisibilities() this method tests a specific configuration of the two scroll bars being visible or hidden. @return When the window content can be shown with only being clipped in an orientation where the scroll bar would be shown then <TRUE/> is returned. */ bool TestScrollBarVisibilities ( bool bHorizontalScrollBarVisible, bool bVerticalScrollBarVisible, const Rectangle& rAvailableArea); void CalcAutoScrollOffset (const Point& rMouseWindowPosition); bool RepeatAutoScroll (void); DECL_LINK(HorizontalScrollBarHandler, ScrollBar*); DECL_LINK(VerticalScrollBarHandler, ScrollBar*); DECL_LINK(AutoScrollTimeoutHandler, Timer*); void PlaceHorizontalScrollBar (const Rectangle& aArea); void PlaceVerticalScrollBar (const Rectangle& aArea); void PlaceFiller (const Rectangle& aArea); /** Make the height of the content window larger or smaller, so that the content size fits exactly in. This is achieved by changing the size of the parent window and rely on the resulting resize. */ void AdaptWindowSize (const Rectangle& rArea); }; } } } // end of namespace ::sd::slidesorter::controller #endif <|endoftext|>
<commit_before>/* Copyright (c) 2013 "Naftoreiclag" https://github.com/Naftoreiclag * * Distributed under the MIT License (http://opensource.org/licenses/mit-license.html) * See accompanying file LICENSE */ #include "util/Sysout.h" #include "Game.h" #include "Luastuff.h" #include "Filestuff.h" #include "Potato.h" #include <iostream> // Print lua errors (Gee, this place is becoming a mess...) void printLuaErrors(lua_State* luaState, int luaScript) { // Does something if(luaScript != 0) { // Print the error message std::cout << lua_tostring(luaState, -1) << std::endl; // Removes that error message lua_pop(luaState, 1); } } // Initialize void initialize() { // Set the display width to 80 chars long (for word-wrap) Sysout::setDisplayWidth(80); // If we are in debug mode, then print that #ifdef DEBUG Sysout::println("Running in DEBUG mode!"); Sysout::printDictionaryEntries(); #endif } // Run void run() { bool running = true; while(running) { // Put a title screen here // Run a game Game* game = new Game(); game->load(); game->run(); delete game; } } // Finalize void finalize() { } int main() { Potato potato; lua_State* luaState; luaState = luaL_newstate(); luaL_openlibs(luaState); potato.luaify(luaState); int luaScript = luaL_dofile(luaState, getLocalFilePath("potatoProp.lua")); printLuaErrors(luaState, luaScript); Sysout::println(potato.tastiness); Sysout::println(potato.bounciness); // Initialize initialize(); // Run run(); // Clean-up finalize(); // Died quietly return 0; } <commit_msg>Closed luaState<commit_after>/* Copyright (c) 2013 "Naftoreiclag" https://github.com/Naftoreiclag * * Distributed under the MIT License (http://opensource.org/licenses/mit-license.html) * See accompanying file LICENSE */ #include "util/Sysout.h" #include "Game.h" #include "Luastuff.h" #include "Filestuff.h" #include "Potato.h" #include <iostream> // Print lua errors (Gee, this place is becoming a mess...) void printLuaErrors(lua_State* luaState, int luaScript) { // Does something if(luaScript != 0) { // Print the error message std::cout << lua_tostring(luaState, -1) << std::endl; // Removes that error message lua_pop(luaState, 1); } } // Initialize void initialize() { // Set the display width to 80 chars long (for word-wrap) Sysout::setDisplayWidth(80); // If we are in debug mode, then print that #ifdef DEBUG Sysout::println("Running in DEBUG mode!"); Sysout::printDictionaryEntries(); #endif } // Run void run() { bool running = true; while(running) { // Put a title screen here // Run a game Game* game = new Game(); game->load(); game->run(); delete game; } } // Finalize void finalize() { } int main() { Potato potato; lua_State* luaState; luaState = luaL_newstate(); luaL_openlibs(luaState); potato.luaify(luaState); int luaScript = luaL_dofile(luaState, getLocalFilePath("potatoProp.lua")); printLuaErrors(luaState, luaScript); Sysout::println(potato.tastiness); Sysout::println(potato.bounciness); lua_close(luaState); // Initialize initialize(); // Run run(); // Clean-up finalize(); // Died quietly return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/settings/settingsmultisendwidget.h" #include "qt/pivx/settings/forms/ui_settingsmultisendwidget.h" #include "qt/pivx/settings/settingsmultisenddialog.h" #include "qt/pivx/qtutils.h" #include "addresstablemodel.h" #include "base58.h" #include "init.h" #include "walletmodel.h" #include "wallet/wallet.h" #define DECORATION_SIZE 65 #define NUM_ITEMS 3 MultiSendModel::MultiSendModel(QObject *parent) : QAbstractTableModel(parent){ updateList(); } void MultiSendModel::updateList(){ emit dataChanged(index(0, 0, QModelIndex()), index((int) pwalletMain->vMultiSend.size(), 5, QModelIndex()) ); } int MultiSendModel::rowCount(const QModelIndex &parent) const{ if (parent.isValid()) return 0; return (int) pwalletMain->vMultiSend.size(); } QVariant MultiSendModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case PERCENTAGE: return pwalletMain->vMultiSend[row].second; case ADDRESS: { return QString::fromStdString(pwalletMain->vMultiSend[row].first); } } } return QVariant(); } QModelIndex MultiSendModel::index(int row, int column, const QModelIndex& parent) const{ Q_UNUSED(parent); return createIndex(row, column, nullptr); } class MultiSendHolder : public FurListRow<QWidget*> { public: MultiSendHolder(); explicit MultiSendHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){} QWidget* createHolder(int pos) override{ QWidget *row = new QWidget(); QVBoxLayout *verticalLayout_2; QFrame *frame_2; QHBoxLayout *horizontalLayout; QLabel *labelName; QSpacerItem *horizontalSpacer; QLabel *labelDate; QLabel *lblDivisory; if (row->objectName().isEmpty()) row->setObjectName(QStringLiteral("multiSendrow")); row->resize(475, 65); row->setStyleSheet(QStringLiteral("")); setCssProperty(row, "container"); verticalLayout_2 = new QVBoxLayout(row); verticalLayout_2->setSpacing(0); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout_2->setContentsMargins(20, 0, 20, 0); frame_2 = new QFrame(row); frame_2->setObjectName(QStringLiteral("frame_2")); frame_2->setStyleSheet(QStringLiteral("border:none;")); frame_2->setFrameShape(QFrame::StyledPanel); frame_2->setFrameShadow(QFrame::Raised); horizontalLayout = new QHBoxLayout(frame_2); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, -1, 0, -1); labelName = new QLabel(frame_2); labelName->setObjectName(QStringLiteral("labelAddress")); setCssProperty(labelName, "text-list-title1"); horizontalLayout->addWidget(labelName); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); labelDate = new QLabel(frame_2); labelDate->setObjectName(QStringLiteral("labelPercentage")); setCssProperty(labelDate, "text-list-caption-medium"); horizontalLayout->addWidget(labelDate); verticalLayout_2->addWidget(frame_2); lblDivisory = new QLabel(row); lblDivisory->setObjectName(QStringLiteral("lblDivisory")); lblDivisory->setMinimumSize(QSize(0, 1)); lblDivisory->setMaximumSize(QSize(16777215, 1)); lblDivisory->setStyleSheet(QStringLiteral("background-color:#bababa;")); lblDivisory->setAlignment(Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft); verticalLayout_2->addWidget(lblDivisory); return row; } void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{ holder->findChild<QLabel*>("labelAddress")->setText(index.data(Qt::DisplayRole).toString()); holder->findChild<QLabel*>("labelPercentage")->setText( QString::number(index.sibling(index.row(), MultiSendModel::PERCENTAGE).data(Qt::DisplayRole).toInt()) + QString("%") ); } QColor rectColor(bool isHovered, bool isSelected) override{ return getRowColor(isLightTheme, isHovered, isSelected); } ~MultiSendHolder() override{} bool isLightTheme; }; SettingsMultisendWidget::SettingsMultisendWidget(PWidget *parent) : PWidget(parent), ui(new Ui::SettingsMultisendWidget) { ui->setupUi(this); this->setStyleSheet(parent->styleSheet()); delegate = new FurAbstractListItemDelegate( DECORATION_SIZE, new MultiSendHolder(isLightTheme()), this ); // Containers setCssProperty(ui->left, "container"); ui->left->setContentsMargins(10,10,10,10); // Title ui->labelTitle->setText("Multisend"); setCssTitleScreen(ui->labelTitle); ui->labelSubtitle1->setText(tr("MultiSend allows you to automatically send up to 100% of your stake or masternode reward to a list of other PIVX addresses after it matures.")); setCssSubtitleScreen(ui->labelSubtitle1); //Button Group ui->pushLeft->setText(tr("Active")); setCssProperty(ui->pushLeft, "btn-check-left"); ui->pushRight->setText(tr("Disable")); setCssProperty(ui->pushRight, "btn-check-right"); setCssProperty(ui->pushImgEmpty, "img-empty-multisend"); ui->labelEmpty->setText(tr("No active recipient yet")); setCssProperty(ui->labelEmpty, "text-empty"); // CheckBox ui->checkBoxStake->setText(tr("Send stakes")); ui->checkBoxRewards->setText(tr("Send masternode rewards")); ui->listView->setItemDelegate(delegate); ui->listView->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listView->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listView->setAttribute(Qt::WA_MacShowFocusRect, false); ui->listView->setSelectionBehavior(QAbstractItemView::SelectRows); // Buttons ui->pushButtonSave->setText(tr("ADD RECIPIENT")); ui->pushButtonClear->setText(tr("CLEAR ALL")); setCssBtnPrimary(ui->pushButtonSave); setCssBtnSecondary(ui->pushButtonClear); connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(onAddRecipientClicked())); connect(ui->pushButtonClear, SIGNAL(clicked()), this, SLOT(clearAll())); } void SettingsMultisendWidget::showEvent(QShowEvent *event) { if (multiSendModel) { multiSendModel->updateList(); updateListState(); } } void SettingsMultisendWidget::loadWalletModel(){ if(walletModel){ multiSendModel = new MultiSendModel(this); ui->listView->setModel(multiSendModel); ui->listView->setModelColumn(MultiSendModel::ADDRESS); ui->pushLeft->setChecked(pwalletMain->isMultiSendEnabled()); ui->checkBoxStake->setChecked(pwalletMain->fMultiSendStake); ui->checkBoxRewards->setChecked(pwalletMain->fMultiSendMasternodeReward); connect(ui->checkBoxStake, SIGNAL(stateChanged(int)), this, SLOT(checkBoxChanged())); connect(ui->checkBoxRewards, SIGNAL(stateChanged(int)), this, SLOT(checkBoxChanged())); connect(ui->pushLeft, SIGNAL(clicked()), this, SLOT(activate())); connect(ui->pushRight, SIGNAL(clicked()), this, SLOT(deactivate())); updateListState(); } } void SettingsMultisendWidget::updateListState(){ if (multiSendModel->rowCount() > 0) { ui->listView->setVisible(true); ui->emptyContainer->setVisible(false); } else { ui->listView->setVisible(false); ui->emptyContainer->setVisible(true); } } void SettingsMultisendWidget::clearAll(){ std::vector<std::pair<std::string, int> > vMultiSendTemp = pwalletMain->vMultiSend; bool fRemoved = true; pwalletMain->vMultiSend.clear(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.EraseMultiSend(vMultiSendTemp)) fRemoved = false; if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend)) fRemoved = false; checkBoxChanged(); multiSendModel->updateList(); updateListState(); inform(fRemoved ? tr("Clear succeed") : tr("Clear all failed, could not locate address in wallet file")); } void SettingsMultisendWidget::checkBoxChanged(){ pwalletMain->fMultiSendStake = ui->checkBoxStake->isChecked(); pwalletMain->fMultiSendMasternodeReward = ui->checkBoxRewards->isChecked(); } void SettingsMultisendWidget::onAddRecipientClicked() { showHideOp(true); SettingsMultisendDialog* dialog = new SettingsMultisendDialog(window); openDialogWithOpaqueBackgroundY(dialog, window, 3, 5); if(dialog->isOk){ addMultiSend( dialog->getAddress(), dialog->getPercentage(), dialog->getLabel() ); } dialog->deleteLater(); } void SettingsMultisendWidget::addMultiSend(QString address, int percentage, QString addressLabel){ std::string strAddress = address.toStdString(); if (!CBitcoinAddress(strAddress).IsValid()) { inform(tr("The entered address: %1 is invalid.\nPlease check the address and try again.").arg(address)); return; } if (percentage > 100 || percentage <= 0) { inform(tr("Invalid percentage, please enter values from 1 to 100.")); return; } int nMultiSendPercent = percentage; int nSumMultiSend = 0; for (int i = 0; i < (int)pwalletMain->vMultiSend.size(); i++) nSumMultiSend += pwalletMain->vMultiSend[i].second; if (nSumMultiSend + nMultiSendPercent > 100) { inform(tr("The total amount of your MultiSend vector is over 100% of your stake reward")); return; } std::pair<std::string, int> pMultiSend; pMultiSend.first = strAddress; pMultiSend.second = nMultiSendPercent; pwalletMain->vMultiSend.push_back(pMultiSend); if (walletModel && walletModel->getAddressTableModel()) { // update the address book with the label given or no label if none was given. CBitcoinAddress address(strAddress); std::string userInputLabel = addressLabel.toStdString(); walletModel->updateAddressBookLabels(address.Get(), (userInputLabel.empty()) ? "(no label)" : userInputLabel, "send"); } CWalletDB walletdb(pwalletMain->strWalletFile); if(!walletdb.WriteMultiSend(pwalletMain->vMultiSend)) { inform(tr("Error saving MultiSend, failed saving properties to the database.")); return; } multiSendModel->updateList(); updateListState(); inform("MultiSend recipient added."); } void SettingsMultisendWidget::activate(){ if(pwalletMain->isMultiSendEnabled()) return; QString strRet; if (pwalletMain->vMultiSend.size() < 1) strRet = tr("Unable to activate MultiSend, no available recipients"); else if (!(ui->checkBoxStake->isChecked() || ui->checkBoxRewards->isChecked())) { strRet = tr("Unable to activate MultiSend\nCheck one or both of the check boxes to send on stake and/or masternode rewards"); } else if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) { pwalletMain->fMultiSendStake = ui->checkBoxStake->isChecked(); pwalletMain->fMultiSendMasternodeReward = ui->checkBoxRewards->isChecked(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.WriteMSettings(pwalletMain->fMultiSendStake, pwalletMain->fMultiSendMasternodeReward, pwalletMain->nLastMultiSendHeight)) strRet = tr("MultiSend activated but writing settings to DB failed"); else strRet = tr("MultiSend activated"); } else strRet = tr("First multiSend address invalid"); inform(strRet); } void SettingsMultisendWidget::deactivate(){ if(pwalletMain->isMultiSendEnabled()) { QString strRet; pwalletMain->setMultiSendDisabled(); CWalletDB walletdb(pwalletMain->strWalletFile); inform(!walletdb.WriteMSettings(false, false, pwalletMain->nLastMultiSendHeight) ? tr("MultiSend deactivated but writing settings to DB failed") : tr("MultiSend deactivated") ); } } void SettingsMultisendWidget::changeTheme(bool isLightTheme, QString& theme){ static_cast<MultiSendHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme; } SettingsMultisendWidget::~SettingsMultisendWidget(){ delete ui; } <commit_msg>[GUI] Settings multisend, list missing container style.<commit_after>// Copyright (c) 2019 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/pivx/settings/settingsmultisendwidget.h" #include "qt/pivx/settings/forms/ui_settingsmultisendwidget.h" #include "qt/pivx/settings/settingsmultisenddialog.h" #include "qt/pivx/qtutils.h" #include "addresstablemodel.h" #include "base58.h" #include "init.h" #include "walletmodel.h" #include "wallet/wallet.h" #define DECORATION_SIZE 65 #define NUM_ITEMS 3 MultiSendModel::MultiSendModel(QObject *parent) : QAbstractTableModel(parent){ updateList(); } void MultiSendModel::updateList(){ emit dataChanged(index(0, 0, QModelIndex()), index((int) pwalletMain->vMultiSend.size(), 5, QModelIndex()) ); } int MultiSendModel::rowCount(const QModelIndex &parent) const{ if (parent.isValid()) return 0; return (int) pwalletMain->vMultiSend.size(); } QVariant MultiSendModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); int row = index.row(); if (role == Qt::DisplayRole || role == Qt::EditRole) { switch (index.column()) { case PERCENTAGE: return pwalletMain->vMultiSend[row].second; case ADDRESS: { return QString::fromStdString(pwalletMain->vMultiSend[row].first); } } } return QVariant(); } QModelIndex MultiSendModel::index(int row, int column, const QModelIndex& parent) const{ Q_UNUSED(parent); return createIndex(row, column, nullptr); } class MultiSendHolder : public FurListRow<QWidget*> { public: MultiSendHolder(); explicit MultiSendHolder(bool _isLightTheme) : FurListRow(), isLightTheme(_isLightTheme){} QWidget* createHolder(int pos) override{ QWidget *row = new QWidget(); QVBoxLayout *verticalLayout_2; QFrame *frame_2; QHBoxLayout *horizontalLayout; QLabel *labelName; QSpacerItem *horizontalSpacer; QLabel *labelDate; QLabel *lblDivisory; if (row->objectName().isEmpty()) row->setObjectName(QStringLiteral("multiSendrow")); row->resize(475, 65); row->setStyleSheet(QStringLiteral("")); setCssProperty(row, "container"); verticalLayout_2 = new QVBoxLayout(row); verticalLayout_2->setSpacing(0); verticalLayout_2->setObjectName(QStringLiteral("verticalLayout_2")); verticalLayout_2->setContentsMargins(20, 0, 20, 0); frame_2 = new QFrame(row); frame_2->setObjectName(QStringLiteral("frame_2")); frame_2->setStyleSheet(QStringLiteral("border:none;")); frame_2->setFrameShape(QFrame::StyledPanel); frame_2->setFrameShadow(QFrame::Raised); horizontalLayout = new QHBoxLayout(frame_2); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, -1, 0, -1); labelName = new QLabel(frame_2); labelName->setObjectName(QStringLiteral("labelAddress")); setCssProperty(labelName, "text-list-title1"); horizontalLayout->addWidget(labelName); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); horizontalLayout->addItem(horizontalSpacer); labelDate = new QLabel(frame_2); labelDate->setObjectName(QStringLiteral("labelPercentage")); setCssProperty(labelDate, "text-list-caption-medium"); horizontalLayout->addWidget(labelDate); verticalLayout_2->addWidget(frame_2); lblDivisory = new QLabel(row); lblDivisory->setObjectName(QStringLiteral("lblDivisory")); lblDivisory->setMinimumSize(QSize(0, 1)); lblDivisory->setMaximumSize(QSize(16777215, 1)); lblDivisory->setStyleSheet(QStringLiteral("background-color:#bababa;")); lblDivisory->setAlignment(Qt::AlignBottom|Qt::AlignLeading|Qt::AlignLeft); verticalLayout_2->addWidget(lblDivisory); return row; } void init(QWidget* holder,const QModelIndex &index, bool isHovered, bool isSelected) const override{ holder->findChild<QLabel*>("labelAddress")->setText(index.data(Qt::DisplayRole).toString()); holder->findChild<QLabel*>("labelPercentage")->setText( QString::number(index.sibling(index.row(), MultiSendModel::PERCENTAGE).data(Qt::DisplayRole).toInt()) + QString("%") ); } QColor rectColor(bool isHovered, bool isSelected) override{ return getRowColor(isLightTheme, isHovered, isSelected); } ~MultiSendHolder() override{} bool isLightTheme; }; SettingsMultisendWidget::SettingsMultisendWidget(PWidget *parent) : PWidget(parent), ui(new Ui::SettingsMultisendWidget) { ui->setupUi(this); this->setStyleSheet(parent->styleSheet()); delegate = new FurAbstractListItemDelegate( DECORATION_SIZE, new MultiSendHolder(isLightTheme()), this ); // Containers setCssProperty(ui->left, "container"); ui->left->setContentsMargins(10,10,10,10); // Title ui->labelTitle->setText("Multisend"); setCssTitleScreen(ui->labelTitle); ui->labelSubtitle1->setText(tr("MultiSend allows you to automatically send up to 100% of your stake or masternode reward to a list of other PIVX addresses after it matures.")); setCssSubtitleScreen(ui->labelSubtitle1); //Button Group ui->pushLeft->setText(tr("Active")); setCssProperty(ui->pushLeft, "btn-check-left"); ui->pushRight->setText(tr("Disable")); setCssProperty(ui->pushRight, "btn-check-right"); setCssProperty(ui->pushImgEmpty, "img-empty-multisend"); ui->labelEmpty->setText(tr("No active recipient yet")); setCssProperty(ui->labelEmpty, "text-empty"); // CheckBox ui->checkBoxStake->setText(tr("Send stakes")); ui->checkBoxRewards->setText(tr("Send masternode rewards")); setCssProperty(ui->listView, "container"); ui->listView->setItemDelegate(delegate); ui->listView->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listView->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listView->setAttribute(Qt::WA_MacShowFocusRect, false); ui->listView->setSelectionBehavior(QAbstractItemView::SelectRows); // Buttons ui->pushButtonSave->setText(tr("ADD RECIPIENT")); ui->pushButtonClear->setText(tr("CLEAR ALL")); setCssBtnPrimary(ui->pushButtonSave); setCssBtnSecondary(ui->pushButtonClear); connect(ui->pushButtonSave, SIGNAL(clicked()), this, SLOT(onAddRecipientClicked())); connect(ui->pushButtonClear, SIGNAL(clicked()), this, SLOT(clearAll())); } void SettingsMultisendWidget::showEvent(QShowEvent *event) { if (multiSendModel) { multiSendModel->updateList(); updateListState(); } } void SettingsMultisendWidget::loadWalletModel(){ if(walletModel){ multiSendModel = new MultiSendModel(this); ui->listView->setModel(multiSendModel); ui->listView->setModelColumn(MultiSendModel::ADDRESS); ui->pushLeft->setChecked(pwalletMain->isMultiSendEnabled()); ui->checkBoxStake->setChecked(pwalletMain->fMultiSendStake); ui->checkBoxRewards->setChecked(pwalletMain->fMultiSendMasternodeReward); connect(ui->checkBoxStake, SIGNAL(stateChanged(int)), this, SLOT(checkBoxChanged())); connect(ui->checkBoxRewards, SIGNAL(stateChanged(int)), this, SLOT(checkBoxChanged())); connect(ui->pushLeft, SIGNAL(clicked()), this, SLOT(activate())); connect(ui->pushRight, SIGNAL(clicked()), this, SLOT(deactivate())); updateListState(); } } void SettingsMultisendWidget::updateListState(){ if (multiSendModel->rowCount() > 0) { ui->listView->setVisible(true); ui->emptyContainer->setVisible(false); } else { ui->listView->setVisible(false); ui->emptyContainer->setVisible(true); } } void SettingsMultisendWidget::clearAll(){ std::vector<std::pair<std::string, int> > vMultiSendTemp = pwalletMain->vMultiSend; bool fRemoved = true; pwalletMain->vMultiSend.clear(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.EraseMultiSend(vMultiSendTemp)) fRemoved = false; if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend)) fRemoved = false; checkBoxChanged(); multiSendModel->updateList(); updateListState(); inform(fRemoved ? tr("Clear succeed") : tr("Clear all failed, could not locate address in wallet file")); } void SettingsMultisendWidget::checkBoxChanged(){ pwalletMain->fMultiSendStake = ui->checkBoxStake->isChecked(); pwalletMain->fMultiSendMasternodeReward = ui->checkBoxRewards->isChecked(); } void SettingsMultisendWidget::onAddRecipientClicked() { showHideOp(true); SettingsMultisendDialog* dialog = new SettingsMultisendDialog(window); openDialogWithOpaqueBackgroundY(dialog, window, 3, 5); if(dialog->isOk){ addMultiSend( dialog->getAddress(), dialog->getPercentage(), dialog->getLabel() ); } dialog->deleteLater(); } void SettingsMultisendWidget::addMultiSend(QString address, int percentage, QString addressLabel){ std::string strAddress = address.toStdString(); if (!CBitcoinAddress(strAddress).IsValid()) { inform(tr("The entered address: %1 is invalid.\nPlease check the address and try again.").arg(address)); return; } if (percentage > 100 || percentage <= 0) { inform(tr("Invalid percentage, please enter values from 1 to 100.")); return; } int nMultiSendPercent = percentage; int nSumMultiSend = 0; for (int i = 0; i < (int)pwalletMain->vMultiSend.size(); i++) nSumMultiSend += pwalletMain->vMultiSend[i].second; if (nSumMultiSend + nMultiSendPercent > 100) { inform(tr("The total amount of your MultiSend vector is over 100% of your stake reward")); return; } std::pair<std::string, int> pMultiSend; pMultiSend.first = strAddress; pMultiSend.second = nMultiSendPercent; pwalletMain->vMultiSend.push_back(pMultiSend); if (walletModel && walletModel->getAddressTableModel()) { // update the address book with the label given or no label if none was given. CBitcoinAddress address(strAddress); std::string userInputLabel = addressLabel.toStdString(); walletModel->updateAddressBookLabels(address.Get(), (userInputLabel.empty()) ? "(no label)" : userInputLabel, "send"); } CWalletDB walletdb(pwalletMain->strWalletFile); if(!walletdb.WriteMultiSend(pwalletMain->vMultiSend)) { inform(tr("Error saving MultiSend, failed saving properties to the database.")); return; } multiSendModel->updateList(); updateListState(); inform("MultiSend recipient added."); } void SettingsMultisendWidget::activate(){ if(pwalletMain->isMultiSendEnabled()) return; QString strRet; if (pwalletMain->vMultiSend.size() < 1) strRet = tr("Unable to activate MultiSend, no available recipients"); else if (!(ui->checkBoxStake->isChecked() || ui->checkBoxRewards->isChecked())) { strRet = tr("Unable to activate MultiSend\nCheck one or both of the check boxes to send on stake and/or masternode rewards"); } else if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) { pwalletMain->fMultiSendStake = ui->checkBoxStake->isChecked(); pwalletMain->fMultiSendMasternodeReward = ui->checkBoxRewards->isChecked(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.WriteMSettings(pwalletMain->fMultiSendStake, pwalletMain->fMultiSendMasternodeReward, pwalletMain->nLastMultiSendHeight)) strRet = tr("MultiSend activated but writing settings to DB failed"); else strRet = tr("MultiSend activated"); } else strRet = tr("First multiSend address invalid"); inform(strRet); } void SettingsMultisendWidget::deactivate(){ if(pwalletMain->isMultiSendEnabled()) { QString strRet; pwalletMain->setMultiSendDisabled(); CWalletDB walletdb(pwalletMain->strWalletFile); inform(!walletdb.WriteMSettings(false, false, pwalletMain->nLastMultiSendHeight) ? tr("MultiSend deactivated but writing settings to DB failed") : tr("MultiSend deactivated") ); } } void SettingsMultisendWidget::changeTheme(bool isLightTheme, QString& theme){ static_cast<MultiSendHolder*>(this->delegate->getRowFactory())->isLightTheme = isLightTheme; } SettingsMultisendWidget::~SettingsMultisendWidget(){ delete ui; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Effective License of whole file: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * Parts "Copyright by Sun Microsystems, Inc" prior to August 2011: * * The Contents of this file are made available subject to the terms of * the GNU Lesser General Public License Version 2.1 * * Copyright: 2000 by Sun Microsystems, Inc. * * Contributor(s): Joerg Budischewski * * All parts contributed on or after August 2011: * * Version: MPL 1.1 / GPLv3+ / LGPLv2.1+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"), * in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable * instead of those above. * ************************************************************************/ #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/compbase1.hxx> #include <cppuhelper/compbase2.hxx> #include <cppuhelper/implementationentry.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include "pq_driver.hxx" using rtl::OUString; using rtl::OUStringToOString; using osl::MutexGuard; using cppu::WeakComponentImplHelper2; using com::sun::star::lang::XSingleComponentFactory; using com::sun::star::lang::XServiceInfo; using com::sun::star::lang::XComponent; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::Exception; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::XInterface; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XComponentContext; using com::sun::star::uno::Any; using com::sun::star::beans::PropertyValue; using com::sun::star::beans::XPropertySet; using com::sun::star::sdbc::XConnection; using com::sun::star::sdbc::SQLException; using com::sun::star::sdbc::DriverPropertyInfo; using com::sun::star::sdbcx::XTablesSupplier; namespace pq_sdbc_driver { #define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) ) OUString DriverGetImplementationName() { static OUString *p; if (! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); static OUString instance( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) ); p = &instance; } return *p; } Sequence< OUString > DriverGetSupportedServiceNames() { static Sequence< OUString > *p; if( ! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) ); static Sequence< OUString > instance( &tmp,1 ); p = &instance; } return *p; } Reference< XConnection > Driver::connect( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { if( ! acceptsURL( url ) ) // XDriver spec tells me to do so ... return Reference< XConnection > (); Sequence< Any > seq ( 2 ); seq[0] <<= url; seq[1] <<= info; return Reference< XConnection> ( m_smgr->createInstanceWithArgumentsAndContext( OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ), seq, m_ctx ), UNO_QUERY ); } sal_Bool Driver::acceptsURL( const ::rtl::OUString& url ) throw (SQLException, RuntimeException) { return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) ); } Sequence< DriverPropertyInfo > Driver::getPropertyInfo( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { (void)url; (void)info; return Sequence< DriverPropertyInfo > (); } sal_Int32 Driver::getMajorVersion( ) throw (RuntimeException) { return PQ_SDBC_MAJOR; } sal_Int32 Driver::getMinorVersion( ) throw (RuntimeException) { return PQ_SDBC_MINOR; } // XServiceInfo OUString SAL_CALL Driver::getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return DriverGetImplementationName(); } sal_Bool Driver::supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { Sequence< OUString > serviceNames = DriverGetSupportedServiceNames(); for( int i = 0 ; i < serviceNames.getLength() ; i ++ ) if( serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > Driver::getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return DriverGetSupportedServiceNames(); } // XComponent void Driver::disposing() { } Reference< XTablesSupplier > Driver::getDataDefinitionByConnection( const Reference< XConnection >& connection ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier >( connection , UNO_QUERY ); } Reference< XTablesSupplier > Driver::getDataDefinitionByURL( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY ); } Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx ) { Reference< XInterface > ret = * new Driver( ctx ); return ret; } class OOneInstanceComponentFactory : public MutexHolder, public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo > { public: OOneInstanceComponentFactory( const OUString & rImplementationName_, cppu::ComponentFactoryFunc fptr, const Sequence< OUString > & serviceNames, const Reference< XComponentContext > & defaultContext) : WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ), m_create( fptr ), m_serviceNames( serviceNames ), m_implName( rImplementationName_ ), m_defaultContext( defaultContext ) { } // XSingleComponentFactory virtual Reference< XInterface > SAL_CALL createInstanceWithContext( Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( Sequence< Any > const & rArguments, Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); // XServiceInfo OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return m_implName; } sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ ) if( m_serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return m_serviceNames; } // XComponent virtual void SAL_CALL disposing(); private: cppu::ComponentFactoryFunc m_create; Sequence< OUString > m_serviceNames; OUString m_implName; Reference< XInterface > m_theInstance; Reference< XComponentContext > m_defaultContext; }; Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext( Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { (void)rArguments; return createInstanceWithContext( ctx ); } Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext( const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { if( ! m_theInstance.is() ) { // work around the problem in sdbc Reference< XComponentContext > useCtx = ctx; if( ! useCtx.is() ) useCtx = m_defaultContext; Reference< XInterface > theInstance = m_create( useCtx ); MutexGuard guard( osl::Mutex::getGlobalMutex() ); if( ! m_theInstance.is () ) { m_theInstance = theInstance; } } return m_theInstance; } void OOneInstanceComponentFactory::disposing() { Reference< XComponent > rComp; { MutexGuard guard( osl::Mutex::getGlobalMutex() ); rComp = Reference< XComponent >( m_theInstance, UNO_QUERY ); m_theInstance.clear(); } if( rComp.is() ) rComp->dispose(); } // Reference< XSingleComponentFactory > createOneInstanceComponentFactory( // cppu::ComponentFactoryFunc fptr, // ::rtl::OUString const & rImplementationName, // ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, // rtl_ModuleCount * pModCount = 0 ) // SAL_THROW(()) // { // return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames); // } } static struct cppu::ImplementationEntry g_entries[] = { { pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName, pq_sdbc_driver::DriverGetSupportedServiceNames, 0, 0 , 0 }, { 0, 0, 0, 0, 0, 0 } }; extern "C" { void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * ) { // need to extract the defaultcontext, because the way, sdbc // bypasses the servicemanager, does not allow to use the // XSingleComponentFactory interface ... void * pRet = 0; Reference< XSingleComponentFactory > xFactory; Reference< XInterface > xSmgr( (XInterface * ) pServiceManager ); for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ ) { OUString implName = g_entries[i].getImplementationName(); if( 0 == implName.compareToAscii( pImplName ) ) { Reference< XComponentContext > defaultContext; Reference< XPropertySet > propSet( xSmgr, UNO_QUERY ); if( propSet.is() ) { try { propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext; } catch( com::sun::star::uno::Exception & ) { // if there is no default context, ignore it } } xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory( implName, g_entries[i].create, g_entries[i].getSupportedServiceNames(), defaultContext ); } } if( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } } <commit_msg>component_getFactory must be exported<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Effective License of whole file: * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * Parts "Copyright by Sun Microsystems, Inc" prior to August 2011: * * The Contents of this file are made available subject to the terms of * the GNU Lesser General Public License Version 2.1 * * Copyright: 2000 by Sun Microsystems, Inc. * * Contributor(s): Joerg Budischewski * * All parts contributed on or after August 2011: * * Version: MPL 1.1 / GPLv3+ / LGPLv2.1+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * [ Copyright (C) 2011 Lionel Elie Mamane <lionel@mamane.lu> ] * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPLv2.1+"), * in which case the provisions of the GPLv3+ or the LGPLv2.1+ are applicable * instead of those above. * ************************************************************************/ #include <stdio.h> #include <cppuhelper/factory.hxx> #include <cppuhelper/compbase1.hxx> #include <cppuhelper/compbase2.hxx> #include <cppuhelper/implementationentry.hxx> #include <com/sun/star/beans/XPropertySet.hpp> #include "pq_driver.hxx" using rtl::OUString; using rtl::OUStringToOString; using osl::MutexGuard; using cppu::WeakComponentImplHelper2; using com::sun::star::lang::XSingleComponentFactory; using com::sun::star::lang::XServiceInfo; using com::sun::star::lang::XComponent; using com::sun::star::uno::RuntimeException; using com::sun::star::uno::Exception; using com::sun::star::uno::Sequence; using com::sun::star::uno::Reference; using com::sun::star::uno::XInterface; using com::sun::star::uno::UNO_QUERY; using com::sun::star::uno::XComponentContext; using com::sun::star::uno::Any; using com::sun::star::beans::PropertyValue; using com::sun::star::beans::XPropertySet; using com::sun::star::sdbc::XConnection; using com::sun::star::sdbc::SQLException; using com::sun::star::sdbc::DriverPropertyInfo; using com::sun::star::sdbcx::XTablesSupplier; namespace pq_sdbc_driver { #define ASCII_STR(x) OUString( RTL_CONSTASCII_USTRINGPARAM( x ) ) OUString DriverGetImplementationName() { static OUString *p; if (! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); static OUString instance( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.connectivity.pq.Driver" ) ); p = &instance; } return *p; } Sequence< OUString > DriverGetSupportedServiceNames() { static Sequence< OUString > *p; if( ! p ) { MutexGuard guard( osl::Mutex::getGlobalMutex() ); OUString tmp( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.sdbc.Driver" ) ); static Sequence< OUString > instance( &tmp,1 ); p = &instance; } return *p; } Reference< XConnection > Driver::connect( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { if( ! acceptsURL( url ) ) // XDriver spec tells me to do so ... return Reference< XConnection > (); Sequence< Any > seq ( 2 ); seq[0] <<= url; seq[1] <<= info; return Reference< XConnection> ( m_smgr->createInstanceWithArgumentsAndContext( OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.connectivity.pq.Connection" ) ), seq, m_ctx ), UNO_QUERY ); } sal_Bool Driver::acceptsURL( const ::rtl::OUString& url ) throw (SQLException, RuntimeException) { return url.matchAsciiL( RTL_CONSTASCII_STRINGPARAM( "sdbc:postgresql:" ) ); } Sequence< DriverPropertyInfo > Driver::getPropertyInfo( const OUString& url,const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { (void)url; (void)info; return Sequence< DriverPropertyInfo > (); } sal_Int32 Driver::getMajorVersion( ) throw (RuntimeException) { return PQ_SDBC_MAJOR; } sal_Int32 Driver::getMinorVersion( ) throw (RuntimeException) { return PQ_SDBC_MINOR; } // XServiceInfo OUString SAL_CALL Driver::getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return DriverGetImplementationName(); } sal_Bool Driver::supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { Sequence< OUString > serviceNames = DriverGetSupportedServiceNames(); for( int i = 0 ; i < serviceNames.getLength() ; i ++ ) if( serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > Driver::getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return DriverGetSupportedServiceNames(); } // XComponent void Driver::disposing() { } Reference< XTablesSupplier > Driver::getDataDefinitionByConnection( const Reference< XConnection >& connection ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier >( connection , UNO_QUERY ); } Reference< XTablesSupplier > Driver::getDataDefinitionByURL( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw (SQLException, RuntimeException) { return Reference< XTablesSupplier > ( connect( url, info ), UNO_QUERY ); } Reference< XInterface > DriverCreateInstance( const Reference < XComponentContext > & ctx ) { Reference< XInterface > ret = * new Driver( ctx ); return ret; } class OOneInstanceComponentFactory : public MutexHolder, public WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo > { public: OOneInstanceComponentFactory( const OUString & rImplementationName_, cppu::ComponentFactoryFunc fptr, const Sequence< OUString > & serviceNames, const Reference< XComponentContext > & defaultContext) : WeakComponentImplHelper2< XSingleComponentFactory, XServiceInfo >( this->m_mutex ), m_create( fptr ), m_serviceNames( serviceNames ), m_implName( rImplementationName_ ), m_defaultContext( defaultContext ) { } // XSingleComponentFactory virtual Reference< XInterface > SAL_CALL createInstanceWithContext( Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); virtual Reference< XInterface > SAL_CALL createInstanceWithArgumentsAndContext( Sequence< Any > const & rArguments, Reference< XComponentContext > const & xContext ) throw (Exception, RuntimeException); // XServiceInfo OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException) { return m_implName; } sal_Bool SAL_CALL supportsService(const OUString& ServiceName) throw(::com::sun::star::uno::RuntimeException) { for( int i = 0 ; i < m_serviceNames.getLength() ; i ++ ) if( m_serviceNames[i] == ServiceName ) return sal_True; return sal_False; } Sequence< OUString > SAL_CALL getSupportedServiceNames(void) throw(::com::sun::star::uno::RuntimeException) { return m_serviceNames; } // XComponent virtual void SAL_CALL disposing(); private: cppu::ComponentFactoryFunc m_create; Sequence< OUString > m_serviceNames; OUString m_implName; Reference< XInterface > m_theInstance; Reference< XComponentContext > m_defaultContext; }; Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithArgumentsAndContext( Sequence< Any > const &rArguments, const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { (void)rArguments; return createInstanceWithContext( ctx ); } Reference< XInterface > OOneInstanceComponentFactory::createInstanceWithContext( const Reference< XComponentContext > & ctx ) throw( RuntimeException, Exception ) { if( ! m_theInstance.is() ) { // work around the problem in sdbc Reference< XComponentContext > useCtx = ctx; if( ! useCtx.is() ) useCtx = m_defaultContext; Reference< XInterface > theInstance = m_create( useCtx ); MutexGuard guard( osl::Mutex::getGlobalMutex() ); if( ! m_theInstance.is () ) { m_theInstance = theInstance; } } return m_theInstance; } void OOneInstanceComponentFactory::disposing() { Reference< XComponent > rComp; { MutexGuard guard( osl::Mutex::getGlobalMutex() ); rComp = Reference< XComponent >( m_theInstance, UNO_QUERY ); m_theInstance.clear(); } if( rComp.is() ) rComp->dispose(); } // Reference< XSingleComponentFactory > createOneInstanceComponentFactory( // cppu::ComponentFactoryFunc fptr, // ::rtl::OUString const & rImplementationName, // ::com::sun::star::uno::Sequence< ::rtl::OUString > const & rServiceNames, // rtl_ModuleCount * pModCount = 0 ) // SAL_THROW(()) // { // return new OOneInstanceComponentFactory( rImplementationName, fptr , rServiceNames); // } } static struct cppu::ImplementationEntry g_entries[] = { { pq_sdbc_driver::DriverCreateInstance, pq_sdbc_driver::DriverGetImplementationName, pq_sdbc_driver::DriverGetSupportedServiceNames, 0, 0 , 0 }, { 0, 0, 0, 0, 0, 0 } }; extern "C" { SAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * ) { // need to extract the defaultcontext, because the way, sdbc // bypasses the servicemanager, does not allow to use the // XSingleComponentFactory interface ... void * pRet = 0; Reference< XSingleComponentFactory > xFactory; Reference< XInterface > xSmgr( (XInterface * ) pServiceManager ); for( sal_Int32 i = 0 ; g_entries[i].create ; i ++ ) { OUString implName = g_entries[i].getImplementationName(); if( 0 == implName.compareToAscii( pImplName ) ) { Reference< XComponentContext > defaultContext; Reference< XPropertySet > propSet( xSmgr, UNO_QUERY ); if( propSet.is() ) { try { propSet->getPropertyValue( ASCII_STR( "DefaultContext" ) ) >>= defaultContext; } catch( com::sun::star::uno::Exception & ) { // if there is no default context, ignore it } } xFactory = new pq_sdbc_driver::OOneInstanceComponentFactory( implName, g_entries[i].create, g_entries[i].getSupportedServiceNames(), defaultContext ); } } if( xFactory.is() ) { xFactory->acquire(); pRet = xFactory.get(); } return pRet; } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <algorithm> #endif #include "DynamicProperty.h" #include "Property.h" #include "PropertyContainer.h" #include <Base/Reader.h> #include <Base/Writer.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Tools.h> using namespace App; DynamicProperty::DynamicProperty(PropertyContainer* p) : pc(p) { } DynamicProperty::~DynamicProperty() { } void DynamicProperty::getPropertyList(std::vector<Property*> &List) const { // get the properties of the base class first and insert the dynamic properties afterwards this->pc->PropertyContainer::getPropertyList(List); for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) List.push_back(it->second.property); } void DynamicProperty::getPropertyMap(std::map<std::string,Property*> &Map) const { // get the properties of the base class first and insert the dynamic properties afterwards this->pc->PropertyContainer::getPropertyMap(Map); for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) Map[it->first] = it->second.property; } Property *DynamicProperty::getPropertyByName(const char* name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.property; return this->pc->PropertyContainer::getPropertyByName(name); } Property *DynamicProperty::getDynamicPropertyByName(const char* name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.property; return 0; } std::vector<std::string> DynamicProperty::getDynamicPropertyNames() const { std::vector<std::string> names; for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { names.push_back(it->first); } return names; } void DynamicProperty::addDynamicProperties(const PropertyContainer* cont) { std::vector<std::string> names = cont->getDynamicPropertyNames(); for (std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) { App::Property* prop = cont->getDynamicPropertyByName(it->c_str()); if (prop) { addDynamicProperty( prop->getTypeId().getName(), prop->getName(), prop->getGroup(), prop->getDocumentation(), prop->getType(), cont->isReadOnly(prop), cont->isHidden(prop)); } } } const char* DynamicProperty::getName(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->first.c_str(); } return this->pc->PropertyContainer::getName(prop); } unsigned int DynamicProperty::getMemSize (void) const { std::map<std::string,Property*> Map; getPropertyMap(Map); std::map<std::string,Property*>::const_iterator It; unsigned int size = 0; for (It = Map.begin(); It != Map.end();++It) size += It->second->getMemSize(); return size; } short DynamicProperty::getPropertyType(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.attr; } return this->pc->PropertyContainer::getPropertyType(prop); } short DynamicProperty::getPropertyType(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.attr; return this->pc->PropertyContainer::getPropertyType(name); } const char* DynamicProperty::getPropertyGroup(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.group.c_str(); } return this->pc->PropertyContainer::getPropertyGroup(prop); } const char* DynamicProperty::getPropertyGroup(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.group.c_str(); return this->pc->PropertyContainer::getPropertyGroup(name); } const char* DynamicProperty::getPropertyDocumentation(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.doc.c_str(); } return this->pc->PropertyContainer::getPropertyDocumentation(prop); } const char* DynamicProperty::getPropertyDocumentation(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.doc.c_str(); return this->pc->PropertyContainer::getPropertyDocumentation(name); } bool DynamicProperty::isReadOnly(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.readonly; } return this->pc->PropertyContainer::isReadOnly(prop); } bool DynamicProperty::isReadOnly(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.readonly; return this->pc->PropertyContainer::isReadOnly(name); } bool DynamicProperty::isHidden(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.hidden; } return this->pc->PropertyContainer::isHidden(prop); } bool DynamicProperty::isHidden(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.hidden; return this->pc->PropertyContainer::isHidden(name); } Property* DynamicProperty::addDynamicProperty(const char* type, const char* name, const char* group, const char* doc, short attr, bool ro, bool hidden) { Base::BaseClass* base = static_cast<Base::BaseClass*>(Base::Type::createInstanceByName(type,true)); if (!base) return 0; if (!base->getTypeId().isDerivedFrom(Property::getClassTypeId())) { delete base; std::stringstream str; str << "'" << type << "' is not a property type"; throw Base::Exception(str.str()); } // get unique name Property* pcProperty = static_cast<Property*>(base); std::string ObjectName; if (name && *name != '\0') ObjectName = getUniquePropertyName(name); else ObjectName = getUniquePropertyName(type); pcProperty->setContainer(this->pc); PropData data; data.property = pcProperty; data.group = (group ? group : ""); data.doc = (doc ? doc : ""); data.attr = attr; data.readonly = ro; data.hidden = hidden; props[ObjectName] = data; return pcProperty; } bool DynamicProperty::removeDynamicProperty(const char* name) { std::map<std::string,PropData>::iterator it = props.find(name); if (it != props.end()) { delete it->second.property; props.erase(it); return true; } return false; } std::string DynamicProperty::getUniquePropertyName(const char *Name) const { std::string CleanName = Base::Tools::getIdentifier(Name); // name in use? std::map<std::string,Property*> objectProps; getPropertyMap(objectProps); std::map<std::string,Property*>::const_iterator pos; pos = objectProps.find(CleanName); if (pos == objectProps.end()) { // if not, name is OK return CleanName; } else { std::vector<std::string> names; names.reserve(objectProps.size()); for (pos = objectProps.begin();pos != objectProps.end();++pos) { names.push_back(pos->first); } return Base::Tools::getUniqueName(CleanName, names); } } std::string DynamicProperty::encodeAttribute(const std::string& str) const { std::string tmp; for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == '<') tmp += "&lt;"; else if (*it == '"') tmp += "&quot;"; else if (*it == '&') tmp += "&amp;"; else if (*it == '>') tmp += "&gt;"; else if (*it == '\n') tmp += " "; else tmp += *it; } return tmp; } void DynamicProperty::Save (Base::Writer &writer) const { std::map<std::string,Property*> Map; getPropertyMap(Map); writer.incInd(); // indention for 'Properties Count' writer.Stream() << writer.ind() << "<Properties Count=\"" << Map.size() << "\">" << std::endl; std::map<std::string,Property*>::iterator it; for (it = Map.begin(); it != Map.end(); ++it) { writer.incInd(); // indention for 'Property name' // check whether a static or dynamic property std::map<std::string,PropData>::const_iterator pt = props.find(it->first); if (pt == props.end()) { writer.Stream() << writer.ind() << "<Property name=\"" << it->first << "\" type=\"" << it->second->getTypeId().getName() << "\">" << std::endl; } else { writer.Stream() << writer.ind() << "<Property name=\"" << it->first << "\" type=\"" << it->second->getTypeId().getName() << "\" group=\"" << encodeAttribute(pt->second.group) << "\" doc=\"" << encodeAttribute(pt->second.doc) << "\" attr=\"" << pt->second.attr << "\" ro=\"" << pt->second.readonly << "\" hide=\"" << pt->second.hidden << "\">" << std::endl; } writer.incInd(); // indention for the actual property try { // We must make sure to handle all exceptions accordingly so that // the project file doesn't get invalidated. In the error case this // means to proceed instead of aborting the write operation. it->second->Save(writer); } catch (const Base::Exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const std::exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const char* e) { Base::Console().Error("%s\n", e); } #ifndef FC_DEBUG catch (...) { Base::Console().Error("DynamicProperty::Save: Unknown C++ exception thrown. Try to continue...\n"); } #endif writer.decInd(); // indention for the actual property writer.Stream() << writer.ind() << "</Property>" << std::endl; writer.decInd(); // indention for 'Property name' } writer.Stream() << writer.ind() << "</Properties>" << std::endl; writer.decInd(); // indention for 'Properties Count' } void DynamicProperty::Restore(Base::XMLReader &reader) { reader.readElement("Properties"); int Cnt = reader.getAttributeAsInteger("Count"); for (int i=0 ;i<Cnt ;i++) { reader.readElement("Property"); const char* PropName = reader.getAttribute("name"); const char* TypeName = reader.getAttribute("type"); Property* prop = getPropertyByName(PropName); try { if (!prop) { short attribute = 0; bool readonly = false, hidden = false; const char *group=0, *doc=0, *attr=0, *ro=0, *hide=0; if (reader.hasAttribute("group")) group = reader.getAttribute("group"); if (reader.hasAttribute("doc")) doc = reader.getAttribute("doc"); if (reader.hasAttribute("attr")) { attr = reader.getAttribute("attr"); if (attr) attribute = attr[0]-48; } if (reader.hasAttribute("ro")) { ro = reader.getAttribute("ro"); if (ro) readonly = (ro[0]-48) != 0; } if (reader.hasAttribute("hide")) { hide = reader.getAttribute("hide"); if (hide) hidden = (hide[0]-48) != 0; } prop = addDynamicProperty(TypeName, PropName, group, doc, attribute, readonly, hidden); } } catch(const Base::Exception& e) { // only handle this exception type Base::Console().Warning(e.what()); } //NOTE: We must also check the type of the current property because a subclass of //PropertyContainer might change the type of a property but not its name. In this //case we would force to read-in a wrong property type and the behaviour would be //undefined. if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0) prop->Restore(reader); else if (prop) Base::Console().Warning("%s: Overread data for property %s of type %s, expected type is %s\n", pc->getTypeId().getName(), prop->getName(), prop->getTypeId().getName(), TypeName); else Base::Console().Warning("%s: No property found with name %s and type %s\n", pc->getTypeId().getName(), PropName, TypeName); reader.readEndElement("Property"); } reader.readEndElement("Properties"); } <commit_msg>+ Do not write transient properties of Python feature classes to project file<commit_after>/*************************************************************************** * Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <algorithm> #endif #include "DynamicProperty.h" #include "Property.h" #include "PropertyContainer.h" #include <Base/Reader.h> #include <Base/Writer.h> #include <Base/Console.h> #include <Base/Exception.h> #include <Base/Tools.h> using namespace App; DynamicProperty::DynamicProperty(PropertyContainer* p) : pc(p) { } DynamicProperty::~DynamicProperty() { } void DynamicProperty::getPropertyList(std::vector<Property*> &List) const { // get the properties of the base class first and insert the dynamic properties afterwards this->pc->PropertyContainer::getPropertyList(List); for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) List.push_back(it->second.property); } void DynamicProperty::getPropertyMap(std::map<std::string,Property*> &Map) const { // get the properties of the base class first and insert the dynamic properties afterwards this->pc->PropertyContainer::getPropertyMap(Map); for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) Map[it->first] = it->second.property; } Property *DynamicProperty::getPropertyByName(const char* name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.property; return this->pc->PropertyContainer::getPropertyByName(name); } Property *DynamicProperty::getDynamicPropertyByName(const char* name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.property; return 0; } std::vector<std::string> DynamicProperty::getDynamicPropertyNames() const { std::vector<std::string> names; for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { names.push_back(it->first); } return names; } void DynamicProperty::addDynamicProperties(const PropertyContainer* cont) { std::vector<std::string> names = cont->getDynamicPropertyNames(); for (std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) { App::Property* prop = cont->getDynamicPropertyByName(it->c_str()); if (prop) { addDynamicProperty( prop->getTypeId().getName(), prop->getName(), prop->getGroup(), prop->getDocumentation(), prop->getType(), cont->isReadOnly(prop), cont->isHidden(prop)); } } } const char* DynamicProperty::getName(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->first.c_str(); } return this->pc->PropertyContainer::getName(prop); } unsigned int DynamicProperty::getMemSize (void) const { std::map<std::string,Property*> Map; getPropertyMap(Map); std::map<std::string,Property*>::const_iterator It; unsigned int size = 0; for (It = Map.begin(); It != Map.end();++It) size += It->second->getMemSize(); return size; } short DynamicProperty::getPropertyType(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.attr; } return this->pc->PropertyContainer::getPropertyType(prop); } short DynamicProperty::getPropertyType(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.attr; return this->pc->PropertyContainer::getPropertyType(name); } const char* DynamicProperty::getPropertyGroup(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.group.c_str(); } return this->pc->PropertyContainer::getPropertyGroup(prop); } const char* DynamicProperty::getPropertyGroup(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.group.c_str(); return this->pc->PropertyContainer::getPropertyGroup(name); } const char* DynamicProperty::getPropertyDocumentation(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.doc.c_str(); } return this->pc->PropertyContainer::getPropertyDocumentation(prop); } const char* DynamicProperty::getPropertyDocumentation(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.doc.c_str(); return this->pc->PropertyContainer::getPropertyDocumentation(name); } bool DynamicProperty::isReadOnly(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.readonly; } return this->pc->PropertyContainer::isReadOnly(prop); } bool DynamicProperty::isReadOnly(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.readonly; return this->pc->PropertyContainer::isReadOnly(name); } bool DynamicProperty::isHidden(const Property* prop) const { for (std::map<std::string,PropData>::const_iterator it = props.begin(); it != props.end(); ++it) { if (it->second.property == prop) return it->second.hidden; } return this->pc->PropertyContainer::isHidden(prop); } bool DynamicProperty::isHidden(const char *name) const { std::map<std::string,PropData>::const_iterator it = props.find(name); if (it != props.end()) return it->second.hidden; return this->pc->PropertyContainer::isHidden(name); } Property* DynamicProperty::addDynamicProperty(const char* type, const char* name, const char* group, const char* doc, short attr, bool ro, bool hidden) { Base::BaseClass* base = static_cast<Base::BaseClass*>(Base::Type::createInstanceByName(type,true)); if (!base) return 0; if (!base->getTypeId().isDerivedFrom(Property::getClassTypeId())) { delete base; std::stringstream str; str << "'" << type << "' is not a property type"; throw Base::Exception(str.str()); } // get unique name Property* pcProperty = static_cast<Property*>(base); std::string ObjectName; if (name && *name != '\0') ObjectName = getUniquePropertyName(name); else ObjectName = getUniquePropertyName(type); pcProperty->setContainer(this->pc); PropData data; data.property = pcProperty; data.group = (group ? group : ""); data.doc = (doc ? doc : ""); data.attr = attr; data.readonly = ro; data.hidden = hidden; props[ObjectName] = data; return pcProperty; } bool DynamicProperty::removeDynamicProperty(const char* name) { std::map<std::string,PropData>::iterator it = props.find(name); if (it != props.end()) { delete it->second.property; props.erase(it); return true; } return false; } std::string DynamicProperty::getUniquePropertyName(const char *Name) const { std::string CleanName = Base::Tools::getIdentifier(Name); // name in use? std::map<std::string,Property*> objectProps; getPropertyMap(objectProps); std::map<std::string,Property*>::const_iterator pos; pos = objectProps.find(CleanName); if (pos == objectProps.end()) { // if not, name is OK return CleanName; } else { std::vector<std::string> names; names.reserve(objectProps.size()); for (pos = objectProps.begin();pos != objectProps.end();++pos) { names.push_back(pos->first); } return Base::Tools::getUniqueName(CleanName, names); } } std::string DynamicProperty::encodeAttribute(const std::string& str) const { std::string tmp; for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) { if (*it == '<') tmp += "&lt;"; else if (*it == '"') tmp += "&quot;"; else if (*it == '&') tmp += "&amp;"; else if (*it == '>') tmp += "&gt;"; else if (*it == '\n') tmp += " "; else tmp += *it; } return tmp; } void DynamicProperty::Save (Base::Writer &writer) const { std::map<std::string,Property*> Map; getPropertyMap(Map); writer.incInd(); // indention for 'Properties Count' writer.Stream() << writer.ind() << "<Properties Count=\"" << Map.size() << "\">" << std::endl; std::map<std::string,Property*>::iterator it; for (it = Map.begin(); it != Map.end(); ++it) { writer.incInd(); // indention for 'Property name' // check whether a static or dynamic property std::map<std::string,PropData>::const_iterator pt = props.find(it->first); if (pt == props.end()) { writer.Stream() << writer.ind() << "<Property name=\"" << it->first << "\" type=\"" << it->second->getTypeId().getName() << "\">" << std::endl; } else { writer.Stream() << writer.ind() << "<Property name=\"" << it->first << "\" type=\"" << it->second->getTypeId().getName() << "\" group=\"" << encodeAttribute(pt->second.group) << "\" doc=\"" << encodeAttribute(pt->second.doc) << "\" attr=\"" << pt->second.attr << "\" ro=\"" << pt->second.readonly << "\" hide=\"" << pt->second.hidden << "\">" << std::endl; } writer.incInd(); // indention for the actual property try { // We must make sure to handle all exceptions accordingly so that // the project file doesn't get invalidated. In the error case this // means to proceed instead of aborting the write operation. // Don't write transient properties if (!(getPropertyType(it->second) & Prop_Transient)) it->second->Save(writer); } catch (const Base::Exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const std::exception &e) { Base::Console().Error("%s\n", e.what()); } catch (const char* e) { Base::Console().Error("%s\n", e); } #ifndef FC_DEBUG catch (...) { Base::Console().Error("DynamicProperty::Save: Unknown C++ exception thrown. Try to continue...\n"); } #endif writer.decInd(); // indention for the actual property writer.Stream() << writer.ind() << "</Property>" << std::endl; writer.decInd(); // indention for 'Property name' } writer.Stream() << writer.ind() << "</Properties>" << std::endl; writer.decInd(); // indention for 'Properties Count' } void DynamicProperty::Restore(Base::XMLReader &reader) { reader.readElement("Properties"); int Cnt = reader.getAttributeAsInteger("Count"); for (int i=0 ;i<Cnt ;i++) { reader.readElement("Property"); const char* PropName = reader.getAttribute("name"); const char* TypeName = reader.getAttribute("type"); Property* prop = getPropertyByName(PropName); try { if (!prop) { short attribute = 0; bool readonly = false, hidden = false; const char *group=0, *doc=0, *attr=0, *ro=0, *hide=0; if (reader.hasAttribute("group")) group = reader.getAttribute("group"); if (reader.hasAttribute("doc")) doc = reader.getAttribute("doc"); if (reader.hasAttribute("attr")) { attr = reader.getAttribute("attr"); if (attr) attribute = attr[0]-48; } if (reader.hasAttribute("ro")) { ro = reader.getAttribute("ro"); if (ro) readonly = (ro[0]-48) != 0; } if (reader.hasAttribute("hide")) { hide = reader.getAttribute("hide"); if (hide) hidden = (hide[0]-48) != 0; } prop = addDynamicProperty(TypeName, PropName, group, doc, attribute, readonly, hidden); } } catch(const Base::Exception& e) { // only handle this exception type Base::Console().Warning(e.what()); } //NOTE: We must also check the type of the current property because a subclass of //PropertyContainer might change the type of a property but not its name. In this //case we would force to read-in a wrong property type and the behaviour would be //undefined. // Don't read transient properties if (!(getPropertyType(prop) & Prop_Transient)) { if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0) prop->Restore(reader); else if (prop) Base::Console().Warning("%s: Overread data for property %s of type %s, expected type is %s\n", pc->getTypeId().getName(), prop->getName(), prop->getTypeId().getName(), TypeName); else Base::Console().Warning("%s: No property found with name %s and type %s\n", pc->getTypeId().getName(), PropName, TypeName); } reader.readEndElement("Property"); } reader.readEndElement("Properties"); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gamepad/platform_data_fetcher_win.h" #include "base/debug/trace_event.h" #include "content/common/gamepad_messages.h" #include "content/common/gamepad_hardware_buffer.h" #include <delayimp.h> #pragma comment(lib, "delayimp.lib") #pragma comment(lib, "xinput.lib") namespace content { using namespace WebKit; namespace { // See http://goo.gl/5VSJR. These are not available in all versions of the // header, but they can be returned from the driver, so we define our own // versions here. static const BYTE kDeviceSubTypeGamepad = 1; static const BYTE kDeviceSubTypeWheel = 2; static const BYTE kDeviceSubTypeArcadeStick = 3; static const BYTE kDeviceSubTypeFlightStick = 4; static const BYTE kDeviceSubTypeDancePad = 5; static const BYTE kDeviceSubTypeGuitar = 6; static const BYTE kDeviceSubTypeGuitarAlternate = 7; static const BYTE kDeviceSubTypeDrumKit = 8; static const BYTE kDeviceSubTypeGuitarBass = 11; static const BYTE kDeviceSubTypeArcadePad = 19; const WebUChar* const GamepadSubTypeName(BYTE sub_type) { switch (sub_type) { case kDeviceSubTypeGamepad: return L"GAMEPAD"; case kDeviceSubTypeWheel: return L"WHEEL"; case kDeviceSubTypeArcadeStick: return L"ARCADE_STICK"; case kDeviceSubTypeFlightStick: return L"FLIGHT_STICK"; case kDeviceSubTypeDancePad: return L"DANCE_PAD"; case kDeviceSubTypeGuitar: return L"GUITAR"; case kDeviceSubTypeGuitarAlternate: return L"GUITAR_ALTERNATE"; case kDeviceSubTypeDrumKit: return L"DRUM_KIT"; case kDeviceSubTypeGuitarBass: return L"GUITAR_BASS"; case kDeviceSubTypeArcadePad: return L"ARCADE_PAD"; default: return L"<UNKNOWN>"; } } // Trap only the exceptions that DELAYLOAD can throw, otherwise rethrow. // See http://msdn.microsoft.com/en-us/library/1c9e046h(v=VS.90).aspx. LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers) { LONG disposition = EXCEPTION_EXECUTE_HANDLER; switch (pExcPointers->ExceptionRecord->ExceptionCode) { case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): case VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND): break; default: // Exception is not related to delay loading. disposition = EXCEPTION_CONTINUE_SEARCH; break; } return disposition; } bool EnableXInput() { // We have specified DELAYLOAD for xinput1_3.dll. If the DLL is not // installed (XP w/o DirectX redist installed), we disable functionality. __try { ;//XInputEnable(true); } __except(DelayLoadDllExceptionFilter(GetExceptionInformation())) { return false; } return true; } } GamepadPlatformDataFetcherWin::GamepadPlatformDataFetcherWin() : xinput_available_(EnableXInput()) { } void GamepadPlatformDataFetcherWin::GetGamepadData(WebGamepads* pads, bool devices_changed_hint) { TRACE_EVENT0("GAMEPAD", "GetGamepadData"); // If there's no XInput DLL on the system, early out so that we don't // call any other XInput functions. if (!xinput_available_) { pads->length = 0; return; } pads->length = WebGamepads::itemsLengthCap; // If we got notification that system devices have been updated, then // run GetCapabilities to update the connected status and the device // identifier. It can be slow to do to both GetCapabilities and // GetState on unconnected devices, so we want to avoid a 2-5ms pause // here by only doing this when the devices are updated (despite // documentation claiming it's OK to call it any time). if (devices_changed_hint) { for (unsigned i = 0; i < WebGamepads::itemsLengthCap; ++i) { WebGamepad& pad = pads->items[i]; TRACE_EVENT1("GAMEPAD", "GetCapabilities", "id", i); XINPUT_CAPABILITIES caps; DWORD res = XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, &caps); if (res == ERROR_DEVICE_NOT_CONNECTED) { pad.connected = false; } else { pad.connected = true; base::swprintf(pad.id, WebGamepad::idLengthCap, L"Xbox 360 Controller (XInput STANDARD %ls)", GamepadSubTypeName(caps.SubType)); } } } // We've updated the connection state if necessary, now update the actual // data for the devices that are connected. for (unsigned i = 0; i < WebGamepads::itemsLengthCap; ++i) { WebGamepad& pad = pads->items[i]; // We rely on device_changed and GetCapabilities to tell us that // something's been connected, but we will mark as disconnected if // GetState returns that we've lost the pad. if (!pad.connected) continue; XINPUT_STATE state; memset(&state, 0, sizeof(XINPUT_STATE)); TRACE_EVENT_BEGIN1("GAMEPAD", "XInputGetState", "id", i); DWORD dwResult = XInputGetState(i, &state); TRACE_EVENT_END1("GAMEPAD", "XInputGetState", "id", i); if (dwResult == ERROR_SUCCESS) { pad.timestamp = state.dwPacketNumber; pad.buttonsLength = 0; #define ADD(b) pad.buttons[pad.buttonsLength++] = \ ((state.Gamepad.wButtons & (b)) ? 1.0 : 0.0); ADD(XINPUT_GAMEPAD_A); ADD(XINPUT_GAMEPAD_B); ADD(XINPUT_GAMEPAD_X); ADD(XINPUT_GAMEPAD_Y); ADD(XINPUT_GAMEPAD_LEFT_SHOULDER); ADD(XINPUT_GAMEPAD_RIGHT_SHOULDER); pad.buttons[pad.buttonsLength++] = state.Gamepad.bLeftTrigger / 255.0; pad.buttons[pad.buttonsLength++] = state.Gamepad.bRightTrigger / 255.0; ADD(XINPUT_GAMEPAD_BACK); ADD(XINPUT_GAMEPAD_START); ADD(XINPUT_GAMEPAD_LEFT_THUMB); ADD(XINPUT_GAMEPAD_RIGHT_THUMB); ADD(XINPUT_GAMEPAD_DPAD_UP); ADD(XINPUT_GAMEPAD_DPAD_DOWN); ADD(XINPUT_GAMEPAD_DPAD_LEFT); ADD(XINPUT_GAMEPAD_DPAD_RIGHT); #undef ADD pad.axesLength = 0; // XInput are +up/+right, -down/-left, we want -up/-left. pad.axes[pad.axesLength++] = state.Gamepad.sThumbLX / 32767.0; pad.axes[pad.axesLength++] = -state.Gamepad.sThumbLY / 32767.0; pad.axes[pad.axesLength++] = state.Gamepad.sThumbRX / 32767.0; pad.axes[pad.axesLength++] = -state.Gamepad.sThumbRY / 32767.0; } else { pad.connected = false; } } } } // namespace content <commit_msg>re-enable call to XInputEnable<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/gamepad/platform_data_fetcher_win.h" #include "base/debug/trace_event.h" #include "content/common/gamepad_messages.h" #include "content/common/gamepad_hardware_buffer.h" #include <delayimp.h> #pragma comment(lib, "delayimp.lib") #pragma comment(lib, "xinput.lib") namespace content { using namespace WebKit; namespace { // See http://goo.gl/5VSJR. These are not available in all versions of the // header, but they can be returned from the driver, so we define our own // versions here. static const BYTE kDeviceSubTypeGamepad = 1; static const BYTE kDeviceSubTypeWheel = 2; static const BYTE kDeviceSubTypeArcadeStick = 3; static const BYTE kDeviceSubTypeFlightStick = 4; static const BYTE kDeviceSubTypeDancePad = 5; static const BYTE kDeviceSubTypeGuitar = 6; static const BYTE kDeviceSubTypeGuitarAlternate = 7; static const BYTE kDeviceSubTypeDrumKit = 8; static const BYTE kDeviceSubTypeGuitarBass = 11; static const BYTE kDeviceSubTypeArcadePad = 19; const WebUChar* const GamepadSubTypeName(BYTE sub_type) { switch (sub_type) { case kDeviceSubTypeGamepad: return L"GAMEPAD"; case kDeviceSubTypeWheel: return L"WHEEL"; case kDeviceSubTypeArcadeStick: return L"ARCADE_STICK"; case kDeviceSubTypeFlightStick: return L"FLIGHT_STICK"; case kDeviceSubTypeDancePad: return L"DANCE_PAD"; case kDeviceSubTypeGuitar: return L"GUITAR"; case kDeviceSubTypeGuitarAlternate: return L"GUITAR_ALTERNATE"; case kDeviceSubTypeDrumKit: return L"DRUM_KIT"; case kDeviceSubTypeGuitarBass: return L"GUITAR_BASS"; case kDeviceSubTypeArcadePad: return L"ARCADE_PAD"; default: return L"<UNKNOWN>"; } } // Trap only the exceptions that DELAYLOAD can throw, otherwise rethrow. // See http://msdn.microsoft.com/en-us/library/1c9e046h(v=VS.90).aspx. LONG WINAPI DelayLoadDllExceptionFilter(PEXCEPTION_POINTERS pExcPointers) { LONG disposition = EXCEPTION_EXECUTE_HANDLER; switch (pExcPointers->ExceptionRecord->ExceptionCode) { case VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND): case VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND): break; default: // Exception is not related to delay loading. disposition = EXCEPTION_CONTINUE_SEARCH; break; } return disposition; } bool EnableXInput() { // We have specified DELAYLOAD for xinput1_3.dll. If the DLL is not // installed (XP w/o DirectX redist installed), we disable functionality. __try { XInputEnable(true); } __except(DelayLoadDllExceptionFilter(GetExceptionInformation())) { return false; } return true; } } GamepadPlatformDataFetcherWin::GamepadPlatformDataFetcherWin() : xinput_available_(EnableXInput()) { } void GamepadPlatformDataFetcherWin::GetGamepadData(WebGamepads* pads, bool devices_changed_hint) { TRACE_EVENT0("GAMEPAD", "GetGamepadData"); // If there's no XInput DLL on the system, early out so that we don't // call any other XInput functions. if (!xinput_available_) { pads->length = 0; return; } pads->length = WebGamepads::itemsLengthCap; // If we got notification that system devices have been updated, then // run GetCapabilities to update the connected status and the device // identifier. It can be slow to do to both GetCapabilities and // GetState on unconnected devices, so we want to avoid a 2-5ms pause // here by only doing this when the devices are updated (despite // documentation claiming it's OK to call it any time). if (devices_changed_hint) { for (unsigned i = 0; i < WebGamepads::itemsLengthCap; ++i) { WebGamepad& pad = pads->items[i]; TRACE_EVENT1("GAMEPAD", "GetCapabilities", "id", i); XINPUT_CAPABILITIES caps; DWORD res = XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, &caps); if (res == ERROR_DEVICE_NOT_CONNECTED) { pad.connected = false; } else { pad.connected = true; base::swprintf(pad.id, WebGamepad::idLengthCap, L"Xbox 360 Controller (XInput STANDARD %ls)", GamepadSubTypeName(caps.SubType)); } } } // We've updated the connection state if necessary, now update the actual // data for the devices that are connected. for (unsigned i = 0; i < WebGamepads::itemsLengthCap; ++i) { WebGamepad& pad = pads->items[i]; // We rely on device_changed and GetCapabilities to tell us that // something's been connected, but we will mark as disconnected if // GetState returns that we've lost the pad. if (!pad.connected) continue; XINPUT_STATE state; memset(&state, 0, sizeof(XINPUT_STATE)); TRACE_EVENT_BEGIN1("GAMEPAD", "XInputGetState", "id", i); DWORD dwResult = XInputGetState(i, &state); TRACE_EVENT_END1("GAMEPAD", "XInputGetState", "id", i); if (dwResult == ERROR_SUCCESS) { pad.timestamp = state.dwPacketNumber; pad.buttonsLength = 0; #define ADD(b) pad.buttons[pad.buttonsLength++] = \ ((state.Gamepad.wButtons & (b)) ? 1.0 : 0.0); ADD(XINPUT_GAMEPAD_A); ADD(XINPUT_GAMEPAD_B); ADD(XINPUT_GAMEPAD_X); ADD(XINPUT_GAMEPAD_Y); ADD(XINPUT_GAMEPAD_LEFT_SHOULDER); ADD(XINPUT_GAMEPAD_RIGHT_SHOULDER); pad.buttons[pad.buttonsLength++] = state.Gamepad.bLeftTrigger / 255.0; pad.buttons[pad.buttonsLength++] = state.Gamepad.bRightTrigger / 255.0; ADD(XINPUT_GAMEPAD_BACK); ADD(XINPUT_GAMEPAD_START); ADD(XINPUT_GAMEPAD_LEFT_THUMB); ADD(XINPUT_GAMEPAD_RIGHT_THUMB); ADD(XINPUT_GAMEPAD_DPAD_UP); ADD(XINPUT_GAMEPAD_DPAD_DOWN); ADD(XINPUT_GAMEPAD_DPAD_LEFT); ADD(XINPUT_GAMEPAD_DPAD_RIGHT); #undef ADD pad.axesLength = 0; // XInput are +up/+right, -down/-left, we want -up/-left. pad.axes[pad.axesLength++] = state.Gamepad.sThumbLX / 32767.0; pad.axes[pad.axesLength++] = -state.Gamepad.sThumbLY / 32767.0; pad.axes[pad.axesLength++] = state.Gamepad.sThumbRX / 32767.0; pad.axes[pad.axesLength++] = -state.Gamepad.sThumbRY / 32767.0; } else { pad.connected = false; } } } } // namespace content <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/sandbox_linux/bpf_gpu_policy_linux.h" #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h" #include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h" #include "content/common/set_process_title.h" #include "content/public/common/content_switches.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" #include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h" #include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h" #include "sandbox/linux/syscall_broker/broker_file_permission.h" #include "sandbox/linux/syscall_broker/broker_process.h" #include "sandbox/linux/system_headers/linux_syscalls.h" using sandbox::arch_seccomp_data; using sandbox::bpf_dsl::Allow; using sandbox::bpf_dsl::ResultExpr; using sandbox::bpf_dsl::Trap; using sandbox::syscall_broker::BrokerFilePermission; using sandbox::syscall_broker::BrokerProcess; using sandbox::SyscallSets; namespace content { namespace { inline bool IsChromeOS() { #if defined(OS_CHROMEOS) return true; #else return false; #endif } inline bool IsArchitectureX86_64() { #if defined(__x86_64__) return true; #else return false; #endif } inline bool IsArchitectureI386() { #if defined(__i386__) return true; #else return false; #endif } inline bool IsArchitectureArm() { #if defined(__arm__) || defined(__aarch64__) return true; #else return false; #endif } inline bool IsOzone() { #if defined(USE_OZONE) return true; #else return false; #endif } inline bool UseLibV4L2() { #if defined(USE_LIBV4L2) return true; #else return false; #endif } bool IsAcceleratedVaapiVideoEncodeEnabled() { bool accelerated_encode_enabled = false; #if defined(OS_CHROMEOS) const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); accelerated_encode_enabled = !command_line.HasSwitch(switches::kDisableVaapiAcceleratedVideoEncode); #endif return accelerated_encode_enabled; } bool IsAcceleratedVideoDecodeEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode); } intptr_t GpuSIGSYS_Handler(const struct arch_seccomp_data& args, void* aux_broker_process) { RAW_CHECK(aux_broker_process); BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux_broker_process); switch (args.nr) { #if !defined(__aarch64__) case __NR_access: return broker_process->Access(reinterpret_cast<const char*>(args.args[0]), static_cast<int>(args.args[1])); case __NR_open: #if defined(MEMORY_SANITIZER) // http://crbug.com/372840 __msan_unpoison_string(reinterpret_cast<const char*>(args.args[0])); #endif return broker_process->Open(reinterpret_cast<const char*>(args.args[0]), static_cast<int>(args.args[1])); #endif // !defined(__aarch64__) case __NR_faccessat: if (static_cast<int>(args.args[0]) == AT_FDCWD) { return broker_process->Access(reinterpret_cast<const char*>(args.args[1]), static_cast<int>(args.args[2])); } else { return -EPERM; } case __NR_openat: // Allow using openat() as open(). if (static_cast<int>(args.args[0]) == AT_FDCWD) { return broker_process->Open(reinterpret_cast<const char*>(args.args[1]), static_cast<int>(args.args[2])); } else { return -EPERM; } default: RAW_CHECK(false); return -ENOSYS; } } void AddV4L2GpuWhitelist(std::vector<BrokerFilePermission>* permissions) { if (IsAcceleratedVideoDecodeEnabled()) { // Device node for V4L2 video decode accelerator drivers. static const char kDevVideoDecPath[] = "/dev/video-dec"; permissions->push_back(BrokerFilePermission::ReadWrite(kDevVideoDecPath)); } // Device node for V4L2 video encode accelerator drivers. static const char kDevVideoEncPath[] = "/dev/video-enc"; permissions->push_back(BrokerFilePermission::ReadWrite(kDevVideoEncPath)); } class GpuBrokerProcessPolicy : public GpuProcessPolicy { public: static sandbox::bpf_dsl::Policy* Create() { return new GpuBrokerProcessPolicy(); } ~GpuBrokerProcessPolicy() override {} ResultExpr EvaluateSyscall(int system_call_number) const override; private: GpuBrokerProcessPolicy() {} DISALLOW_COPY_AND_ASSIGN(GpuBrokerProcessPolicy); }; // x86_64/i386 or desktop ARM. // A GPU broker policy is the same as a GPU policy with access, open, // openat and in the non-Chrome OS case unlink allowed. ResultExpr GpuBrokerProcessPolicy::EvaluateSyscall(int sysno) const { switch (sysno) { #if !defined(__aarch64__) case __NR_access: case __NR_open: #endif // !defined(__aarch64__) case __NR_faccessat: case __NR_openat: #if !defined(OS_CHROMEOS) // The broker process needs to able to unlink the temporary // files that it may create. This is used by DRI3. case __NR_unlink: #endif return Allow(); default: return GpuProcessPolicy::EvaluateSyscall(sysno); } } void UpdateProcessTypeToGpuBroker() { base::CommandLine::StringVector exec = base::CommandLine::ForCurrentProcess()->GetArgs(); base::CommandLine::Reset(); base::CommandLine::Init(0, NULL); base::CommandLine::ForCurrentProcess()->InitFromArgv(exec); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kProcessType, "gpu-broker"); // Update the process title. The argv was already cached by the call to // SetProcessTitleFromCommandLine in content_main_runner.cc, so we can pass // NULL here (we don't have the original argv at this point). SetProcessTitleFromCommandLine(NULL); } bool UpdateProcessTypeAndEnableSandbox( sandbox::bpf_dsl::Policy* (*broker_sandboxer_allocator)(void)) { DCHECK(broker_sandboxer_allocator); UpdateProcessTypeToGpuBroker(); return SandboxSeccompBPF::StartSandboxWithExternalPolicy( make_scoped_ptr(broker_sandboxer_allocator()), base::ScopedFD()); } } // namespace GpuProcessPolicy::GpuProcessPolicy() : GpuProcessPolicy(false) { } GpuProcessPolicy::GpuProcessPolicy(bool allow_mincore) : broker_process_(NULL), allow_mincore_(allow_mincore) { } GpuProcessPolicy::~GpuProcessPolicy() {} // Main policy for x86_64/i386. Extended by CrosArmGpuProcessPolicy. ResultExpr GpuProcessPolicy::EvaluateSyscall(int sysno) const { switch (sysno) { #if !defined(OS_CHROMEOS) case __NR_ftruncate: #endif case __NR_ioctl: return Allow(); case __NR_mincore: if (allow_mincore_) { return Allow(); } else { return SandboxBPFBasePolicy::EvaluateSyscall(sysno); } #if defined(__i386__) || defined(__x86_64__) || defined(__mips__) // The Nvidia driver uses flags not in the baseline policy // (MAP_LOCKED | MAP_EXECUTABLE | MAP_32BIT) case __NR_mmap: #endif // We also hit this on the linux_chromeos bot but don't yet know what // weird flags were involved. case __NR_mprotect: // TODO(jln): restrict prctl. case __NR_prctl: return Allow(); #if !defined(__aarch64__) case __NR_access: case __NR_open: #endif // !defined(__aarch64__) case __NR_faccessat: case __NR_openat: DCHECK(broker_process_); return Trap(GpuSIGSYS_Handler, broker_process_); case __NR_sched_getaffinity: case __NR_sched_setaffinity: return sandbox::RestrictSchedTarget(GetPolicyPid(), sysno); default: if (SyscallSets::IsEventFd(sysno)) return Allow(); // Default on the baseline policy. return SandboxBPFBasePolicy::EvaluateSyscall(sysno); } } bool GpuProcessPolicy::PreSandboxHook() { // Warm up resources needed by the policy we're about to enable and // eventually start a broker process. const bool chromeos_arm_gpu = IsChromeOS() && IsArchitectureArm(); // This policy is for x86 or Desktop. DCHECK(!chromeos_arm_gpu); DCHECK(!broker_process()); // Create a new broker process. InitGpuBrokerProcess( GpuBrokerProcessPolicy::Create, std::vector<BrokerFilePermission>()); // No extra files in whitelist. if (IsArchitectureX86_64() || IsArchitectureI386()) { // Accelerated video dlopen()'s some shared objects // inside the sandbox, so preload them now. if (IsAcceleratedVaapiVideoEncodeEnabled() || IsAcceleratedVideoDecodeEnabled()) { const char* I965DrvVideoPath = NULL; if (IsArchitectureX86_64()) { I965DrvVideoPath = "/usr/lib64/va/drivers/i965_drv_video.so"; } else if (IsArchitectureI386()) { I965DrvVideoPath = "/usr/lib/va/drivers/i965_drv_video.so"; } dlopen(I965DrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); dlopen("libva.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #if defined(USE_OZONE) dlopen("libva-drm.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #elif defined(USE_X11) dlopen("libva-x11.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #endif } } return true; } void GpuProcessPolicy::InitGpuBrokerProcess( sandbox::bpf_dsl::Policy* (*broker_sandboxer_allocator)(void), const std::vector<BrokerFilePermission>& permissions_extra) { static const char kDriRcPath[] = "/etc/drirc"; static const char kDriCard0Path[] = "/dev/dri/card0"; static const char kDevShm[] = "/dev/shm/"; CHECK(broker_process_ == NULL); // All GPU process policies need these files brokered out. std::vector<BrokerFilePermission> permissions; permissions.push_back(BrokerFilePermission::ReadWrite(kDriCard0Path)); permissions.push_back(BrokerFilePermission::ReadOnly(kDriRcPath)); if (!IsChromeOS()) { permissions.push_back( BrokerFilePermission::ReadWriteCreateUnlinkRecursive(kDevShm)); } else if (IsArchitectureArm() || IsOzone()){ AddV4L2GpuWhitelist(&permissions); if (UseLibV4L2()) { dlopen("/usr/lib/libv4l2.so", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); // This is a device-specific encoder plugin. dlopen("/usr/lib/libv4l/plugins/libv4l-encplugin.so", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); } } // Add eventual extra files from permissions_extra. for (const auto& perm : permissions_extra) { permissions.push_back(perm); } broker_process_ = new BrokerProcess(GetFSDeniedErrno(), permissions); // The initialization callback will perform generic initialization and then // call broker_sandboxer_callback. CHECK(broker_process_->Init(base::Bind(&UpdateProcessTypeAndEnableSandbox, broker_sandboxer_allocator))); } } // namespace content <commit_msg>[Tizen] Hard code for va driver<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/sandbox_linux/bpf_gpu_policy_linux.h" #include <dlfcn.h> #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h" #include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h" #include "content/common/set_process_title.h" #include "content/public/common/content_switches.h" #include "sandbox/linux/bpf_dsl/bpf_dsl.h" #include "sandbox/linux/seccomp-bpf-helpers/syscall_parameters_restrictions.h" #include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h" #include "sandbox/linux/syscall_broker/broker_file_permission.h" #include "sandbox/linux/syscall_broker/broker_process.h" #include "sandbox/linux/system_headers/linux_syscalls.h" using sandbox::arch_seccomp_data; using sandbox::bpf_dsl::Allow; using sandbox::bpf_dsl::ResultExpr; using sandbox::bpf_dsl::Trap; using sandbox::syscall_broker::BrokerFilePermission; using sandbox::syscall_broker::BrokerProcess; using sandbox::SyscallSets; namespace content { namespace { inline bool IsChromeOS() { #if defined(OS_CHROMEOS) return true; #else return false; #endif } inline bool IsArchitectureX86_64() { #if defined(__x86_64__) return true; #else return false; #endif } inline bool IsArchitectureI386() { #if defined(__i386__) return true; #else return false; #endif } inline bool IsArchitectureArm() { #if defined(__arm__) || defined(__aarch64__) return true; #else return false; #endif } inline bool IsOzone() { #if defined(USE_OZONE) return true; #else return false; #endif } inline bool UseLibV4L2() { #if defined(USE_LIBV4L2) return true; #else return false; #endif } bool IsAcceleratedVaapiVideoEncodeEnabled() { bool accelerated_encode_enabled = false; #if defined(OS_CHROMEOS) const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); accelerated_encode_enabled = !command_line.HasSwitch(switches::kDisableVaapiAcceleratedVideoEncode); #endif return accelerated_encode_enabled; } bool IsAcceleratedVideoDecodeEnabled() { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode); } intptr_t GpuSIGSYS_Handler(const struct arch_seccomp_data& args, void* aux_broker_process) { RAW_CHECK(aux_broker_process); BrokerProcess* broker_process = static_cast<BrokerProcess*>(aux_broker_process); switch (args.nr) { #if !defined(__aarch64__) case __NR_access: return broker_process->Access(reinterpret_cast<const char*>(args.args[0]), static_cast<int>(args.args[1])); case __NR_open: #if defined(MEMORY_SANITIZER) // http://crbug.com/372840 __msan_unpoison_string(reinterpret_cast<const char*>(args.args[0])); #endif return broker_process->Open(reinterpret_cast<const char*>(args.args[0]), static_cast<int>(args.args[1])); #endif // !defined(__aarch64__) case __NR_faccessat: if (static_cast<int>(args.args[0]) == AT_FDCWD) { return broker_process->Access(reinterpret_cast<const char*>(args.args[1]), static_cast<int>(args.args[2])); } else { return -EPERM; } case __NR_openat: // Allow using openat() as open(). if (static_cast<int>(args.args[0]) == AT_FDCWD) { return broker_process->Open(reinterpret_cast<const char*>(args.args[1]), static_cast<int>(args.args[2])); } else { return -EPERM; } default: RAW_CHECK(false); return -ENOSYS; } } void AddV4L2GpuWhitelist(std::vector<BrokerFilePermission>* permissions) { if (IsAcceleratedVideoDecodeEnabled()) { // Device node for V4L2 video decode accelerator drivers. static const char kDevVideoDecPath[] = "/dev/video-dec"; permissions->push_back(BrokerFilePermission::ReadWrite(kDevVideoDecPath)); } // Device node for V4L2 video encode accelerator drivers. static const char kDevVideoEncPath[] = "/dev/video-enc"; permissions->push_back(BrokerFilePermission::ReadWrite(kDevVideoEncPath)); } class GpuBrokerProcessPolicy : public GpuProcessPolicy { public: static sandbox::bpf_dsl::Policy* Create() { return new GpuBrokerProcessPolicy(); } ~GpuBrokerProcessPolicy() override {} ResultExpr EvaluateSyscall(int system_call_number) const override; private: GpuBrokerProcessPolicy() {} DISALLOW_COPY_AND_ASSIGN(GpuBrokerProcessPolicy); }; // x86_64/i386 or desktop ARM. // A GPU broker policy is the same as a GPU policy with access, open, // openat and in the non-Chrome OS case unlink allowed. ResultExpr GpuBrokerProcessPolicy::EvaluateSyscall(int sysno) const { switch (sysno) { #if !defined(__aarch64__) case __NR_access: case __NR_open: #endif // !defined(__aarch64__) case __NR_faccessat: case __NR_openat: #if !defined(OS_CHROMEOS) // The broker process needs to able to unlink the temporary // files that it may create. This is used by DRI3. case __NR_unlink: #endif return Allow(); default: return GpuProcessPolicy::EvaluateSyscall(sysno); } } void UpdateProcessTypeToGpuBroker() { base::CommandLine::StringVector exec = base::CommandLine::ForCurrentProcess()->GetArgs(); base::CommandLine::Reset(); base::CommandLine::Init(0, NULL); base::CommandLine::ForCurrentProcess()->InitFromArgv(exec); base::CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kProcessType, "gpu-broker"); // Update the process title. The argv was already cached by the call to // SetProcessTitleFromCommandLine in content_main_runner.cc, so we can pass // NULL here (we don't have the original argv at this point). SetProcessTitleFromCommandLine(NULL); } bool UpdateProcessTypeAndEnableSandbox( sandbox::bpf_dsl::Policy* (*broker_sandboxer_allocator)(void)) { DCHECK(broker_sandboxer_allocator); UpdateProcessTypeToGpuBroker(); return SandboxSeccompBPF::StartSandboxWithExternalPolicy( make_scoped_ptr(broker_sandboxer_allocator()), base::ScopedFD()); } } // namespace GpuProcessPolicy::GpuProcessPolicy() : GpuProcessPolicy(false) { } GpuProcessPolicy::GpuProcessPolicy(bool allow_mincore) : broker_process_(NULL), allow_mincore_(allow_mincore) { } GpuProcessPolicy::~GpuProcessPolicy() {} // Main policy for x86_64/i386. Extended by CrosArmGpuProcessPolicy. ResultExpr GpuProcessPolicy::EvaluateSyscall(int sysno) const { switch (sysno) { #if !defined(OS_CHROMEOS) case __NR_ftruncate: #endif case __NR_ioctl: return Allow(); case __NR_mincore: if (allow_mincore_) { return Allow(); } else { return SandboxBPFBasePolicy::EvaluateSyscall(sysno); } #if defined(__i386__) || defined(__x86_64__) || defined(__mips__) // The Nvidia driver uses flags not in the baseline policy // (MAP_LOCKED | MAP_EXECUTABLE | MAP_32BIT) case __NR_mmap: #endif // We also hit this on the linux_chromeos bot but don't yet know what // weird flags were involved. case __NR_mprotect: // TODO(jln): restrict prctl. case __NR_prctl: return Allow(); #if !defined(__aarch64__) case __NR_access: case __NR_open: #endif // !defined(__aarch64__) case __NR_faccessat: case __NR_openat: DCHECK(broker_process_); return Trap(GpuSIGSYS_Handler, broker_process_); case __NR_sched_getaffinity: case __NR_sched_setaffinity: return sandbox::RestrictSchedTarget(GetPolicyPid(), sysno); default: if (SyscallSets::IsEventFd(sysno)) return Allow(); // Default on the baseline policy. return SandboxBPFBasePolicy::EvaluateSyscall(sysno); } } bool GpuProcessPolicy::PreSandboxHook() { // Warm up resources needed by the policy we're about to enable and // eventually start a broker process. const bool chromeos_arm_gpu = IsChromeOS() && IsArchitectureArm(); // This policy is for x86 or Desktop. DCHECK(!chromeos_arm_gpu); DCHECK(!broker_process()); // Create a new broker process. InitGpuBrokerProcess( GpuBrokerProcessPolicy::Create, std::vector<BrokerFilePermission>()); // No extra files in whitelist. if (IsArchitectureX86_64() || IsArchitectureI386()) { // Accelerated video dlopen()'s some shared objects // inside the sandbox, so preload them now. if (IsAcceleratedVaapiVideoEncodeEnabled() || IsAcceleratedVideoDecodeEnabled()) { const char* I965DrvVideoPath = NULL; #if defined(OS_TIZEN) if (IsArchitectureX86_64()) { // TODO(halton): Add 64-bit VA driver when 64-bit Tizen support // is ready. return false; } else if (IsArchitectureI386()) { I965DrvVideoPath = "/usr/lib/dri/i965_dri.so"; } #else if (IsArchitectureX86_64()) { I965DrvVideoPath = "/usr/lib64/va/drivers/i965_drv_video.so"; } else if (IsArchitectureI386()) { I965DrvVideoPath = "/usr/lib/va/drivers/i965_drv_video.so"; } #endif dlopen(I965DrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); dlopen("libva.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #if defined(USE_OZONE) dlopen("libva-drm.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #elif defined(USE_X11) dlopen("libva-x11.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); #endif } } return true; } void GpuProcessPolicy::InitGpuBrokerProcess( sandbox::bpf_dsl::Policy* (*broker_sandboxer_allocator)(void), const std::vector<BrokerFilePermission>& permissions_extra) { static const char kDriRcPath[] = "/etc/drirc"; static const char kDriCard0Path[] = "/dev/dri/card0"; static const char kDevShm[] = "/dev/shm/"; CHECK(broker_process_ == NULL); // All GPU process policies need these files brokered out. std::vector<BrokerFilePermission> permissions; permissions.push_back(BrokerFilePermission::ReadWrite(kDriCard0Path)); permissions.push_back(BrokerFilePermission::ReadOnly(kDriRcPath)); if (!IsChromeOS()) { permissions.push_back( BrokerFilePermission::ReadWriteCreateUnlinkRecursive(kDevShm)); } else if (IsArchitectureArm() || IsOzone()){ AddV4L2GpuWhitelist(&permissions); if (UseLibV4L2()) { dlopen("/usr/lib/libv4l2.so", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); // This is a device-specific encoder plugin. dlopen("/usr/lib/libv4l/plugins/libv4l-encplugin.so", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE); } } // Add eventual extra files from permissions_extra. for (const auto& perm : permissions_extra) { permissions.push_back(perm); } broker_process_ = new BrokerProcess(GetFSDeniedErrno(), permissions); // The initialization callback will perform generic initialization and then // call broker_sandboxer_callback. CHECK(broker_process_->Init(base::Bind(&UpdateProcessTypeAndEnableSandbox, broker_sandboxer_allocator))); } } // namespace content <|endoftext|>
<commit_before>// SciTE - Scintilla based Text Editor /** @file UniqueInstance.cxx ** Class to ensure a unique instance of the editor, if requested. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "SciTEWin.h" UniqueInstance::UniqueInstance() { stw = 0; identityMessage = ::RegisterWindowMessage("SciTEInstanceIdentifier"); mutex = 0; bAlreadyRunning = false; hOtherWindow = NULL; } UniqueInstance::~UniqueInstance() { if (mutex) { ::CloseHandle(mutex); } } void UniqueInstance::Init(SciTEWin *stw_) { stw = stw_; } /** * Try to create a mutex. * If succeed, it is the first/only instance. * Otherwise, there is already an instance holding this mutex. */ bool UniqueInstance::AcceptToOpenFiles(bool bAccept) { bool bError = false; stw->openFilesHere = bAccept; if (bAccept) { // We create a mutex because it is an atomic operation. // An operation like EnumWindows is long, so if we use it only, we can fall in a race condition. // Note from MSDN: "The system closes the handle automatically when the process terminates. // The mutex object is destroyed when its last handle has been closed." // If the mutex already exists, the new process get a handle on it, so even if the first // process exits, the mutex isn't destroyed, until all SciTE instances exit. mutex = ::CreateMutex(NULL, FALSE, mutexName.c_str()); // The call fails with ERROR_ACCESS_DENIED if the mutex was // created in a different user session because of passing // NULL for the SECURITY_ATTRIBUTES on mutex creation bError = (::GetLastError() == ERROR_ALREADY_EXISTS || ::GetLastError() == ERROR_ACCESS_DENIED); } else { ::CloseHandle(mutex); } return !bError; } /** * Toggle the open files here option. * If set, search if another instance have this option set. * If found, we ask it to yield this option, * so we are the only one to accept files. */ void UniqueInstance::ToggleOpenFilesHere() { // If the openFilesHere option is set, we unset it and remove the handle. // Else, we set the option and try to set the mutex. if (!AcceptToOpenFiles(!stw->openFilesHere)) { // Cannot set the mutex, search the previous instance holding it HWND hOtherWindow = NULL; ::EnumWindows(SearchOtherInstance, reinterpret_cast<LPARAM>(this)); if (hOtherWindow != NULL) { // Found, we indicate it to yield the acceptation of files ::SendMessage(hOtherWindow, identityMessage, 0, static_cast<LPARAM>(1)); } } stw->CheckMenus(); } /** * Manage the received COPYDATA message with a command line from another instance. */ LRESULT UniqueInstance::CopyData(COPYDATASTRUCT *pcds) { if (pcds) { if (stw->props.GetInt("minimize.to.tray")) { stw->RestoreFromTray(); } const char *text = static_cast<char *>(pcds->lpData); if (text && strlen(text) > 0) { SString args = stw->ProcessArgs(text); stw->ProcessCommandLine(args, 0); stw->ProcessCommandLine(args, 1); } ::FlashWindow(stw->MainHWND(), FALSE); } return TRUE; } /** * If the given message is the identity message and we hold the * open files here option, we answer the message (so other instances know * we are the one holding the option). * If the message ask to yield this option, we do it nicely... */ LRESULT UniqueInstance::CheckMessage(UINT message, WPARAM wParam, LPARAM lParam) { if (message == identityMessage) { if (stw->openFilesHere || wParam != 0) { // We answer only if the menu item is checked to accept files, // or if the caller force answering by setting wParam to non null // which can be used to find all instances (not used yet). if (stw->openFilesHere && lParam != 0) { // An instance indicates it takes control of the Open Files Here // feature, so this one no longer accept them. AcceptToOpenFiles(false); stw->CheckMenus(); // Update the checkmark } return identityMessage; } } return 0; } /** * To be called only if check.if.already.open option is set to 1. * Create the mutex name, try to set the mutex. * If failed, renounce to the open files here option. */ void UniqueInstance::CheckOtherInstance() { // Use the method explained by Joseph M. Newcomer to avoid multiple instances of an application: // http://www.codeproject.com/cpp/avoidmultinstance.asp // I limit instances by desktop, it seems to make sense with a GUI application... mutexName = "SciTE-UniqueInstanceMutex-"; // I doubt I really need a GUID here... HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId()); DWORD len = 0; // Query the needed size for the buffer BOOL result = ::GetUserObjectInformation(desktop, UOI_NAME, NULL, 0, &len); if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // WinNT / Win2000 char *info = new char[len]; ::GetUserObjectInformation(desktop, UOI_NAME, info, len, &len); mutexName += info; delete []info; } else { // Win9x: no multiple desktop, GetUserObjectInformation can be called // but is bogus... mutexName += "Win9x"; } // Try to set the mutex. If return false, it failed, there is already another instance. bAlreadyRunning = !AcceptToOpenFiles(true); if (bAlreadyRunning) { // Don't answer to requests from other starting instances stw->openFilesHere = false; } } /** * If we know there is another instance with open files here option, * we search it by enumerating windows. * @return true if found. */ bool UniqueInstance::FindOtherInstance() { if (bAlreadyRunning && identityMessage != 0) { ::EnumWindows(SearchOtherInstance, reinterpret_cast<LPARAM>(this)); if (hOtherWindow) { return true; } } return false; } /** * Send the COPYDATA messages to transmit the command line to * the instance holding the open files here option. * After that, the current instance will exit. */ void UniqueInstance::SendCommands(const char *cmdLine) { // On Win2k, windows can't get focus by themselves, // so it is the responsability of the new process to bring the window // to foreground. // Put the other SciTE uniconized and to forefront. if (::IsIconic(hOtherWindow)) { ::ShowWindow(hOtherWindow, SW_RESTORE); } ::SetForegroundWindow(hOtherWindow); COPYDATASTRUCT cds; cds.dwData = 0; // Send 2 messages - first the CWD, so paths relative to // the new instance can be resolved in the old instance, // then the real command line. // (Restoring the cwd could be done, // but keeping it to the last file opened can also // be useful) TCHAR cwdCmd[MAX_PATH + 7]; // 7 for "-cwd:" and 2x'"' strcpy(cwdCmd, "\"-cwd:"); getcwd(cwdCmd + strlen(cwdCmd), MAX_PATH); strcat(cwdCmd, "\""); // Defeat the "\" mangling - convert "\" to "/" for (char *temp = cwdCmd; *temp; temp++) { if (*temp == '\\') { *temp = '/'; } } cds.cbData = static_cast<DWORD>(strlen(cwdCmd) + 1); cds.lpData = static_cast<void *>(cwdCmd); ::SendMessage(hOtherWindow, WM_COPYDATA, 0, reinterpret_cast<LPARAM>(&cds)); // Now the command line itself. cds.cbData = static_cast<DWORD>(strlen(cmdLine) + 1); cds.lpData = static_cast<void *>(const_cast<char *>(cmdLine)); ::SendMessage(hOtherWindow, WM_COPYDATA, 0, reinterpret_cast<LPARAM>(&cds)); } /** * Function called by EnumWindows. * @a hWnd is the handle to the currently enumerated window. * @a lParam is seen as a pointer to the current UniqueInstance * so it can be used to access all members. * @return FALSE if found, to stop EnumWindows. */ BOOL CALLBACK UniqueInstance::SearchOtherInstance(HWND hWnd, LPARAM lParam) { BOOL bResult = TRUE; DWORD result; UniqueInstance *ui = reinterpret_cast<UniqueInstance *>(lParam); // First, avoid to send a message to ourself if (hWnd != reinterpret_cast<HWND>(ui->stw->MainHWND())) { // Send a message to the given window, to see if it will answer with // the same message. If it does, it is a Gui window with // openFilesHere set. // We use a timeout to avoid being blocked by hung processes. LRESULT found = ::SendMessageTimeout(hWnd, ui->identityMessage, 0, 0, SMTO_BLOCK | SMTO_ABORTIFHUNG, 200, &result); if (found != 0 && result == static_cast<DWORD>(ui->identityMessage)) { // Another Gui window found! // We memorise its window handle ui->hOtherWindow = hWnd; // We stop the EnumWindows bResult = FALSE; } } return bResult; } <commit_msg>Patch from Bruce Dodson to make compile with Digital Mars.<commit_after>// SciTE - Scintilla based Text Editor /** @file UniqueInstance.cxx ** Class to ensure a unique instance of the editor, if requested. **/ // Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "SciTEWin.h" UniqueInstance::UniqueInstance() { stw = 0; identityMessage = ::RegisterWindowMessage("SciTEInstanceIdentifier"); mutex = 0; bAlreadyRunning = false; hOtherWindow = NULL; } UniqueInstance::~UniqueInstance() { if (mutex) { ::CloseHandle(mutex); } } void UniqueInstance::Init(SciTEWin *stw_) { stw = stw_; } /** * Try to create a mutex. * If succeed, it is the first/only instance. * Otherwise, there is already an instance holding this mutex. */ bool UniqueInstance::AcceptToOpenFiles(bool bAccept) { bool bError = false; stw->openFilesHere = bAccept; if (bAccept) { // We create a mutex because it is an atomic operation. // An operation like EnumWindows is long, so if we use it only, we can fall in a race condition. // Note from MSDN: "The system closes the handle automatically when the process terminates. // The mutex object is destroyed when its last handle has been closed." // If the mutex already exists, the new process get a handle on it, so even if the first // process exits, the mutex isn't destroyed, until all SciTE instances exit. mutex = ::CreateMutex(NULL, FALSE, mutexName.c_str()); // The call fails with ERROR_ACCESS_DENIED if the mutex was // created in a different user session because of passing // NULL for the SECURITY_ATTRIBUTES on mutex creation bError = (::GetLastError() == ERROR_ALREADY_EXISTS || ::GetLastError() == ERROR_ACCESS_DENIED); } else { ::CloseHandle(mutex); } return !bError; } /** * Toggle the open files here option. * If set, search if another instance have this option set. * If found, we ask it to yield this option, * so we are the only one to accept files. */ void UniqueInstance::ToggleOpenFilesHere() { // If the openFilesHere option is set, we unset it and remove the handle. // Else, we set the option and try to set the mutex. if (!AcceptToOpenFiles(!stw->openFilesHere)) { // Cannot set the mutex, search the previous instance holding it HWND hOtherWindow = NULL; ::EnumWindows(reinterpret_cast<WNDENUMPROC>(SearchOtherInstance), reinterpret_cast<LPARAM>(this)); if (hOtherWindow != NULL) { // Found, we indicate it to yield the acceptation of files ::SendMessage(hOtherWindow, identityMessage, 0, static_cast<LPARAM>(1)); } } stw->CheckMenus(); } /** * Manage the received COPYDATA message with a command line from another instance. */ LRESULT UniqueInstance::CopyData(COPYDATASTRUCT *pcds) { if (pcds) { if (stw->props.GetInt("minimize.to.tray")) { stw->RestoreFromTray(); } const char *text = static_cast<char *>(pcds->lpData); if (text && strlen(text) > 0) { SString args = stw->ProcessArgs(text); stw->ProcessCommandLine(args, 0); stw->ProcessCommandLine(args, 1); } ::FlashWindow(stw->MainHWND(), FALSE); } return TRUE; } /** * If the given message is the identity message and we hold the * open files here option, we answer the message (so other instances know * we are the one holding the option). * If the message ask to yield this option, we do it nicely... */ LRESULT UniqueInstance::CheckMessage(UINT message, WPARAM wParam, LPARAM lParam) { if (message == identityMessage) { if (stw->openFilesHere || wParam != 0) { // We answer only if the menu item is checked to accept files, // or if the caller force answering by setting wParam to non null // which can be used to find all instances (not used yet). if (stw->openFilesHere && lParam != 0) { // An instance indicates it takes control of the Open Files Here // feature, so this one no longer accept them. AcceptToOpenFiles(false); stw->CheckMenus(); // Update the checkmark } return identityMessage; } } return 0; } /** * To be called only if check.if.already.open option is set to 1. * Create the mutex name, try to set the mutex. * If failed, renounce to the open files here option. */ void UniqueInstance::CheckOtherInstance() { // Use the method explained by Joseph M. Newcomer to avoid multiple instances of an application: // http://www.codeproject.com/cpp/avoidmultinstance.asp // I limit instances by desktop, it seems to make sense with a GUI application... mutexName = "SciTE-UniqueInstanceMutex-"; // I doubt I really need a GUID here... HDESK desktop = ::GetThreadDesktop(::GetCurrentThreadId()); DWORD len = 0; // Query the needed size for the buffer BOOL result = ::GetUserObjectInformation(desktop, UOI_NAME, NULL, 0, &len); if (result == 0 && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { // WinNT / Win2000 char *info = new char[len]; ::GetUserObjectInformation(desktop, UOI_NAME, info, len, &len); mutexName += info; delete []info; } else { // Win9x: no multiple desktop, GetUserObjectInformation can be called // but is bogus... mutexName += "Win9x"; } // Try to set the mutex. If return false, it failed, there is already another instance. bAlreadyRunning = !AcceptToOpenFiles(true); if (bAlreadyRunning) { // Don't answer to requests from other starting instances stw->openFilesHere = false; } } /** * If we know there is another instance with open files here option, * we search it by enumerating windows. * @return true if found. */ bool UniqueInstance::FindOtherInstance() { if (bAlreadyRunning && identityMessage != 0) { ::EnumWindows(reinterpret_cast<WNDENUMPROC>(SearchOtherInstance), reinterpret_cast<LPARAM>(this)); if (hOtherWindow) { return true; } } return false; } /** * Send the COPYDATA messages to transmit the command line to * the instance holding the open files here option. * After that, the current instance will exit. */ void UniqueInstance::SendCommands(const char *cmdLine) { // On Win2k, windows can't get focus by themselves, // so it is the responsability of the new process to bring the window // to foreground. // Put the other SciTE uniconized and to forefront. if (::IsIconic(hOtherWindow)) { ::ShowWindow(hOtherWindow, SW_RESTORE); } ::SetForegroundWindow(hOtherWindow); COPYDATASTRUCT cds; cds.dwData = 0; // Send 2 messages - first the CWD, so paths relative to // the new instance can be resolved in the old instance, // then the real command line. // (Restoring the cwd could be done, // but keeping it to the last file opened can also // be useful) TCHAR cwdCmd[MAX_PATH + 7]; // 7 for "-cwd:" and 2x'"' strcpy(cwdCmd, "\"-cwd:"); getcwd(cwdCmd + strlen(cwdCmd), MAX_PATH); strcat(cwdCmd, "\""); // Defeat the "\" mangling - convert "\" to "/" for (char *temp = cwdCmd; *temp; temp++) { if (*temp == '\\') { *temp = '/'; } } cds.cbData = static_cast<DWORD>(strlen(cwdCmd) + 1); cds.lpData = static_cast<void *>(cwdCmd); ::SendMessage(hOtherWindow, WM_COPYDATA, 0, reinterpret_cast<LPARAM>(&cds)); // Now the command line itself. cds.cbData = static_cast<DWORD>(strlen(cmdLine) + 1); cds.lpData = static_cast<void *>(const_cast<char *>(cmdLine)); ::SendMessage(hOtherWindow, WM_COPYDATA, 0, reinterpret_cast<LPARAM>(&cds)); } /** * Function called by EnumWindows. * @a hWnd is the handle to the currently enumerated window. * @a lParam is seen as a pointer to the current UniqueInstance * so it can be used to access all members. * @return FALSE if found, to stop EnumWindows. */ BOOL CALLBACK UniqueInstance::SearchOtherInstance(HWND hWnd, LPARAM lParam) { BOOL bResult = TRUE; DWORD result; UniqueInstance *ui = reinterpret_cast<UniqueInstance *>(lParam); // First, avoid to send a message to ourself if (hWnd != reinterpret_cast<HWND>(ui->stw->MainHWND())) { // Send a message to the given window, to see if it will answer with // the same message. If it does, it is a Gui window with // openFilesHere set. // We use a timeout to avoid being blocked by hung processes. LRESULT found = ::SendMessageTimeout(hWnd, ui->identityMessage, 0, 0, SMTO_BLOCK | SMTO_ABORTIFHUNG, 200, &result); if (found != 0 && result == static_cast<DWORD>(ui->identityMessage)) { // Another Gui window found! // We memorise its window handle ui->hOtherWindow = hWnd; // We stop the EnumWindows bResult = FALSE; } } return bResult; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: TestInterpolationFunctions.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #define VTK_EPSILON 1e-10 // Subclass of vtkCell //#include "vtkEmptyCell.h" #include "vtkGenericCell.h" #include "vtkLine.h" #include "vtkPixel.h" //#include "vtkPolygon.h" //#include "vtkPolyLine.h" //#include "vtkPolyVertex.h" #include "vtkQuad.h" #include "vtkTriangle.h" //#include "vtkTriangleStrip.h" #include "vtkVertex.h" // Subclass of vtkCell3D //#include "vtkConvexPointSet.h" #include "vtkHexagonalPrism.h" #include "vtkHexahedron.h" #include "vtkPentagonalPrism.h" #include "vtkPyramid.h" #include "vtkTetra.h" #include "vtkVoxel.h" #include "vtkWedge.h" // Subclass of vtkNonLinearCell //#include "vtkExplicitCell.h" #include "vtkQuadraticEdge.h" #include "vtkQuadraticHexahedron.h" #include "vtkQuadraticPyramid.h" #include "vtkQuadraticQuad.h" #include "vtkQuadraticTetra.h" #include "vtkQuadraticTriangle.h" #include "vtkQuadraticWedge.h" // Bi/Tri linear quadratic cells #include "vtkBiQuadraticQuad.h" #include "vtkBiQuadraticQuadraticHexahedron.h" #include "vtkBiQuadraticQuadraticWedge.h" #include "vtkQuadraticLinearQuad.h" #include "vtkQuadraticLinearWedge.h" #include "vtkTriQuadraticHexahedron.h" template <class TCell> int TestOneInterpolationFunction() { TCell *cell = TCell::New(); int numPts = cell->GetNumberOfPoints(); double *sf = new double[numPts]; double *coords = cell->GetParametricCoords(); int r = 0; for(int i=0;i<numPts;++i) { double *point = coords + 3*i; double sum = 0.; TCell::InterpolationFunctions(point, sf); // static function for(int j=0;j<numPts;j++) { sum += sf[j]; if(j == (i/3)) { if( fabs(sf[j] - 1) > VTK_EPSILON) { ++r; } } else { if( fabs(sf[j] - 0) > VTK_EPSILON ) { ++r; } } } if( fabs(sum - 1) > VTK_EPSILON ) { ++r; } } // Let's test unity condition on the center point: double center[3]; cell->GetParametricCenter(center); TCell::InterpolationFunctions(center, sf); // static function double sum = 0.; for(int j=0;j<numPts;j++) { sum += sf[j]; } if( fabs(sum - 1) > VTK_EPSILON ) { ++r; } cell->Delete(); delete[] sf; return r; } int TestInterpolationFunctions(int, char *[]) { int r = 0; // Subclass of vtkCell3D //r += TestOneInterpolationFunction<vtkEmptyCell>(); // not implemented //r += TestOneInterpolationFunction<vtkGenericCell>(); // not implemented r += TestOneInterpolationFunction<vtkLine>(); r += TestOneInterpolationFunction<vtkPixel>(); //r += TestOneInterpolationFunction<vtkPolygon>(); // not implemented //r += TestOneInterpolationFunction<vtkPolyLine>(); // not implemented //r += TestOneInterpolationFunction<vtkPolyVertex>(); // not implemented r += TestOneInterpolationFunction<vtkQuad>(); r += TestOneInterpolationFunction<vtkTriangle>(); //r += TestOneInterpolationFunction<vtkTriangleStrip>(); // not implemented r += TestOneInterpolationFunction<vtkVertex>(); // Subclass of vtkCell3D //r += TestOneInterpolationFunction<vtkConvexPointSet>(); // not implemented r += TestOneInterpolationFunction<vtkHexagonalPrism>(); r += TestOneInterpolationFunction<vtkHexahedron>(); r += TestOneInterpolationFunction<vtkPentagonalPrism>(); r += TestOneInterpolationFunction<vtkPyramid>(); r += TestOneInterpolationFunction<vtkTetra>(); r += TestOneInterpolationFunction<vtkVoxel>(); r += TestOneInterpolationFunction<vtkWedge>(); // Subclass of vtkNonLinearCell //r += TestOneInterpolationFunction<vtkExplicitCell>(); // not implemented r += TestOneInterpolationFunction<vtkQuadraticEdge>(); r += TestOneInterpolationFunction<vtkQuadraticHexahedron>(); r += TestOneInterpolationFunction<vtkQuadraticPyramid>(); r += TestOneInterpolationFunction<vtkQuadraticQuad>(); r += TestOneInterpolationFunction<vtkQuadraticTetra>(); r += TestOneInterpolationFunction<vtkQuadraticTriangle>(); r += TestOneInterpolationFunction<vtkQuadraticWedge>(); // Bi/Tri linear quadratic cells r += TestOneInterpolationFunction<vtkBiQuadraticQuad>(); r += TestOneInterpolationFunction<vtkBiQuadraticQuadraticHexahedron>(); r += TestOneInterpolationFunction<vtkBiQuadraticQuadraticWedge>(); r += TestOneInterpolationFunction<vtkQuadraticLinearQuad>(); r += TestOneInterpolationFunction<vtkQuadraticLinearWedge>(); r += TestOneInterpolationFunction<vtkTriQuadraticHexahedron>(); return r; } <commit_msg>BUG: Wrong index<commit_after>/*========================================================================= Program: Visualization Toolkit Module: TestInterpolationFunctions.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #define VTK_EPSILON 1e-10 // Subclass of vtkCell //#include "vtkEmptyCell.h" #include "vtkGenericCell.h" #include "vtkLine.h" #include "vtkPixel.h" //#include "vtkPolygon.h" //#include "vtkPolyLine.h" //#include "vtkPolyVertex.h" #include "vtkQuad.h" #include "vtkTriangle.h" //#include "vtkTriangleStrip.h" #include "vtkVertex.h" // Subclass of vtkCell3D //#include "vtkConvexPointSet.h" #include "vtkHexagonalPrism.h" #include "vtkHexahedron.h" #include "vtkPentagonalPrism.h" #include "vtkPyramid.h" #include "vtkTetra.h" #include "vtkVoxel.h" #include "vtkWedge.h" // Subclass of vtkNonLinearCell //#include "vtkExplicitCell.h" #include "vtkQuadraticEdge.h" #include "vtkQuadraticHexahedron.h" #include "vtkQuadraticPyramid.h" #include "vtkQuadraticQuad.h" #include "vtkQuadraticTetra.h" #include "vtkQuadraticTriangle.h" #include "vtkQuadraticWedge.h" // Bi/Tri linear quadratic cells #include "vtkBiQuadraticQuad.h" #include "vtkBiQuadraticQuadraticHexahedron.h" #include "vtkBiQuadraticQuadraticWedge.h" #include "vtkQuadraticLinearQuad.h" #include "vtkQuadraticLinearWedge.h" #include "vtkTriQuadraticHexahedron.h" template <class TCell> int TestOneInterpolationFunction() { TCell *cell = TCell::New(); int numPts = cell->GetNumberOfPoints(); double *sf = new double[numPts]; double *coords = cell->GetParametricCoords(); int r = 0; for(int i=0;i<numPts;++i) { double *point = coords + 3*i; double sum = 0.; TCell::InterpolationFunctions(point, sf); // static function for(int j=0;j<numPts;j++) { sum += sf[j]; if(j == i) { if( fabs(sf[j] - 1) > VTK_EPSILON) { ++r; } } else { if( fabs(sf[j] - 0) > VTK_EPSILON ) { ++r; } } } if( fabs(sum - 1) > VTK_EPSILON ) { ++r; } } // Let's test unity condition on the center point: double center[3]; cell->GetParametricCenter(center); TCell::InterpolationFunctions(center, sf); // static function double sum = 0.; for(int j=0;j<numPts;j++) { sum += sf[j]; } if( fabs(sum - 1) > VTK_EPSILON ) { ++r; } cell->Delete(); delete[] sf; return r; } int TestInterpolationFunctions(int, char *[]) { int r = 0; // Subclass of vtkCell3D //r += TestOneInterpolationFunction<vtkEmptyCell>(); // not implemented //r += TestOneInterpolationFunction<vtkGenericCell>(); // not implemented r += TestOneInterpolationFunction<vtkLine>(); r += TestOneInterpolationFunction<vtkPixel>(); //r += TestOneInterpolationFunction<vtkPolygon>(); // not implemented //r += TestOneInterpolationFunction<vtkPolyLine>(); // not implemented //r += TestOneInterpolationFunction<vtkPolyVertex>(); // not implemented r += TestOneInterpolationFunction<vtkQuad>(); r += TestOneInterpolationFunction<vtkTriangle>(); //r += TestOneInterpolationFunction<vtkTriangleStrip>(); // not implemented r += TestOneInterpolationFunction<vtkVertex>(); // Subclass of vtkCell3D //r += TestOneInterpolationFunction<vtkConvexPointSet>(); // not implemented r += TestOneInterpolationFunction<vtkHexagonalPrism>(); r += TestOneInterpolationFunction<vtkHexahedron>(); r += TestOneInterpolationFunction<vtkPentagonalPrism>(); r += TestOneInterpolationFunction<vtkPyramid>(); r += TestOneInterpolationFunction<vtkTetra>(); r += TestOneInterpolationFunction<vtkVoxel>(); r += TestOneInterpolationFunction<vtkWedge>(); // Subclass of vtkNonLinearCell //r += TestOneInterpolationFunction<vtkExplicitCell>(); // not implemented r += TestOneInterpolationFunction<vtkQuadraticEdge>(); r += TestOneInterpolationFunction<vtkQuadraticHexahedron>(); r += TestOneInterpolationFunction<vtkQuadraticPyramid>(); r += TestOneInterpolationFunction<vtkQuadraticQuad>(); r += TestOneInterpolationFunction<vtkQuadraticTetra>(); r += TestOneInterpolationFunction<vtkQuadraticTriangle>(); r += TestOneInterpolationFunction<vtkQuadraticWedge>(); // Bi/Tri linear quadratic cells r += TestOneInterpolationFunction<vtkBiQuadraticQuad>(); r += TestOneInterpolationFunction<vtkBiQuadraticQuadraticHexahedron>(); r += TestOneInterpolationFunction<vtkBiQuadraticQuadraticWedge>(); r += TestOneInterpolationFunction<vtkQuadraticLinearQuad>(); r += TestOneInterpolationFunction<vtkQuadraticLinearWedge>(); r += TestOneInterpolationFunction<vtkTriQuadraticHexahedron>(); return r; } <|endoftext|>
<commit_before>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * exnetperf -- Shows how to use the statistical functions in GNE. This * example should serve well for GNE to measure network performance, as best * as is possible with the GNE and HawkNL APIs. This example uses event- * driven networking since that is what is most likely to be used once the * game has started, and the method that most likely has the largest impact * on performace. (SyncConnection will most likely be used only while * connecting). * This example could also be used to test the bandwidth throttling. */ #include "../../include/gnelib.h" #include <iostream> using namespace std; using namespace GNE; using namespace GNE::PacketParser; using namespace GNE::Console; class OurClient : public ConnectionListener { public: OurClient() : conn(NULL) { mprintf("Client listener created.\n"); } ~OurClient() { mprintf("Client listener destroyed.\n"); } void onDisconnect() { mprintf("Client just disconnected.\n"); //This is an iffy practice. If we do this, we have to be careful to //always note that each new connection we use this listener with gets //its own new copy which we don't destroy later. delete this; } void onConnect(SyncConnection& conn2) { conn = conn2.getConnection(); mprintf("Connection to server successful.\n"); } void onReceive() { Packet* message = conn->stream().getNextPacket(); if (message->getType() == MIN_USER_ID) { HelloPacket* helloMessage = (HelloPacket*)message; mprintf("got message: \""); mprintf(helloMessage->getMessage().c_str()); mprintf("\"\n"); } else mprintf("got bad packet.\n"); delete message; } void onFailure(const Error& error) { mprintf("Socket failure: %s\n", error.toString().c_str()); } void onError(const Error& error) { mprintf("Socket error: %s\n", error.toString().c_str()); conn->disconnect(); } void onConnectFailure(const Error& error) { mprintf("Connection to server failed.\n"); mprintf("GNE reported error: %s\n", error.toString().c_str()); } private: Connection* conn; }; class OurServer : public ConnectionListener { public: OurServer() : conn(NULL), received(false) { mprintf("Server instance created\n"); } virtual ~OurServer() { mprintf("ServerConnection instance killed\n"); } void onDisconnect() { mprintf("ServerConnection just disconnected.\n"); if (!received) mprintf("No message received.\n"); delete this; } void onNewConn(SyncConnection& conn2) { conn = conn2.getConnection(); mprintf("Connection received from %s; waiting for message...\n", conn->getRemoteAddress(true).toString().c_str()); } void onReceive() { Packet* message = conn->stream().getNextPacket(); delete message; } void onFailure(const Error& error) { gout << acquire << "Socket failure: " << error << endl << release; } void onError(const Error& error) { mprintf("Socket error: %s\n", error.toString().c_str()); conn->disconnect(); } private: Connection* conn; bool received; }; class OurListener : public ServerConnectionListener { public: OurListener() : ServerConnectionListener() { } virtual ~OurListener() {} void onListenFailure(const Error& error, const Address& from, ConnectionListener* listener) { mprintf("Connection error: %s\n", error.toString().c_str()); mprintf(" Error received from %s", from.toString().c_str()); delete listener; } void getNewConnectionParams(int& inRate, int& outRate, ConnectionListener*& listener) { inRate = outRate = 0; //0 meaning no limits on rates. listener = new OurServer(); } private: }; void errorExit(const char* error) { gout << "Error: " << error << endl; exit(1); } int getPort(const char* prompt) { int port; gout << "Which port should we " << prompt << ": "; gin >> port; while ((port < 1) || (port > 65535)) { gout << "Ports range from 1 to 65535, please select one in this range: "; gin >> port; } return port; } int main() { if (initGNE(NL_IP, atexit)) { cout << "Unable to initialize GNE" << endl; exit(2); } setUserVersion(1); //sets our user protocol version number, used in //the connection process by GNE to version check. if (initConsole(atexit)) { cout << "Unable to initialize GNE Console" << endl; exit(3); } setTitle("GNE Net Performance Tester"); return 0; }<commit_msg>More work on exnetperf.<commit_after>/* GNE - Game Networking Engine, a portable multithreaded networking library. * Copyright (C) 2001 Jason Winnebeck (gillius@mail.rit.edu) * Project website: http://www.rit.edu/~jpw9607/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * exnetperf -- Shows how to use the statistical functions in GNE. This * example should serve well for GNE to measure network performance, as best * as is possible with the GNE and HawkNL APIs. This example uses event- * driven networking since that is what is most likely to be used once the * game has started, and the method that most likely has the largest impact * on performace. (SyncConnection will most likely be used only while * connecting). * This example could also be used to test the bandwidth throttling. */ #include "../../include/gnelib.h" #include <iostream> using namespace std; using namespace GNE; using namespace GNE::PacketParser; using namespace GNE::Console; //The PerfTester class works on both the client and the server side. class PerfTester : public ConnectionListener { public: PerfTester() : conn(NULL) {} ~PerfTester() {} void onDisconnect() { delete this; } void onConnect(SyncConnection& conn2) { conn = conn2.getConnection(); writePackets(); //Send an initial batch of data. } void onNewConn(SyncConnection& conn2) { conn = conn2.getConnection(); writePackets(); } void onReceive() { delete conn->stream().getNextPacket(); //We don't need to do anything to the data we are being sent. The low- //level routines will keep track of the stats for us. } void onFailure(const Error& error) { mprintf("Socket failure: %s\n", error.toString().c_str()); //No need to disconnect, this has already happened on a failure. } void onError(const Error& error) { mprintf("Socket error: %s\n", error.toString().c_str()); conn->disconnect();//For simplicity we treat even normal errors as fatal. } void onConnectFailure(const Error& error) { mprintf("Connection to server failed.\n"); mprintf(" GNE reported error: %s\n", error.toString().c_str()); } void onDoneWriting() { writePackets(); } //Try to send out some more packets. void writePackets() { } private: Connection* conn; }; class OurListener : public ServerConnectionListener { public: OurListener() : ServerConnectionListener() { } virtual ~OurListener() {} void onListenFailure(const Error& error, const Address& from, ConnectionListener* listener) { mlprintf(0, 0, "Connection error: %s ", error.toString().c_str()); mlprintf(0, 1, " Error received from %s ", from.toString().c_str()); delete listener; } void getNewConnectionParams(int& inRate, int& outRate, ConnectionListener*& listener) { inRate = outRate = 0; //0 meaning no limits on rates. listener = new PerfTester(); } private: }; void errorExit(const char* error) { gout << "Error: " << error << endl; exit(1); } int getPort(const char* prompt) { int port; gout << "Which port should we " << prompt << ": "; gin >> port; while ((port < 1) || (port > 65535)) { gout << "Ports range from 1 to 65535, please select one in this range: "; gin >> port; } return port; } int main() { if (initGNE(NL_IP, atexit)) { cout << "Unable to initialize GNE" << endl; exit(2); } setUserVersion(1); //sets our user protocol version number, used in //the connection process by GNE to version check. if (initConsole(atexit)) { cout << "Unable to initialize GNE Console" << endl; exit(3); } setTitle("GNE Net Performance Tester"); return 0; }<|endoftext|>
<commit_before>#pragma once #include <Utils/OpenGL.hh> #include <Utils/Dependency.hpp> #include <Render/Key.hh> #include <Render/MemoryGPU.hh> #include <map> #include <Utils/Containers/Vector.hpp> #include <glm/glm.hpp> #include <Render/UniformBlock.hh> #include <Render/Material.hh> #include <cassert> #include <Render/GeometryManager.hh> #include <Render/MaterialManager.hh> #include <Render/Render.hh> #include <Render/Shader.hh> #include <Core/Drawable.hh> #include <Render/MacroRenderManager.hh> namespace gl { struct Uniform; struct Sampler; struct InterfaceBlock; class Texture; class UniformBuffer; struct BindingRenderPass; struct BindingShader; class Pipeline; class RenderManager : public Dependency<RenderManager> { public: GeometryManager geometryManager; MaterialManager materialManager; public: RenderManager(); ~RenderManager(); // shader handling RenderManager &createPreShaderQuad(); Key<Shader> addComputeShader(std::string const &compute); Key<Shader> addShader(std::string const &vert, std::string const &frag); Key<Shader> addShader(std::string const &geometry, std::string const &vert, std::string const &frag); Key<Shader> getShader(size_t index) const; Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::mat4 const &value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::mat3 const &value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, float value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::vec4 const &value); Key<Uniform> getShaderUniform(Key<Shader> const &shader, size_t index); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::mat4 const &mat4); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::vec4 const &vec4); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, float v); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::mat3 const &mat3); Key<Sampler> addShaderSampler(Key<Shader> const &shader, std::string const &flag); Key<Sampler> getShaderSampler(Key<Shader> const &shader, size_t index); RenderManager &setShaderSampler(Key<Shader> const &shader, Key<Sampler> const &key, Key<Texture> const &keytexture); Key<InterfaceBlock> addShaderInterfaceBlock(Key<Shader> const &shader, std::string const &flag, Key<UniformBlock> const &keyUniformBlock); Key<InterfaceBlock> getShaderInterfaceBlock(Key<Shader> const &shader, size_t index); Key<UniformBlock> addUniformBlock(size_t nbrElement, size_t *sizeElement); RenderManager &rmUniformBlock(Key<UniformBlock> &uniformBlock); Key<UniformBlock> getUniformBlock(size_t index) const; template <typename TYPE> RenderManager &setUniformBlock(Key<UniformBlock> const &key, size_t index, TYPE const &value); RenderManager &bindTransformationToShader(Key<Shader> const &keyShader, Key<Uniform> const &keyUniform); template <typename TYPE> RenderManager &bindMaterialToShader(Key<Shader> const &s, Key<Uniform> const &u); RenderManager &unbindMaterialToShader(Key<Shader> const &s, Key<Uniform> const &u); // Texture Key<Texture> addTexture2D(GLsizei width, GLsizei height, GLenum internalFormat, bool mipmapping); RenderManager &uploadTexture(Key<Texture> const &key, GLenum format, GLenum type, GLvoid *img); RenderManager &downloadTexture(Key<Texture> const &key, GLenum format, GLenum type, GLvoid *img); RenderManager &setlevelTargetTexture(Key<Texture> const &key, uint8_t level); RenderManager &bindTexture(Key<Texture> const &key); RenderManager &unbindTexture(Key<Texture> const &key); RenderManager &configUploadTexture2D(Key<Texture> const &key, glm::ivec4 const &rect); RenderManager &parameterTexture(Key<Texture> const &key, GLenum pname, GLint param); RenderManager &rmTexture(Key<Texture> &key); Key<Texture> getTexture(size_t target) const; GLenum getTypeTexture(Key<Texture> const &key); // RenderPass Key<RenderPass> addRenderPass(Key<Shader> const &shader, glm::ivec4 const &rect); Key<RenderPass> getRenderPass(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderPass) RenderManager &configRenderPass(Key<RenderPass> const &renderPass, glm::ivec4 const &rect, GLenum mode = GL_TRIANGLES, GLint sample = 1); RenderManager &pushOutputColorRenderPass(Key<RenderPass> const &key, GLenum attachement, GLenum internalFormat); RenderManager &popOutputColorRenderPass(Key<RenderPass> const &key); RenderManager &pushInputColorRenderPass(Key<RenderPass> const &key, Key<Sampler> const &s); RenderManager &popInputColorRenderPass(Key<RenderPass> const &key); RenderManager &createDepthBufferRenderPass(Key<RenderPass> const &key); RenderManager &createStencilBufferRenderPass(Key<RenderPass> const &key); RenderManager &useInputDepthRenderPass(Key<RenderPass> const &key); RenderManager &unUseInputDepthRenderPass(Key<RenderPass> const &key); RenderManager &useInputStencilRenderPass(Key<RenderPass> const &key); RenderManager &unUseInputStencilRenderPass(Key<RenderPass> const &key); RenderManager &useInputColorRenderPass(Key<RenderPass> const &key, GLenum attachement); RenderManager &unUseInputColorRenderPass(Key<RenderPass> const &key, GLenum attachement); // RenderPostEffect Key<RenderPostEffect> addRenderPostEffect(Key<Shader> const &s, glm::ivec4 const &rect); Key<RenderPostEffect> getRenderPostEffect(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderPostEffect) RenderManager &configRenderPostEffect(Key<RenderPostEffect> const &renderPass, glm::ivec4 const &rect, GLenum mode = GL_TRIANGLES, GLint sample = 1); RenderManager &pushOutputColorRenderPostEffect(Key<RenderPostEffect> const &key, GLenum attachement, GLenum internalFormat); RenderManager &popOutputColorRenderPostEffect(Key<RenderPostEffect> const &key); RenderManager &pushInputColorRenderPostEffect(Key<RenderPostEffect> const &key, Key<Sampler> const &s); RenderManager &popInputColorRenderPostEffect(Key<RenderPostEffect> const &key); // RenderOnScreen Key<RenderOnScreen> addRenderOnScreen(glm::ivec4 const &rect); Key<RenderOnScreen> getRenderOnScreen(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderOnScreen); RenderManager &configRenderOnScreen(Key<RenderOnScreen> const &renderOnScreen, glm::ivec4 const &rect, GLenum mode); RenderManager &branch(Key<RenderPass> const &from, Key<RenderPass> const &to); RenderManager &branch(Key<RenderPass> const &from, Key<RenderPostEffect> const &to); RenderManager &branch(Key<RenderPass> const &from, Key<RenderOnScreen> const &to); RenderManager &branch(Key<RenderPostEffect> const &from, Key<RenderOnScreen> const &to); // Pipeline Key<Pipeline> addPipeline(); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderPass> const &r); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderPostEffect> const &r); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderOnScreen> const &r); Key<Pipeline> getPipeline(size_t target); RenderManager &updatePipeline(Key<Pipeline> const &p, AGE::Vector<AGE::Drawable> const &objectRender); // drawing RenderManager &drawPipelines(); RenderManager &drawPipeline(Key<Pipeline> const &key, AGE::Vector<AGE::Drawable> const &objectRender); RenderManager &draw(Key<RenderOnScreen> const &key, Key<RenderPass> const &r, AGE::Vector<AGE::Drawable> const &objectRender); private: // all map std::map<Key<Shader>, Shader *> _shaders; Shader * _preShaderQuad; std::map<Key<UniformBlock>, UniformBlock> _uniformBlock; std::map<Key<Texture>, Texture *> _textures; std::map<Key<RenderPass>, RenderPass *> _renderPass; std::map<Key<RenderPostEffect>, RenderPostEffect *> _renderPostEffect; std::map<Key<RenderOnScreen>, RenderOnScreen *> _renderOnScreen; std::map<Key<Pipeline>, Pipeline> _pipelines; uint8_t _minTime; uint8_t _maxTime; // optimize search in map std::pair<Key<Shader>, Shader *> _optimizeShaderSearch; std::pair<Key<UniformBlock>, UniformBlock *> _optimizeUniformBlockSearch; std::pair<Key<Texture>, Texture *> _optimizeTextureSearch; std::pair<Key<RenderPass>, RenderPass *> _optimizeRenderPassSearch; std::pair<Key<RenderPostEffect>, RenderPostEffect *> _optimizeRenderPostEffectSearch; std::pair<Key<RenderOnScreen>, RenderOnScreen *> _optimizeRenderOnScreenSearch; std::pair<Key<Pipeline>, Pipeline *> _optimizePipelineSearch; // tool use in intern for search Shader *getShader(Key<Shader> const &key); UniformBlock *getUniformBlock(Key<UniformBlock> const &key); Texture *getTexture(Key<Texture> const &key); RenderPass *getRenderPass(Key<RenderPass> const &key); RenderPostEffect *getRenderPostEffect(Key<RenderPostEffect> const &key); RenderOnScreen *getRenderOnScreen(Key<RenderOnScreen> const &key); Pipeline *getPipeline(Key<Pipeline> const &key); }; template <typename TYPE> RenderManager &RenderManager::bindMaterialToShader(Key<Shader> const &shaderKey, Key<Uniform> const &uniformKey) { Shader *shader; if ((shader = getShader(shaderKey)) == NULL) return (*this); shader->bindingMaterial<TYPE>(uniformKey); return (*this); } template <typename TYPE> RenderManager &RenderManager::setUniformBlock(Key<UniformBlock> const &key, size_t index, TYPE const &value) { UniformBlock *uniformBlock; if ((uniformBlock = getUniformBlock(key)) == NULL) return (*this); uniformBlock->set<TYPE>(index, value); return (*this); } template <typename TYPE1> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); } template <typename TYPE1, typename TYPE2> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); } template <typename TYPE1, typename TYPE2, typename TYPE3> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4, typename TYPE5> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); tab[4] = sizeof(TYPE5); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4, typename TYPE5, typename TYPE6> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); tab[4] = sizeof(TYPE5); tab[5] = sizeof(TYPE6); } }<commit_msg>best commit ever : add lightManager on renderManager<commit_after>#pragma once #include <Utils/OpenGL.hh> #include <Utils/Dependency.hpp> #include <Render/Key.hh> #include <Render/MemoryGPU.hh> #include <map> #include <Utils/Containers/Vector.hpp> #include <glm/glm.hpp> #include <Render/UniformBlock.hh> #include <Render/Material.hh> #include <cassert> #include <Render/GeometryManager.hh> #include <Render/MaterialManager.hh> #include <Render/LightManager.hh> #include <Render/Render.hh> #include <Render/Shader.hh> #include <Core/Drawable.hh> #include <Render/MacroRenderManager.hh> namespace gl { struct Uniform; struct Sampler; struct InterfaceBlock; class Texture; class UniformBuffer; struct BindingRenderPass; struct BindingShader; class Pipeline; class RenderManager : public Dependency<RenderManager> { public: GeometryManager geometryManager; MaterialManager materialManager; LightManager lightManager; public: RenderManager(); ~RenderManager(); // shader handling RenderManager &createPreShaderQuad(); Key<Shader> addComputeShader(std::string const &compute); Key<Shader> addShader(std::string const &vert, std::string const &frag); Key<Shader> addShader(std::string const &geometry, std::string const &vert, std::string const &frag); Key<Shader> getShader(size_t index) const; Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::mat4 const &value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::mat3 const &value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, float value); Key<Uniform> addShaderUniform(Key<Shader> const &shader, std::string const &flag, glm::vec4 const &value); Key<Uniform> getShaderUniform(Key<Shader> const &shader, size_t index); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::mat4 const &mat4); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::vec4 const &vec4); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, float v); RenderManager &setShaderUniform(Key<Shader> const &shader, Key<Uniform> const &key, glm::mat3 const &mat3); Key<Sampler> addShaderSampler(Key<Shader> const &shader, std::string const &flag); Key<Sampler> getShaderSampler(Key<Shader> const &shader, size_t index); RenderManager &setShaderSampler(Key<Shader> const &shader, Key<Sampler> const &key, Key<Texture> const &keytexture); Key<InterfaceBlock> addShaderInterfaceBlock(Key<Shader> const &shader, std::string const &flag, Key<UniformBlock> const &keyUniformBlock); Key<InterfaceBlock> getShaderInterfaceBlock(Key<Shader> const &shader, size_t index); Key<UniformBlock> addUniformBlock(size_t nbrElement, size_t *sizeElement); RenderManager &rmUniformBlock(Key<UniformBlock> &uniformBlock); Key<UniformBlock> getUniformBlock(size_t index) const; template <typename TYPE> RenderManager &setUniformBlock(Key<UniformBlock> const &key, size_t index, TYPE const &value); RenderManager &bindTransformationToShader(Key<Shader> const &keyShader, Key<Uniform> const &keyUniform); template <typename TYPE> RenderManager &bindMaterialToShader(Key<Shader> const &s, Key<Uniform> const &u); RenderManager &unbindMaterialToShader(Key<Shader> const &s, Key<Uniform> const &u); // Texture Key<Texture> addTexture2D(GLsizei width, GLsizei height, GLenum internalFormat, bool mipmapping); RenderManager &uploadTexture(Key<Texture> const &key, GLenum format, GLenum type, GLvoid *img); RenderManager &downloadTexture(Key<Texture> const &key, GLenum format, GLenum type, GLvoid *img); RenderManager &setlevelTargetTexture(Key<Texture> const &key, uint8_t level); RenderManager &bindTexture(Key<Texture> const &key); RenderManager &unbindTexture(Key<Texture> const &key); RenderManager &configUploadTexture2D(Key<Texture> const &key, glm::ivec4 const &rect); RenderManager &parameterTexture(Key<Texture> const &key, GLenum pname, GLint param); RenderManager &rmTexture(Key<Texture> &key); Key<Texture> getTexture(size_t target) const; GLenum getTypeTexture(Key<Texture> const &key); // RenderPass Key<RenderPass> addRenderPass(Key<Shader> const &shader, glm::ivec4 const &rect); Key<RenderPass> getRenderPass(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderPass) RenderManager &configRenderPass(Key<RenderPass> const &renderPass, glm::ivec4 const &rect, GLenum mode = GL_TRIANGLES, GLint sample = 1); RenderManager &pushOutputColorRenderPass(Key<RenderPass> const &key, GLenum attachement, GLenum internalFormat); RenderManager &popOutputColorRenderPass(Key<RenderPass> const &key); RenderManager &pushInputColorRenderPass(Key<RenderPass> const &key, Key<Sampler> const &s); RenderManager &popInputColorRenderPass(Key<RenderPass> const &key); RenderManager &createDepthBufferRenderPass(Key<RenderPass> const &key); RenderManager &createStencilBufferRenderPass(Key<RenderPass> const &key); RenderManager &useInputDepthRenderPass(Key<RenderPass> const &key); RenderManager &unUseInputDepthRenderPass(Key<RenderPass> const &key); RenderManager &useInputStencilRenderPass(Key<RenderPass> const &key); RenderManager &unUseInputStencilRenderPass(Key<RenderPass> const &key); RenderManager &useInputColorRenderPass(Key<RenderPass> const &key, GLenum attachement); RenderManager &unUseInputColorRenderPass(Key<RenderPass> const &key, GLenum attachement); // RenderPostEffect Key<RenderPostEffect> addRenderPostEffect(Key<Shader> const &s, glm::ivec4 const &rect); Key<RenderPostEffect> getRenderPostEffect(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderPostEffect) RenderManager &configRenderPostEffect(Key<RenderPostEffect> const &renderPass, glm::ivec4 const &rect, GLenum mode = GL_TRIANGLES, GLint sample = 1); RenderManager &pushOutputColorRenderPostEffect(Key<RenderPostEffect> const &key, GLenum attachement, GLenum internalFormat); RenderManager &popOutputColorRenderPostEffect(Key<RenderPostEffect> const &key); RenderManager &pushInputColorRenderPostEffect(Key<RenderPostEffect> const &key, Key<Sampler> const &s); RenderManager &popInputColorRenderPostEffect(Key<RenderPostEffect> const &key); // RenderOnScreen Key<RenderOnScreen> addRenderOnScreen(glm::ivec4 const &rect); Key<RenderOnScreen> getRenderOnScreen(size_t target) const; GEN_DEC_RENDER_PUSH_TASK(RenderOnScreen); RenderManager &configRenderOnScreen(Key<RenderOnScreen> const &renderOnScreen, glm::ivec4 const &rect, GLenum mode); RenderManager &branch(Key<RenderPass> const &from, Key<RenderPass> const &to); RenderManager &branch(Key<RenderPass> const &from, Key<RenderPostEffect> const &to); RenderManager &branch(Key<RenderPass> const &from, Key<RenderOnScreen> const &to); RenderManager &branch(Key<RenderPostEffect> const &from, Key<RenderOnScreen> const &to); // Pipeline Key<Pipeline> addPipeline(); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderPass> const &r); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderPostEffect> const &r); RenderManager &setPipeline(Key<Pipeline> const &p, uint8_t time, Key<RenderOnScreen> const &r); Key<Pipeline> getPipeline(size_t target); RenderManager &updatePipeline(Key<Pipeline> const &p, AGE::Vector<AGE::Drawable> const &objectRender); // drawing RenderManager &drawPipelines(); RenderManager &drawPipeline(Key<Pipeline> const &key, AGE::Vector<AGE::Drawable> const &objectRender); RenderManager &draw(Key<RenderOnScreen> const &key, Key<RenderPass> const &r, AGE::Vector<AGE::Drawable> const &objectRender); private: // all map std::map<Key<Shader>, Shader *> _shaders; Shader * _preShaderQuad; std::map<Key<UniformBlock>, UniformBlock> _uniformBlock; std::map<Key<Texture>, Texture *> _textures; std::map<Key<RenderPass>, RenderPass *> _renderPass; std::map<Key<RenderPostEffect>, RenderPostEffect *> _renderPostEffect; std::map<Key<RenderOnScreen>, RenderOnScreen *> _renderOnScreen; std::map<Key<Pipeline>, Pipeline> _pipelines; uint8_t _minTime; uint8_t _maxTime; // optimize search in map std::pair<Key<Shader>, Shader *> _optimizeShaderSearch; std::pair<Key<UniformBlock>, UniformBlock *> _optimizeUniformBlockSearch; std::pair<Key<Texture>, Texture *> _optimizeTextureSearch; std::pair<Key<RenderPass>, RenderPass *> _optimizeRenderPassSearch; std::pair<Key<RenderPostEffect>, RenderPostEffect *> _optimizeRenderPostEffectSearch; std::pair<Key<RenderOnScreen>, RenderOnScreen *> _optimizeRenderOnScreenSearch; std::pair<Key<Pipeline>, Pipeline *> _optimizePipelineSearch; // tool use in intern for search Shader *getShader(Key<Shader> const &key); UniformBlock *getUniformBlock(Key<UniformBlock> const &key); Texture *getTexture(Key<Texture> const &key); RenderPass *getRenderPass(Key<RenderPass> const &key); RenderPostEffect *getRenderPostEffect(Key<RenderPostEffect> const &key); RenderOnScreen *getRenderOnScreen(Key<RenderOnScreen> const &key); Pipeline *getPipeline(Key<Pipeline> const &key); }; template <typename TYPE> RenderManager &RenderManager::bindMaterialToShader(Key<Shader> const &shaderKey, Key<Uniform> const &uniformKey) { Shader *shader; if ((shader = getShader(shaderKey)) == NULL) return (*this); shader->bindingMaterial<TYPE>(uniformKey); return (*this); } template <typename TYPE> RenderManager &RenderManager::setUniformBlock(Key<UniformBlock> const &key, size_t index, TYPE const &value) { UniformBlock *uniformBlock; if ((uniformBlock = getUniformBlock(key)) == NULL) return (*this); uniformBlock->set<TYPE>(index, value); return (*this); } template <typename TYPE1> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); } template <typename TYPE1, typename TYPE2> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); } template <typename TYPE1, typename TYPE2, typename TYPE3> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4, typename TYPE5> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); tab[4] = sizeof(TYPE5); } template <typename TYPE1, typename TYPE2, typename TYPE3, typename TYPE4, typename TYPE5, typename TYPE6> inline void set_tab_sizetype(size_t *tab) { tab[0] = sizeof(TYPE1); tab[1] = sizeof(TYPE2); tab[2] = sizeof(TYPE3); tab[3] = sizeof(TYPE4); tab[4] = sizeof(TYPE5); tab[5] = sizeof(TYPE6); } }<|endoftext|>
<commit_before><commit_msg>some cleanup, add missing options for linux gpu tracker event display<commit_after><|endoftext|>
<commit_before><commit_msg>start with maximized window<commit_after><|endoftext|>
<commit_before>// $Id$ AliJetEmbeddingTask* AddTaskJetEmbedding( const char *tracksName = "Tracks", const char *clusName = "CaloClustersCorr", const char *taskName = "JetEmbeddingTask", const Double_t minPt = 10, const Double_t maxPt = 10, const Double_t minEta = -0.9, const Double_t maxEta = 0.9, const Double_t minPhi = 0, const Double_t maxPhi = TMath::Pi() * 2, const Int_t nTracks = 1, const Int_t nClus = 0, const Bool_t copyArray = kFALSE ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetEmbedding", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetEmbedding", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- AliJetEmbeddingTask *jetEmb = new AliJetEmbeddingTask(taskName); jetEmb->SetTracksName(tracksName); jetEmb->SetClusName(clusName); jetEmb->SetEtaRange(minEta, maxEta); jetEmb->SetPhiRange(minPhi, maxPhi); jetEmb->SetPtRange(minPt, maxPt); jetEmb->SetCopyArray(copyArray); jetEmb->SetNClusters(nClus); jetEmb->SetNTracks(nTracks); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetEmb); // Create containers for input/output mgr->ConnectInput (jetEmb, 0, mgr->GetCommonInputContainer() ); return jetEmb; } <commit_msg>fix for input TTree<commit_after>// $Id$ AliJetEmbeddingTask* AddTaskJetEmbedding( const char *tracksName = "Tracks", const char *clusName = "CaloClustersCorr", const char *taskName = "JetEmbeddingTask", const Double_t minPt = 10, const Double_t maxPt = 10, const Double_t minEta = -0.9, const Double_t maxEta = 0.9, const Double_t minPhi = 0, const Double_t maxPhi = TMath::Pi() * 2, const Int_t nTracks = 1, const Int_t nClus = 0, const Bool_t copyArray = kFALSE ) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetEmbedding", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetEmbedding", "This task requires an input event handler"); return NULL; } //------------------------------------------------------- // Init the task and do settings //------------------------------------------------------- AliJetEmbeddingTask *jetEmb = new AliJetEmbeddingTask(taskName); jetEmb->SetTracksName(tracksName); jetEmb->SetClusName(clusName); jetEmb->SetEtaRange(minEta, maxEta); jetEmb->SetPhiRange(minPhi, maxPhi); jetEmb->SetPtRange(minPt, maxPt); jetEmb->SetCopyArray(copyArray); jetEmb->SetNClusters(nClus); jetEmb->SetNTracks(nTracks); //------------------------------------------------------- // Final settings, pass to manager and set the containers //------------------------------------------------------- mgr->AddTask(jetEmb); // Create containers for input/output mgr->ConnectInput (jetEmb, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName(wagonName); contName+="Input"; TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); return jetEmb; } <|endoftext|>
<commit_before>#pragma once #include <cstddef> #include <utility> #include "type.hpp" #ifdef STX_DEBUG # include "assert.hpp" #endif namespace stx { class refcounted_interface; template<typename T> class weak; template<typename T, typename Tdel> class owned; // == owned<T, Tdelete> ============================================================== template<typename T, typename Tdel = stx::default_delete<T>> class owned { private: using Tself = owned<T, Tdel>; using Tptr = pointer_to<T>; using Tref = remove_pointer<Tptr>&; mutable Tptr m_pointer; mutable Tdel m_deleter; public: constexpr inline owned(std::nullptr_t = nullptr) : m_pointer(nullptr), m_deleter() {} constexpr inline owned(Tptr ptr, const Tdel& del = Tdel()) : m_pointer(ptr), m_deleter(del) {} inline ~owned() { reset(); } constexpr inline owned(Tself&& other) : m_pointer(std::move(other.m_pointer)), m_deleter(std::move(other.m_deleter)) { other.m_pointer = nullptr; } constexpr inline Tself& operator=(Tself&& other) { reset(other.m_pointer, other.m_deleter); other.m_pointer = nullptr; return *this; } owned(Tself const&) = delete; Tself& operator=(Tself const&) = delete; constexpr inline void reset(Tptr ptr = nullptr, const Tdel& del = Tdel()) { if(m_pointer) { m_deleter(m_pointer); } m_pointer = nullptr; m_deleter = del; } constexpr inline Tptr release() noexcept { auto tmp = std::move(m_pointer); m_pointer = nullptr; return tmp; } constexpr inline operator bool() const noexcept { return m_pointer != nullptr; } constexpr inline Tptr get() const noexcept { return m_pointer; } constexpr inline Tptr operator->() const noexcept { return m_pointer; } constexpr inline Tref operator*() const noexcept { return *m_pointer; } constexpr inline operator Tptr() const noexcept { return m_pointer; } template<typename Idx, typename = typename std::enable_if<is_array<T>>> Tref operator[](Idx i) const noexcept { return m_pointer[i]; } }; template<typename T, typename Tdel = stx::default_delete<T>> constexpr inline owned<T, Tdel> own(T* t, Tdel const& del = Tdel()) noexcept { return owned<T, Tdel>(t, del); } template<typename T, typename... ARGS> owned<T> new_owned(ARGS&&... args) noexcept { return owned<T>(new T(std::forward<ARGS>(args)...)); } // == shared<T> ============================================================== namespace detail { class shared_block { private: unsigned m_shared_refs; unsigned m_weak_refs; protected: constexpr inline shared_block() : m_shared_refs(0), m_weak_refs(0) {} inline void decrement_shared() noexcept { --m_shared_refs; if(m_shared_refs == 0) { destroy_pointer(); } } inline void increment_shared() noexcept { ++m_shared_refs; } inline void decrement_weak() noexcept { --m_weak_refs; if(m_weak_refs == 0) { destroy_block(); } } inline void increment_weak() noexcept { ++m_weak_refs; } virtual void destroy_pointer() = 0; virtual void destroy_block() = 0; struct shared_ownership { inline void operator()(shared_block* b) const noexcept { b->decrement_shared(); } }; struct weak_ownership { inline void operator()(shared_block* b) const noexcept { b->decrement_weak(); } }; public: using shared_ref = owned<shared_block, shared_ownership>; using weak_ref = owned<shared_block, weak_ownership>; inline int shared_refs() const noexcept { return m_shared_refs; } inline int weak_refs() const noexcept { return m_weak_refs; } inline shared_ref new_shared_ref() noexcept { increment_shared(); return shared_ref(this); } inline weak_ref new_weak_ref() noexcept { increment_weak(); return weak_ref(this); } virtual ~shared_block() {} }; template<typename T, typename Tdel = stx::default_delete<T>> class simple_shared_block : public shared_block { using Tptr = pointer_to<T>; Tptr m_pointer; Tdel m_deleter; public: constexpr simple_shared_block(Tptr ptr, const Tdel& del = Tdel()) : m_pointer(ptr), m_deleter(m_deleter) {} inline Tptr pointer() noexcept { return m_pointer; } void destroy_pointer() override { m_deleter(m_pointer); } void destroy_block() override { delete this; } }; template<typename T> class aligned_shared_block : public shared_block { char m_data[sizeof(T)]; public: template<typename... ARGS> constexpr aligned_shared_block(ARGS&&... args) { #ifdef STX_DEBUG xassertmsg( new (m_data) T(std::forward<ARGS>(args)...) == pointer(), "STX code error! Please open an issue with reproduction information on github!" ); #else new (m_data) T(std::forward<ARGS>(args)...); #endif } ~aligned_shared_block() { reinterpret_cast<T*>(m_data)->~T(); } inline T* pointer() noexcept { return reinterpret_cast<T*>(m_data); } void destroy_pointer() override { pointer()->~T(); } void destroy_block() override { delete this; } }; } // namespace detail template<typename T> class shared { using Tself = shared<T>; using Tptr = pointer_to<T>; using Tref = remove_pointer<Tptr>&; detail::shared_block::shared_ref m_shared_block; mutable Tptr m_pointer; public: constexpr shared(std::nullptr_t = nullptr) : m_pointer(nullptr) {} shared(detail::shared_block* block, Tptr ptr) : shared(nullptr) { if(block && block->shared_refs()) { m_shared_block = block->new_shared_ref(); m_pointer = ptr; } } shared(Tself const& other) : shared(other.m_shared_block.get(), other.m_pointer) {} shared(Tself&& other) : m_shared_block(std::move(other.m_shared_block)), m_pointer(other.m_pointer) { other.m_pointer = nullptr; } template<typename Tx> shared<Tx> cast() { return shared<Tx>(m_shared_block.get(), static_cast<pointer_to<Tx>>(m_pointer)); } Tself& operator=(Tself const& other) noexcept { m_shared_block = other.m_shared_block ? other.m_shared_block->new_shared_ref() : nullptr; m_pointer = other.m_pointer; other.m_pointer = nullptr; return *this; } Tself& operator=(Tself&& other) noexcept { m_shared_block = std::move(other.m_shared_block); m_pointer = other.m_pointer; other.m_pointer = nullptr; return *this; } constexpr inline Tptr get() const noexcept { return m_pointer; } constexpr inline Tptr operator->() const noexcept { return m_pointer; } constexpr inline Tref operator*() const noexcept { return *m_pointer; } constexpr inline operator Tptr() const noexcept { return m_pointer; } template<typename Idx, typename = typename std::enable_if<is_array<T>, Idx>::type> Tref operator[](Idx i) const noexcept { return m_pointer[i]; } }; template<typename T, typename Tdel = stx::default_delete<T>> shared<T> share(T* t, Tdel const& del = Tdel()) noexcept { return share<T>(new detail::simple_shared_block<T, Tdel>(t, del), t); } template<typename T, typename... ARGS> shared<T> new_shared(ARGS&&... args) noexcept { auto* block = new detail::aligned_shared_block<T>(std::forward<ARGS>(args)...); return shared<T>(block, block->pointer()); } // == weak<T> ============================================================== template<typename T> class weak { using Tself = weak<T>; using Tshared = shared<T>; mutable detail::shared_block::weak_ref m_shared_block; mutable T* m_pointer; public: weak(detail::shared_block* block, T* ptr) : m_shared_block(), m_pointer(nullptr) { if(block && block->shared_refs()) { m_shared_block = block->new_weak_ref(); m_pointer = ptr; } else { m_shared_block = nullptr; m_pointer = nullptr; } } void reset(detail::shared_block* block, T* ptr) { if(block && block->shared_refs()) { m_shared_block = block->new_weak_ref(); m_pointer = ptr; } else { m_shared_block = nullptr; m_pointer = nullptr; } } void reset() { m_shared_block = nullptr; m_pointer = nullptr; } weak(Tself const& other) : weak(other.m_shared_block.get(), other.pointer) { if(other.m_shared_block && other.m_shared_block->shared_refs()) m_shared_block = other.m_shared_block->new_weak_ref(); m_pointer = other.m_pointer; } weak(Tself&& other) : m_shared_block(std::move(other.m_shared_block)), m_pointer(other) {} weak(Tshared const& s) : weak() {} void operator=(Tself const& other) { reset(other.m_shared_block.get(), other.m_pointer); } void operator=(Tself&& other) { reset(other.m_shared_block.release(), other.m_pointer); other.m_pointer = nullptr; } operator bool() const { if(m_shared_block && m_shared_block->shared_refs()) return true; else { m_shared_block.reset(); m_pointer = nullptr; return false; } } shared<T> lock() noexcept { if(*this) return shared<T>(m_shared_block.get(), m_pointer); else return nullptr; } inline T* get() const noexcept { if(*this) return m_pointer; else return nullptr; } inline T* operator->() const noexcept { return get(); } inline T& operator*() const noexcept { return *get(); } }; } // namespace stx <commit_msg>Removed unnecessary inline keywords and got weak<T> more usable<commit_after>#pragma once #include <cstddef> #include <utility> #include "type.hpp" #ifdef STX_DEBUG # include "assert.hpp" #endif namespace stx { class refcounted_interface; template<typename T> class weak; template<typename T, typename Tdel> class owned; // == owned<T, Tdelete> ============================================================== template<typename T, typename Tdel = stx::default_delete<T>> class owned { private: using Tself = owned<T, Tdel>; using Tptr = pointer_to<T>; using Tref = remove_pointer<Tptr>&; mutable Tptr m_pointer; mutable Tdel m_deleter; public: constexpr inline owned(std::nullptr_t = nullptr) : m_pointer(nullptr), m_deleter() {} constexpr inline owned(Tptr ptr, const Tdel& del = Tdel()) : m_pointer(ptr), m_deleter(del) {} inline ~owned() { reset(); } constexpr inline owned(Tself&& other) : m_pointer(std::move(other.m_pointer)), m_deleter(std::move(other.m_deleter)) { other.m_pointer = nullptr; } constexpr inline Tself& operator=(Tself&& other) { reset(other.m_pointer, other.m_deleter); other.m_pointer = nullptr; return *this; } owned(Tself const&) = delete; Tself& operator=(Tself const&) = delete; constexpr inline void reset(Tptr ptr = nullptr, const Tdel& del = Tdel()) { if(m_pointer) { m_deleter(m_pointer); } m_pointer = nullptr; m_deleter = del; } constexpr inline Tptr release() noexcept { auto tmp = std::move(m_pointer); m_pointer = nullptr; return tmp; } constexpr inline operator bool() const noexcept { return m_pointer != nullptr; } constexpr inline Tptr get() const noexcept { return m_pointer; } constexpr inline Tptr operator->() const noexcept { return m_pointer; } constexpr inline Tref operator*() const noexcept { return *m_pointer; } constexpr inline operator Tptr() const noexcept { return m_pointer; } template<typename Idx, typename = typename std::enable_if<is_array<T>>> Tref operator[](Idx i) const noexcept { return m_pointer[i]; } }; template<typename T, typename Tdel = stx::default_delete<T>> constexpr inline owned<T, Tdel> own(T* t, Tdel const& del = Tdel()) noexcept { return owned<T, Tdel>(t, del); } template<typename T, typename... ARGS> owned<T> new_owned(ARGS&&... args) noexcept { return owned<T>(new T(std::forward<ARGS>(args)...)); } // == shared<T> ============================================================== namespace detail { class shared_block { private: unsigned m_shared_refs; unsigned m_weak_refs; protected: constexpr inline shared_block() : m_shared_refs(0), m_weak_refs(0) {} inline void decrement_shared() noexcept { --m_shared_refs; if(m_shared_refs == 0) { destroy_pointer(); } } inline void increment_shared() noexcept { ++m_shared_refs; } inline void decrement_weak() noexcept { --m_weak_refs; if(m_weak_refs == 0) { destroy_block(); } } inline void increment_weak() noexcept { ++m_weak_refs; } virtual void destroy_pointer() = 0; virtual void destroy_block() = 0; struct shared_ownership { inline void operator()(shared_block* b) const noexcept { b->decrement_shared(); } }; struct weak_ownership { inline void operator()(shared_block* b) const noexcept { b->decrement_weak(); } }; public: using shared_ref = owned<shared_block, shared_ownership>; using weak_ref = owned<shared_block, weak_ownership>; inline int shared_refs() const noexcept { return m_shared_refs; } inline int weak_refs() const noexcept { return m_weak_refs; } inline shared_ref new_shared_ref() noexcept { increment_shared(); return shared_ref(this); } inline weak_ref new_weak_ref() noexcept { increment_weak(); return weak_ref(this); } virtual ~shared_block() {} }; template<typename T, typename Tdel = stx::default_delete<T>> class simple_shared_block : public shared_block { using Tptr = pointer_to<T>; Tptr m_pointer; Tdel m_deleter; public: constexpr simple_shared_block(Tptr ptr, const Tdel& del = Tdel()) : m_pointer(ptr), m_deleter(m_deleter) {} inline Tptr pointer() noexcept { return m_pointer; } void destroy_pointer() override { m_deleter(m_pointer); } void destroy_block() override { delete this; } }; template<typename T> class aligned_shared_block : public shared_block { char m_data[sizeof(T)]; public: template<typename... ARGS> constexpr aligned_shared_block(ARGS&&... args) { #ifdef STX_DEBUG xassertmsg( new (m_data) T(std::forward<ARGS>(args)...) == pointer(), "STX code error! Please open an issue with reproduction information on github!" ); #else new (m_data) T(std::forward<ARGS>(args)...); #endif } ~aligned_shared_block() { reinterpret_cast<T*>(m_data)->~T(); } inline T* pointer() noexcept { return reinterpret_cast<T*>(m_data); } void destroy_pointer() override { pointer()->~T(); } void destroy_block() override { delete this; } }; } // namespace detail template<typename T> class shared { using Tself = shared<T>; using Tptr = pointer_to<T>; using Tref = remove_pointer<Tptr>&; mutable detail::shared_block::shared_ref m_shared_block; mutable Tptr m_pointer; public: constexpr shared(std::nullptr_t = nullptr) : m_pointer(nullptr) {} shared(detail::shared_block* block, Tptr ptr) : shared(nullptr) { if(block && block->shared_refs()) { m_shared_block = block->new_shared_ref(); m_pointer = ptr; } } shared(Tself const& other) : shared(other.m_shared_block.get(), other.m_pointer) {} shared(Tself&& other) : m_shared_block(std::move(other.m_shared_block)), m_pointer(other.m_pointer) { other.m_pointer = nullptr; } template<typename Tx> shared<Tx> cast() { return shared<Tx>(m_shared_block.get(), static_cast<pointer_to<Tx>>(m_pointer)); } Tself& operator=(Tself const& other) noexcept { m_shared_block = other.m_shared_block ? other.m_shared_block->new_shared_ref() : nullptr; m_pointer = other.m_pointer; other.m_pointer = nullptr; return *this; } Tself& operator=(Tself&& other) noexcept { m_shared_block = std::move(other.m_shared_block); m_pointer = other.m_pointer; other.m_pointer = nullptr; return *this; } constexpr inline Tptr get() const noexcept { return m_pointer; } constexpr inline Tptr operator->() const noexcept { return m_pointer; } constexpr inline Tref operator*() const noexcept { return *m_pointer; } constexpr inline detail::shared_block* get_block() const noexcept { return m_shared_block.get(); } constexpr inline operator Tptr() const noexcept { return m_pointer; } template<typename Idx, typename = typename std::enable_if<is_array<T>, Idx>::type> Tref operator[](Idx i) const noexcept { return m_pointer[i]; } }; template<typename T, typename Tdel = stx::default_delete<T>> shared<T> share(T* t, Tdel const& del = Tdel()) noexcept { return share<T>(new detail::simple_shared_block<T, Tdel>(t, del), t); } template<typename T, typename... ARGS> shared<T> new_shared(ARGS&&... args) noexcept { auto* block = new detail::aligned_shared_block<T>(std::forward<ARGS>(args)...); return shared<T>(block, block->pointer()); } // == weak<T> ======================================================== template<typename T> class weak { using Tself = weak<T>; using Tshared = shared<T>; mutable detail::shared_block::weak_ref m_shared_block; mutable T* m_pointer; public: // -- Constructor ----------------------------------------- weak() : m_shared_block(), m_pointer(nullptr) {} weak(detail::shared_block* block, T* ptr) : m_shared_block(), m_pointer(nullptr) { if(block && block->shared_refs()) { m_shared_block = block->new_weak_ref(); m_pointer = ptr; } else { m_shared_block = nullptr; m_pointer = nullptr; } } // -- Copy & Move --------------------------------------------- weak(Tself const& other) : weak(other.m_shared_block.get(), other.pointer) { if(other.m_shared_block && other.m_shared_block->shared_refs()) m_shared_block = other.m_shared_block->new_weak_ref(); m_pointer = other.m_pointer; } weak(Tself&& other) : m_shared_block(std::move(other.m_shared_block)), m_pointer(other) {} Tself& operator=(Tself const& other) { reset(other.m_shared_block.get(), other.m_pointer); return *this; } Tself& operator=(Tself&& other) { reset(other.m_shared_block.release(), other.m_pointer); other.m_pointer = nullptr; return *this; } // -- Assignment -------------------------------------------- weak(Tshared const& s) : weak(s.get_block(), s.get()) {} Tself& operator=(Tshared const& s) { reset(s); return *this; } // -- General operations ----------------------------------- void reset(detail::shared_block* block, T* ptr) { if(block && block->shared_refs()) { m_shared_block = block->new_weak_ref(); m_pointer = ptr; } else { m_shared_block = nullptr; m_pointer = nullptr; } } void reset(Tshared const& s) { reset(s.get_block(), s.get()); } void reset() { m_shared_block = nullptr; m_pointer = nullptr; } shared<T> lock() noexcept { if(*this) return shared<T>(m_shared_block.get(), m_pointer); else return nullptr; } inline T* get() const noexcept { if(*this) return m_pointer; else return nullptr; } operator bool() const { if(m_shared_block && m_shared_block->shared_refs()) return true; else { m_shared_block.reset(); m_pointer = nullptr; return false; } } inline T* operator->() const noexcept { return get(); } inline T& operator*() const noexcept { return *get(); } }; } // namespace stx <|endoftext|>
<commit_before>#include "tesselator.hpp" #include "geometry_coding.hpp" #include "../geometry/robust_orientation.hpp" #include "../coding/writer.hpp" #include "../base/assert.hpp" #include "../base/logging.hpp" #include "../std/queue.hpp" #include "../../3party/sgitess/interface.h" #include "../base/start_mem_debug.hpp" namespace tesselator { struct AddTessPointF { tess::Tesselator & m_tess; AddTessPointF(tess::Tesselator & tess) : m_tess(tess) {} void operator()(m2::PointD const & p) { m_tess.add(tess::Vertex(p.x, p.y)); } }; void TesselateInterior(PolygonsT const & polys, TrianglesInfo & info) { tess::VectorDispatcher disp; tess::Tesselator tess; tess.setDispatcher(&disp); tess.setWindingRule(tess::WindingOdd); tess.beginPolygon(); for (PolygonsT::const_iterator it = polys.begin(); it != polys.end(); ++it) { tess.beginContour(); for_each(it->begin(), it->end(), AddTessPointF(tess)); tess.endContour(); } tess.endPolygon(); // assign points vector<tess::Vertex> const & vert = disp.vertices(); info.AssignPoints(vert.begin(), vert.end()); for (size_t i = 0; i < disp.indices().size(); ++i) { if (disp.indices()[i].first != tess::TrianglesList) { LOG(LERROR, ("We've got invalid type during teselation:", disp.indices()[i].first)); continue; } vector<uintptr_t> const & indices = disp.indices()[i].second; size_t const count = indices.size(); ASSERT_GREATER(count, 0, ()); ASSERT_EQUAL(count % 3, 0, ()); info.Reserve(count / 3); for (size_t j = 0; j < count; j += 3) { ASSERT_LESS ( j+2, count, () ); info.Add(&indices[j]); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // TrianglesInfo::ListInfo implementation /////////////////////////////////////////////////////////////////////////////////////////////////////////// int TrianglesInfo::ListInfo::empty_key = -1; void TrianglesInfo::ListInfo::AddNeighbour(int p1, int p2, int trg) { // find or insert element for key pair<neighbors_t::iterator, bool> ret = m_neighbors.insert(make_pair(make_pair(p1, p2), trg)); // triangles should not duplicate CHECK ( ret.second, ("Duplicating triangles for indices : ", p1, p2) ); } void TrianglesInfo::ListInfo::Add(uintptr_t const * arr) { int arr32[] = { arr[0], arr[1], arr[2] }; m_triangles.push_back(Triangle(arr32)); size_t const trg = m_triangles.size()-1; for (int i = 0; i < 3; ++i) AddNeighbour(arr32[i], arr32[(i+1)%3], trg); } template <class IterT> size_t GetBufferSize(IterT b, IterT e) { vector<char> buffer; MemWriter<vector<char> > writer(buffer); while (b != e) WriteVarUint(writer, *b++); return buffer.size(); } /// Find best (cheap in serialization) start edge for processing. TrianglesInfo::ListInfo::iter_t TrianglesInfo::ListInfo::FindStartTriangle(PointsInfo const & points) const { iter_t ret = m_neighbors.end(); size_t cr = numeric_limits<size_t>::max(); for (iter_t i = m_neighbors.begin(); i != m_neighbors.end(); ++i) { if (!m_visited[i->second] && m_neighbors.find(make_pair(i->first.second, i->first.first)) == m_neighbors.end()) { uint64_t deltas[3]; deltas[0] = EncodeDelta(points.m_points[i->first.first], points.m_base); deltas[1] = EncodeDelta(points.m_points[i->first.second], points.m_points[i->first.first]); deltas[2] = EncodeDelta(points.m_points[m_triangles[i->second].GetPoint3(i->first)], points.m_points[i->first.second]); size_t const sz = GetBufferSize(deltas, deltas + 3); if (sz < cr) { ret = i; cr = sz; } } } ASSERT ( ret != m_neighbors.end(), ("?WTF? There is no border triangles!") ); return ret; } /// Return indexes of common edges of [to, from] triangles. pair<int, int> CommonEdge(Triangle const & to, Triangle const & from) { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (to.m_p[i] == from.m_p[my::NextModN(j, 3)] && to.m_p[my::NextModN(i, 3)] == from.m_p[j]) return make_pair(i, j); } } ASSERT ( false, ("?WTF? Triangles not neighbors!") ); return make_pair(-1, -1); } /// Get neighbors of 'trg' triangle, which was achieved from 'from' triangle. /// @param[out] nb neighbors indexes of 'trg' if 0->1 is common edge with'from': /// - nb[0] - by 1->2 edge; /// - nb[1] - by 2->0 edge; void TrianglesInfo::ListInfo::GetNeighbors( Triangle const & trg, Triangle const & from, int * nb) const { int i = my::NextModN(CommonEdge(trg, from).first, 3); int j = my::NextModN(i, 3); int ind = 0; iter_t it = m_neighbors.find(make_pair(trg.m_p[j], trg.m_p[i])); nb[ind++] = (it != m_neighbors.end()) ? it->second : empty_key; it = m_neighbors.find(make_pair(trg.m_p[my::NextModN(j, 3)], trg.m_p[j])); nb[ind++] = (it != m_neighbors.end()) ? it->second : empty_key; } /// Calc delta of 'from'->'to' graph edge. uint64_t TrianglesInfo::ListInfo::CalcDelta( PointsInfo const & points, Triangle const & from, Triangle const & to) const { pair<int, int> const p = CommonEdge(to, from); m2::PointU const prediction = PredictPointInTriangle(points.m_max, // common edge with 'to' points.m_points[from.m_p[(p.second+1) % 3]], points.m_points[from.m_p[(p.second)]], // diagonal point of 'from' points.m_points[from.m_p[(p.second+2) % 3]]); // delta from prediction to diagonal point of 'to' return EncodeDelta(points.m_points[to.m_p[(p.first+2) % 3]], prediction); } template <class TPopOrder> void TrianglesInfo::ListInfo::MakeTrianglesChainImpl( PointsInfo const & points, iter_t start, vector<Edge> & chain) const { chain.clear(); Triangle const fictive(start->first.second, start->first.first, -1); priority_queue<Edge, vector<Edge>, TPopOrder> q; q.push(Edge(-1, start->second, 0, -1)); while (!q.empty()) { // pop current element Edge e = q.top(); q.pop(); // check if already processed if (m_visited[e.m_p[1]]) continue; m_visited[e.m_p[1]] = true; // push to chain chain.push_back(e); Triangle const & trg = m_triangles[e.m_p[1]]; // get neighbors int nb[2]; GetNeighbors(trg, (e.m_p[0] == -1) ? fictive : m_triangles[e.m_p[0]], nb); // push neighbors to queue for (int i = 0; i < 2; ++i) if (nb[i] != empty_key && !m_visited[nb[i]]) q.push(Edge(e.m_p[1], nb[i], CalcDelta(points, trg, m_triangles[nb[i]]), i)); } } // Element with less m_delta is better than another one. struct edge_greater_delta { bool operator() (Edge const & e1, Edge const & e2) const { return (e1.m_delta > e2.m_delta); } }; // Experimental ... struct edge_less_delta { bool operator() (Edge const & e1, Edge const & e2) const { return (e1.m_delta < e2.m_delta); } }; void TrianglesInfo::ListInfo::MakeTrianglesChain( PointsInfo const & points, iter_t start, vector<Edge> & chain, bool /*goodOrder*/) const { //if (goodOrder) MakeTrianglesChainImpl<edge_greater_delta>(points, start, chain); //else // MakeTrianglesChainImpl<edge_less_delta>(points, start, chain); } void TrianglesInfo::Add(uintptr_t const * arr) { // When adding triangles, check that they all have identical orientation! m2::PointD arrP[] = { m_points[arr[0]], m_points[arr[1]], m_points[arr[2]] }; double const cp = m2::robust::OrientedS(arrP[0], arrP[1], arrP[2]); if (cp != 0.0) { bool const isCCW = (cp > 0.0); if (m_isCCW == 0) m_isCCW = (isCCW ? 1 : -1); else CHECK_EQUAL ( m_isCCW == 1, isCCW, () ); m_triangles.back().Add(arr); } } void TrianglesInfo::GetPointsInfo(m2::PointU const & baseP, m2::PointU const & maxP, function<m2::PointU (m2::PointD)> const & convert, PointsInfo & info) const { info.m_base = baseP; info.m_max = maxP; size_t const count = m_points.size(); info.m_points.reserve(count); for (size_t i = 0; i < count; ++i) info.m_points.push_back(convert(m_points[i])); } } <commit_msg>Remove triangles orientation checking after tesselation.<commit_after>#include "tesselator.hpp" #include "geometry_coding.hpp" #include "../geometry/robust_orientation.hpp" #include "../coding/writer.hpp" #include "../base/assert.hpp" #include "../base/logging.hpp" #include "../std/queue.hpp" #include "../../3party/sgitess/interface.h" #include "../base/start_mem_debug.hpp" namespace tesselator { struct AddTessPointF { tess::Tesselator & m_tess; AddTessPointF(tess::Tesselator & tess) : m_tess(tess) {} void operator()(m2::PointD const & p) { m_tess.add(tess::Vertex(p.x, p.y)); } }; void TesselateInterior(PolygonsT const & polys, TrianglesInfo & info) { tess::VectorDispatcher disp; tess::Tesselator tess; tess.setDispatcher(&disp); tess.setWindingRule(tess::WindingOdd); tess.beginPolygon(); for (PolygonsT::const_iterator it = polys.begin(); it != polys.end(); ++it) { tess.beginContour(); for_each(it->begin(), it->end(), AddTessPointF(tess)); tess.endContour(); } tess.endPolygon(); // assign points vector<tess::Vertex> const & vert = disp.vertices(); info.AssignPoints(vert.begin(), vert.end()); for (size_t i = 0; i < disp.indices().size(); ++i) { if (disp.indices()[i].first != tess::TrianglesList) { LOG(LERROR, ("We've got invalid type during teselation:", disp.indices()[i].first)); continue; } vector<uintptr_t> const & indices = disp.indices()[i].second; size_t const count = indices.size(); ASSERT_GREATER(count, 0, ()); ASSERT_EQUAL(count % 3, 0, ()); info.Reserve(count / 3); for (size_t j = 0; j < count; j += 3) { ASSERT_LESS ( j+2, count, () ); info.Add(&indices[j]); } } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// // TrianglesInfo::ListInfo implementation /////////////////////////////////////////////////////////////////////////////////////////////////////////// int TrianglesInfo::ListInfo::empty_key = -1; void TrianglesInfo::ListInfo::AddNeighbour(int p1, int p2, int trg) { // find or insert element for key pair<neighbors_t::iterator, bool> ret = m_neighbors.insert(make_pair(make_pair(p1, p2), trg)); // triangles should not duplicate CHECK ( ret.second, ("Duplicating triangles for indices : ", p1, p2) ); } void TrianglesInfo::ListInfo::Add(uintptr_t const * arr) { int arr32[] = { arr[0], arr[1], arr[2] }; m_triangles.push_back(Triangle(arr32)); size_t const trg = m_triangles.size()-1; for (int i = 0; i < 3; ++i) AddNeighbour(arr32[i], arr32[(i+1)%3], trg); } template <class IterT> size_t GetBufferSize(IterT b, IterT e) { vector<char> buffer; MemWriter<vector<char> > writer(buffer); while (b != e) WriteVarUint(writer, *b++); return buffer.size(); } /// Find best (cheap in serialization) start edge for processing. TrianglesInfo::ListInfo::iter_t TrianglesInfo::ListInfo::FindStartTriangle(PointsInfo const & points) const { iter_t ret = m_neighbors.end(); size_t cr = numeric_limits<size_t>::max(); for (iter_t i = m_neighbors.begin(); i != m_neighbors.end(); ++i) { if (!m_visited[i->second] && m_neighbors.find(make_pair(i->first.second, i->first.first)) == m_neighbors.end()) { uint64_t deltas[3]; deltas[0] = EncodeDelta(points.m_points[i->first.first], points.m_base); deltas[1] = EncodeDelta(points.m_points[i->first.second], points.m_points[i->first.first]); deltas[2] = EncodeDelta(points.m_points[m_triangles[i->second].GetPoint3(i->first)], points.m_points[i->first.second]); size_t const sz = GetBufferSize(deltas, deltas + 3); if (sz < cr) { ret = i; cr = sz; } } } ASSERT ( ret != m_neighbors.end(), ("?WTF? There is no border triangles!") ); return ret; } /// Return indexes of common edges of [to, from] triangles. pair<int, int> CommonEdge(Triangle const & to, Triangle const & from) { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (to.m_p[i] == from.m_p[my::NextModN(j, 3)] && to.m_p[my::NextModN(i, 3)] == from.m_p[j]) return make_pair(i, j); } } ASSERT ( false, ("?WTF? Triangles not neighbors!") ); return make_pair(-1, -1); } /// Get neighbors of 'trg' triangle, which was achieved from 'from' triangle. /// @param[out] nb neighbors indexes of 'trg' if 0->1 is common edge with'from': /// - nb[0] - by 1->2 edge; /// - nb[1] - by 2->0 edge; void TrianglesInfo::ListInfo::GetNeighbors( Triangle const & trg, Triangle const & from, int * nb) const { int i = my::NextModN(CommonEdge(trg, from).first, 3); int j = my::NextModN(i, 3); int ind = 0; iter_t it = m_neighbors.find(make_pair(trg.m_p[j], trg.m_p[i])); nb[ind++] = (it != m_neighbors.end()) ? it->second : empty_key; it = m_neighbors.find(make_pair(trg.m_p[my::NextModN(j, 3)], trg.m_p[j])); nb[ind++] = (it != m_neighbors.end()) ? it->second : empty_key; } /// Calc delta of 'from'->'to' graph edge. uint64_t TrianglesInfo::ListInfo::CalcDelta( PointsInfo const & points, Triangle const & from, Triangle const & to) const { pair<int, int> const p = CommonEdge(to, from); m2::PointU const prediction = PredictPointInTriangle(points.m_max, // common edge with 'to' points.m_points[from.m_p[(p.second+1) % 3]], points.m_points[from.m_p[(p.second)]], // diagonal point of 'from' points.m_points[from.m_p[(p.second+2) % 3]]); // delta from prediction to diagonal point of 'to' return EncodeDelta(points.m_points[to.m_p[(p.first+2) % 3]], prediction); } template <class TPopOrder> void TrianglesInfo::ListInfo::MakeTrianglesChainImpl( PointsInfo const & points, iter_t start, vector<Edge> & chain) const { chain.clear(); Triangle const fictive(start->first.second, start->first.first, -1); priority_queue<Edge, vector<Edge>, TPopOrder> q; q.push(Edge(-1, start->second, 0, -1)); while (!q.empty()) { // pop current element Edge e = q.top(); q.pop(); // check if already processed if (m_visited[e.m_p[1]]) continue; m_visited[e.m_p[1]] = true; // push to chain chain.push_back(e); Triangle const & trg = m_triangles[e.m_p[1]]; // get neighbors int nb[2]; GetNeighbors(trg, (e.m_p[0] == -1) ? fictive : m_triangles[e.m_p[0]], nb); // push neighbors to queue for (int i = 0; i < 2; ++i) if (nb[i] != empty_key && !m_visited[nb[i]]) q.push(Edge(e.m_p[1], nb[i], CalcDelta(points, trg, m_triangles[nb[i]]), i)); } } // Element with less m_delta is better than another one. struct edge_greater_delta { bool operator() (Edge const & e1, Edge const & e2) const { return (e1.m_delta > e2.m_delta); } }; // Experimental ... struct edge_less_delta { bool operator() (Edge const & e1, Edge const & e2) const { return (e1.m_delta < e2.m_delta); } }; void TrianglesInfo::ListInfo::MakeTrianglesChain( PointsInfo const & points, iter_t start, vector<Edge> & chain, bool /*goodOrder*/) const { //if (goodOrder) MakeTrianglesChainImpl<edge_greater_delta>(points, start, chain); //else // MakeTrianglesChainImpl<edge_less_delta>(points, start, chain); } void TrianglesInfo::Add(uintptr_t const * arr) { // When adding triangles, check that they all have identical orientation! /* m2::PointD arrP[] = { m_points[arr[0]], m_points[arr[1]], m_points[arr[2]] }; double const cp = m2::robust::OrientedS(arrP[0], arrP[1], arrP[2]); if (cp != 0.0) { bool const isCCW = (cp > 0.0); if (m_isCCW == 0) m_isCCW = (isCCW ? 1 : -1); else CHECK_EQUAL ( m_isCCW == 1, isCCW, () ); m_triangles.back().Add(arr); } */ m_triangles.back().Add(arr); } void TrianglesInfo::GetPointsInfo(m2::PointU const & baseP, m2::PointU const & maxP, function<m2::PointU (m2::PointD)> const & convert, PointsInfo & info) const { info.m_base = baseP; info.m_max = maxP; size_t const count = m_points.size(); info.m_points.reserve(count); for (size_t i = 0; i < count; ++i) info.m_points.push_back(convert(m_points[i])); } } <|endoftext|>
<commit_before>//! @Alan @pezy //! //! Exercise 9.24: //! Write a program that fetches the first element in a vector using at, //! the subscript operator, front, and begin. Test your program on an empty vector. //! #include <iostream> #include <vector> int main() { std::vector<int> v; std::cout << v.at(0); // terminating with uncaught exception of type std::out_of_range std::cout << v[0]; // Segmentation fault: 11 std::cout << v.front(); // Segmentation fault: 11 std::cout << *v.begin(); // Segmentation fault: 11 return 0; } <commit_msg>Update ex9_24.cpp<commit_after>//! @Yue Wang @pezy //! //! Exercise 9.24: //! Write a program that fetches the first element in a vector using at, //! the subscript operator, front, and begin. Test your program on an empty vector. //! #include <iostream> #include <vector> int main() { std::vector<int> v; std::cout << v.at(0); // terminating with uncaught exception of type std::out_of_range std::cout << v[0]; // Segmentation fault: 11 std::cout << v.front(); // Segmentation fault: 11 std::cout << *v.begin(); // Segmentation fault: 11 return 0; } <|endoftext|>
<commit_before>// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <fstream> #include <getopt.h> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <svdpi.h> #include "log_trace_listener.h" #include "otbn_memutil.h" #include "otbn_trace_checker.h" #include "otbn_trace_source.h" #include "sv_scoped.h" #include "verilated_toplevel.h" #include "verilator_memutil.h" #include "verilator_sim_ctrl.h" extern "C" { extern unsigned int otbn_base_call_stack_get_size(); extern unsigned int otbn_base_call_stack_get_element(int index); extern unsigned int otbn_base_reg_get(int index); extern unsigned int otbn_bignum_reg_get(int index, int quarter); } /** * SimCtrlExtension that adds a '--otbn-trace-file' command line option. If set * it sets up a LogTraceListener that will dump out the trace to the given log * file */ class OtbnTraceUtil : public SimCtrlExtension { private: std::unique_ptr<LogTraceListener> log_trace_listener_; bool SetupTraceLog(const std::string &log_filename) { try { log_trace_listener_ = std::make_unique<LogTraceListener>(log_filename); OtbnTraceSource::get().AddListener(log_trace_listener_.get()); return true; } catch (const std::runtime_error &err) { std::cerr << "ERROR: Failed to set up trace log: " << err.what() << std::endl; return false; } return false; } void PrintHelp() { std::cout << "Trace log utilities:\n\n" "--otbn-trace-file=FILE\n" " Write OTBN trace log to FILE\n\n"; } public: virtual bool ParseCLIArguments(int argc, char **argv, bool &exit_app) { const struct option long_options[] = { {"otbn-trace-file", required_argument, nullptr, 'l'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0}}; // Reset the command parsing index in-case other utils have already parsed // some arguments optind = 1; while (1) { int c = getopt_long(argc, argv, "h", long_options, nullptr); if (c == -1) { break; } switch (c) { case 0: break; case 'l': return SetupTraceLog(optarg); case 'h': PrintHelp(); break; } } return true; } ~OtbnTraceUtil() { if (log_trace_listener_) OtbnTraceSource::get().RemoveListener(log_trace_listener_.get()); } }; int main(int argc, char **argv) { otbn_top_sim top; OtbnMemUtil otbn_memutil("TOP.otbn_top_sim"); VerilatorMemUtil memutil(&otbn_memutil); OtbnTraceUtil traceutil; VerilatorSimCtrl &simctrl = VerilatorSimCtrl::GetInstance(); simctrl.SetTop(&top, &top.IO_CLK, &top.IO_RST_N, VerilatorSimCtrlFlags::ResetPolarityNegative); simctrl.RegisterExtension(&memutil); simctrl.RegisterExtension(&traceutil); std::cout << "Simulation of OTBN" << std::endl << "==================" << std::endl << std::endl; auto pr = simctrl.Exec(argc, argv); int ret_code = pr.first; bool ran_simulation = pr.second; if (ret_code != 0 || !ran_simulation) { return ret_code; } svSetScope(svGetScopeFromName("TOP.otbn_top_sim")); svBit model_err = otbn_err_get(); if (model_err) { return 1; } std::cout << "Call Stack:" << std::endl; std::cout << "-----------" << std::endl; for (int i = 0; i < otbn_base_call_stack_get_size(); ++i) { std::cout << std::setfill(' ') << "0x" << std::hex << std::setw(8) << std::setfill('0') << std::right << otbn_base_call_stack_get_element(i) << std::endl; } std::cout << std::endl; std::cout << "Final Base Register Values:" << std::endl; std::cout << "Reg | Value" << std::endl; std::cout << "----------------" << std::endl; for (int i = 2; i < 32; ++i) { std::cout << "x" << std::left << std::dec << std::setw(2) << std::setfill(' ') << i << " | 0x" << std::hex << std::setw(8) << std::setfill('0') << std::right << otbn_base_reg_get(i) << std::endl; } std::cout << std::endl; std::cout << "Final Bignum Register Values:" << std::endl; std::cout << "Reg | Value" << std::endl; std::cout << "---------------------------------------------------------------" "----------------" << std::endl; for (int i = 0; i < 32; ++i) { std::cout << "w" << std::left << std::dec << std::setw(2) << std::setfill(' ') << i << " | 0x" << std::hex; std::cout << std::setw(8) << std::setfill('0') << std::right << otbn_bignum_reg_get(i, 7) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 6) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 5) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 4) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 3) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 2) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 1) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 0) << std::endl; } int exp_stop_pc = otbn_memutil.GetExpEndAddr(); if (exp_stop_pc >= 0) { SVScoped core_scope("TOP.otbn_top_sim.u_otbn_core_model"); int act_stop_pc = otbn_core_get_stop_pc(); if (exp_stop_pc != act_stop_pc) { std::cerr << "ERROR: Expected stop PC from ELF file was 0x" << std::hex << exp_stop_pc << ", but simulation actually stopped at 0x" << act_stop_pc << ".\n"; return 1; } } return 0; } <commit_msg>[otbn] Add missing extern function declarations<commit_after>// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <fstream> #include <getopt.h> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <svdpi.h> #include "log_trace_listener.h" #include "otbn_memutil.h" #include "otbn_trace_checker.h" #include "otbn_trace_source.h" #include "sv_scoped.h" #include "verilated_toplevel.h" #include "verilator_memutil.h" #include "verilator_sim_ctrl.h" extern "C" { extern unsigned int otbn_base_call_stack_get_size(); extern unsigned int otbn_base_call_stack_get_element(int index); extern unsigned int otbn_base_reg_get(int index); extern unsigned int otbn_bignum_reg_get(int index, int quarter); extern svBit otbn_err_get(); extern int otbn_core_get_stop_pc(); } /** * SimCtrlExtension that adds a '--otbn-trace-file' command line option. If set * it sets up a LogTraceListener that will dump out the trace to the given log * file */ class OtbnTraceUtil : public SimCtrlExtension { private: std::unique_ptr<LogTraceListener> log_trace_listener_; bool SetupTraceLog(const std::string &log_filename) { try { log_trace_listener_ = std::make_unique<LogTraceListener>(log_filename); OtbnTraceSource::get().AddListener(log_trace_listener_.get()); return true; } catch (const std::runtime_error &err) { std::cerr << "ERROR: Failed to set up trace log: " << err.what() << std::endl; return false; } return false; } void PrintHelp() { std::cout << "Trace log utilities:\n\n" "--otbn-trace-file=FILE\n" " Write OTBN trace log to FILE\n\n"; } public: virtual bool ParseCLIArguments(int argc, char **argv, bool &exit_app) { const struct option long_options[] = { {"otbn-trace-file", required_argument, nullptr, 'l'}, {"help", no_argument, nullptr, 'h'}, {nullptr, no_argument, nullptr, 0}}; // Reset the command parsing index in-case other utils have already parsed // some arguments optind = 1; while (1) { int c = getopt_long(argc, argv, "h", long_options, nullptr); if (c == -1) { break; } switch (c) { case 0: break; case 'l': return SetupTraceLog(optarg); case 'h': PrintHelp(); break; } } return true; } ~OtbnTraceUtil() { if (log_trace_listener_) OtbnTraceSource::get().RemoveListener(log_trace_listener_.get()); } }; int main(int argc, char **argv) { otbn_top_sim top; OtbnMemUtil otbn_memutil("TOP.otbn_top_sim"); VerilatorMemUtil memutil(&otbn_memutil); OtbnTraceUtil traceutil; VerilatorSimCtrl &simctrl = VerilatorSimCtrl::GetInstance(); simctrl.SetTop(&top, &top.IO_CLK, &top.IO_RST_N, VerilatorSimCtrlFlags::ResetPolarityNegative); simctrl.RegisterExtension(&memutil); simctrl.RegisterExtension(&traceutil); std::cout << "Simulation of OTBN" << std::endl << "==================" << std::endl << std::endl; auto pr = simctrl.Exec(argc, argv); int ret_code = pr.first; bool ran_simulation = pr.second; if (ret_code != 0 || !ran_simulation) { return ret_code; } svSetScope(svGetScopeFromName("TOP.otbn_top_sim")); svBit model_err = otbn_err_get(); if (model_err) { return 1; } std::cout << "Call Stack:" << std::endl; std::cout << "-----------" << std::endl; for (int i = 0; i < otbn_base_call_stack_get_size(); ++i) { std::cout << std::setfill(' ') << "0x" << std::hex << std::setw(8) << std::setfill('0') << std::right << otbn_base_call_stack_get_element(i) << std::endl; } std::cout << std::endl; std::cout << "Final Base Register Values:" << std::endl; std::cout << "Reg | Value" << std::endl; std::cout << "----------------" << std::endl; for (int i = 2; i < 32; ++i) { std::cout << "x" << std::left << std::dec << std::setw(2) << std::setfill(' ') << i << " | 0x" << std::hex << std::setw(8) << std::setfill('0') << std::right << otbn_base_reg_get(i) << std::endl; } std::cout << std::endl; std::cout << "Final Bignum Register Values:" << std::endl; std::cout << "Reg | Value" << std::endl; std::cout << "---------------------------------------------------------------" "----------------" << std::endl; for (int i = 0; i < 32; ++i) { std::cout << "w" << std::left << std::dec << std::setw(2) << std::setfill(' ') << i << " | 0x" << std::hex; std::cout << std::setw(8) << std::setfill('0') << std::right << otbn_bignum_reg_get(i, 7) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 6) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 5) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 4) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 3) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 2) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 1) << "_"; std::cout << std::setw(8) << std::setfill('0') << otbn_bignum_reg_get(i, 0) << std::endl; } int exp_stop_pc = otbn_memutil.GetExpEndAddr(); if (exp_stop_pc >= 0) { SVScoped core_scope("TOP.otbn_top_sim.u_otbn_core_model"); int act_stop_pc = otbn_core_get_stop_pc(); if (exp_stop_pc != act_stop_pc) { std::cerr << "ERROR: Expected stop PC from ELF file was 0x" << std::hex << exp_stop_pc << ", but simulation actually stopped at 0x" << act_stop_pc << ".\n"; return 1; } } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transliteration_Ignore.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-20 04:41:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ #define _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ #include <transliteration_commonclass.hxx> #include <i18nutil/oneToOneMapping.hxx> typedef sal_Unicode (*TransFunc)(const sal_Unicode); typedef struct { sal_Unicode previousChar; sal_Unicode currentChar; sal_Unicode replaceChar; sal_Bool two2one; } Mapping; namespace com { namespace sun { namespace star { namespace i18n { class transliteration_Ignore : public transliteration_commonclass { public: virtual rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); // This method is shared. sal_Bool SAL_CALL equals( const rtl::OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1, const rtl::OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 ) throw(com::sun::star::uno::RuntimeException); // This method is implemented in sub class if needed. Otherwise, the method implemented in this class will be used. com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2 ) throw(com::sun::star::uno::RuntimeException); // Methods which are shared. sal_Int16 SAL_CALL getType( ) throw(com::sun::star::uno::RuntimeException); rtl::OUString SAL_CALL transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset ) throw(com::sun::star::uno::RuntimeException); virtual sal_Unicode SAL_CALL transliterateChar2Char( sal_Unicode inChar) throw(com::sun::star::uno::RuntimeException, com::sun::star::i18n::MultipleCharsOutputException); com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2, XTransliteration& t1, XTransliteration& t2 ) throw(com::sun::star::uno::RuntimeException); protected: TransFunc func; oneToOneMapping *table; Mapping *map; }; #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name ();\ }; #if defined( TRANSLITERATION_BaFa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(BaFa_ja_JP) #endif #if defined( TRANSLITERATION_HyuByu_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(HyuByu_ja_JP) #endif #if defined( TRANSLITERATION_SeZe_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(SeZe_ja_JP) #endif #if defined( TRANSLITERATION_TiJi_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TiJi_ja_JP) #endif #if defined( TRANSLITERATION_MiddleDot_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(MiddleDot_ja_JP) #endif #if defined( TRANSLITERATION_MinusSign_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(MinusSign_ja_JP) #endif #if defined( TRANSLITERATION_Separator_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Separator_ja_JP) #endif #if defined( TRANSLITERATION_Space_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Space_ja_JP) #endif #if defined( TRANSLITERATION_TraditionalKana_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TraditionalKana_ja_JP) #endif #if defined( TRANSLITERATION_TraditionalKanji_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TraditionalKanji_ja_JP) #endif #if defined( TRANSLITERATION_ZiZu_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(ZiZu_ja_JP) #endif #undef TRANSLITERATION_IGNORE #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name () {\ func = (TransFunc) 0;\ table = 0;\ map = 0;\ transliterationName = "ignore"#name;\ implementationName = "com.sun.star.i18n.Transliteration.ignore"#name;\ };\ rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, \ com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); \ }; #if defined( TRANSLITERATION_KiKuFollowedBySa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(KiKuFollowedBySa_ja_JP) #endif #if defined( TRANSLITERATION_IandEfollowedByYa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(IandEfollowedByYa_ja_JP) #endif #if defined( TRANSLITERATION_IterationMark_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(IterationMark_ja_JP) #endif #if defined( TRANSLITERATION_ProlongedSoundMark_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(ProlongedSoundMark_ja_JP) #endif #undef TRANSLITERATION_IGNORE #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name () {\ func = (TransFunc) 0;\ table = 0;\ map = 0;\ transliterationName = "ignore"#name;\ implementationName = "com.sun.star.i18n.Transliteration.ignore"#name;\ };\ rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, \ com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); \ using transliteration_Ignore::transliterateRange;\ com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, \ const rtl::OUString& str2 ) throw(com::sun::star::uno::RuntimeException); \ sal_Unicode SAL_CALL \ transliterateChar2Char( sal_Unicode inChar) \ throw(com::sun::star::uno::RuntimeException,\ com::sun::star::i18n::MultipleCharsOutputException);\ }; #if defined( TRANSLITERATION_Kana ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Kana) #endif #if defined( TRANSLITERATION_Width ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Width) #endif #if defined( TRANSLITERATION_Size_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Size_ja_JP) #endif #undef TRANSLITERATION_IGNORE } } } } #endif // _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ <commit_msg>INTEGRATION: CWS changefileheader (1.8.154); FILE MERGED 2008/03/31 16:01:17 rt 1.8.154.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: transliteration_Ignore.hxx,v $ * $Revision: 1.9 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ #define _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ #include <transliteration_commonclass.hxx> #include <i18nutil/oneToOneMapping.hxx> typedef sal_Unicode (*TransFunc)(const sal_Unicode); typedef struct { sal_Unicode previousChar; sal_Unicode currentChar; sal_Unicode replaceChar; sal_Bool two2one; } Mapping; namespace com { namespace sun { namespace star { namespace i18n { class transliteration_Ignore : public transliteration_commonclass { public: virtual rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); // This method is shared. sal_Bool SAL_CALL equals( const rtl::OUString& str1, sal_Int32 pos1, sal_Int32 nCount1, sal_Int32& nMatch1, const rtl::OUString& str2, sal_Int32 pos2, sal_Int32 nCount2, sal_Int32& nMatch2 ) throw(com::sun::star::uno::RuntimeException); // This method is implemented in sub class if needed. Otherwise, the method implemented in this class will be used. com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2 ) throw(com::sun::star::uno::RuntimeException); // Methods which are shared. sal_Int16 SAL_CALL getType( ) throw(com::sun::star::uno::RuntimeException); rtl::OUString SAL_CALL transliterate( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, com::sun::star::uno::Sequence< sal_Int32 >& offset ) throw(com::sun::star::uno::RuntimeException); virtual sal_Unicode SAL_CALL transliterateChar2Char( sal_Unicode inChar) throw(com::sun::star::uno::RuntimeException, com::sun::star::i18n::MultipleCharsOutputException); com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, const rtl::OUString& str2, XTransliteration& t1, XTransliteration& t2 ) throw(com::sun::star::uno::RuntimeException); protected: TransFunc func; oneToOneMapping *table; Mapping *map; }; #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name ();\ }; #if defined( TRANSLITERATION_BaFa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(BaFa_ja_JP) #endif #if defined( TRANSLITERATION_HyuByu_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(HyuByu_ja_JP) #endif #if defined( TRANSLITERATION_SeZe_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(SeZe_ja_JP) #endif #if defined( TRANSLITERATION_TiJi_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TiJi_ja_JP) #endif #if defined( TRANSLITERATION_MiddleDot_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(MiddleDot_ja_JP) #endif #if defined( TRANSLITERATION_MinusSign_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(MinusSign_ja_JP) #endif #if defined( TRANSLITERATION_Separator_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Separator_ja_JP) #endif #if defined( TRANSLITERATION_Space_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Space_ja_JP) #endif #if defined( TRANSLITERATION_TraditionalKana_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TraditionalKana_ja_JP) #endif #if defined( TRANSLITERATION_TraditionalKanji_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(TraditionalKanji_ja_JP) #endif #if defined( TRANSLITERATION_ZiZu_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(ZiZu_ja_JP) #endif #undef TRANSLITERATION_IGNORE #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name () {\ func = (TransFunc) 0;\ table = 0;\ map = 0;\ transliterationName = "ignore"#name;\ implementationName = "com.sun.star.i18n.Transliteration.ignore"#name;\ };\ rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, \ com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); \ }; #if defined( TRANSLITERATION_KiKuFollowedBySa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(KiKuFollowedBySa_ja_JP) #endif #if defined( TRANSLITERATION_IandEfollowedByYa_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(IandEfollowedByYa_ja_JP) #endif #if defined( TRANSLITERATION_IterationMark_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(IterationMark_ja_JP) #endif #if defined( TRANSLITERATION_ProlongedSoundMark_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(ProlongedSoundMark_ja_JP) #endif #undef TRANSLITERATION_IGNORE #define TRANSLITERATION_IGNORE( name ) \ class ignore##name : public transliteration_Ignore {\ public:\ ignore##name () {\ func = (TransFunc) 0;\ table = 0;\ map = 0;\ transliterationName = "ignore"#name;\ implementationName = "com.sun.star.i18n.Transliteration.ignore"#name;\ };\ rtl::OUString SAL_CALL folding( const rtl::OUString& inStr, sal_Int32 startPos, sal_Int32 nCount, \ com::sun::star::uno::Sequence< sal_Int32 >& offset) throw(com::sun::star::uno::RuntimeException); \ using transliteration_Ignore::transliterateRange;\ com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL transliterateRange( const rtl::OUString& str1, \ const rtl::OUString& str2 ) throw(com::sun::star::uno::RuntimeException); \ sal_Unicode SAL_CALL \ transliterateChar2Char( sal_Unicode inChar) \ throw(com::sun::star::uno::RuntimeException,\ com::sun::star::i18n::MultipleCharsOutputException);\ }; #if defined( TRANSLITERATION_Kana ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Kana) #endif #if defined( TRANSLITERATION_Width ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Width) #endif #if defined( TRANSLITERATION_Size_ja_JP ) || defined( TRANSLITERATION_ALL ) TRANSLITERATION_IGNORE(Size_ja_JP) #endif #undef TRANSLITERATION_IGNORE } } } } #endif // _I18N_TRANSLITERATION_TRANSLITERATION_IGNORE_H_ <|endoftext|>
<commit_before> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v2.0.0 Copyright(c) 2015 - 2017 Denis Blank <denis.blank at outlook dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #ifndef CONTINUABLE_DETAIL_AWAITING_HPP_INCLUDED__ #define CONTINUABLE_DETAIL_AWAITING_HPP_INCLUDED__ // Exlude this header when coroutines are not available #ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE #include <experimental/coroutine> #include <continuable/continuable-api.hpp> #include <continuable/detail/expected.hpp> #include <continuable/detail/features.hpp> namespace cti { namespace detail { namespace awaiting { /// We import the coroutine handle in our namespace using std::experimental::coroutine_handle; /// An object which provides the internal buffer and helper methods /// for waiting on a continuable in a stackless coroutine. template <typename Continuable> struct awaitable { Continuable continuable_; /// A cache which is used to // expected::expected<int> cache_; /// Since continuables are evaluated lazily we are not /// capable to say whether the resumption will be instantly. bool await_ready() const noexcept { return false; } /// Suspend the current context // TODO Convert this to an r-value function once possible void await_suspend(coroutine_handle<> h) { // Forward every result to the current awaitable std::move(continuable_).flow([h, this](auto&&... args) { resolve(); h.resume(); }); } void await_resume() { // if ec throw // return n; // return } /// Resolve the continuation through the result template <typename... Args> void resolve(Args&&... args) { // ... } /// Resolve the continuation through an error void resolve(types::dispatch_error_tag, types::error_type error) { // ... } }; /// Converts a continuable into an awaitable object as described by /// the C++ coroutine TS. template <typename T> auto create_awaiter(T&& continuable) { return awaitable<std::decay_t<T>>{std::forward<T>(continuable)}; } } // namespace awaiting } // namespace detail } // namespace cti #endif // CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE #endif // CONTINUABLE_DETAIL_UTIL_HPP_INCLUDED__ <commit_msg>More work on await<commit_after> /* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v2.0.0 Copyright(c) 2015 - 2017 Denis Blank <denis.blank at outlook dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #ifndef CONTINUABLE_DETAIL_AWAITING_HPP_INCLUDED__ #define CONTINUABLE_DETAIL_AWAITING_HPP_INCLUDED__ // Exlude this header when coroutines are not available #ifdef CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE #include <experimental/coroutine> #include <continuable/continuable-api.hpp> #include <continuable/detail/expected.hpp> #include <continuable/detail/features.hpp> namespace cti { namespace detail { namespace awaiting { /// We import the coroutine handle in our namespace using std::experimental::coroutine_handle; /// An object which provides the internal buffer and helper methods /// for waiting on a continuable in a stackless coroutine. template <typename Continuable> class awaitable { /// The continuable which is invoked upon suspension Continuable continuable_; /// A cache which is used to pass the result of the continuation /// to the expected::expected<int /*TODO*/> cache_; public: /// Since continuables are evaluated lazily we are not /// capable to say whether the resumption will be instantly. bool await_ready() const noexcept { return false; } /// Suspend the current context // TODO Convert this to an r-value function once possible void await_suspend(coroutine_handle<> h) { // Forward every result to the current awaitable std::move(continuable_).flow([h, this](auto&&... args) { resolve(); h.resume(); }); } void await_resume() { // if ec throw // return n; // return } private: /// Resolve the continuation through the result template <typename... Args> void resolve(Args&&... args) { // ... } /// Resolve the continuation through an error void resolve(types::dispatch_error_tag, types::error_type error) { // ... } }; /// Converts a continuable into an awaitable object as described by /// the C++ coroutine TS. template <typename T> auto create_awaiter(T&& continuable) { return awaitable<std::decay_t<T>>{std::forward<T>(continuable)}; } } // namespace awaiting } // namespace detail } // namespace cti #endif // CONTINUABLE_HAS_EXPERIMENTAL_COROUTINE #endif // CONTINUABLE_DETAIL_UTIL_HPP_INCLUDED__ <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "etl/impl/transpose.hpp" #include "etl/impl/fft.hpp" /*! * \file inplace_assignable.hpp * \brief Use CRTP technique to inject inplace operations into expressions and value classes. */ namespace etl { /*! * \brief CRTP class to inject inplace operations to matrix and vector structures. * * This CRTP class injects inplace FFT, Transposition, flipping and scaling. */ template <typename D> struct inplace_assignable { using derived_t = D; ///< The derived type /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() noexcept { return *static_cast<derived_t*>(this); } /*! * \brief Scale the matrix by the factor e, in place. * * \param e The scaling factor. */ template <typename E> derived_t& scale_inplace(E&& e) { as_derived() *= e; return as_derived(); } /*! * \brief Flip the matrix horizontally and vertically, in place. */ derived_t& fflip_inplace() { static_assert(etl_traits<derived_t>::dimensions() <= 2, "Impossible to fflip a matrix of D > 2"); if (is_2d<derived_t>) { std::reverse(as_derived().begin(), as_derived().end()); } return as_derived(); } /*! * \brief Fully flip each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(etl_traits<S>::dimensions() > 3)> derived_t& deep_fflip_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).deep_fflip_inplace(); } return mat; } /*! * \brief Fully flip each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_3d<S>)> derived_t& deep_fflip_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).fflip_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S> && (etl_traits<S>::dimensions() > 3))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_deep_transpose_inplace(); } static constexpr size_t d = etl_traits<S>::dimensions(); using std::swap; swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2)); return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S> && (is_3d<S>))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_transpose_inplace(); } static constexpr size_t d = etl_traits<S>::dimensions(); using std::swap; swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2)); return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(!is_dyn_matrix<S> && (etl_traits<S>::dimensions() > 3))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).deep_transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(!is_dyn_matrix<S> && (is_3d<S>))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(etl_traits<S>::dimensions() > 3)> derived_t& direct_deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_deep_transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_3d<S>)> derived_t& direct_deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_transpose_inplace(); } return mat; } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ template <typename S = D, cpp_disable_iff(is_dyn_matrix<S>)> derived_t& transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); cpp_assert(etl::dim<0>(as_derived()) == etl::dim<1>(as_derived()), "Only square fast matrices can be tranposed inplace"); detail::inplace_square_transpose::apply(as_derived()); return as_derived(); } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S>)> derived_t& transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); decltype(auto) mat = as_derived(); if (etl::dim<0>(mat) == etl::dim<1>(mat)) { detail::inplace_square_transpose::apply(mat); } else { detail::inplace_rectangular_transpose::apply(mat); using std::swap; swap(mat.unsafe_dimension_access(0), mat.unsafe_dimension_access(1)); } return mat; } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ derived_t& direct_transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); decltype(auto) mat = as_derived(); if (etl::dim<0>(mat) == etl::dim<1>(mat)) { detail::inplace_square_transpose::apply(mat); } else { detail::inplace_rectangular_transpose::apply(mat); } return mat; } /*! * \brief Perform inplace 1D FFT of the vector. */ derived_t& fft_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(is_1d<derived_t>, "Only vector can use fft_inplace, use fft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::fft1_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform many inplace 1D FFT of the matrix. * * This function considers the first dimension as being batches of 1D FFT. */ derived_t& fft_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrix of dimensions > 1 can use fft_many_inplace"); decltype(auto) mat = as_derived(); detail::fft1_many_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform inplace 1D Inverse FFT of the vector. */ derived_t& ifft_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace IFFT"); static_assert(is_1d<derived_t>, "Only vector can use ifft_inplace, use ifft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::ifft1_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform many inplace 1D Inverse FFT of the vector. */ derived_t& ifft_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace IFFT"); static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrices can use ifft_many_inplace"); decltype(auto) mat = as_derived(); detail::ifft1_many_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform inplace 2D FFT of the matrix. */ derived_t& fft2_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(is_2d<derived_t>, "Only matrix can use fft2_inplace, use fft_inplace for vectors"); decltype(auto) mat = as_derived(); detail::fft2_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform many inplace 2D FFT of the matrix. * * This function considers the first dimension as being batches of 2D FFT. */ derived_t& fft2_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix of dimensions > 2 can use fft2_many_inplace"); decltype(auto) mat = as_derived(); detail::fft2_many_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform inplace 2D Inverse FFT of the matrix. */ derived_t& ifft2_inplace() { static_assert(is_complex<derived_t>, "Only complex matrix can use inplace IFFT"); static_assert(is_2d<derived_t>, "Only vector can use ifft_inplace, use ifft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::ifft2_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } /*! * \brief Perform many inplace 2D Inverse FFT of the matrix. */ derived_t& ifft2_many_inplace() { static_assert(is_complex<derived_t>, "Only complex matrix can use inplace IFFT"); static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix > 2D can use ifft2_many_inplace"); decltype(auto) mat = as_derived(); detail::ifft2_many_impl::apply(mat, mat); mat.ensure_cpu_up_to_date(); return mat; } }; } //end of namespace etl <commit_msg>Remove unecessary sync to CPU<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include "etl/impl/transpose.hpp" #include "etl/impl/fft.hpp" /*! * \file inplace_assignable.hpp * \brief Use CRTP technique to inject inplace operations into expressions and value classes. */ namespace etl { /*! * \brief CRTP class to inject inplace operations to matrix and vector structures. * * This CRTP class injects inplace FFT, Transposition, flipping and scaling. */ template <typename D> struct inplace_assignable { using derived_t = D; ///< The derived type /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() noexcept { return *static_cast<derived_t*>(this); } /*! * \brief Scale the matrix by the factor e, in place. * * \param e The scaling factor. */ template <typename E> derived_t& scale_inplace(E&& e) { as_derived() *= e; return as_derived(); } /*! * \brief Flip the matrix horizontally and vertically, in place. */ derived_t& fflip_inplace() { static_assert(etl_traits<derived_t>::dimensions() <= 2, "Impossible to fflip a matrix of D > 2"); if (is_2d<derived_t>) { std::reverse(as_derived().begin(), as_derived().end()); } return as_derived(); } /*! * \brief Fully flip each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(etl_traits<S>::dimensions() > 3)> derived_t& deep_fflip_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).deep_fflip_inplace(); } return mat; } /*! * \brief Fully flip each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_3d<S>)> derived_t& deep_fflip_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).fflip_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S> && (etl_traits<S>::dimensions() > 3))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_deep_transpose_inplace(); } static constexpr size_t d = etl_traits<S>::dimensions(); using std::swap; swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2)); return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S> && (is_3d<S>))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_transpose_inplace(); } static constexpr size_t d = etl_traits<S>::dimensions(); using std::swap; swap(mat.unsafe_dimension_access(d - 1), mat.unsafe_dimension_access(d - 2)); return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(!is_dyn_matrix<S> && (etl_traits<S>::dimensions() > 3))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).deep_transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(!is_dyn_matrix<S> && (is_3d<S>))> derived_t& deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(etl_traits<S>::dimensions() > 3)> derived_t& direct_deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_deep_transpose_inplace(); } return mat; } /*! * \brief Transpose each sub 2D matrix in place. */ template <typename S = D, cpp_enable_iff(is_3d<S>)> derived_t& direct_deep_transpose_inplace() { decltype(auto) mat = as_derived(); for (size_t i = 0; i < etl::dim<0>(mat); ++i) { mat(i).direct_transpose_inplace(); } return mat; } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ template <typename S = D, cpp_disable_iff(is_dyn_matrix<S>)> derived_t& transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); cpp_assert(etl::dim<0>(as_derived()) == etl::dim<1>(as_derived()), "Only square fast matrices can be tranposed inplace"); detail::inplace_square_transpose::apply(as_derived()); return as_derived(); } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ template <typename S = D, cpp_enable_iff(is_dyn_matrix<S>)> derived_t& transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); decltype(auto) mat = as_derived(); if (etl::dim<0>(mat) == etl::dim<1>(mat)) { detail::inplace_square_transpose::apply(mat); } else { detail::inplace_rectangular_transpose::apply(mat); using std::swap; swap(mat.unsafe_dimension_access(0), mat.unsafe_dimension_access(1)); } return mat; } /*! * \brief Transpose the matrix in place. * * Only square fast matrix can be transpose in place, dyn matrix don't have any limitation. */ derived_t& direct_transpose_inplace() { static_assert(is_2d<derived_t>, "Only 2D matrix can be transposed"); decltype(auto) mat = as_derived(); if (etl::dim<0>(mat) == etl::dim<1>(mat)) { detail::inplace_square_transpose::apply(mat); } else { detail::inplace_rectangular_transpose::apply(mat); } return mat; } /*! * \brief Perform inplace 1D FFT of the vector. */ derived_t& fft_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(is_1d<derived_t>, "Only vector can use fft_inplace, use fft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::fft1_impl::apply(mat, mat); return mat; } /*! * \brief Perform many inplace 1D FFT of the matrix. * * This function considers the first dimension as being batches of 1D FFT. */ derived_t& fft_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrix of dimensions > 1 can use fft_many_inplace"); decltype(auto) mat = as_derived(); detail::fft1_many_impl::apply(mat, mat); return mat; } /*! * \brief Perform inplace 1D Inverse FFT of the vector. */ derived_t& ifft_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace IFFT"); static_assert(is_1d<derived_t>, "Only vector can use ifft_inplace, use ifft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::ifft1_impl::apply(mat, mat); return mat; } /*! * \brief Perform many inplace 1D Inverse FFT of the vector. */ derived_t& ifft_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace IFFT"); static_assert(etl_traits<derived_t>::dimensions() > 1, "Only matrices can use ifft_many_inplace"); decltype(auto) mat = as_derived(); detail::ifft1_many_impl::apply(mat, mat); return mat; } /*! * \brief Perform inplace 2D FFT of the matrix. */ derived_t& fft2_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(is_2d<derived_t>, "Only matrix can use fft2_inplace, use fft_inplace for vectors"); decltype(auto) mat = as_derived(); detail::fft2_impl::apply(mat, mat); return mat; } /*! * \brief Perform many inplace 2D FFT of the matrix. * * This function considers the first dimension as being batches of 2D FFT. */ derived_t& fft2_many_inplace() { static_assert(is_complex<derived_t>, "Only complex vector can use inplace FFT"); static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix of dimensions > 2 can use fft2_many_inplace"); decltype(auto) mat = as_derived(); detail::fft2_many_impl::apply(mat, mat); return mat; } /*! * \brief Perform inplace 2D Inverse FFT of the matrix. */ derived_t& ifft2_inplace() { static_assert(is_complex<derived_t>, "Only complex matrix can use inplace IFFT"); static_assert(is_2d<derived_t>, "Only vector can use ifft_inplace, use ifft2_inplace for matrices"); decltype(auto) mat = as_derived(); detail::ifft2_impl::apply(mat, mat); return mat; } /*! * \brief Perform many inplace 2D Inverse FFT of the matrix. */ derived_t& ifft2_many_inplace() { static_assert(is_complex<derived_t>, "Only complex matrix can use inplace IFFT"); static_assert(etl_traits<derived_t>::dimensions() > 2, "Only matrix > 2D can use ifft2_many_inplace"); decltype(auto) mat = as_derived(); detail::ifft2_many_impl::apply(mat, mat); return mat; } }; } //end of namespace etl <|endoftext|>
<commit_before>/** * @file centrality.tcc * @author Sean Massung */ #include <stack> #include <queue> #include <vector> #include <unordered_map> #include "parallel/parallel_for.h" namespace meta { namespace graph { namespace algorithms { template <class Graph> centrality_result degree_centrality(const Graph& g) { centrality_result res; res.reserve(g.size()); for (auto& n : g) res.emplace_back(n.id, g.adjacent(n.id).size()); std::sort(res.begin(), res.end(), [&](auto a, auto b) { return a.second > b.second; }); return res; } template <class Graph> centrality_result betweenness_centrality(const Graph& g) { centrality_result cb; cb.reserve(g.size()); for (auto& n : g) cb.emplace_back(n.id, 0.0); std::mutex print_mut; // progress mutex std::mutex calc_mut; // centrality calculation mutex printing::progress prog{" Calculating betweenness centrality ", g.size()}; size_t done = 0; parallel::parallel_for(g.begin(), g.end(), [&](auto n) { internal::betweenness_step(g, cb, n.id, calc_mut); std::lock_guard<std::mutex> lock{print_mut}; prog(++done); }); prog.end(); std::sort(cb.begin(), cb.end(), [&](auto a, auto b) { return a.second > b.second; }); return cb; } template <class Graph> centrality_result eigenvector_centrality(const Graph& g, uint64_t max_iters /* = 100 */) { std::vector<double> v(g.size(), 1.0); std::vector<double> w(g.size(), 0.0); printing::progress prog{" Calculating eigenvector centrality ", max_iters}; for (uint64_t iter = 0; iter < max_iters; ++iter) { prog(iter); w.assign(w.size(), 0.0); for (uint64_t i = 0; i < g.size(); ++i) for (auto& n : g.adjacent(node_id{i})) w[n.first] += v[i]; v.swap(w); } prog.end(); centrality_result evc; evc.reserve(g.size()); node_id id{0}; double sum = std::accumulate(v.begin(), v.end(), 0.0); for (auto& n : v) evc.emplace_back(id++, n / sum); std::sort(evc.begin(), evc.end(), [&](auto a, auto b) { return a.second > b.second; }); return evc; } namespace internal { template <class Graph> void betweenness_step(const Graph& g, centrality_result& cb, node_id n, std::mutex& calc_mut) { std::stack<node_id> stack; std::unordered_map<node_id, std::vector<node_id>> parent; std::vector<double> sigma(g.size(), 0.0); sigma[n] = 1.0; std::vector<double> d(g.size(), -1.0); d[n] = 0; std::queue<node_id> queue; queue.push(n); while (!queue.empty()) { auto v = queue.front(); queue.pop(); stack.push(v); for (auto& neighbor : g.adjacent(v)) { auto w = neighbor.first; // w found for the first time? if (d[w] < 0) { queue.push(w); d[w] = d[v] + 1; } // shortest path to w via v? if (d[w] == d[v] + 1) { sigma[w] = sigma[w] + sigma[v]; parent[w].push_back(v); } } } std::vector<double> delta(g.size(), 0); // S returns vertices in order of non-increasing distance from n while (!stack.empty()) { auto w = stack.top(); stack.pop(); for (auto& v : parent[w]) delta[v] += (sigma[v] / sigma[w]) * (1.0 + delta[w]); if (w != n) { std::lock_guard<std::mutex> lock{calc_mut}; cb[w].second += delta[w]; } } } } } } } <commit_msg>remove some c++14 features<commit_after>/** * @file centrality.tcc * @author Sean Massung */ #include <stack> #include <queue> #include <vector> #include <unordered_map> #include "parallel/parallel_for.h" namespace meta { namespace graph { namespace algorithms { template <class Graph> centrality_result degree_centrality(const Graph& g) { centrality_result res; res.reserve(g.size()); for (auto& n : g) res.emplace_back(n.id, g.adjacent(n.id).size()); using pair_t = std::pair<node_id, double>; std::sort(res.begin(), res.end(), [&](const pair_t& a, const pair_t& b) { return a.second > b.second; }); return res; } template <class Graph> centrality_result betweenness_centrality(const Graph& g) { centrality_result cb; cb.reserve(g.size()); for (auto& n : g) cb.emplace_back(n.id, 0.0); std::mutex print_mut; // progress mutex std::mutex calc_mut; // centrality calculation mutex printing::progress prog{" Calculating betweenness centrality ", g.size()}; size_t done = 0; parallel::parallel_for(g.begin(), g.end(), [&](decltype(*g.begin()) n) { internal::betweenness_step(g, cb, n.id, calc_mut); std::lock_guard<std::mutex> lock{print_mut}; prog(++done); }); prog.end(); using pair_t = std::pair<node_id, double>; std::sort(cb.begin(), cb.end(), [&](const pair_t& a, const pair_t& b) { return a.second > b.second; }); return cb; } template <class Graph> centrality_result eigenvector_centrality(const Graph& g, uint64_t max_iters /* = 100 */) { std::vector<double> v(g.size(), 1.0); std::vector<double> w(g.size(), 0.0); printing::progress prog{" Calculating eigenvector centrality ", max_iters}; for (uint64_t iter = 0; iter < max_iters; ++iter) { prog(iter); w.assign(w.size(), 0.0); for (uint64_t i = 0; i < g.size(); ++i) for (auto& n : g.adjacent(node_id{i})) w[n.first] += v[i]; v.swap(w); } prog.end(); centrality_result evc; evc.reserve(g.size()); node_id id{0}; double sum = std::accumulate(v.begin(), v.end(), 0.0); for (auto& n : v) evc.emplace_back(id++, n / sum); using pair_t = std::pair<node_id, double>; std::sort(evc.begin(), evc.end(), [&](const pair_t& a, const pair_t& b) { return a.second > b.second; }); return evc; } namespace internal { template <class Graph> void betweenness_step(const Graph& g, centrality_result& cb, node_id n, std::mutex& calc_mut) { std::stack<node_id> stack; std::unordered_map<node_id, std::vector<node_id>> parent; std::vector<double> sigma(g.size(), 0.0); sigma[n] = 1.0; std::vector<double> d(g.size(), -1.0); d[n] = 0; std::queue<node_id> queue; queue.push(n); while (!queue.empty()) { auto v = queue.front(); queue.pop(); stack.push(v); for (auto& neighbor : g.adjacent(v)) { auto w = neighbor.first; // w found for the first time? if (d[w] < 0) { queue.push(w); d[w] = d[v] + 1; } // shortest path to w via v? if (d[w] == d[v] + 1) { sigma[w] = sigma[w] + sigma[v]; parent[w].push_back(v); } } } std::vector<double> delta(g.size(), 0); // S returns vertices in order of non-increasing distance from n while (!stack.empty()) { auto w = stack.top(); stack.pop(); for (auto& v : parent[w]) delta[v] += (sigma[v] / sigma[w]) * (1.0 + delta[w]); if (w != n) { std::lock_guard<std::mutex> lock{calc_mut}; cb[w].second += delta[w]; } } } } } } } <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #include "libtorrent/config.hpp" #include "libtorrent/io_service_fwd.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/address.hpp" #include "libtorrent/error_code.hpp" #include <boost/shared_ptr.hpp> #include <boost/function/function3.hpp> #include <list> namespace libtorrent { TORRENT_EXPORT bool is_local(address const& a); TORRENT_EXPORT bool is_loopback(address const& addr); TORRENT_EXPORT bool is_multicast(address const& addr); TORRENT_EXPORT bool is_any(address const& addr); TORRENT_EXPORT bool is_teredo(address const& addr); TORRENT_EXPORT int cidr_distance(address const& a1, address const& a2); // determines if the operating system supports IPv6 TORRENT_EXPORT bool supports_ipv6(); TORRENT_EXPORT int common_bits(unsigned char const* b1 , unsigned char const* b2, int n); TORRENT_EXPORT address guess_local_address(io_service&); typedef boost::function<void(udp::endpoint const& from , char* buffer, int size)> receive_handler_t; class TORRENT_EXPORT broadcast_socket { public: broadcast_socket(io_service& ios, udp::endpoint const& multicast_endpoint , receive_handler_t const& handler, bool loopback = true); ~broadcast_socket() { close(); } enum flags_t { broadcast = 1 }; void send(char const* buffer, int size, error_code& ec, int flags = 0); void close(); int num_send_sockets() const { return m_unicast_sockets.size(); } void enable_ip_broadcast(bool e); private: struct socket_entry { socket_entry(boost::shared_ptr<datagram_socket> const& s) : socket(s), broadcast(false) {} socket_entry(boost::shared_ptr<datagram_socket> const& s , address_v4 const& mask): socket(s), netmask(mask), broadcast(false) {} boost::shared_ptr<datagram_socket> socket; char buffer[1500]; udp::endpoint remote; address_v4 netmask; bool broadcast; void close() { if (!socket) return; error_code ec; socket->close(ec); } bool can_broadcast() const { error_code ec; return broadcast && netmask != address_v4() && socket->local_endpoint(ec).address().is_v4(); } address_v4 broadcast_address() const { error_code ec; return address_v4::broadcast(socket->local_endpoint(ec).address().to_v4(), netmask); } }; void on_receive(socket_entry* s, error_code const& ec , std::size_t bytes_transferred); void open_unicast_socket(io_service& ios, address const& addr , address_v4 const& mask); void open_multicast_socket(io_service& ios, address const& addr , bool loopback, error_code& ec); // if we're aborting, destruct the handler and return true bool maybe_abort(); // these sockets are used to // join the multicast group (on each interface) // and receive multicast messages std::list<socket_entry> m_sockets; // these sockets are not bound to any // specific port and are used to // send messages to the multicast group // and receive unicast responses std::list<socket_entry> m_unicast_sockets; udp::endpoint m_multicast_endpoint; receive_handler_t m_on_receive; // the number of outstanding async operations // we have on these sockets. The m_on_receive // handler may not be destructed until this reaches // 0, since it may be holding references to // the broadcast_socket itself. int m_outstanding_operations; // when set to true, we're trying to shut down // don't initiate new operations and once the // outstanding counter reaches 0, destruct // the handler object bool m_abort; }; } #endif <commit_msg>workaround an old asio bug on 64 bit machines<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #define TORRENT_BROADCAST_SOCKET_HPP_INCLUDED #include "libtorrent/config.hpp" #include "libtorrent/io_service_fwd.hpp" #include "libtorrent/socket.hpp" #include "libtorrent/address.hpp" #include "libtorrent/error_code.hpp" #include <boost/shared_ptr.hpp> #include <boost/function/function3.hpp> #include <list> namespace libtorrent { TORRENT_EXPORT bool is_local(address const& a); TORRENT_EXPORT bool is_loopback(address const& addr); TORRENT_EXPORT bool is_multicast(address const& addr); TORRENT_EXPORT bool is_any(address const& addr); TORRENT_EXPORT bool is_teredo(address const& addr); TORRENT_EXPORT int cidr_distance(address const& a1, address const& a2); // determines if the operating system supports IPv6 TORRENT_EXPORT bool supports_ipv6(); TORRENT_EXPORT int common_bits(unsigned char const* b1 , unsigned char const* b2, int n); TORRENT_EXPORT address guess_local_address(io_service&); typedef boost::function<void(udp::endpoint const& from , char* buffer, int size)> receive_handler_t; class TORRENT_EXPORT broadcast_socket { public: broadcast_socket(io_service& ios, udp::endpoint const& multicast_endpoint , receive_handler_t const& handler, bool loopback = true); ~broadcast_socket() { close(); } enum flags_t { broadcast = 1 }; void send(char const* buffer, int size, error_code& ec, int flags = 0); void close(); int num_send_sockets() const { return m_unicast_sockets.size(); } void enable_ip_broadcast(bool e); private: struct socket_entry { socket_entry(boost::shared_ptr<datagram_socket> const& s) : socket(s), broadcast(false) {} socket_entry(boost::shared_ptr<datagram_socket> const& s , address_v4 const& mask): socket(s), netmask(mask), broadcast(false) {} boost::shared_ptr<datagram_socket> socket; char buffer[1500]; udp::endpoint remote; address_v4 netmask; bool broadcast; void close() { if (!socket) return; error_code ec; socket->close(ec); } bool can_broadcast() const { error_code ec; return broadcast && netmask != address_v4() && socket->local_endpoint(ec).address().is_v4(); } address_v4 broadcast_address() const { error_code ec; #if BOOST_VERSION < 104700 return address_v4(socket->local_endpoint(ec).address().to_v4().to_ulong() | ((~netmask.to_ulong()) & 0xffffffff)); #else return address_v4::broadcast(socket->local_endpoint(ec).address().to_v4(), netmask); #endif } }; void on_receive(socket_entry* s, error_code const& ec , std::size_t bytes_transferred); void open_unicast_socket(io_service& ios, address const& addr , address_v4 const& mask); void open_multicast_socket(io_service& ios, address const& addr , bool loopback, error_code& ec); // if we're aborting, destruct the handler and return true bool maybe_abort(); // these sockets are used to // join the multicast group (on each interface) // and receive multicast messages std::list<socket_entry> m_sockets; // these sockets are not bound to any // specific port and are used to // send messages to the multicast group // and receive unicast responses std::list<socket_entry> m_unicast_sockets; udp::endpoint m_multicast_endpoint; receive_handler_t m_on_receive; // the number of outstanding async operations // we have on these sockets. The m_on_receive // handler may not be destructed until this reaches // 0, since it may be holding references to // the broadcast_socket itself. int m_outstanding_operations; // when set to true, we're trying to shut down // don't initiate new operations and once the // outstanding counter reaches 0, destruct // the handler object bool m_abort; }; } #endif <|endoftext|>
<commit_before>namespace mant { inline void verify( const bool expression, const std::string& errorMessage); template <typename T> bool isRotationMatrix( const arma::Mat<T>& parameter) noexcept; inline bool isPermutation( const arma::Col<unsigned int>& parameter, const std::size_t lowerBound, const std::size_t upperBound) noexcept; // // Implementation // inline void verify( const bool expression, const std::string& errorMessage) { if(!expression) { throw std::logic_error(errorMessage); } } template <typename T> bool isRotationMatrix( const arma::Mat<T>& parameter) noexcept { // is suqare? if (!parameter.is_square()) { return false; // is orthonormal? return false; // determinant is either 1 or -1? } else if(std::abs(std::abs(arma::det(parameter)) - 1.0) > 1.0e-12) { // Is the rotation matrix square? // For (nearly) singular matrices, the inversion might throw an exception. try { if(arma::any(arma::vectorise(arma::abs(parameter.i() - parameter.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(parameter))))))) { return false; } } catch (...) { return false; } return true; } inline bool isPermutation( const arma::Col<unsigned int>& parameter, const std::size_t lowerBound, const std::size_t upperBound) noexcept { // TODO Add logic return true; } } <commit_msg>Rearranged the conditions and improved some comments<commit_after>namespace mant { inline void verify( const bool expression, const std::string& errorMessage); template <typename T> bool isRotationMatrix( const arma::Mat<T>& parameter) noexcept; inline bool isPermutation( const arma::Col<unsigned int>& parameter, const std::size_t lowerBound, const std::size_t upperBound) noexcept; // // Implementation // inline void verify( const bool expression, const std::string& errorMessage) { if(!expression) { throw std::logic_error(errorMessage); } } template <typename T> bool isRotationMatrix( const arma::Mat<T>& parameter) noexcept { // Is the rotation matrix square? if (!parameter.is_square()) { return false; } // Is its determinant either 1 or -1? if(std::abs(std::abs(arma::det(parameter)) - 1.0) > 1.0e-12) { return false; } // Is the rotation matrix square? // For (nearly) singular matrices, the inversion might throw an exception. try { if(arma::any(arma::vectorise(arma::abs(parameter.i() - parameter.t()) > 1.0e-12 * std::max(1.0, std::abs(arma::median(arma::vectorise(parameter))))))) { return false; } } catch (...) { return false; } return true; } inline bool isPermutation( const arma::Col<unsigned int>& parameter, const std::size_t lowerBound, const std::size_t upperBound) noexcept { // TODO Add logic return true; } } <|endoftext|>
<commit_before>#pragma once #include <limits> #include "rapidcheck/detail/Utility.h" namespace rc { namespace detail { template <typename T> constexpr int numBits() { return std::numeric_limits<T>::digits + (std::is_signed<T>::value ? 1 : 0); } template <typename Source> BitStream<Source>::BitStream(Source source) : m_source(source) , m_bits(0) , m_numBits(0) {} template <typename Source> template <typename T> T BitStream<Source>::next() { return next<T>(numBits<T>()); } template <typename Source> template <typename T> T BitStream<Source>::next(int nbits) { return next<T>(nbits, std::is_same<T, bool>()); } template <typename Source> template <typename T> T BitStream<Source>::next(int /*nbits*/, std::true_type) { return next<unsigned int>(1) != 0; } template <typename Source> template <typename T> T BitStream<Source>::next(int nbits, std::false_type) { using SourceType = decltype(m_source.next()); SourceType sourceTypeLength = (sizeof(SourceType) * 8); if (nbits == 0) { return 0; } T value = 0; int wantBits = nbits; while (wantBits > 0) { // Out of bits, refill if (m_numBits == 0) { m_bits = m_source.next(); m_numBits += numBits<SourceType>(); } const auto n = std::min(m_numBits, wantBits); const auto bits = m_bits & bitMask<SourceType>(n); value |= (bits << (nbits - wantBits)); // To avoid right-shifting data beyond the width of the given type (which is // undefined behavior, because of course it is) only perform this shift- // assignment if we have room. if (static_cast<SourceType>(n) < sourceTypeLength) { m_bits >>= static_cast<SourceType>(n); } m_numBits -= n; wantBits -= n; } if (std::is_signed<T>::value) { T signBit = static_cast<T>(0x1) << static_cast<T>(nbits - 1); if ((value & signBit) != 0) { // For signed values, we use the last bit as the sign bit. Since this // was 1, mask away by setting all bits above this one to 1 to make it a // negative number in 2's complement value |= ~bitMask<T>(nbits); } } return value; } template <typename Source> template <typename T> T BitStream<Source>::nextWithSize(int size) { return next<T>((size * numBits<T>() + (kNominalSize / 2)) / kNominalSize); } template <typename Source> BitStream<Source &> bitStreamOf(Source &source) { return BitStream<Source &>(source); } /// Returns a bitstream with the given source as a copy. template <typename Source> BitStream<Source> bitStreamOf(const Source &source) { return BitStream<Source>(source); } } // namespace detail } // namespace rc <commit_msg>Use `numBits` rather than `sizeof` in BitStream.hpp<commit_after>#pragma once #include <limits> #include "rapidcheck/detail/Utility.h" namespace rc { namespace detail { template <typename T> constexpr int numBits() { return std::numeric_limits<T>::digits + (std::is_signed<T>::value ? 1 : 0); } template <typename Source> BitStream<Source>::BitStream(Source source) : m_source(source) , m_bits(0) , m_numBits(0) {} template <typename Source> template <typename T> T BitStream<Source>::next() { return next<T>(numBits<T>()); } template <typename Source> template <typename T> T BitStream<Source>::next(int nbits) { return next<T>(nbits, std::is_same<T, bool>()); } template <typename Source> template <typename T> T BitStream<Source>::next(int /*nbits*/, std::true_type) { return next<unsigned int>(1) != 0; } template <typename Source> template <typename T> T BitStream<Source>::next(int nbits, std::false_type) { using SourceType = decltype(m_source.next()); if (nbits == 0) { return 0; } T value = 0; int wantBits = nbits; while (wantBits > 0) { // Out of bits, refill if (m_numBits == 0) { m_bits = m_source.next(); m_numBits += numBits<SourceType>(); } const auto n = std::min(m_numBits, wantBits); const auto bits = m_bits & bitMask<SourceType>(n); value |= (bits << (nbits - wantBits)); // To avoid right-shifting data beyond the width of the given type (which is // undefined behavior, because of course it is) only perform this shift- // assignment if we have room. if (static_cast<SourceType>(n) < numBits<SourceType>()) { m_bits >>= static_cast<SourceType>(n); } m_numBits -= n; wantBits -= n; } if (std::is_signed<T>::value) { T signBit = static_cast<T>(0x1) << static_cast<T>(nbits - 1); if ((value & signBit) != 0) { // For signed values, we use the last bit as the sign bit. Since this // was 1, mask away by setting all bits above this one to 1 to make it a // negative number in 2's complement value |= ~bitMask<T>(nbits); } } return value; } template <typename Source> template <typename T> T BitStream<Source>::nextWithSize(int size) { return next<T>((size * numBits<T>() + (kNominalSize / 2)) / kNominalSize); } template <typename Source> BitStream<Source &> bitStreamOf(Source &source) { return BitStream<Source &>(source); } /// Returns a bitstream with the given source as a copy. template <typename Source> BitStream<Source> bitStreamOf(const Source &source) { return BitStream<Source>(source); } } // namespace detail } // namespace rc <|endoftext|>
<commit_before>#pragma once #ifdef __has_include # if __has_include(<optional>) # include<optional> namespace staticjson { namespace nonpublic { template<typename T> using optional = std::optional<T>; auto& nullopt = std::nullopt; }} # elif __has_include(<experimental/optional>) # include <experimental/optional> namespace staticjson { namespace nonpublic { template<typename T> using optional = std::experimental::optional<T>; auto& nullopt = std::experimental::nullopt; }} # else # error "Missing <optional>" # endif #else # error "Missing <optional>" #endif namespace staticjson { template <class T> class Handler<nonpublic::optional<T>> : public BaseHandler { public: using ElementType = T; protected: mutable nonpublic::optional<T>* m_value; mutable std::unique_ptr<Handler<ElementType>> internal_handler; int depth = 0; public: explicit Handler(nonpublic::optional<T>* value) : m_value(value) {} protected: void initialize() { if (!internal_handler) { *m_value = T{}; internal_handler.reset(new Handler<ElementType>(&(m_value->value()))); } } void reset() override { depth = 0; internal_handler.reset(); *m_value = nonpublic::nullopt; } bool postcheck(bool success) { if (success) this->parsed = internal_handler->is_parsed(); return success; } public: bool Null() override { if (depth == 0) { *m_value = nonpublic::nullopt; this->parsed = true; return true; } else { initialize(); return postcheck(internal_handler->Null()); } } bool write(IHandler* out) const override { if (!m_value || !(*m_value)) { return out->Null(); } if (!internal_handler) { internal_handler.reset(new Handler<ElementType>(&(m_value->value()))); } return internal_handler->write(out); } void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override { const_cast<Handler<nonpublic::optional<T>>*>(this)->initialize(); output.SetObject(); Value anyOf(rapidjson::kArrayType); Value nullDescriptor(rapidjson::kObjectType); nullDescriptor.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("null"), alloc); Value descriptor; internal_handler->generate_schema(descriptor, alloc); anyOf.PushBack(nullDescriptor, alloc); anyOf.PushBack(descriptor, alloc); output.AddMember(rapidjson::StringRef("anyOf"), anyOf, alloc); } bool Bool(bool b) override { initialize(); return postcheck(internal_handler->Bool(b)); } bool Int(int i) override { initialize(); return postcheck(internal_handler->Int(i)); } bool Uint(unsigned i) override { initialize(); return postcheck(internal_handler->Uint(i)); } bool Int64(std::int64_t i) override { initialize(); return postcheck(internal_handler->Int64(i)); } bool Uint64(std::uint64_t i) override { initialize(); return postcheck(internal_handler->Uint64(i)); } bool Double(double i) override { initialize(); return postcheck(internal_handler->Double(i)); } bool String(const char* str, SizeType len, bool copy) override { initialize(); return postcheck(internal_handler->String(str, len, copy)); } bool Key(const char* str, SizeType len, bool copy) override { initialize(); return postcheck(internal_handler->Key(str, len, copy)); } bool StartObject() override { initialize(); ++depth; return internal_handler->StartObject(); } bool EndObject(SizeType len) override { initialize(); --depth; return postcheck(internal_handler->EndObject(len)); } bool StartArray() override { initialize(); ++depth; return postcheck(internal_handler->StartArray()); } bool EndArray(SizeType len) override { initialize(); --depth; return postcheck(internal_handler->EndArray(len)); } bool has_error() const override { return internal_handler && internal_handler->has_error(); } bool reap_error(ErrorStack& stk) override { return internal_handler && internal_handler->reap_error(stk); } std::string type_name() const override { if (this->internal_handler) { return "std::optional<" + this->internal_handler->type_name() + ">"; } return "std::optional"; } }; } <commit_msg>missing import<commit_after>#pragma once #include "stl_types.hpp" #ifdef __has_include # if __has_include(<optional>) # include<optional> namespace staticjson { namespace nonpublic { template<typename T> using optional = std::optional<T>; auto& nullopt = std::nullopt; }} # elif __has_include(<experimental/optional>) # include <experimental/optional> namespace staticjson { namespace nonpublic { template<typename T> using optional = std::experimental::optional<T>; auto& nullopt = std::experimental::nullopt; }} # else # error "Missing <optional>" # endif #else # error "Missing <optional>" #endif namespace staticjson { template <class T> class Handler<nonpublic::optional<T>> : public BaseHandler { public: using ElementType = T; protected: mutable nonpublic::optional<T>* m_value; mutable std::unique_ptr<Handler<ElementType>> internal_handler; int depth = 0; public: explicit Handler(nonpublic::optional<T>* value) : m_value(value) {} protected: void initialize() { if (!internal_handler) { *m_value = T{}; internal_handler.reset(new Handler<ElementType>(&(m_value->value()))); } } void reset() override { depth = 0; internal_handler.reset(); *m_value = nonpublic::nullopt; } bool postcheck(bool success) { if (success) this->parsed = internal_handler->is_parsed(); return success; } public: bool Null() override { if (depth == 0) { *m_value = nonpublic::nullopt; this->parsed = true; return true; } else { initialize(); return postcheck(internal_handler->Null()); } } bool write(IHandler* out) const override { if (!m_value || !(*m_value)) { return out->Null(); } if (!internal_handler) { internal_handler.reset(new Handler<ElementType>(&(m_value->value()))); } return internal_handler->write(out); } void generate_schema(Value& output, MemoryPoolAllocator& alloc) const override { const_cast<Handler<nonpublic::optional<T>>*>(this)->initialize(); output.SetObject(); Value anyOf(rapidjson::kArrayType); Value nullDescriptor(rapidjson::kObjectType); nullDescriptor.AddMember(rapidjson::StringRef("type"), rapidjson::StringRef("null"), alloc); Value descriptor; internal_handler->generate_schema(descriptor, alloc); anyOf.PushBack(nullDescriptor, alloc); anyOf.PushBack(descriptor, alloc); output.AddMember(rapidjson::StringRef("anyOf"), anyOf, alloc); } bool Bool(bool b) override { initialize(); return postcheck(internal_handler->Bool(b)); } bool Int(int i) override { initialize(); return postcheck(internal_handler->Int(i)); } bool Uint(unsigned i) override { initialize(); return postcheck(internal_handler->Uint(i)); } bool Int64(std::int64_t i) override { initialize(); return postcheck(internal_handler->Int64(i)); } bool Uint64(std::uint64_t i) override { initialize(); return postcheck(internal_handler->Uint64(i)); } bool Double(double i) override { initialize(); return postcheck(internal_handler->Double(i)); } bool String(const char* str, SizeType len, bool copy) override { initialize(); return postcheck(internal_handler->String(str, len, copy)); } bool Key(const char* str, SizeType len, bool copy) override { initialize(); return postcheck(internal_handler->Key(str, len, copy)); } bool StartObject() override { initialize(); ++depth; return internal_handler->StartObject(); } bool EndObject(SizeType len) override { initialize(); --depth; return postcheck(internal_handler->EndObject(len)); } bool StartArray() override { initialize(); ++depth; return postcheck(internal_handler->StartArray()); } bool EndArray(SizeType len) override { initialize(); --depth; return postcheck(internal_handler->EndArray(len)); } bool has_error() const override { return internal_handler && internal_handler->has_error(); } bool reap_error(ErrorStack& stk) override { return internal_handler && internal_handler->reap_error(stk); } std::string type_name() const override { if (this->internal_handler) { return "std::optional<" + this->internal_handler->type_name() + ">"; } return "std::optional"; } }; } <|endoftext|>
<commit_before>//============================================================================ // vSMC/include/vsmc/utility/aligned_memory.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2016, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_UTILITY_ALIGNED_MEMORY #define VSMC_UTILITY_ALIGNED_MEMORY #include <vsmc/internal/assert.hpp> #include <vsmc/internal/config.h> #include <cstddef> #include <cstdlib> #include <memory> #include <vector> #if VSMC_HAS_POSIX #include <stdlib.h> #elif defined(VSMC_MSVC) #include <malloc.h> #endif #if VSMC_HAS_TBB_MALLOC #include <tbb/scalable_allocator.h> #endif #if VSMC_HAS_MKL #include <mkl_service.h> #endif /// \brief Default AlignedMemory type /// \ingroup Config #ifndef VSMC_ALIGNED_MEMORY_TYPE #if VSMC_HAS_TBB_MALLOC #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemoryTBB #elif VSMC_HAS_MKL #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemoryMKL #elif VSMC_HAS_POSIX || defined(VSMC_MSVC) #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemorySYS #else #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemorySTD #endif #endif /// \brief Defualt alignment /// \ingroup Config #ifndef VSMC_ALIGNMENT #define VSMC_ALIGNMENT 32 #endif #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_POWER_OF_TWO(alignment) \ VSMC_RUNTIME_ASSERT( \ (alignment != 0 && (alignment & (alignment - 1)) == 0), \ "**aligned_malloc** USED WITH ALIGNMENT NOT A POWER OF TWO") #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_SIZEOF_VOID(alignemnt) \ VSMC_RUNTIME_ASSERT((alignment >= sizeof(void *)), \ "**aligned_malloc** USED WITH ALIGNMENT LESS THAN sizeof(void *)") #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY \ VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_POWER_OF_TWO(alignment); \ VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_SIZEOF_VOID(alignment); namespace vsmc { /// \brief Aligned memory using `std::malloc` and `std::free` /// \ingroup AlignedMemory /// /// \details /// Memory allocated through this class is aligned but some bytes might be /// wasted in each allocation. class AlignedMemorySTD { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *orig_ptr = std::malloc(n + alignment + sizeof(void *)); if (orig_ptr == nullptr) throw std::bad_alloc(); uintptr_t address = reinterpret_cast<uintptr_t>(orig_ptr); uintptr_t offset = alignment - (address + sizeof(void *)) % alignment; void *ptr = reinterpret_cast<void *>(address + offset + sizeof(void *)); void **orig = reinterpret_cast<void **>(address + offset); *orig = orig_ptr; return ptr; } static void aligned_free(void *ptr) { std::free(*reinterpret_cast<void **>( reinterpret_cast<uintptr_t>(ptr) - sizeof(void *))); } }; // class AlignedMemmorySTD #if VSMC_HAS_POSIX /// \brief Aligned memory using native system aligned memory allocation /// \ingroup AlignedMemory /// /// \details /// This class use `posix_memalign` and `free` on POSIX systems (Mac OS X, /// Linux, etc.) and `_aligned_malloc` and `_aligned_free` on Windows. class AlignedMemorySYS { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr; if (posix_memalign(&ptr, alignment, n) != 0) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { free(ptr); } }; // class AlignedMallocSYS #elif defined(VSMC_MSVC) class AlignedMemorySYS { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = _aligned_malloc(n, alignment); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { _aligned_free(ptr); } }; // class AlignedMemorySYS #endif // VSMC_HAS_POSIX #if VSMC_HAS_TBB_MALLOC /// \brief Aligned memory using Intel TBB `scalable_aligned_malloc` and /// `scalable_aligned_free`. /// \ingroup AlignedMemory class AlignedMemoryTBB { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = scalable_aligned_malloc(n, alignment); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { scalable_aligned_free(ptr); } }; // class AlignedMemoryTBB #endif // VSMC_HAS_TBB_MALLOC #if VSMC_HAS_MKL /// \brief Aligned memory using Intel MKL `mkl_malloc` and `mkl_free` /// \ingroup AlignedMemory class AlignedMemoryMKL { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = mkl_malloc(n, static_cast<int>(alignment)); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { mkl_free(ptr); } }; // class AlignedMemoryMKL #endif // VSMC_HAS_MKL /// \brief Default AlignedMemory type /// \ingroup AlignedMemory using AlignedMemory = VSMC_ALIGNED_MEMORY_TYPE; /// \brief Aligned allocator /// \ingroup AlignedMemory /// /// \tparam T The value type /// \tparam Alignment The alignment requirement of memory, must be a power of /// two and no less than `sizeof(void *)`. /// \tparam Memory The memory management class. Must provides two static member /// functions, `aligned_malloc` and `aligned_free`. The member function /// `aligned_malloc` shall behave similar to `std::malloc` but take an /// additional arguments for alignment. The member function `aligned_free` /// shall behave just like `std::free`. template <typename T, std::size_t Alignment = VSMC_ALIGNMENT, typename Memory = AlignedMemory> class AlignedAllocator { static_assert(Alignment != 0 && (Alignment & (Alignment - 1)) == 0, "**AlignedAllocator** USED WITH Alignment OTHER THAN A POWER OF TWO " "POSITIVE INTEGER"); static_assert(Alignment >= sizeof(void *), "**AlignedAllocator** USED WITH Alignment LESS THAN sizeof(void *)"); public: using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T *; using const_pointer = const T *; using reference = typename std::add_lvalue_reference<T>::type; using const_reference = typename std::add_lvalue_reference<const T>::type; using is_always_equal = std::true_type; template <typename U> class rebind { public: using other = AlignedAllocator<U, Alignment, Memory>; }; // class rebind AlignedAllocator() noexcept {} AlignedAllocator(const AlignedAllocator<T, Alignment, Memory> &) noexcept { } template <typename U> AlignedAllocator(const AlignedAllocator<U, Alignment, Memory> &) noexcept { } ~AlignedAllocator() noexcept {} static pointer address(reference x) noexcept { return std::addressof(x); } static const_pointer address(const_reference x) noexcept { return std::addressof(x); } static pointer allocate(size_type n, const void * = nullptr) { if (n == 0) return nullptr; return static_cast<pointer>( Memory::aligned_malloc(sizeof(T) * n, Alignment)); } static void deallocate(pointer ptr, size_type) { if (ptr != nullptr) Memory::aligned_free(ptr); } static constexpr size_type max_size() noexcept { return std::numeric_limits<size_type>::max(); } template <typename U, typename... Args> static void construct(U *ptr, Args &&... args) { construct(std::integral_constant<bool, std::is_scalar<U>::value>(), ptr, std::forward<Args>(args)...); } template <typename U> static void destroy(U *ptr) { std::allocator<U> alloc; alloc.destroy(ptr); } private: template <typename U, typename... Args> static void construct(std::true_type, U *, Args &&...) { } template <typename U, typename... Args> static void construct(std::false_type, U *ptr, Args &&... args) { std::allocator<U> alloc; alloc.construct(ptr, std::forward<Args>(args)...); } }; // class AlignedAllocator template <std::size_t Alignment, typename Memory> class AlignedAllocator<void, Alignment, Memory> { using value_type = void; using pointer = void *; using const_pointer = const void *; template <class U> struct rebind { using other = AlignedAllocator<U, Alignment, Memory>; }; }; // class AlignedAllocator template <std::size_t Alignment, typename Memory> class AlignedAllocator<const void, Alignment, Memory> { using value_type = const void; using pointer = const void *; using const_pointer = const void *; template <class U> struct rebind { using other = AlignedAllocator<U, Alignment, Memory>; }; }; // class AlignedAllocator template <typename T1, typename T2, std::size_t Alignment, typename Memory> inline bool operator==(const AlignedAllocator<T1, Alignment, Memory> &, const AlignedAllocator<T2, Alignment, Memory> &) noexcept { return true; } template <typename T1, typename T2, std::size_t Alignment, typename Memory> inline bool operator!=(const AlignedAllocator<T1, Alignment, Memory> &, const AlignedAllocator<T2, Alignment, Memory> &) noexcept { return false; } /// \brief AlignedAllocator for scalar type and `std::allocator` for others /// \ingroup AlignedMemory template <typename T> using Allocator = typename std::conditional<std::is_scalar<T>::value, AlignedAllocator<T>, std::allocator<T>>::type; /// \brief Vector type using AlignedAllocator /// \ingroup AlignedMemory template <typename T> using AlignedVector = std::vector<T, AlignedAllocator<T>>; /// \brief AlignedVector for scalar type and `std::vector` for others /// \ingroup AlignedMemory template <typename T> using Vector = typename std::conditional<std::is_scalar<T>::value, AlignedVector<T>, std::vector<T>>::type; } // namespace vsmc #endif // VSMC_UTILITY_ALIGNED_MEMORY <commit_msg>fix missing header<commit_after>//============================================================================ // vSMC/include/vsmc/utility/aligned_memory.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2016, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_UTILITY_ALIGNED_MEMORY #define VSMC_UTILITY_ALIGNED_MEMORY #include <vsmc/internal/assert.hpp> #include <vsmc/internal/config.h> #include <cstddef> #include <cstdlib> #include <limits> #include <memory> #include <vector> #if VSMC_HAS_POSIX #include <stdlib.h> #elif defined(VSMC_MSVC) #include <malloc.h> #endif #if VSMC_HAS_TBB_MALLOC #include <tbb/scalable_allocator.h> #endif #if VSMC_HAS_MKL #include <mkl_service.h> #endif /// \brief Default AlignedMemory type /// \ingroup Config #ifndef VSMC_ALIGNED_MEMORY_TYPE #if VSMC_HAS_TBB_MALLOC #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemoryTBB #elif VSMC_HAS_MKL #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemoryMKL #elif VSMC_HAS_POSIX || defined(VSMC_MSVC) #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemorySYS #else #define VSMC_ALIGNED_MEMORY_TYPE ::vsmc::AlignedMemorySTD #endif #endif /// \brief Defualt alignment /// \ingroup Config #ifndef VSMC_ALIGNMENT #define VSMC_ALIGNMENT 32 #endif #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_POWER_OF_TWO(alignment) \ VSMC_RUNTIME_ASSERT( \ (alignment != 0 && (alignment & (alignment - 1)) == 0), \ "**aligned_malloc** USED WITH ALIGNMENT NOT A POWER OF TWO") #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_SIZEOF_VOID(alignemnt) \ VSMC_RUNTIME_ASSERT((alignment >= sizeof(void *)), \ "**aligned_malloc** USED WITH ALIGNMENT LESS THAN sizeof(void *)") #define VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY \ VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_POWER_OF_TWO(alignment); \ VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY_SIZEOF_VOID(alignment); namespace vsmc { /// \brief Aligned memory using `std::malloc` and `std::free` /// \ingroup AlignedMemory /// /// \details /// Memory allocated through this class is aligned but some bytes might be /// wasted in each allocation. class AlignedMemorySTD { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *orig_ptr = std::malloc(n + alignment + sizeof(void *)); if (orig_ptr == nullptr) throw std::bad_alloc(); uintptr_t address = reinterpret_cast<uintptr_t>(orig_ptr); uintptr_t offset = alignment - (address + sizeof(void *)) % alignment; void *ptr = reinterpret_cast<void *>(address + offset + sizeof(void *)); void **orig = reinterpret_cast<void **>(address + offset); *orig = orig_ptr; return ptr; } static void aligned_free(void *ptr) { std::free(*reinterpret_cast<void **>( reinterpret_cast<uintptr_t>(ptr) - sizeof(void *))); } }; // class AlignedMemmorySTD #if VSMC_HAS_POSIX /// \brief Aligned memory using native system aligned memory allocation /// \ingroup AlignedMemory /// /// \details /// This class use `posix_memalign` and `free` on POSIX systems (Mac OS X, /// Linux, etc.) and `_aligned_malloc` and `_aligned_free` on Windows. class AlignedMemorySYS { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr; if (posix_memalign(&ptr, alignment, n) != 0) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { free(ptr); } }; // class AlignedMallocSYS #elif defined(VSMC_MSVC) class AlignedMemorySYS { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = _aligned_malloc(n, alignment); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { _aligned_free(ptr); } }; // class AlignedMemorySYS #endif // VSMC_HAS_POSIX #if VSMC_HAS_TBB_MALLOC /// \brief Aligned memory using Intel TBB `scalable_aligned_malloc` and /// `scalable_aligned_free`. /// \ingroup AlignedMemory class AlignedMemoryTBB { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = scalable_aligned_malloc(n, alignment); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { scalable_aligned_free(ptr); } }; // class AlignedMemoryTBB #endif // VSMC_HAS_TBB_MALLOC #if VSMC_HAS_MKL /// \brief Aligned memory using Intel MKL `mkl_malloc` and `mkl_free` /// \ingroup AlignedMemory class AlignedMemoryMKL { public: static void *aligned_malloc(std::size_t n, std::size_t alignment) { VSMC_RUNTIME_ASSERT_UTILITY_ALIGNED_MEMORY; if (n == 0) return nullptr; void *ptr = mkl_malloc(n, static_cast<int>(alignment)); if (ptr == nullptr) throw std::bad_alloc(); return ptr; } static void aligned_free(void *ptr) { mkl_free(ptr); } }; // class AlignedMemoryMKL #endif // VSMC_HAS_MKL /// \brief Default AlignedMemory type /// \ingroup AlignedMemory using AlignedMemory = VSMC_ALIGNED_MEMORY_TYPE; /// \brief Aligned allocator /// \ingroup AlignedMemory /// /// \tparam T The value type /// \tparam Alignment The alignment requirement of memory, must be a power of /// two and no less than `sizeof(void *)`. /// \tparam Memory The memory management class. Must provides two static member /// functions, `aligned_malloc` and `aligned_free`. The member function /// `aligned_malloc` shall behave similar to `std::malloc` but take an /// additional arguments for alignment. The member function `aligned_free` /// shall behave just like `std::free`. template <typename T, std::size_t Alignment = VSMC_ALIGNMENT, typename Memory = AlignedMemory> class AlignedAllocator { static_assert(Alignment != 0 && (Alignment & (Alignment - 1)) == 0, "**AlignedAllocator** USED WITH Alignment OTHER THAN A POWER OF TWO " "POSITIVE INTEGER"); static_assert(Alignment >= sizeof(void *), "**AlignedAllocator** USED WITH Alignment LESS THAN sizeof(void *)"); public: using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using pointer = T *; using const_pointer = const T *; using reference = typename std::add_lvalue_reference<T>::type; using const_reference = typename std::add_lvalue_reference<const T>::type; using is_always_equal = std::true_type; template <typename U> class rebind { public: using other = AlignedAllocator<U, Alignment, Memory>; }; // class rebind AlignedAllocator() noexcept {} AlignedAllocator(const AlignedAllocator<T, Alignment, Memory> &) noexcept { } template <typename U> AlignedAllocator(const AlignedAllocator<U, Alignment, Memory> &) noexcept { } ~AlignedAllocator() noexcept {} static pointer address(reference x) noexcept { return std::addressof(x); } static const_pointer address(const_reference x) noexcept { return std::addressof(x); } static pointer allocate(size_type n, const void * = nullptr) { if (n == 0) return nullptr; return static_cast<pointer>( Memory::aligned_malloc(sizeof(T) * n, Alignment)); } static void deallocate(pointer ptr, size_type) { if (ptr != nullptr) Memory::aligned_free(ptr); } static constexpr size_type max_size() noexcept { return std::numeric_limits<size_type>::max(); } template <typename U, typename... Args> static void construct(U *ptr, Args &&... args) { construct(std::integral_constant<bool, std::is_scalar<U>::value>(), ptr, std::forward<Args>(args)...); } template <typename U> static void destroy(U *ptr) { std::allocator<U> alloc; alloc.destroy(ptr); } private: template <typename U, typename... Args> static void construct(std::true_type, U *, Args &&...) { } template <typename U, typename... Args> static void construct(std::false_type, U *ptr, Args &&... args) { std::allocator<U> alloc; alloc.construct(ptr, std::forward<Args>(args)...); } }; // class AlignedAllocator template <std::size_t Alignment, typename Memory> class AlignedAllocator<void, Alignment, Memory> { using value_type = void; using pointer = void *; using const_pointer = const void *; template <class U> struct rebind { using other = AlignedAllocator<U, Alignment, Memory>; }; }; // class AlignedAllocator template <std::size_t Alignment, typename Memory> class AlignedAllocator<const void, Alignment, Memory> { using value_type = const void; using pointer = const void *; using const_pointer = const void *; template <class U> struct rebind { using other = AlignedAllocator<U, Alignment, Memory>; }; }; // class AlignedAllocator template <typename T1, typename T2, std::size_t Alignment, typename Memory> inline bool operator==(const AlignedAllocator<T1, Alignment, Memory> &, const AlignedAllocator<T2, Alignment, Memory> &) noexcept { return true; } template <typename T1, typename T2, std::size_t Alignment, typename Memory> inline bool operator!=(const AlignedAllocator<T1, Alignment, Memory> &, const AlignedAllocator<T2, Alignment, Memory> &) noexcept { return false; } /// \brief AlignedAllocator for scalar type and `std::allocator` for others /// \ingroup AlignedMemory template <typename T> using Allocator = typename std::conditional<std::is_scalar<T>::value, AlignedAllocator<T>, std::allocator<T>>::type; /// \brief Vector type using AlignedAllocator /// \ingroup AlignedMemory template <typename T> using AlignedVector = std::vector<T, AlignedAllocator<T>>; /// \brief AlignedVector for scalar type and `std::vector` for others /// \ingroup AlignedMemory template <typename T> using Vector = typename std::conditional<std::is_scalar<T>::value, AlignedVector<T>, std::vector<T>>::type; } // namespace vsmc #endif // VSMC_UTILITY_ALIGNED_MEMORY <|endoftext|>
<commit_before>/* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "gvplugin.h" #include "gvplugin_gdiplus.h" extern gvplugin_installed_t gvrender_gdiplus_types[]; extern gvplugin_installed_t gvtextlayout_gdiplus_types[]; extern gvplugin_installed_t gvloadimage_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types_for_cairo[]; using namespace std; using namespace Gdiplus; /* class id corresponding to each format_type */ static GUID format_id [] = { GUID_NULL, GUID_NULL, ImageFormatBMP, ImageFormatEMF, ImageFormatEMF, ImageFormatGIF, ImageFormatJPEG, ImageFormatPNG, ImageFormatTIFF }; static ULONG_PTR _gdiplusToken = NULL; static void UnuseGdiplus() { GdiplusShutdown(_gdiplusToken); } void UseGdiplus() { /* only startup once, and ensure we get shutdown */ if (!_gdiplusToken) { GdiplusStartupInput input; GdiplusStartup(&_gdiplusToken, &input, NULL); atexit(&UnuseGdiplus); } } const Gdiplus::StringFormat* GetGenericTypographic() { const Gdiplus::StringFormat* format = StringFormat::GenericTypographic(); return format; } void SaveBitmapToStream(Bitmap &bitmap, IStream *stream, int format) { /* search the encoders for one that matches our device id, then save the bitmap there */ GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); UINT encoderNum; UINT encoderSize; GetImageEncodersSize(&encoderNum, &encoderSize); vector<char> codec_buffer(encoderSize); ImageCodecInfo *codecs = (ImageCodecInfo *)&codec_buffer.front(); GetImageEncoders(encoderNum, encoderSize, codecs); for (UINT i = 0; i < encoderNum; ++i) if (memcmp(&(format_id[format]), &codecs[i].FormatID, sizeof(GUID)) == 0) { bitmap.Save(stream, &codecs[i].Clsid, NULL); break; } } static gvplugin_api_t apis[] = { {API_render, gvrender_gdiplus_types}, {API_textlayout, gvtextlayout_gdiplus_types}, {API_loadimage, gvloadimage_gdiplus_types}, {API_device, gvdevice_gdiplus_types}, {API_device, gvdevice_gdiplus_types_for_cairo}, {(api_t)0, 0}, }; #ifdef _WIN32 # define GVPLUGIN_GDIPLUS_API __declspec(dllexport) #else # define GVPLUGIN_GDIPLUS_API #endif GVPLUGIN_GDIPLUS_API gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; <commit_msg>Add `extern "C"` to export in plugin/gdiplus<commit_after>/* $Id$ $Revision$ */ /* vim:set shiftwidth=4 ts=8: */ /************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ *************************************************************************/ #include "gvplugin.h" #include "gvplugin_gdiplus.h" extern gvplugin_installed_t gvrender_gdiplus_types[]; extern gvplugin_installed_t gvtextlayout_gdiplus_types[]; extern gvplugin_installed_t gvloadimage_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types[]; extern gvplugin_installed_t gvdevice_gdiplus_types_for_cairo[]; using namespace std; using namespace Gdiplus; /* class id corresponding to each format_type */ static GUID format_id [] = { GUID_NULL, GUID_NULL, ImageFormatBMP, ImageFormatEMF, ImageFormatEMF, ImageFormatGIF, ImageFormatJPEG, ImageFormatPNG, ImageFormatTIFF }; static ULONG_PTR _gdiplusToken = NULL; static void UnuseGdiplus() { GdiplusShutdown(_gdiplusToken); } void UseGdiplus() { /* only startup once, and ensure we get shutdown */ if (!_gdiplusToken) { GdiplusStartupInput input; GdiplusStartup(&_gdiplusToken, &input, NULL); atexit(&UnuseGdiplus); } } const Gdiplus::StringFormat* GetGenericTypographic() { const Gdiplus::StringFormat* format = StringFormat::GenericTypographic(); return format; } void SaveBitmapToStream(Bitmap &bitmap, IStream *stream, int format) { /* search the encoders for one that matches our device id, then save the bitmap there */ GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); UINT encoderNum; UINT encoderSize; GetImageEncodersSize(&encoderNum, &encoderSize); vector<char> codec_buffer(encoderSize); ImageCodecInfo *codecs = (ImageCodecInfo *)&codec_buffer.front(); GetImageEncoders(encoderNum, encoderSize, codecs); for (UINT i = 0; i < encoderNum; ++i) if (memcmp(&(format_id[format]), &codecs[i].FormatID, sizeof(GUID)) == 0) { bitmap.Save(stream, &codecs[i].Clsid, NULL); break; } } static gvplugin_api_t apis[] = { {API_render, gvrender_gdiplus_types}, {API_textlayout, gvtextlayout_gdiplus_types}, {API_loadimage, gvloadimage_gdiplus_types}, {API_device, gvdevice_gdiplus_types}, {API_device, gvdevice_gdiplus_types_for_cairo}, {(api_t)0, 0}, }; #ifdef __cplusplus extern "C" { #endif #ifdef _WIN32 # define GVPLUGIN_GDIPLUS_API __declspec(dllexport) #else # define GVPLUGIN_GDIPLUS_API #endif GVPLUGIN_GDIPLUS_API gvplugin_library_t gvplugin_gdiplus_LTX_library = { "gdiplus", apis }; #ifdef __cplusplus } #endif <|endoftext|>
<commit_before>// recordmatch.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" class GameStartEndHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; GameStartEndHandler gameStartEndHandler; std::string path; bool started = false; std::string filename; BZ_GET_PLUGIN_VERSION BZF_PLUGIN_CALL int bz_Load ( const char* commandLine ) { bz_registerEvent(bz_eGameStartEvent,&gameStartEndHandler); bz_registerEvent(bz_eGameEndEvent,&gameStartEndHandler); bz_debugMessage(4,"recordmatch plugin loaded"); filename = commandLine; return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_debugMessage(4,"recordmatch plugin unloaded"); bz_removeEvent(bz_eGameStartEvent,&gameStartEndHandler); bz_removeEvent(bz_eGameEndEvent,&gameStartEndHandler); return 0; } void GameStartEndHandler::process( bz_EventData *eventData ) { switch(eventData->eventType) { case bz_eGameStartEvent: { started = bz_startRecBuf(); bz_localTime time; bz_getLocaltime(&time); char temp[512]; sprintf(temp,"%d%d%d-%d%d%d.rec",time.month,time.day,time.year,time.hour,time.minute,time.second); filename = temp; } break; case bz_eGameEndEvent: { if (!started) break; std::string recFile = path + filename; bz_saveRecBuf(recFile.c_str(),0); started = false; } break; } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>stop the recording after we save it<commit_after>// recordmatch.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" class GameStartEndHandler : public bz_EventHandler { public: virtual void process ( bz_EventData *eventData ); }; GameStartEndHandler gameStartEndHandler; std::string path; bool started = false; std::string filename; BZ_GET_PLUGIN_VERSION BZF_PLUGIN_CALL int bz_Load ( const char* commandLine ) { bz_registerEvent(bz_eGameStartEvent,&gameStartEndHandler); bz_registerEvent(bz_eGameEndEvent,&gameStartEndHandler); bz_debugMessage(4,"recordmatch plugin loaded"); filename = commandLine; return 0; } BZF_PLUGIN_CALL int bz_Unload ( void ) { bz_debugMessage(4,"recordmatch plugin unloaded"); bz_removeEvent(bz_eGameStartEvent,&gameStartEndHandler); bz_removeEvent(bz_eGameEndEvent,&gameStartEndHandler); return 0; } void GameStartEndHandler::process( bz_EventData *eventData ) { switch(eventData->eventType) { case bz_eGameStartEvent: { started = bz_startRecBuf(); bz_localTime time; bz_getLocaltime(&time); char temp[512]; sprintf(temp,"%d%d%d-%d%d%d.rec",time.month,time.day,time.year,time.hour,time.minute,time.second); filename = temp; } break; case bz_eGameEndEvent: { if (!started) break; std::string recFile = path + filename; bz_saveRecBuf(recFile.c_str(),0); bz_stopRecBuf(); started = false; } break; } } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <csignal> #include <ctime> #include <functional> #include <iostream> #include <sstream> #include <string> #include <boost/asio.hpp> #include "spdlog/spdlog.h" #include "config_netfortune.hpp" #include "fserver.hpp" int main() { // TODO: Add multiple sinks to our logger // std::vector<spdlog::sink_ptr> sinks; //sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>()); //sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>("logfile", "txt", 23, 59)); // auto combined_logger = std::make_shared<spdlog::logger>("name", // begin(sinks), end(sinks)); ////register it if you need to access it globally // spdlog::register_logger(combined_logger); // asynchronous logging spdlog::set_async_mode(512, spdlog::async_overflow_policy::discard_log_msg); auto logger = spdlog::stdout_color_mt("multi_logger"); logger->set_level(spdlog::level::level_enum::debug); std::stringstream ss; ss << NETFORTUNE_VERSION_MAJOR << "." << NETFORTUNE_VERSION_MINOR; #ifdef netfortune_VERSION_PATCH ss << "." << NETFORTUNE_VERSION_PATCH; #endif logger->info("Netfortune Server Version " + ss.str()); boost::asio::io_service io_service; boost::asio::signal_set signal_set(io_service, SIGINT, SIGTERM); signal_set.async_wait([&io_service, &logger]( const boost::system::error_code &error, int signal_number) { std::unordered_map<int, std::string> signal_name = { {SIGINT, "SIGINT"}, {SIGTERM, "SIGTERM"}}; logger->debug("Got signal " + signal_name.at(signal_number) + "; stopping io_service."); io_service.stop(); }); FServer s(io_service, 13); io_service.run(); spdlog::drop_all(); // boost::asio::io_service io; // try { // boost::asio::io_service io_service; // tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13)); // for (;;) { // tcp::socket socket(io_service); //acceptor.accept(socket); // std::string message = make_daytime_string(); //message.erase(std::remove(message.begin(), message.end(), '\n'), //message.end()); // nlohmann::json j; // j["daytime"] = message; // boost::system::error_code ignored_error; //boost::asio::write(socket, boost::asio::buffer(j.dump(2)), // ignored_error); //} //} catch (std::exception& e) { //std::cerr << e.what() << std::endl; //} return 0; } <commit_msg>Fix indention<commit_after>#include <csignal> #include <ctime> #include <functional> #include <iostream> #include <sstream> #include <string> #include <boost/asio.hpp> #include "spdlog/spdlog.h" #include "config_netfortune.hpp" #include "fserver.hpp" int main() { // TODO: Add multiple sinks to our logger // std::vector<spdlog::sink_ptr> sinks; //sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>()); //sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>("logfile", "txt", 23, 59)); // auto combined_logger = std::make_shared<spdlog::logger>("name", // begin(sinks), end(sinks)); ////register it if you need to access it globally // spdlog::register_logger(combined_logger); // asynchronous logging spdlog::set_async_mode(512, spdlog::async_overflow_policy::discard_log_msg); auto logger = spdlog::stdout_color_mt("multi_logger"); logger->set_level(spdlog::level::level_enum::debug); std::stringstream ss; ss << NETFORTUNE_VERSION_MAJOR << "." << NETFORTUNE_VERSION_MINOR; #ifdef netfortune_VERSION_PATCH ss << "." << NETFORTUNE_VERSION_PATCH; #endif logger->info("Netfortune Server Version " + ss.str()); boost::asio::io_service io_service; boost::asio::signal_set signal_set(io_service, SIGINT, SIGTERM); signal_set.async_wait([&io_service, &logger]( const boost::system::error_code &error, int signal_number) { std::unordered_map<int, std::string> signal_name = { {SIGINT, "SIGINT"}, {SIGTERM, "SIGTERM"}}; logger->debug("Got signal " + signal_name.at(signal_number) + "; stopping io_service."); io_service.stop(); }); FServer s(io_service, 13); io_service.run(); spdlog::drop_all(); // boost::asio::io_service io; // try { // boost::asio::io_service io_service; // tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13)); // for (;;) { // tcp::socket socket(io_service); //acceptor.accept(socket); // std::string message = make_daytime_string(); //message.erase(std::remove(message.begin(), message.end(), '\n'), //message.end()); // nlohmann::json j; // j["daytime"] = message; // boost::system::error_code ignored_error; //boost::asio::write(socket, boost::asio::buffer(j.dump(2)), // ignored_error); //} //} catch (std::exception& e) { //std::cerr << e.what() << std::endl; //} return 0; } <|endoftext|>
<commit_before>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include <stdio.h> #include "rustllvm.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm-c/Transforms/PassManagerBuilder.h" using namespace llvm; using namespace llvm::legacy; extern cl::opt<bool> EnableARMEHABI; typedef struct LLVMOpaquePass *LLVMPassRef; typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef) DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef) DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder, LLVMPassManagerBuilderRef) extern "C" void LLVMInitializePasses() { PassRegistry &Registry = *PassRegistry::getPassRegistry(); initializeCore(Registry); initializeCodeGen(Registry); initializeScalarOpts(Registry); initializeVectorization(Registry); initializeIPO(Registry); initializeAnalysis(Registry); #if LLVM_VERSION_MINOR == 7 initializeIPA(Registry); #endif initializeTransformUtils(Registry); initializeInstCombine(Registry); initializeInstrumentation(Registry); initializeTarget(Registry); } enum class SupportedPassKind { Function, Module, Unsupported }; extern "C" Pass* LLVMRustFindAndCreatePass(const char *PassName) { StringRef SR(PassName); PassRegistry *PR = PassRegistry::getPassRegistry(); const PassInfo *PI = PR->getPassInfo(SR); if (PI) { return PI->createPass(); } return NULL; } extern "C" SupportedPassKind LLVMRustPassKind(Pass *pass) { assert(pass); PassKind passKind = pass->getPassKind(); if (passKind == PT_Module) { return SupportedPassKind::Module; } else if (passKind == PT_Function) { return SupportedPassKind::Function; } else { return SupportedPassKind::Unsupported; } } extern "C" void LLVMRustAddPass(LLVMPassManagerRef PM, Pass *pass) { assert(pass); PassManagerBase *pm = unwrap(PM); pm->add(pass); } #ifdef LLVM_COMPONENT_X86 #define SUBTARGET_X86 SUBTARGET(X86) #else #define SUBTARGET_X86 #endif #ifdef LLVM_COMPONENT_ARM #define SUBTARGET_ARM SUBTARGET(ARM) #else #define SUBTARGET_ARM #endif #ifdef LLVM_COMPONENT_AARCH64 #define SUBTARGET_AARCH64 SUBTARGET(AArch64) #else #define SUBTARGET_AARCH64 #endif #ifdef LLVM_COMPONENT_MIPS #define SUBTARGET_MIPS SUBTARGET(Mips) #else #define SUBTARGET_MIPS #endif #ifdef LLVM_COMPONENT_POWERPC #define SUBTARGET_PPC SUBTARGET(PPC) #else #define SUBTARGET_PPC #endif #define GEN_SUBTARGETS \ SUBTARGET_X86 \ SUBTARGET_ARM \ SUBTARGET_AARCH64 \ SUBTARGET_MIPS \ SUBTARGET_PPC #define SUBTARGET(x) namespace llvm { \ extern const SubtargetFeatureKV x##FeatureKV[]; \ extern const SubtargetFeatureKV x##SubTypeKV[]; \ } GEN_SUBTARGETS #undef SUBTARGET extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM, const char *feature) { TargetMachine *Target = unwrap(TM); const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo(); const FeatureBitset &Bits = MCInfo->getFeatureBits(); const llvm::SubtargetFeatureKV *FeatureEntry; #define SUBTARGET(x) \ if (MCInfo->isCPUStringValid(x##SubTypeKV[0].Key)) { \ FeatureEntry = x##FeatureKV; \ } else GEN_SUBTARGETS { return false; } #undef SUBTARGET while (strcmp(feature, FeatureEntry->Key) != 0) FeatureEntry++; return (Bits & FeatureEntry->Value) == FeatureEntry->Value; } extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(const char *triple, const char *cpu, const char *feature, CodeModel::Model CM, Reloc::Model RM, CodeGenOpt::Level OptLevel, bool UseSoftFloat, bool PositionIndependentExecutable, bool FunctionSections, bool DataSections) { std::string Error; Triple Trip(Triple::normalize(triple)); const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Trip.getTriple(), Error); if (TheTarget == NULL) { LLVMRustSetLastError(Error.c_str()); return NULL; } StringRef real_cpu = cpu; if (real_cpu == "native") { real_cpu = sys::getHostCPUName(); } TargetOptions Options; Options.PositionIndependentExecutable = PositionIndependentExecutable; Options.FloatABIType = FloatABI::Default; if (UseSoftFloat) { Options.FloatABIType = FloatABI::Soft; } Options.DataSections = DataSections; Options.FunctionSections = FunctionSections; TargetMachine *TM = TheTarget->createTargetMachine(Trip.getTriple(), real_cpu, feature, Options, RM, CM, OptLevel); return wrap(TM); } extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) { delete unwrap(TM); } // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis // passes for a target to a pass manager. We export that functionality through // this function. extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM, LLVMPassManagerRef PMR, LLVMModuleRef M) { PassManagerBase *PM = unwrap(PMR); PM->add(createTargetTransformInfoWrapperPass( unwrap(TM)->getTargetIRAnalysis())); } extern "C" void LLVMRustConfigurePassManagerBuilder(LLVMPassManagerBuilderRef PMB, CodeGenOpt::Level OptLevel, bool MergeFunctions, bool SLPVectorize, bool LoopVectorize) { // Ignore mergefunc for now as enabling it causes crashes. //unwrap(PMB)->MergeFunctions = MergeFunctions; unwrap(PMB)->SLPVectorize = SLPVectorize; unwrap(PMB)->OptLevel = OptLevel; unwrap(PMB)->LoopVectorize = LoopVectorize; } // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo` // field of a PassManagerBuilder, we expose our own method of doing so. extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMB, LLVMModuleRef M, bool DisableSimplifyLibCalls) { Triple TargetTriple(unwrap(M)->getTargetTriple()); TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple); if (DisableSimplifyLibCalls) TLI->disableAllFunctions(); unwrap(PMB)->LibraryInfo = TLI; } // Unfortunately, the LLVM C API doesn't provide a way to create the // TargetLibraryInfo pass, so we use this method to do so. extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMB, LLVMModuleRef M, bool DisableSimplifyLibCalls) { Triple TargetTriple(unwrap(M)->getTargetTriple()); TargetLibraryInfoImpl TLII(TargetTriple); if (DisableSimplifyLibCalls) TLII.disableAllFunctions(); unwrap(PMB)->add(new TargetLibraryInfoWrapperPass(TLII)); } // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over // all the functions in a module, so we do that manually here. You'll find // similar code in clang's BackendUtil.cpp file. extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) { llvm::legacy::FunctionPassManager *P = unwrap<llvm::legacy::FunctionPassManager>(PM); P->doInitialization(); for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E; ++I) if (!I->isDeclaration()) P->run(*I); P->doFinalization(); } extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) { // Initializing the command-line options more than once is not allowed. So, // check if they've already been initialized. (This could happen if we're // being called from rustpkg, for example). If the arguments change, then // that's just kinda unfortunate. static bool initialized = false; if (initialized) return; initialized = true; cl::ParseCommandLineOptions(Argc, Argv); } extern "C" bool LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR, LLVMModuleRef M, const char *path, TargetMachine::CodeGenFileType FileType) { llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR); std::string ErrorInfo; std::error_code EC; raw_fd_ostream OS(path, EC, sys::fs::F_None); if (EC) ErrorInfo = EC.message(); if (ErrorInfo != "") { LLVMRustSetLastError(ErrorInfo.c_str()); return false; } unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false); PM->run(*unwrap(M)); // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output // stream (OS), so the only real safe place to delete this is here? Don't we // wish this was written in Rust? delete PM; return true; } extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M, const char* path) { llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR); std::string ErrorInfo; std::error_code EC; raw_fd_ostream OS(path, EC, sys::fs::F_None); if (EC) ErrorInfo = EC.message(); formatted_raw_ostream FOS(OS); PM->add(createPrintModulePass(FOS)); PM->run(*unwrap(M)); } extern "C" void LLVMRustPrintPasses() { LLVMInitializePasses(); struct MyListener : PassRegistrationListener { void passEnumerate(const PassInfo *info) { if (info->getPassArgument() && *info->getPassArgument()) { printf("%15s - %s\n", info->getPassArgument(), info->getPassName()); } } } listener; PassRegistry *PR = PassRegistry::getPassRegistry(); PR->enumerateWith(&listener); } extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMB, bool AddLifetimes) { unwrap(PMB)->Inliner = createAlwaysInlinerPass(AddLifetimes); } extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **symbols, size_t len) { PassManager passes; ArrayRef<const char*> ref(symbols, len); passes.add(llvm::createInternalizePass(ref)); passes.run(*unwrap(M)); } extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) { for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E; ++GV) { GV->setDoesNotThrow(); Function *F = dyn_cast<Function>(GV); if (F == NULL) continue; for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) { for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) { if (isa<InvokeInst>(I)) { InvokeInst *CI = cast<InvokeInst>(I); CI->setDoesNotThrow(); } } } } } extern "C" void LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module, LLVMTargetMachineRef TMR) { TargetMachine *Target = unwrap(TMR); unwrap(Module)->setDataLayout(Target->createDataLayout()); } extern "C" LLVMTargetDataRef LLVMRustGetModuleDataLayout(LLVMModuleRef M) { return wrap(&unwrap(M)->getDataLayout()); } <commit_msg>[LLVM-3.9] Preserve certain functions when internalizing<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #include <stdio.h> #include "rustllvm.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetSubtargetInfo.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm-c/Transforms/PassManagerBuilder.h" using namespace llvm; using namespace llvm::legacy; extern cl::opt<bool> EnableARMEHABI; typedef struct LLVMOpaquePass *LLVMPassRef; typedef struct LLVMOpaqueTargetMachine *LLVMTargetMachineRef; DEFINE_STDCXX_CONVERSION_FUNCTIONS(Pass, LLVMPassRef) DEFINE_STDCXX_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef) DEFINE_STDCXX_CONVERSION_FUNCTIONS(PassManagerBuilder, LLVMPassManagerBuilderRef) extern "C" void LLVMInitializePasses() { PassRegistry &Registry = *PassRegistry::getPassRegistry(); initializeCore(Registry); initializeCodeGen(Registry); initializeScalarOpts(Registry); initializeVectorization(Registry); initializeIPO(Registry); initializeAnalysis(Registry); #if LLVM_VERSION_MINOR == 7 initializeIPA(Registry); #endif initializeTransformUtils(Registry); initializeInstCombine(Registry); initializeInstrumentation(Registry); initializeTarget(Registry); } enum class SupportedPassKind { Function, Module, Unsupported }; extern "C" Pass* LLVMRustFindAndCreatePass(const char *PassName) { StringRef SR(PassName); PassRegistry *PR = PassRegistry::getPassRegistry(); const PassInfo *PI = PR->getPassInfo(SR); if (PI) { return PI->createPass(); } return NULL; } extern "C" SupportedPassKind LLVMRustPassKind(Pass *pass) { assert(pass); PassKind passKind = pass->getPassKind(); if (passKind == PT_Module) { return SupportedPassKind::Module; } else if (passKind == PT_Function) { return SupportedPassKind::Function; } else { return SupportedPassKind::Unsupported; } } extern "C" void LLVMRustAddPass(LLVMPassManagerRef PM, Pass *pass) { assert(pass); PassManagerBase *pm = unwrap(PM); pm->add(pass); } #ifdef LLVM_COMPONENT_X86 #define SUBTARGET_X86 SUBTARGET(X86) #else #define SUBTARGET_X86 #endif #ifdef LLVM_COMPONENT_ARM #define SUBTARGET_ARM SUBTARGET(ARM) #else #define SUBTARGET_ARM #endif #ifdef LLVM_COMPONENT_AARCH64 #define SUBTARGET_AARCH64 SUBTARGET(AArch64) #else #define SUBTARGET_AARCH64 #endif #ifdef LLVM_COMPONENT_MIPS #define SUBTARGET_MIPS SUBTARGET(Mips) #else #define SUBTARGET_MIPS #endif #ifdef LLVM_COMPONENT_POWERPC #define SUBTARGET_PPC SUBTARGET(PPC) #else #define SUBTARGET_PPC #endif #define GEN_SUBTARGETS \ SUBTARGET_X86 \ SUBTARGET_ARM \ SUBTARGET_AARCH64 \ SUBTARGET_MIPS \ SUBTARGET_PPC #define SUBTARGET(x) namespace llvm { \ extern const SubtargetFeatureKV x##FeatureKV[]; \ extern const SubtargetFeatureKV x##SubTypeKV[]; \ } GEN_SUBTARGETS #undef SUBTARGET extern "C" bool LLVMRustHasFeature(LLVMTargetMachineRef TM, const char *feature) { TargetMachine *Target = unwrap(TM); const MCSubtargetInfo *MCInfo = Target->getMCSubtargetInfo(); const FeatureBitset &Bits = MCInfo->getFeatureBits(); const llvm::SubtargetFeatureKV *FeatureEntry; #define SUBTARGET(x) \ if (MCInfo->isCPUStringValid(x##SubTypeKV[0].Key)) { \ FeatureEntry = x##FeatureKV; \ } else GEN_SUBTARGETS { return false; } #undef SUBTARGET while (strcmp(feature, FeatureEntry->Key) != 0) FeatureEntry++; return (Bits & FeatureEntry->Value) == FeatureEntry->Value; } extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine(const char *triple, const char *cpu, const char *feature, CodeModel::Model CM, Reloc::Model RM, CodeGenOpt::Level OptLevel, bool UseSoftFloat, bool PositionIndependentExecutable, bool FunctionSections, bool DataSections) { std::string Error; Triple Trip(Triple::normalize(triple)); const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Trip.getTriple(), Error); if (TheTarget == NULL) { LLVMRustSetLastError(Error.c_str()); return NULL; } StringRef real_cpu = cpu; if (real_cpu == "native") { real_cpu = sys::getHostCPUName(); } TargetOptions Options; Options.PositionIndependentExecutable = PositionIndependentExecutable; Options.FloatABIType = FloatABI::Default; if (UseSoftFloat) { Options.FloatABIType = FloatABI::Soft; } Options.DataSections = DataSections; Options.FunctionSections = FunctionSections; TargetMachine *TM = TheTarget->createTargetMachine(Trip.getTriple(), real_cpu, feature, Options, RM, CM, OptLevel); return wrap(TM); } extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) { delete unwrap(TM); } // Unfortunately, LLVM doesn't expose a C API to add the corresponding analysis // passes for a target to a pass manager. We export that functionality through // this function. extern "C" void LLVMRustAddAnalysisPasses(LLVMTargetMachineRef TM, LLVMPassManagerRef PMR, LLVMModuleRef M) { PassManagerBase *PM = unwrap(PMR); PM->add(createTargetTransformInfoWrapperPass( unwrap(TM)->getTargetIRAnalysis())); } extern "C" void LLVMRustConfigurePassManagerBuilder(LLVMPassManagerBuilderRef PMB, CodeGenOpt::Level OptLevel, bool MergeFunctions, bool SLPVectorize, bool LoopVectorize) { // Ignore mergefunc for now as enabling it causes crashes. //unwrap(PMB)->MergeFunctions = MergeFunctions; unwrap(PMB)->SLPVectorize = SLPVectorize; unwrap(PMB)->OptLevel = OptLevel; unwrap(PMB)->LoopVectorize = LoopVectorize; } // Unfortunately, the LLVM C API doesn't provide a way to set the `LibraryInfo` // field of a PassManagerBuilder, we expose our own method of doing so. extern "C" void LLVMRustAddBuilderLibraryInfo(LLVMPassManagerBuilderRef PMB, LLVMModuleRef M, bool DisableSimplifyLibCalls) { Triple TargetTriple(unwrap(M)->getTargetTriple()); TargetLibraryInfoImpl *TLI = new TargetLibraryInfoImpl(TargetTriple); if (DisableSimplifyLibCalls) TLI->disableAllFunctions(); unwrap(PMB)->LibraryInfo = TLI; } // Unfortunately, the LLVM C API doesn't provide a way to create the // TargetLibraryInfo pass, so we use this method to do so. extern "C" void LLVMRustAddLibraryInfo(LLVMPassManagerRef PMB, LLVMModuleRef M, bool DisableSimplifyLibCalls) { Triple TargetTriple(unwrap(M)->getTargetTriple()); TargetLibraryInfoImpl TLII(TargetTriple); if (DisableSimplifyLibCalls) TLII.disableAllFunctions(); unwrap(PMB)->add(new TargetLibraryInfoWrapperPass(TLII)); } // Unfortunately, the LLVM C API doesn't provide an easy way of iterating over // all the functions in a module, so we do that manually here. You'll find // similar code in clang's BackendUtil.cpp file. extern "C" void LLVMRustRunFunctionPassManager(LLVMPassManagerRef PM, LLVMModuleRef M) { llvm::legacy::FunctionPassManager *P = unwrap<llvm::legacy::FunctionPassManager>(PM); P->doInitialization(); for (Module::iterator I = unwrap(M)->begin(), E = unwrap(M)->end(); I != E; ++I) if (!I->isDeclaration()) P->run(*I); P->doFinalization(); } extern "C" void LLVMRustSetLLVMOptions(int Argc, char **Argv) { // Initializing the command-line options more than once is not allowed. So, // check if they've already been initialized. (This could happen if we're // being called from rustpkg, for example). If the arguments change, then // that's just kinda unfortunate. static bool initialized = false; if (initialized) return; initialized = true; cl::ParseCommandLineOptions(Argc, Argv); } extern "C" bool LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMPassManagerRef PMR, LLVMModuleRef M, const char *path, TargetMachine::CodeGenFileType FileType) { llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR); std::string ErrorInfo; std::error_code EC; raw_fd_ostream OS(path, EC, sys::fs::F_None); if (EC) ErrorInfo = EC.message(); if (ErrorInfo != "") { LLVMRustSetLastError(ErrorInfo.c_str()); return false; } unwrap(Target)->addPassesToEmitFile(*PM, OS, FileType, false); PM->run(*unwrap(M)); // Apparently `addPassesToEmitFile` adds a pointer to our on-the-stack output // stream (OS), so the only real safe place to delete this is here? Don't we // wish this was written in Rust? delete PM; return true; } extern "C" void LLVMRustPrintModule(LLVMPassManagerRef PMR, LLVMModuleRef M, const char* path) { llvm::legacy::PassManager *PM = unwrap<llvm::legacy::PassManager>(PMR); std::string ErrorInfo; std::error_code EC; raw_fd_ostream OS(path, EC, sys::fs::F_None); if (EC) ErrorInfo = EC.message(); formatted_raw_ostream FOS(OS); PM->add(createPrintModulePass(FOS)); PM->run(*unwrap(M)); } extern "C" void LLVMRustPrintPasses() { LLVMInitializePasses(); struct MyListener : PassRegistrationListener { void passEnumerate(const PassInfo *info) { if (info->getPassArgument() && *info->getPassArgument()) { printf("%15s - %s\n", info->getPassArgument(), info->getPassName()); } } } listener; PassRegistry *PR = PassRegistry::getPassRegistry(); PR->enumerateWith(&listener); } extern "C" void LLVMRustAddAlwaysInlinePass(LLVMPassManagerBuilderRef PMB, bool AddLifetimes) { unwrap(PMB)->Inliner = createAlwaysInlinerPass(AddLifetimes); } extern "C" void LLVMRustRunRestrictionPass(LLVMModuleRef M, char **symbols, size_t len) { llvm::legacy::PassManager passes; #if LLVM_VERSION_MINOR <= 8 ArrayRef<const char*> ref(symbols, len); passes.add(llvm::createInternalizePass(ref)); #else auto PreserveFunctions = [=](const GlobalValue &GV) { for (size_t i=0; i<len; i++) { if (GV.getName() == symbols[i]) { return true; } } return false; }; passes.add(llvm::createInternalizePass(PreserveFunctions)); #endif passes.run(*unwrap(M)); } extern "C" void LLVMRustMarkAllFunctionsNounwind(LLVMModuleRef M) { for (Module::iterator GV = unwrap(M)->begin(), E = unwrap(M)->end(); GV != E; ++GV) { GV->setDoesNotThrow(); Function *F = dyn_cast<Function>(GV); if (F == NULL) continue; for (Function::iterator B = F->begin(), BE = F->end(); B != BE; ++B) { for (BasicBlock::iterator I = B->begin(), IE = B->end(); I != IE; ++I) { if (isa<InvokeInst>(I)) { InvokeInst *CI = cast<InvokeInst>(I); CI->setDoesNotThrow(); } } } } } extern "C" void LLVMRustSetDataLayoutFromTargetMachine(LLVMModuleRef Module, LLVMTargetMachineRef TMR) { TargetMachine *Target = unwrap(TMR); unwrap(Module)->setDataLayout(Target->createDataLayout()); } extern "C" LLVMTargetDataRef LLVMRustGetModuleDataLayout(LLVMModuleRef M) { return wrap(&unwrap(M)->getDataLayout()); } <|endoftext|>
<commit_before>#include <QObject> #include <QGraphicsSceneMouseEvent> #include <QtGlobal> #include <dcpmainpage.h> #include "dcpcategorycomponent.h" #include "dcpsinglecomponent.h" #include <QSignalSpy> #include <MContainer> #include "ut_dcpmainpage.h" #include <MLayout> #include <QGraphicsLinearLayout> void Ut_DcpMainPage::init() { m_subject = new DcpMainPage(); } void Ut_DcpMainPage::cleanup() { delete m_subject; m_subject = 0; } void Ut_DcpMainPage::initTestCase() { } void Ut_DcpMainPage::testCreation() { QVERIFY(m_subject); QSignalSpy spy(m_subject, SIGNAL(appeared())); m_subject->createContent(); m_subject->appear(); QVERIFY(spy.count() == 1); } void Ut_DcpMainPage::testCreateContent() { m_subject->createContent(); QVERIFY(m_subject->m_OtherComp); QCOMPARE((void*)(m_subject->m_OtherComp), (void*)((QGraphicsWidget*)(m_subject->mainLayout()->itemAt(0)))); QGraphicsWidget *otherCategories = m_subject->m_OtherComp->centralWidget(); QVERIFY(otherCategories); } void Ut_DcpMainPage::testCreateContentLate() { m_subject->createContentsLate(); QVERIFY(m_subject->isContentCreated()); QVERIFY(m_subject->mainLayout()); QVERIFY(m_subject->m_RecentlyComp); } /* void Ut_DcpMainPage::testReload() { QSKIP("incomplete", SkipSingle); // remove this when you've finished } */ void Ut_DcpMainPage::testShown() { // case 1: No contents yet QSignalSpy spy(m_subject, SIGNAL(firstShown())); // QSignalSpy spyReloaded((QObject*)(m_subject->m_RecentlyComp), SIGNAL(reloaded())); m_subject->shown(); QVERIFY(m_subject->m_HasContent); QCOMPARE(spy.count(), 1); // case 2: there is content yet m_subject->m_WasHidden = true; m_subject->shown(); QVERIFY(m_subject->m_WasHidden == false); QCOMPARE(spy.count(), 1); // not incrementing // QCOMPARE(spyReloaded.count(), 1); // case 3: there is content and visible m_subject->m_WasHidden = false; m_subject->shown(); QVERIFY(m_subject->m_WasHidden == false); QCOMPARE(spy.count(), 1); // not incrementing // QCOMPARE(spyReloaded.count(), 1);// not incrementing } /* void Ut_DcpMainPage::testBack() { m_subject->back(); QSKIP("incomplete", SkipSingle); // remove this when you've finished } */ void Ut_DcpMainPage::testRetranslateUi() { // first we need to create all the contents m_subject->createContent(); m_subject->createContentsLate(); m_subject->retranslateUi(); QCOMPARE(m_subject->title(), qtTrId(QT_TRID_NOOP("qtn_sett_main_title"))); QCOMPARE(m_subject->m_RecentlyComp->title(), qtTrId(QT_TRID_NOOP("qtn_sett_main_most"))); // QCOMPARE(m_subject->m_OtherComp->title(), // qtTrId(QT_TRID_NOOP("qtn_sett_main_other"))); for (int i=0; i<m_subject->m_CategoryButtons.count(); i++) { DcpSingleComponent* comp = m_subject->m_CategoryButtons.at(i); QCOMPARE(comp->title(), qtTrId(QT_TRID_NOOP("qtn-fake"))); } } void Ut_DcpMainPage::testHideEvent() { m_subject->m_WasHidden = false; m_subject->hideEvent(0); QVERIFY(m_subject->m_WasHidden); } void Ut_DcpMainPage::cleanupTestCase() { } QTEST_APPLESS_MAIN(Ut_DcpMainPage) <commit_msg>fixing ut_dcpmainpage test<commit_after>#include <QObject> #include <QGraphicsSceneMouseEvent> #include <QtGlobal> #include <dcpmainpage.h> #include "dcpcategorycomponent.h" #include "dcpsinglecomponent.h" #include <QSignalSpy> #include <MContainer> #include "ut_dcpmainpage.h" #include <MLayout> #include <QGraphicsLinearLayout> void Ut_DcpMainPage::init() { m_subject = new DcpMainPage(); } void Ut_DcpMainPage::cleanup() { delete m_subject; m_subject = 0; } void Ut_DcpMainPage::initTestCase() { } void Ut_DcpMainPage::testCreation() { QVERIFY(m_subject); QSignalSpy spy(m_subject, SIGNAL(appeared())); m_subject->createContent(); m_subject->appear(); QVERIFY(spy.count() == 1); } void Ut_DcpMainPage::testCreateContent() { m_subject->createContent(); QVERIFY(m_subject->m_OtherComp); QCOMPARE((void*)(m_subject->m_OtherComp), (void*)((QGraphicsWidget*)(m_subject->mainLayout()->itemAt(0)))); QGraphicsWidget *otherCategories = m_subject->m_OtherComp->centralWidget(); QVERIFY(otherCategories); } void Ut_DcpMainPage::testCreateContentLate() { m_subject->createContentsLate(); QVERIFY(m_subject->isContentCreated()); QVERIFY(m_subject->mainLayout()); QVERIFY(m_subject->m_RecentlyComp); } /* void Ut_DcpMainPage::testReload() { QSKIP("incomplete", SkipSingle); // remove this when you've finished } */ void Ut_DcpMainPage::testShown() { // case 1: No contents yet QSignalSpy spy(m_subject, SIGNAL(firstShown())); // QSignalSpy spyReloaded((QObject*)(m_subject->m_RecentlyComp), SIGNAL(reloaded())); m_subject->shown(); QVERIFY(m_subject->m_HasContent); QCOMPARE(spy.count(), 1); // case 2: there is content yet m_subject->m_WasHidden = true; m_subject->shown(); QVERIFY(m_subject->m_WasHidden == false); QCOMPARE(spy.count(), 1); // not incrementing // QCOMPARE(spyReloaded.count(), 1); // case 3: there is content and visible m_subject->m_WasHidden = false; m_subject->shown(); QVERIFY(m_subject->m_WasHidden == false); QCOMPARE(spy.count(), 1); // not incrementing // QCOMPARE(spyReloaded.count(), 1);// not incrementing } /* void Ut_DcpMainPage::testBack() { m_subject->back(); QSKIP("incomplete", SkipSingle); // remove this when you've finished } */ void Ut_DcpMainPage::testRetranslateUi() { // first we need to create all the contents m_subject->createContent(); m_subject->createContentsLate(); m_subject->retranslateUi(); QCOMPARE(m_subject->title(), qtTrId(QT_TRID_NOOP("qtn_sett_main_title"))); QCOMPARE(m_subject->m_RecentlyComp->title(), qtTrId(QT_TRID_NOOP("qtn_sett_main_most"))); // QCOMPARE(m_subject->m_OtherComp->title(), // qtTrId(QT_TRID_NOOP("qtn_sett_main_other"))); for (int i=0; i<m_subject->m_CategoryButtons.count(); i++) { DcpSingleComponent* comp = m_subject->m_CategoryButtons.at(i); QCOMPARE(comp->title(), qtTrId(QT_TRID_NOOP(i % 2 ? "qtn-fake-2" : "qtn-fake"))); } } void Ut_DcpMainPage::testHideEvent() { m_subject->m_WasHidden = false; m_subject->hideEvent(0); QVERIFY(m_subject->m_WasHidden); } void Ut_DcpMainPage::cleanupTestCase() { } QTEST_APPLESS_MAIN(Ut_DcpMainPage) <|endoftext|>
<commit_before>/// /// @file PhiTiny.cpp /// @brief phi(x, a) counts the numbers <= x that are not /// divisible by any of the first a primes. /// PhiTiny computes phi(x, a) in constant time /// for a <= 6 using lookup tables. /// /// phi(x, a) = (x / pp) * φ(a) + phi(x % pp, a) /// pp = 2 * 3 * ... * prime[a] /// φ(a) = \prod_{i=1}^{a} (prime[i] - 1) /// /// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiTiny.hpp> #include <stdint.h> #include <array> #include <vector> namespace primecount { const std::array<int, 7> PhiTiny::primes = { 0, 2, 3, 5, 7, 11, 13 }; // prime_products[n] = \prod_{i=1}^{n} primes[i] const std::array<int, 7> PhiTiny::prime_products = { 1, 2, 6, 30, 210, 2310, 30030 }; // totients[n] = \prod_{i=1}^{n} (primes[i] - 1) const std::array<int, 7> PhiTiny::totients = { 1, 1, 2, 8, 48, 480, 5760 }; // Number of primes below x const std::array<int, 13> PhiTiny::pi = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5 }; // Singleton const PhiTiny phiTiny; PhiTiny::PhiTiny() { phi_[0].resize(1); phi_[0][0] = 0; // initialize phi(x % pp, a) lookup tables for (int a = 1; a <= max_a(); a++) { int pp = prime_products[a]; phi_[a].resize(pp); for (int x = 0; x < pp; x++) { auto phi_xa = phi(x, a - 1) - phi(x / primes[a], a - 1); phi_[a][x] = (int16_t) phi_xa; } } } } // namespace <commit_msg>Refactor<commit_after>/// /// @file PhiTiny.cpp /// @brief phi(x, a) counts the numbers <= x that are not divisible /// by any of the first a primes. PhiTiny computes phi(x, a) /// in constant time for a <= 6 using lookup tables. /// /// phi(x, a) = (x / pp) * φ(a) + phi(x % pp, a) /// pp = 2 * 3 * ... * prime[a] /// φ(a) = \prod_{i=1}^{a} (prime[i] - 1) /// /// Copyright (C) 2020 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <PhiTiny.hpp> #include <stdint.h> #include <array> #include <vector> namespace primecount { const std::array<int, 7> PhiTiny::primes = { 0, 2, 3, 5, 7, 11, 13 }; // prime_products[n] = \prod_{i=1}^{n} primes[i] const std::array<int, 7> PhiTiny::prime_products = { 1, 2, 6, 30, 210, 2310, 30030 }; // totients[n] = \prod_{i=1}^{n} (primes[i] - 1) const std::array<int, 7> PhiTiny::totients = { 1, 1, 2, 8, 48, 480, 5760 }; // Number of primes below x const std::array<int, 13> PhiTiny::pi = { 0, 0, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5 }; // Singleton const PhiTiny phiTiny; PhiTiny::PhiTiny() { // initialize phi(x % pp, a) lookup tables for (int a = 0; a <= max_a(); a++) { int pp = prime_products[a]; phi_[a].resize(pp); phi_[a][0] = 0; for (int x = 1; x < pp; x++) { auto phi_xa = phi(x, a - 1) - phi(x / primes[a], a - 1); phi_[a][x] = (int16_t) phi_xa; } } } } // namespace <|endoftext|>
<commit_before>/* ofxTableGestures (formerly OF-TangibleFramework) Developed for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2011 Daniel Gallardo Grassot <daniel.gallardo@upf.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Polygon.h" #include "CollisionHelper.h" #include "ofMain.h" #include "Triangulate.h" using namespace std; namespace Figures { Polygon::Polygon() { last_texture_state = false; mesh.setMode(OF_PRIMITIVE_TRIANGLES); linemesh.setMode(OF_PRIMITIVE_LINE_STRIP); } Polygon::Polygon(vector_points):processed(false),it_is_empty(true) { centre = ofPoint(-1.0,-1.0); } void Polygon::AddVertex(ofPoint vertex) { raw_vertexs.push_back(vertex); linemesh.addVertex(vertex); bbox.AddPoint(vertex.x,vertex.y); if(it_is_empty) { centre = ofPoint(vertex); } else { centre += vertex; centre = centre / 2; } processed = false; } void Polygon::RebuildGeometry() { if(raw_vertexs.size() >= 3) { updatedVertexs.clear(); textureVertexs.clear(); Triangulate::Process(raw_vertexs,updatedVertexs); float rx = bbox.GetXmax() - bbox.GetXmin(); float ry = bbox.GetYmax() - bbox.GetYmin(); for(unsigned int i = 0; i < updatedVertexs.size(); i++) { textureVertexs.push_back(ofPoint( 1 - ((updatedVertexs[i].x - bbox.GetXmin())/rx), 1 - ((updatedVertexs[i].y - bbox.GetYmin())/ry) )); } } mesh.clear(); int tcount = updatedVertexs.size()/3; for (int i=0; i<tcount; i++) { mesh.addVertex(ofVec3f(updatedVertexs[i*3+0].x,updatedVertexs[i*3+0].y)); mesh.addVertex(ofVec3f(updatedVertexs[i*3+1].x,updatedVertexs[i*3+1].y)); mesh.addVertex(ofVec3f(updatedVertexs[i*3+2].x,updatedVertexs[i*3+2].y)); if(has_texture) { mesh.addTexCoord(ofVec2f(textureVertexs[i*3+0].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+0].y * texture.getTextureReference().texData.tex_u)); mesh.addTexCoord(ofVec2f(textureVertexs[i*3+1].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+1].y * texture.getTextureReference().texData.tex_u)); mesh.addTexCoord(ofVec2f(textureVertexs[i*3+2].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+2].y * texture.getTextureReference().texData.tex_u)); } } } int Polygon::GetTriangleNumber() { if (!processed) RebuildGeometry(); return updatedVertexs.size()/3; } void Polygon::Design() { if (!processed || (has_texture && !last_texture_state)) RebuildGeometry(); last_texture_state = has_texture; int tcount = updatedVertexs.size()/3; if(has_texture) { mesh.enableTextures(); texture.getTextureReference().bind(); mesh.draw(); texture.getTextureReference().unbind(); } else { mesh.disableTextures(); mesh.draw(); } } void Polygon::DesignStroke() { linemesh.draw(); } bool Polygon::CheckCollision(ofPoint const & point) { if (!processed) RebuildGeometry(); int tcount = updatedVertexs.size()/3; for (int i=0; i<tcount; i++) { if(CollisionHelper::CollideTriangle(updatedVertexs[i*3+0],updatedVertexs[i*3+1],updatedVertexs[i*3+2],point.x, point.y)) return true; } return false; } void Polygon::GetCentre(float & x, float & y) { x = centre.x; y = centre.y; } } <commit_msg>stroke lines were not closing<commit_after>/* ofxTableGestures (formerly OF-TangibleFramework) Developed for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2011 Daniel Gallardo Grassot <daniel.gallardo@upf.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Polygon.h" #include "CollisionHelper.h" #include "ofMain.h" #include "Triangulate.h" using namespace std; namespace Figures { Polygon::Polygon() { last_texture_state = false; mesh.setMode(OF_PRIMITIVE_TRIANGLES); linemesh.setMode(OF_PRIMITIVE_LINE_LOOP); } Polygon::Polygon(vector_points):processed(false),it_is_empty(true) { centre = ofPoint(-1.0,-1.0); } void Polygon::AddVertex(ofPoint vertex) { raw_vertexs.push_back(vertex); linemesh.addVertex(vertex); bbox.AddPoint(vertex.x,vertex.y); if(it_is_empty) { centre = ofPoint(vertex); } else { centre += vertex; centre = centre / 2; } processed = false; } void Polygon::RebuildGeometry() { if(raw_vertexs.size() >= 3) { updatedVertexs.clear(); textureVertexs.clear(); Triangulate::Process(raw_vertexs,updatedVertexs); float rx = bbox.GetXmax() - bbox.GetXmin(); float ry = bbox.GetYmax() - bbox.GetYmin(); for(unsigned int i = 0; i < updatedVertexs.size(); i++) { textureVertexs.push_back(ofPoint( 1 - ((updatedVertexs[i].x - bbox.GetXmin())/rx), 1 - ((updatedVertexs[i].y - bbox.GetYmin())/ry) )); } } mesh.clear(); int tcount = updatedVertexs.size()/3; for (int i=0; i<tcount; i++) { mesh.addVertex(ofVec3f(updatedVertexs[i*3+0].x,updatedVertexs[i*3+0].y)); mesh.addVertex(ofVec3f(updatedVertexs[i*3+1].x,updatedVertexs[i*3+1].y)); mesh.addVertex(ofVec3f(updatedVertexs[i*3+2].x,updatedVertexs[i*3+2].y)); if(has_texture) { mesh.addTexCoord(ofVec2f(textureVertexs[i*3+0].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+0].y * texture.getTextureReference().texData.tex_u)); mesh.addTexCoord(ofVec2f(textureVertexs[i*3+1].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+1].y * texture.getTextureReference().texData.tex_u)); mesh.addTexCoord(ofVec2f(textureVertexs[i*3+2].x * texture.getTextureReference().texData.tex_t, textureVertexs[i*3+2].y * texture.getTextureReference().texData.tex_u)); } } } int Polygon::GetTriangleNumber() { if (!processed) RebuildGeometry(); return updatedVertexs.size()/3; } void Polygon::Design() { if (!processed || (has_texture && !last_texture_state)) RebuildGeometry(); last_texture_state = has_texture; int tcount = updatedVertexs.size()/3; if(has_texture) { mesh.enableTextures(); texture.getTextureReference().bind(); mesh.draw(); texture.getTextureReference().unbind(); } else { mesh.disableTextures(); mesh.draw(); } } void Polygon::DesignStroke() { linemesh.draw(); } bool Polygon::CheckCollision(ofPoint const & point) { if (!processed) RebuildGeometry(); int tcount = updatedVertexs.size()/3; for (int i=0; i<tcount; i++) { if(CollisionHelper::CollideTriangle(updatedVertexs[i*3+0],updatedVertexs[i*3+1],updatedVertexs[i*3+2],point.x, point.y)) return true; } return false; } void Polygon::GetCentre(float & x, float & y) { x = centre.x; y = centre.y; } } <|endoftext|>
<commit_before>#if !defined(OMR_OBJECTMAP_INL_HPP_) #define OMR_OBJECTMAP_INL_HPP_ #include <OMR/Om/Allocator.hpp> #include <OMR/Om/Context.hpp> #include <OMR/Om/ObjectMap.hpp> #include <OMR/Om/TransitionSet.inl.hpp> namespace OMR { namespace Om { inline ObjectMap::ObjectMap( MetaMap* meta, ObjectMap* parent, const Infra::Span<const SlotDescriptor>& descriptors) : baseMap_(meta, Map::Kind::OBJECT_MAP), parent_(parent), transitions_(), // TODO: Find a clearer way to construct a map without a parent. slotOffset_(parent ? (parent->slotOffset() + parent->slotWidth()) : 0), slotWidth_(0), slotCount_(descriptors.length()) { for (std::size_t i = 0; i < slotCount_; i++) { descriptors_[i] = descriptors[i]; slotWidth_ += descriptors[i].type().width(); } } inline Cell* ObjectMapInitializer::operator()(Context& cx, Cell* cell) noexcept { auto meta = cx.globals().metaMap(); new (cell) ObjectMap(meta, parent, descriptors); return cell; } inline ObjectMap* ObjectMap::allocate( Context& cx, Handle<ObjectMap> parent, Infra::Span<const SlotDescriptor> descriptors) { ObjectMapInitializer init; init.parent = parent; init.descriptors = descriptors; std::size_t size = calculateAllocSize(descriptors.length()); ObjectMap* result = BaseAllocator::allocate<ObjectMap>(cx, init, size); RootRef<ObjectMap> root(cx, result); bool ok = construct(cx, root); if (!ok) { return result = nullptr; } else { result = root.get(); } return result; } inline ObjectMap* ObjectMap::allocate(Context& cx) { // TODO: Don't construct a bogus handle here, find a clearer way to do this. ObjectMap* parent = nullptr; return allocate(cx, Handle<ObjectMap>(parent), Infra::Span<const SlotDescriptor>(nullptr, 0)); } inline bool ObjectMap::construct(Context& cx, Handle<ObjectMap> self) { return TransitionSet::construct(cx, {self, &ObjectMap::transitions_}); } inline ObjectMap* ObjectMap::lookUpTransition( Context& cx, const Infra::Span<const SlotDescriptor>& descriptors, std::size_t hash) { return transitions_.lookup(descriptors, hash); } inline ObjectMap* ObjectMap::derive( Context& cx, Handle<ObjectMap> base, const Infra::Span<const SlotDescriptor>& descriptors, std::size_t hash) { ObjectMap* derivation = ObjectMap::allocate(cx, base, descriptors); base->transitions_.tryStore(derivation, hash); // TODO: Write barrier? the object map return derivation; } template <typename VisitorT> inline void ObjectMap::visit(Context& cx, VisitorT& visitor) { baseMap().visit(cx, visitor); visitor.edge(cx, (Cell*)this, (Cell*)parent()); transitions_.visit(cx, visitor); } } // namespace Om } // namespace OMR #endif // OMR_OBJECTMAP_INL_HPP_<commit_msg>Include missing header file<commit_after>#if !defined(OMR_OBJECTMAP_INL_HPP_) #define OMR_OBJECTMAP_INL_HPP_ #include <OMR/Om/Allocator.hpp> #include <OMR/Om/Context.hpp> #include <OMR/Om/Map.inl.hpp> #include <OMR/Om/ObjectMap.hpp> #include <OMR/Om/TransitionSet.inl.hpp> namespace OMR { namespace Om { inline ObjectMap::ObjectMap( MetaMap* meta, ObjectMap* parent, const Infra::Span<const SlotDescriptor>& descriptors) : baseMap_(meta, Map::Kind::OBJECT_MAP), parent_(parent), transitions_(), // TODO: Find a clearer way to construct a map without a parent. slotOffset_(parent ? (parent->slotOffset() + parent->slotWidth()) : 0), slotWidth_(0), slotCount_(descriptors.length()) { for (std::size_t i = 0; i < slotCount_; i++) { descriptors_[i] = descriptors[i]; slotWidth_ += descriptors[i].type().width(); } } inline Cell* ObjectMapInitializer::operator()(Context& cx, Cell* cell) noexcept { auto meta = cx.globals().metaMap(); new (cell) ObjectMap(meta, parent, descriptors); return cell; } inline ObjectMap* ObjectMap::allocate( Context& cx, Handle<ObjectMap> parent, Infra::Span<const SlotDescriptor> descriptors) { ObjectMapInitializer init; init.parent = parent; init.descriptors = descriptors; std::size_t size = calculateAllocSize(descriptors.length()); ObjectMap* result = BaseAllocator::allocate<ObjectMap>(cx, init, size); RootRef<ObjectMap> root(cx, result); bool ok = construct(cx, root); if (!ok) { return result = nullptr; } else { result = root.get(); } return result; } inline ObjectMap* ObjectMap::allocate(Context& cx) { // TODO: Don't construct a bogus handle here, find a clearer way to do this. ObjectMap* parent = nullptr; return allocate(cx, Handle<ObjectMap>(parent), Infra::Span<const SlotDescriptor>(nullptr, 0)); } inline bool ObjectMap::construct(Context& cx, Handle<ObjectMap> self) { return TransitionSet::construct(cx, {self, &ObjectMap::transitions_}); } inline ObjectMap* ObjectMap::lookUpTransition( Context& cx, const Infra::Span<const SlotDescriptor>& descriptors, std::size_t hash) { return transitions_.lookup(descriptors, hash); } inline ObjectMap* ObjectMap::derive( Context& cx, Handle<ObjectMap> base, const Infra::Span<const SlotDescriptor>& descriptors, std::size_t hash) { ObjectMap* derivation = ObjectMap::allocate(cx, base, descriptors); base->transitions_.tryStore(derivation, hash); // TODO: Write barrier? the object map return derivation; } template <typename VisitorT> inline void ObjectMap::visit(Context& cx, VisitorT& visitor) { baseMap().visit(cx, visitor); visitor.edge(cx, (Cell*)this, (Cell*)parent()); transitions_.visit(cx, visitor); } } // namespace Om } // namespace OMR #endif // OMR_OBJECTMAP_INL_HPP_<|endoftext|>
<commit_before>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int H, W; ll A, B; bool f[210][210]; ll solve() { bool x[110][110][4]; for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { x[i][j][0] = f[i-1][j-1]; x[i][j][1] = f[H-1-i+1][j-1]; x[i][j][2] = f[i-1][W-1-j+1]; x[i][j][3] = f[H-1-i+1][W-1-j+1]; } } /* for (auto k = 0; k < 4; ++k) { // cerr << "k = " << k << endl; for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { // cerr << (x[i][j][k] ? 'S' : '.'); } // cerr << endl; } } */ ll dp[110][110]; fill(&dp[0][0], &dp[0][0]+110*110, 0); for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1]; int cnt = 0; for (auto k = 0; k < 4; ++k) { if (x[i][j][k]) cnt++; } if (cnt == 4 || cnt == 3) { dp[i][j] += A + B + max(A, B); } else if (cnt == 1) { dp[i][j] += A + B; } else if (cnt == 2) { if (x[i][j][0] == x[i][j][1] && x[i][j][2] == x[i][j][3]) { dp[i][j] += A; } else if (x[i][j][0] == x[i][j][2] && x[i][j][1] == x[i][j][3]) { dp[i][j] += B; } dp[i][j] += A + B; } // cerr << "dp[" << i << "][" << j << "] = " << dp[i][j] << endl; } } ll amari = 0; bool taisho[2] = {true, true}; for (auto i = 0; i < H/2; ++i) { for (auto j = 0; j < W; ++j) { if (f[i][j] != f[H-i-1][j]) { taisho[0] = false; } } } for (auto i = 0; i < H; ++i) { for (auto j = 0; j < W/2; ++j) { if (f[i][j] != f[i][W-j-1]) { taisho[1] = false; } } } if (taisho[0]) amari += A; if (taisho[1]) amari += B; return dp[H/2][W/2] + A + B - amari; } int main () { cin >> H >> W >> A >> B; string m[210]; for (auto i = 0; i < H; ++i) { cin >> m[i]; } fill(&f[0][0], &f[0][0]+210*210, false); for (auto i = 0; i < H; ++i) { for (auto j = 0; j < W; ++j) { f[i][j] = (m[i][j] == 'S'); } } ll ans = solve(); cout << ans << endl; } <commit_msg>tried D2.cpp to 'D'<commit_after>#include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> // get<n>(xxx) #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> // S.insert(M); // if (S.find(key) != S.end()) { } // for (auto it=S.begin(); it != S.end(); it++) { } // auto it = S.lower_bound(M); #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // atoi(xxx) using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. // insert #if<tab> by my emacs. #if DEBUG == 1 ... #end typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; int H, W; ll A, B; bool f[210][210]; ll solve() { bool x[110][110][4]; for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { x[i][j][0] = f[i-1][j-1]; x[i][j][1] = f[H-1-i+1][j-1]; x[i][j][2] = f[i-1][W-1-j+1]; x[i][j][3] = f[H-1-i+1][W-1-j+1]; } } for (auto k = 0; k < 4; ++k) { cerr << "k = " << k << endl; for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { cerr << (x[i][j][k] ? 'S' : '.'); }cerr << endl; } } ll dp[110][110]; fill(&dp[0][0], &dp[0][0]+110*110, 0); for (auto i = 1; i < H/2+1; ++i) { for (auto j = 1; j < W/2+1; ++j) { dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1]; int cnt = 0; for (auto k = 0; k < 4; ++k) { if (x[i][j][k]) cnt++; } if (cnt == 4 || cnt == 3) { dp[i][j] += A + B + max(A, B); } else if (cnt == 1) { dp[i][j] += A + B; } else if (cnt == 2) { if (x[i][j][0] == x[i][j][1] && x[i][j][2] == x[i][j][3]) { dp[i][j] += A; } else if (x[i][j][0] == x[i][j][2] && x[i][j][1] == x[i][j][3]) { dp[i][j] += B; } dp[i][j] += A + B; } cerr << "dp[" << i << "][" << j << "] = " << dp[i][j] << endl; } } ll amari = 0; bool taisho[2] = {true, true}; for (auto i = 0; i < H/2; ++i) { for (auto j = 0; j < W; ++j) { if (f[i][j] != f[H-i-1][j]) { taisho[0] = false; } } } for (auto i = 0; i < H; ++i) { for (auto j = 0; j < W/2; ++j) { if (f[i][j] != f[i][W-j-1]) { taisho[1] = false; } } } if (taisho[0]) amari += A; if (taisho[1]) amari += B; return dp[H/2][W/2] + A + B - amari; } int main () { cin >> H >> W >> A >> B; string m[210]; for (auto i = 0; i < H; ++i) { cin >> m[i]; } fill(&f[0][0], &f[0][0]+210*210, false); for (auto i = 0; i < H; ++i) { for (auto j = 0; j < W; ++j) { f[i][j] = (m[i][j] == 'S'); } } ll ans = solve(); cout << ans << endl; } <|endoftext|>
<commit_before>/** * File : E.cpp * Author : Kazune Takahashi * Created : 12/22/2018, 9:09:29 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class BIT { // index starts at 1. public: int N; ll *data; BIT(int n) : N(n) { data = new ll[N + 1]; for (auto i = 1; i <= N; ++i) { data[i] = 0; } } ~BIT() { delete[] data; } ll sum(int i) { // [1, i] ll s = 0; while (i > 0) { s += data[i]; i -= i & -i; } return s; } ll sum(int a, int b) { // [a, b) return sum(b - 1) - sum(a - 1); } void add(int i, ll x) { while (i <= N) { data[i] += x; i += i & -i; } } void add(int i) { add(i, 1); } }; ll calc(ll x, ll y) { if (x > y) { ll res = 0; ll mult = 1; while (x > y * mult) { res += 2; mult *= 4; } return res; } else { ll res = 0; ll mult = 1; while (x * (mult * 4) > y) { res -= 2; mult *= 4; } return res; } } int N; ll A[200010]; ll X[200010]; ll imos_X[200010]; ll ans_X[200010]; ll B[200010]; ll Y[200010]; ll imos_Y[200010]; ll ans_Y[200010]; typedef tuple<ll, int> T; int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; } X[0] = 0; for (auto i = 1; i < N; i++) { X[i] = calc(A[i - 1], A[i]); } imos_X[0] = 0; for (auto i = 1; i < N; i++) { imos_X[i] = X[i] + imos_X[i - 1]; // cerr << "imos_X[" << i << "] = " << imos_X[i] << endl; } vector<T> V; BIT bit_X = BIT(N); BIT bit_cnt_X = BIT(N); for (auto i = 0; i < N; i++) { V.push_back(T(imos_X[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < N; i++) { ll M = get<0>(V[i]); int ind = get<1>(V[i]) + 1; bit_X.add(ind, M); bit_cnt_X.add(ind); ans_X[ind - 1] = bit_X.sum(ind, N + 1) - M * bit_cnt_X.sum(ind, N + 1); } for (auto i = 0; i < N; i++) { B[i] = A[i]; } reverse(B, B + N); Y[0] = 0; for (auto i = 1; i < N; i++) { Y[i] = calc(B[i - 1], B[i]); } imos_Y[0] = 0; for (auto i = 1; i < N; i++) { imos_Y[i] = Y[i] + imos_Y[i - 1]; } V.clear(); BIT bit_Y = BIT(N); BIT bit_cnt_Y = BIT(N); for (auto i = 0; i < N; i++) { V.push_back(T(imos_Y[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < N; i++) { ll M = get<0>(V[i]); int ind = get<1>(V[i]) + 1; bit_Y.add(ind, M); bit_cnt_Y.add(ind); ans_Y[ind - 1] = bit_Y.sum(ind, N + 1) - M * bit_cnt_Y.sum(ind, N + 1); } reverse(ans_Y, ans_Y + N); ll ans = 10000000000000000; for (auto i = 0; i <= N; i++) { ll t_ans = i; cerr << "i = " << i << endl; if (i < N) { t_ans += ans_X[i]; cerr << "ans_X[" << i << "] = " << ans_X[i] << endl; } if (i > 0) { t_ans += ans_Y[i - 1]; cerr << "ans_Y[" << i - 1 << "] = " << ans_Y[i - 1] << endl; } ans = min(t_ans, ans); } cout << ans << endl; }<commit_msg>tried E.cpp to 'E'<commit_after>/** * File : E.cpp * Author : Kazune Takahashi * Created : 12/22/2018, 9:09:29 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(19920725)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; class BIT { // index starts at 1. public: int N; ll *data; BIT(int n) : N(n) { data = new ll[N + 1]; for (auto i = 1; i <= N; ++i) { data[i] = 0; } } ~BIT() { delete[] data; } ll sum(int i) { // [1, i] ll s = 0; while (i > 0) { s += data[i]; i -= i & -i; } return s; } ll sum(int a, int b) { // [a, b) return sum(b - 1) - sum(a - 1); } void add(int i, ll x) { while (i <= N) { data[i] += x; i += i & -i; } } void add(int i) { add(i, 1); } }; ll calc(ll x, ll y) { if (x > y) { ll res = 0; ll mult = 1; while (x > y * mult) { res += 2; mult *= 4; } return res; } else { ll res = 0; ll mult = 1; while (x * (mult * 4) > y) { res -= 2; mult *= 4; } return res; } } int N; ll A[200010]; ll X[200010]; ll imos_X[200010]; ll ans_X[200010]; ll B[200010]; ll Y[200010]; ll imos_Y[200010]; ll ans_Y[200010]; typedef tuple<ll, int> T; int main() { cin >> N; for (auto i = 0; i < N; i++) { cin >> A[i]; } X[0] = 0; for (auto i = 1; i < N; i++) { X[i] = calc(A[i - 1], A[i]); } imos_X[0] = 0; for (auto i = 1; i < N; i++) { imos_X[i] = X[i] + imos_X[i - 1]; cerr << "imos_X[" << i << "] = " << imos_X[i] << endl; } vector<T> V; BIT bit_X = BIT(N); BIT bit_cnt_X = BIT(N); for (auto i = 0; i < N; i++) { V.push_back(T(imos_X[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < N; i++) { ll M = get<0>(V[i]); int ind = get<1>(V[i]) + 1; bit_X.add(ind, M); bit_cnt_X.add(ind); ans_X[ind - 1] = bit_X.sum(ind, N + 1) - M * bit_cnt_X.sum(ind, N + 1); } for (auto i = 0; i < N; i++) { B[i] = A[i]; } reverse(B, B + N); Y[0] = 0; for (auto i = 1; i < N; i++) { Y[i] = calc(B[i - 1], B[i]); } imos_Y[0] = 0; for (auto i = 1; i < N; i++) { imos_Y[i] = Y[i] + imos_Y[i - 1]; } V.clear(); BIT bit_Y = BIT(N); BIT bit_cnt_Y = BIT(N); for (auto i = 0; i < N; i++) { V.push_back(T(imos_Y[i], i)); } sort(V.begin(), V.end()); reverse(V.begin(), V.end()); for (auto i = 0; i < N; i++) { ll M = get<0>(V[i]); int ind = get<1>(V[i]) + 1; bit_Y.add(ind, M); bit_cnt_Y.add(ind); ans_Y[ind - 1] = bit_Y.sum(ind, N + 1) - M * bit_cnt_Y.sum(ind, N + 1); } reverse(ans_Y, ans_Y + N); ll ans = 10000000000000000; for (auto i = 0; i <= N; i++) { ll t_ans = i; cerr << "i = " << i << endl; if (i < N) { t_ans += ans_X[i]; cerr << "ans_X[" << i << "] = " << ans_X[i] << endl; } if (i > 0) { t_ans += ans_Y[i - 1]; cerr << "ans_Y[" << i - 1 << "] = " << ans_Y[i - 1] << endl; } ans = min(t_ans, ans); } cout << ans << endl; }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019/12/24 20:41:23 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes(int i) { cout << i << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int H, W; vector<string> S; void stamp(int x, int y) { for (auto i = x; i < min(H, x + H / 2); i++) { for (auto j = y; j < min(W, y + W / 2); j++) { S[i][j] = '#'; } } } int main() { cin >> H >> W; S.resize(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } set<int> X, Y; for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { if (S[i][j] == '.') { X.insert(i); Y.insert(j); } } } if (X.empty()) { Yes(0); } auto it = X.begin(); int ubh{*it}; it = X.end(); it--; int lbh{*it}; it = Y.begin(); int ubw{*it}; it = Y.end(); it--; int lbw{*it}; int height{lbh - ubh + 1}; int width{lbw - ubw + 1}; if (height <= H / 2 && width <= W / 2) { Yes(1); } if (height <= H / 2) { Yes(2); } if (width <= W / 2) { Yes(2); } int cnt{0}; for (auto k = 0; k < H + W - 1; k++) { for (auto i = 0; i <= k; i++) { auto j = k - i; if (i < H && j < W && S[i][j] == '.') { ++cnt; stamp(i, j); } } } if (cnt > 4) { assert(false); } cout << cnt << endl; } <commit_msg>submit F.cpp to 'F - Stamps 1' (xmascon19) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019/12/24 20:41:23 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes(int i) { cout << i << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- main() ----- int H, W; vector<string> S; void stamp(int x, int y) { #if DEBUG == 1 cerr << "stamp(" << x << ", " << y << ")" << endl; #endif for (auto i = x; i < min(H, x + H / 2); i++) { for (auto j = y; j < min(W, y + W / 2); j++) { S[i][j] = '#'; #if DEBUG == 1 cerr << "S[" << i << "][" << j << "]" << endl; #endif } } } int main() { cin >> H >> W; S.resize(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } set<int> X, Y; for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { if (S[i][j] == '.') { X.insert(i); Y.insert(j); } } } if (X.empty()) { Yes(0); } auto it = X.begin(); int ubh{*it}; it = X.end(); it--; int lbh{*it}; it = Y.begin(); int ubw{*it}; it = Y.end(); it--; int lbw{*it}; int height{lbh - ubh + 1}; int width{lbw - ubw + 1}; if (height <= H / 2 && width <= W / 2) { Yes(1); } if (height <= H / 2) { Yes(2); } if (width <= W / 2) { Yes(2); } int cnt{0}; for (auto k = 0; k < H + W - 1; k++) { for (auto i = 0; i <= k; i++) { auto j = k - i; if (i < H && j < W && S[i][j] == '.') { ++cnt; stamp(i, j); } } } if (cnt > 4) { assert(false); } cout << cnt << endl; } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : G.cpp * Author : Kazune Takahashi * Created : 12/25/2019, 6:29:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Bipartite ----- // for C++14 // Bipartite<> graph(N); template <typename T = int> class Bipartite { public: struct edge { bool used; size_t rev; int from, to; T id; edge(int from, int to, size_t rev, T id = T{}, bool used = false) : used{used}, rev{rev}, from{from}, to{to}, id{id} {} }; private: int N; vector<vector<edge>> G; vector<edge *> match; vector<bool> used; public: Bipartite(int N) : N{N}, G(N), match(N), used(N) {} void add_edge(int u, int v, T id = T{}) { G[u].push_back({u, v, G[v].size(), id, false}); G[v].push_back({v, u, G[u].size() - 1, id, false}); } int bipartite_matching() { int res{0}; fill(match.begin(), match.end(), nullptr); for (auto v = 0; v < N; v++) { if (!match[v]) { fill(used.begin(), used.end(), false); if (dfs(v)) { ++res; } } } #if DEBUG == 1 cerr << "res = " << res << endl; #endif for (auto &e : match) { e->used = true; } return res; } vector<edge *> const &matching() const { return match; } private: bool dfs(int v) { used[v] = true; for (auto &e : G[v]) { if (e.used) { continue; } auto u{e.to}; // for C++14 auto w{match[u]}; if (!w || (!used[w->to] && dfs(w->to))) { match[v] = &e; match[u] = &G[u][e.rev]; return true; } } return false; } }; // ----- main() ----- class Solve { constexpr static int P{5}; constexpr static int Q{2}; constexpr static int C{P * P + Q * Q}; int H, W; vector<string> S; Bipartite<> graph; vector<vector<bool>> G; public: Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), graph(2 * C), G(C, vector<bool>(C, true)) { for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { if (S[i][j] == '.') { G[i % C][j % C] = false; } } } for (auto x = 0; x < C; x++) { for (auto y = 0; y < C; y++) { if (!G[x][y]) { graph.add_edge(calc_k_A(x, y), calc_k_B(x, y)); } } } } int calc() { return graph.bipartite_matching(); }; private: // helper function static int calc_k_A(int x, int y) { for (auto b = 0; b < Q; b++) { int tmp{Q * x + P * y + C * b}; if (tmp % Q == 0) { return (tmp / Q) % C; } } assert(false); return -1; } static int calc_k_B(int x, int y) { for (auto b = 0; b < P; b++) { int tmp{P * x + Q * y + C * b}; if (tmp % P == 0) { return (tmp / P) % C + C; } } assert(false); return -1; } }; int main() { int H, W; cin >> H >> W; vector<string> S(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } Solve solve(H, W, S); cout << solve.calc() << endl; } <commit_msg>tried G.cpp to 'G'<commit_after>#define DEBUG 1 /** * File : G.cpp * Author : Kazune Takahashi * Created : 12/25/2019, 6:29:12 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Bipartite ----- // for C++14 // Bipartite<> graph(N); template <typename T = int> class Bipartite { public: struct edge { bool used; size_t rev; int from, to; T id; edge(int from, int to, size_t rev, T id = T{}, bool used = false) : used{used}, rev{rev}, from{from}, to{to}, id{id} {} }; private: int N; vector<vector<edge>> G; vector<edge *> match; vector<bool> used; public: Bipartite(int N) : N{N}, G(N), match(N), used(N) {} void add_edge(int u, int v, T id = T{}) { G[u].push_back({u, v, G[v].size(), id, false}); G[v].push_back({v, u, G[u].size() - 1, id, false}); } int bipartite_matching() { int res{0}; fill(match.begin(), match.end(), nullptr); for (auto v = 0; v < N; v++) { if (!match[v]) { fill(used.begin(), used.end(), false); if (dfs(v)) { ++res; } } } for (auto &e : match) { #if DEBUG == 1 cerr << "e->id = " << e->id << endl; #endif e->used = true; } return res; } vector<edge *> const &matching() const { return match; } private: bool dfs(int v) { used[v] = true; for (auto &e : G[v]) { if (e.used) { continue; } auto u{e.to}; // for C++14 auto w{match[u]}; if (!w || (!used[w->to] && dfs(w->to))) { match[v] = &e; match[u] = &G[u][e.rev]; return true; } } return false; } }; // ----- main() ----- class Solve { constexpr static int P{5}; constexpr static int Q{2}; constexpr static int C{P * P + Q * Q}; int H, W; vector<string> S; Bipartite<> graph; vector<vector<bool>> G; public: Solve(int H, int W, vector<string> const &S) : H{H}, W{W}, S(S), graph(2 * C), G(C, vector<bool>(C, true)) { for (auto i = 0; i < H; i++) { for (auto j = 0; j < W; j++) { if (S[i][j] == '.') { G[i % C][j % C] = false; } } } for (auto x = 0; x < C; x++) { for (auto y = 0; y < C; y++) { if (!G[x][y]) { graph.add_edge(calc_k_A(x, y), calc_k_B(x, y)); } } } } int calc() { return graph.bipartite_matching(); }; private: // helper function static int calc_k_A(int x, int y) { for (auto b = 0; b < Q; b++) { int tmp{Q * x + P * y + C * b}; if (tmp % Q == 0) { return (tmp / Q) % C; } } assert(false); return -1; } static int calc_k_B(int x, int y) { for (auto b = 0; b < P; b++) { int tmp{P * x + Q * y + C * b}; if (tmp % P == 0) { return (tmp / P) % C + C; } } assert(false); return -1; } }; int main() { int H, W; cin >> H >> W; vector<string> S(H); for (auto i = 0; i < H; i++) { cin >> S[i]; } Solve solve(H, W, S); cout << solve.calc() << endl; } <|endoftext|>
<commit_before>#include "./JPetRecoImageTools.h" #include <vector> #include <utility> #include <cmath> #include <functional> #include <cassert> #include <memory> JPetRecoImageTools::JPetRecoImageTools() {} JPetRecoImageTools::~JPetRecoImageTools() {} double JPetRecoImageTools::nearestNeighbour(std::vector<std::vector<int>> &emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if (sang) { y = (int)std::round(a * x + b) + center; if (y >= 0 && y < (int)emissionMatrix[0].size()) return emissionMatrix[x + center][y]; else return 0; } else { x = (int)std::round(a * y + b) + center; if (x >= 0 && x < (int)emissionMatrix.size()) return emissionMatrix[x + 1][y + center]; // not really know why need to +1 to x, but it works else return 0; } } double JPetRecoImageTools::linear(std::vector<std::vector<int>> &emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if (sang) { y = (int)std::round(a * x + b) + center; double weight = std::abs((a * x + b) - std::ceil(a * x + b)); if (y >= 0 && y < (int)emissionMatrix[0].size()) { return (1 - weight) * emissionMatrix[x + center][y] + weight * emissionMatrix[x + center][y + 1]; } else return 0; } else { x = (int)std::round(a * y + b) + center; double weight = std::abs((a * y + b) - std::ceil(a * y + b)); if (x >= 0 && x + 1 < (int)emissionMatrix.size()) { if(weight == 0) return emissionMatrix[x + 1][y + center]; //same as above else return (1 - weight) * emissionMatrix[x][y + center] + weight * emissionMatrix[x + 1][y + center]; } else return 0; } } /*! \brief Function returning vector of vectors with value of sinogram * \param emissionMatrix matrix, need to be NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix[0].size() / scans * \param interpolationFunction function to interpolate values (Optional, default linear) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) * \param scaleResult if set to true, scale result to <min, max> (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) */ std::vector<std::vector<double>> JPetRecoImageTools::sinogram(std::vector<std::vector<int>> &emissionMatrix, int views,int scans, std::function<double(std::vector<std::vector<int>>&, double, double, int, int, int, bool)> interpolationFunction, float ang1, float ang2, bool scaleResult, int min, int max) { assert(emissionMatrix.size() > 0); assert(emissionMatrix.size() == emissionMatrix[0].size()); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); //create vector of size views, initialize it with vector of size scans std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); float phi = 0.; float stepsize = (ang2 - ang1) / views; assert(stepsize > 0); //maybe != 0 ? const int inputMatrixSize = emissionMatrix.size(); const int center = inputMatrixSize / 2; //if no. scans is greater than the image width, then scale will be <1 const double scale = inputMatrixSize / scans; //* 1.42 const double sang = std::sqrt(2) / 2; int N = 0; int i = 0; double sinValue = 0., cosValue = 0.; double a = 0., aa = 0.; for (phi = ang1; phi < ang2; phi = phi + stepsize) { sinValue = std::sin((double)phi * M_PI / 180 - M_PI / 2); cosValue = std::cos((double)phi * M_PI / 180 - M_PI / 2); if(std::abs(sinValue) < 0.0000001) { sinValue = 0; } if(std::abs(cosValue) < 0.0000001) { cosValue = 0; } a = -cosValue / sinValue; if(std::isinf(a) || std::isinf(-a) || std::abs(a) < 0.0000001) { a = 0; aa = 0; } else aa = 1 / a; for (int scanNumber = 0; scanNumber < scans; scanNumber++) { N = scanNumber - scans / 2; proj[i][scans - 1 - scanNumber] = JPetRecoImageTools::calculateValue(emissionMatrix, std::abs(sinValue) > sang, N, cosValue, sinValue, scale, center, interpolationFunction, a, aa); } i++; } if (scaleResult) { JPetRecoImageTools::scale(proj, min, max); } return proj; } double JPetRecoImageTools::calculateValue(std::vector<std::vector<int>> &emissionMatrix, bool sang, int N, double cos, double sin, double scale, int center, std::function<double(std::vector<std::vector<int>> &, double, double, int, int, int, bool)> &interpolationFunction, double a, double aa) { double b = 0.; if (sang) b = (N - cos - sin) / sin; else b = (N - cos - sin) / cos; b *= scale; double value = 0.; int x = 0; int y = 0; if (sang) { for (x = -center; x < center; x++) { value += interpolationFunction(emissionMatrix, a, b, center, x, y, sang); } value /= std::abs(sin); } else { for (y = -center; y < center; y++) { value += interpolationFunction(emissionMatrix, aa, b, center, x, y, sang); } value /= std::abs(cos); } return value; } void JPetRecoImageTools::scale(std::vector<std::vector<double>> &v, int min, int max) { double datamax = v[0][0]; double datamin = v[0][0]; for (unsigned int k = 0; k < v.size(); k++) { for (unsigned int j = 0; j < v[0].size(); j++) { if (v[k][j] < min) v[k][j] = min; if (v[k][j] > datamax) datamax = v[k][j]; if (v[k][j] < datamin) datamin = v[k][j]; } } if (datamax == 0.) // if max value is 0, no need to scale return; for (unsigned int k = 0; k < v.size(); k++) { for (unsigned int j = 0; j < v[0].size(); j++) { v[k][j] = (double)((v[k][j] - datamin) * max / datamax); } } }<commit_msg>Fix interpolation, add +1 to x before checking<commit_after>#include "./JPetRecoImageTools.h" #include <vector> #include <utility> #include <cmath> #include <functional> #include <cassert> #include <memory> JPetRecoImageTools::JPetRecoImageTools() {} JPetRecoImageTools::~JPetRecoImageTools() {} double JPetRecoImageTools::nearestNeighbour(std::vector<std::vector<int>> &emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if (sang) { y = (int)std::round(a * x + b) + center; if (y >= 0 && y < (int)emissionMatrix[0].size()) return emissionMatrix[x + center][y]; else return 0; } else { x = (int)std::round(a * y + b) + center + 1; // not really know why need to +1 to x, but it works if (x >= 0 && x < (int)emissionMatrix.size()) return emissionMatrix[x][y + center]; else return 0; } } double JPetRecoImageTools::linear(std::vector<std::vector<int>> &emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if (sang) { y = (int)std::round(a * x + b) + center; double weight = std::abs((a * x + b) - std::ceil(a * x + b)); if (y >= 0 && y < (int)emissionMatrix[0].size()) { return (1 - weight) * emissionMatrix[x + center][y] + weight * emissionMatrix[x + center][y + 1]; } else return 0; } else { x = (int)std::round(a * y + b) + center + 1; // not really know why need to +1 to x, but it works double weight = std::abs((a * y + b) - std::ceil(a * y + b)); if (x >= 0 && x + 1 < (int)emissionMatrix.size()) { if(weight == 0) return emissionMatrix[x][y + center]; else return (1 - weight) * emissionMatrix[x][y + center] + weight * emissionMatrix[x + 1][y + center]; } else return 0; } } /*! \brief Function returning vector of vectors with value of sinogram * \param emissionMatrix matrix, need to be NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix[0].size() / scans * \param interpolationFunction function to interpolate values (Optional, default linear) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) * \param scaleResult if set to true, scale result to <min, max> (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) */ std::vector<std::vector<double>> JPetRecoImageTools::sinogram(std::vector<std::vector<int>> &emissionMatrix, int views,int scans, std::function<double(std::vector<std::vector<int>>&, double, double, int, int, int, bool)> interpolationFunction, float ang1, float ang2, bool scaleResult, int min, int max) { assert(emissionMatrix.size() > 0); assert(emissionMatrix.size() == emissionMatrix[0].size()); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); //create vector of size views, initialize it with vector of size scans std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); float phi = 0.; float stepsize = (ang2 - ang1) / views; assert(stepsize > 0); //maybe != 0 ? const int inputMatrixSize = emissionMatrix.size(); const int center = inputMatrixSize / 2; //if no. scans is greater than the image width, then scale will be <1 const double scale = inputMatrixSize / scans; //* 1.42 const double sang = std::sqrt(2) / 2; int N = 0; int i = 0; double sinValue = 0., cosValue = 0.; double a = 0., aa = 0.; for (phi = ang1; phi < ang2; phi = phi + stepsize) { sinValue = std::sin((double)phi * M_PI / 180 - M_PI / 2); cosValue = std::cos((double)phi * M_PI / 180 - M_PI / 2); if(std::abs(sinValue) < 0.0000001) { sinValue = 0; } if(std::abs(cosValue) < 0.0000001) { cosValue = 0; } a = -cosValue / sinValue; if(std::isinf(a) || std::isinf(-a) || std::abs(a) < 0.0000001) { a = 0; aa = 0; } else aa = 1 / a; for (int scanNumber = 0; scanNumber < scans; scanNumber++) { N = scanNumber - scans / 2; proj[i][scans - 1 - scanNumber] = JPetRecoImageTools::calculateValue(emissionMatrix, std::abs(sinValue) > sang, N, cosValue, sinValue, scale, center, interpolationFunction, a, aa); } i++; } if (scaleResult) { JPetRecoImageTools::scale(proj, min, max); } return proj; } double JPetRecoImageTools::calculateValue(std::vector<std::vector<int>> &emissionMatrix, bool sang, int N, double cos, double sin, double scale, int center, std::function<double(std::vector<std::vector<int>> &, double, double, int, int, int, bool)> &interpolationFunction, double a, double aa) { double b = 0.; if (sang) b = (N - cos - sin) / sin; else b = (N - cos - sin) / cos; b *= scale; double value = 0.; int x = 0; int y = 0; if (sang) { for (x = -center; x < center; x++) { value += interpolationFunction(emissionMatrix, a, b, center, x, y, sang); } value /= std::abs(sin); } else { for (y = -center; y < center; y++) { value += interpolationFunction(emissionMatrix, aa, b, center, x, y, sang); } value /= std::abs(cos); } return value; } void JPetRecoImageTools::scale(std::vector<std::vector<double>> &v, int min, int max) { double datamax = v[0][0]; double datamin = v[0][0]; for (unsigned int k = 0; k < v.size(); k++) { for (unsigned int j = 0; j < v[0].size(); j++) { if (v[k][j] < min) v[k][j] = min; if (v[k][j] > datamax) datamax = v[k][j]; if (v[k][j] < datamin) datamin = v[k][j]; } } if (datamax == 0.) // if max value is 0, no need to scale return; for (unsigned int k = 0; k < v.size(); k++) { for (unsigned int j = 0; j < v[0].size(); j++) { v[k][j] = (double)((v[k][j] - datamin) * max / datamax); } } }<|endoftext|>
<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/glue/plugins/plugin_lib.h" #include <dlfcn.h> #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "webkit/glue/plugins/plugin_list.h" // These headers must be included in this order to make the declaration gods // happy. #include "base/third_party/nspr/prcpucfg_linux.h" #include "third_party/mozilla/include/nsplugindefs.h" namespace NPAPI { bool PluginLib::ReadWebPluginInfo(const FilePath& filename, WebPluginInfo* info) { // The file to reference is: // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp void* dl = base::LoadNativeLibrary(filename); if (!dl) return false; info->path = filename; // See comments in plugin_lib_mac regarding this symbol. typedef const char* (*NP_GetMimeDescriptionType)(); NP_GetMimeDescriptionType NP_GetMIMEDescription = reinterpret_cast<NP_GetMimeDescriptionType>( dlsym(dl, "NP_GetMIMEDescription")); const char* mime_description = NULL; if (NP_GetMIMEDescription) mime_description = NP_GetMIMEDescription(); if (mime_description) { // We parse the description here into WebPluginMimeType structures. // Description for Flash 10 looks like (all as one string): // "application/x-shockwave-flash:swf:Shockwave Flash;" // "application/futuresplash:spl:FutureSplash Player" std::vector<std::string> descriptions; SplitString(mime_description, ';', &descriptions); for (size_t i = 0; i < descriptions.size(); ++i) { if (descriptions[i].empty()) continue; // Don't warn if they have trailing semis. std::vector<std::string> fields; SplitString(descriptions[i], ':', &fields); if (fields.size() != 3) { LOG(WARNING) << "Couldn't parse plugin info: " << descriptions[i]; continue; } WebPluginMimeType mime_type; mime_type.mime_type = fields[0]; SplitString(fields[1], ',', &mime_type.file_extensions); mime_type.description = UTF8ToWide(fields[2]); info->mime_types.push_back(mime_type); } } // The plugin name and description live behind NP_GetValue calls. typedef NPError (*NP_GetValueType)(void* unused, nsPluginVariable variable, void* value_out); NP_GetValueType NP_GetValue = reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue")); if (NP_GetValue) { const char* name = NULL; NP_GetValue(NULL, nsPluginVariable_NameString, &name); if (name) info->name = UTF8ToWide(name); const char* description = NULL; NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description); if (description) info->desc = UTF8ToWide(description); } base::UnloadNativeLibrary(dl); return true; } } // namespace NPAPI <commit_msg>linux: test plugin for appropriate architecture before loading<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "webkit/glue/plugins/plugin_lib.h" #include <dlfcn.h> #include <elf.h> #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "webkit/glue/plugins/plugin_list.h" // These headers must be included in this order to make the declaration gods // happy. #include "base/third_party/nspr/prcpucfg_linux.h" #include "third_party/mozilla/include/nsplugindefs.h" namespace { // Read the ELF header and return true if it is usable on // the current architecture (e.g. 32-bit ELF on 32-bit build). // Returns false on other errors as well. bool ELFMatchesCurrentArchitecture(const FilePath& filename) { FILE* file = fopen(filename.value().c_str(), "rb"); if (!file) return false; char buffer[5]; if (fread(buffer, 5, 1, file) != 1) { fclose(file); return false; } fclose(file); if (buffer[0] != ELFMAG0 || buffer[1] != ELFMAG1 || buffer[2] != ELFMAG2 || buffer[3] != ELFMAG3) { // Not an ELF file, perhaps? return false; } int elf_class = buffer[EI_CLASS]; #if defined(ARCH_CPU_32_BITS) if (elf_class == ELFCLASS32) return true; #elif defined(ARCH_CPU_64_BITS) if (elf_class == ELFCLASS64) return true; #endif return false; } } // anonymous namespace namespace NPAPI { bool PluginLib::ReadWebPluginInfo(const FilePath& filename, WebPluginInfo* info) { // The file to reference is: // http://mxr.mozilla.org/firefox/source/modules/plugin/base/src/nsPluginsDirUnix.cpp // Skip files that aren't appropriate for our architecture. if (!ELFMatchesCurrentArchitecture(filename)) return false; void* dl = base::LoadNativeLibrary(filename); if (!dl) return false; info->path = filename; // See comments in plugin_lib_mac regarding this symbol. typedef const char* (*NP_GetMimeDescriptionType)(); NP_GetMimeDescriptionType NP_GetMIMEDescription = reinterpret_cast<NP_GetMimeDescriptionType>( dlsym(dl, "NP_GetMIMEDescription")); const char* mime_description = NULL; if (NP_GetMIMEDescription) mime_description = NP_GetMIMEDescription(); if (mime_description) { // We parse the description here into WebPluginMimeType structures. // Description for Flash 10 looks like (all as one string): // "application/x-shockwave-flash:swf:Shockwave Flash;" // "application/futuresplash:spl:FutureSplash Player" std::vector<std::string> descriptions; SplitString(mime_description, ';', &descriptions); for (size_t i = 0; i < descriptions.size(); ++i) { if (descriptions[i].empty()) continue; // Don't warn if they have trailing semis. std::vector<std::string> fields; SplitString(descriptions[i], ':', &fields); if (fields.size() != 3) { LOG(WARNING) << "Couldn't parse plugin info: " << descriptions[i]; continue; } WebPluginMimeType mime_type; mime_type.mime_type = fields[0]; SplitString(fields[1], ',', &mime_type.file_extensions); mime_type.description = UTF8ToWide(fields[2]); info->mime_types.push_back(mime_type); } } // The plugin name and description live behind NP_GetValue calls. typedef NPError (*NP_GetValueType)(void* unused, nsPluginVariable variable, void* value_out); NP_GetValueType NP_GetValue = reinterpret_cast<NP_GetValueType>(dlsym(dl, "NP_GetValue")); if (NP_GetValue) { const char* name = NULL; NP_GetValue(NULL, nsPluginVariable_NameString, &name); if (name) info->name = UTF8ToWide(name); const char* description = NULL; NP_GetValue(NULL, nsPluginVariable_DescriptionString, &description); if (description) info->desc = UTF8ToWide(description); } base::UnloadNativeLibrary(dl); return true; } } // namespace NPAPI <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(OS_WIN) #define MAYBE_Infobars Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <commit_msg>Marking ExtensionApiTest.Infobars as DISABLED on Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/common/chrome_switches.h" #if defined(OS_WIN) // Also marking this as disabled on Windows. See http://crbug.com/75451. #define MAYBE_Infobars DISABLED_Infobars #else // Need to finish port to Linux. See http://crbug.com/39916 for details. // Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details. #define MAYBE_Infobars DISABLED_Infobars #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) { // TODO(finnur): Remove once infobars are no longer experimental (bug 39511). CommandLine::ForCurrentProcess()->AppendSwitch( switches::kEnableExperimentalExtensionApis); ASSERT_TRUE(RunExtensionTest("infobars")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(jcampan): http://crbug.com/27216 disabled because failing. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; } <commit_msg>Re-enable the ExtensionApiTest.Storage test.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" // TODO(jcampan): http://crbug.com/27216 disabled because failing. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) { ASSERT_TRUE(RunExtensionTest("storage")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "chrome/browser/gtk/blocked_popup_container_view_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/string_util.h" #include "chrome/browser/gtk/custom_button.h" #include "chrome/browser/gtk/gtk_chrome_button.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/browser/gtk/rounded_window.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view_gtk.h" #include "chrome/common/gtk_util.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" namespace { // The minimal border around the edge of the notification. const int kSmallPadding = 2; // Color of the gradient in the background. const double kBackgroundColorTop[] = { 246.0 / 255, 250.0 / 255, 1.0 }; const double kBackgroundColorBottom[] = { 219.0 / 255, 235.0 / 255, 1.0 }; // Rounded corner radius (in pixels). const int kCornerSize = 4; } // namespace // static BlockedPopupContainerView* BlockedPopupContainerView::Create( BlockedPopupContainer* container) { return new BlockedPopupContainerViewGtk(container); } BlockedPopupContainerViewGtk::~BlockedPopupContainerViewGtk() { container_.Destroy(); } TabContentsViewGtk* BlockedPopupContainerViewGtk::ContainingView() { return static_cast<TabContentsViewGtk*>( model_->GetConstrainingContents(NULL)->view()); } void BlockedPopupContainerViewGtk::GetURLAndTitleForPopup( size_t index, string16* url, string16* title) const { DCHECK(url); DCHECK(title); TabContents* tab_contents = model_->GetTabContentsAt(index); const GURL& tab_contents_url = tab_contents->GetURL().GetOrigin(); *url = UTF8ToUTF16(tab_contents_url.possibly_invalid_spec()); *title = tab_contents->GetTitle(); } // Overridden from BlockedPopupContainerView: void BlockedPopupContainerViewGtk::SetPosition() { // No-op. Not required with the GTK version. } void BlockedPopupContainerViewGtk::ShowView() { // TODO(erg): Animate in. gtk_widget_show_all(container_.get()); } void BlockedPopupContainerViewGtk::UpdateLabel() { size_t blocked_notices = model_->GetBlockedNoticeCount(); size_t blocked_items = model_->GetBlockedPopupCount() + blocked_notices; GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_)); if (!label) { label = gtk_label_new(""); gtk_container_add(GTK_CONTAINER(menu_button_), label); } std::string label_text; if (blocked_items == 0) { label_text = l10n_util::GetStringUTF8(IDS_POPUPS_UNBLOCKED); } else if (blocked_notices == 0) { label_text = l10n_util::GetStringFUTF8(IDS_POPUPS_BLOCKED_COUNT, UintToString16(blocked_items)); } else { label_text = l10n_util::GetStringFUTF8(IDS_BLOCKED_NOTICE_COUNT, UintToString16(blocked_items)); } gtk_label_set_text(GTK_LABEL(label), label_text.c_str()); } void BlockedPopupContainerViewGtk::HideView() { // TODO(erg): Animate out. gtk_widget_hide(container_.get()); } void BlockedPopupContainerViewGtk::Destroy() { ContainingView()->RemoveBlockedPopupView(this); delete this; } void BlockedPopupContainerViewGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_THEME_CHANGED); // Make sure the label exists (so we can change its colors). UpdateLabel(); // Update the label's colors. GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_)); if (theme_provider_->UseGtkTheme()) { gtk_util::SetLabelColor(label, NULL); } else { GdkColor color = theme_provider_->GetGdkColor( BrowserThemeProvider::COLOR_BOOKMARK_TEXT); gtk_util::SetLabelColor(label, &color); } GdkColor color = theme_provider_->GetBorderColor(); gtk_util::SetRoundedWindowBorderColor(container_.get(), color); } bool BlockedPopupContainerViewGtk::IsCommandEnabled(int command_id) const { return true; } bool BlockedPopupContainerViewGtk::IsItemChecked(int id) const { // |id| should be > 0 since all index based commands have 1 added to them. DCHECK_GT(id, 0); size_t id_size_t = static_cast<size_t>(id); if (id_size_t > BlockedPopupContainer::kImpossibleNumberOfPopups) { id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1; if (id_size_t < model_->GetPopupHostCount()) return model_->IsHostWhitelisted(id_size_t); } return false; } void BlockedPopupContainerViewGtk::ExecuteCommand(int id) { DCHECK_GT(id, 0); size_t id_size_t = static_cast<size_t>(id); // Is this a click on a popup? if (id_size_t < BlockedPopupContainer::kImpossibleNumberOfPopups) { model_->LaunchPopupAtIndex(id_size_t - 1); return; } // |id| shouldn't be == kImpossibleNumberOfPopups since the popups end before // this and the hosts start after it. (If it is used, it is as a separator.) DCHECK_NE(id_size_t, BlockedPopupContainer::kImpossibleNumberOfPopups); id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1; // Is this a click on a host? size_t host_count = model_->GetPopupHostCount(); if (id_size_t < host_count) { model_->ToggleWhitelistingForHost(id_size_t); return; } // |id shouldn't be == host_count since this is the separator between hosts // and notices. DCHECK_NE(id_size_t, host_count); id_size_t -= host_count + 1; // Nothing to do for now for notices. } BlockedPopupContainerViewGtk::BlockedPopupContainerViewGtk( BlockedPopupContainer* container) : model_(container), theme_provider_(GtkThemeProvider::GetFrom(container->profile())), close_button_(CustomDrawButton::CloseButton(theme_provider_)) { Init(); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); } void BlockedPopupContainerViewGtk::Init() { menu_button_ = theme_provider_->BuildChromeButton(); UpdateLabel(); g_signal_connect(menu_button_, "clicked", G_CALLBACK(OnMenuButtonClicked), this); GtkWidget* hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), menu_button_, FALSE, FALSE, kSmallPadding); gtk_util::CenterWidgetInHBox(hbox, close_button_->widget(), true, 0); g_signal_connect(close_button_->widget(), "clicked", G_CALLBACK(OnCloseButtonClicked), this); container_.Own(gtk_util::CreateGtkBorderBin(hbox, NULL, kSmallPadding, kSmallPadding, kSmallPadding, kSmallPadding)); // Connect an expose signal that draws the background. Most connect before // the ActAsRoundedWindow one. g_signal_connect(container_.get(), "expose-event", G_CALLBACK(OnRoundedExposeCallback), this); gtk_util::ActAsRoundedWindow( container_.get(), gfx::kGdkBlack, kCornerSize, gtk_util::ROUNDED_TOP_LEFT | gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_LEFT | gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT); ContainingView()->AttachBlockedPopupView(this); } void BlockedPopupContainerViewGtk::OnMenuButtonClicked( GtkButton *button, BlockedPopupContainerViewGtk* container) { container->launch_menu_.reset(new MenuGtk(container, false)); // Set items 1 .. popup_count as individual popups. size_t popup_count = container->model_->GetBlockedPopupCount(); for (size_t i = 0; i < popup_count; ++i) { string16 url, title; container->GetURLAndTitleForPopup(i, &url, &title); // We can't just use the index into container_ here because Menu reserves // the value 0 as the nop command. container->launch_menu_->AppendMenuItemWithLabel(i + 1, l10n_util::GetStringFUTF8(IDS_POPUP_TITLE_FORMAT, url, title)); } // Set items (kImpossibleNumberOfPopups + 1) .. // (kImpossibleNumberOfPopups + hosts.size()) as hosts. std::vector<std::string> hosts(container->model_->GetHosts()); if (!hosts.empty() && (popup_count > 0)) container->launch_menu_->AppendSeparator(); size_t first_host = BlockedPopupContainer::kImpossibleNumberOfPopups + 1; for (size_t i = 0; i < hosts.size(); ++i) { container->launch_menu_->AppendCheckMenuItemWithLabel(first_host + i, l10n_util::GetStringFUTF8(IDS_POPUP_HOST_FORMAT, UTF8ToUTF16(hosts[i]))); } // Set items (kImpossibleNumberOfPopups + hosts.size() + 2) .. // (kImpossibleNumberOfPopups + hosts.size() + 1 + notice_count) as notices. size_t notice_count = container->model_->GetBlockedNoticeCount(); if (notice_count && (!hosts.empty() || (popup_count > 0))) container->launch_menu_->AppendSeparator(); size_t first_notice = first_host + hosts.size() + 1; for (size_t i = 0; i < notice_count; ++i) { std::string host; string16 reason; container->model_->GetHostAndReasonForNotice(i, &host, &reason); container->launch_menu_->AppendMenuItemWithLabel(first_notice + i, l10n_util::GetStringFUTF8(IDS_NOTICE_TITLE_FORMAT, UTF8ToUTF16(host), reason)); } container->launch_menu_->PopupAsContext(gtk_get_current_event_time()); } void BlockedPopupContainerViewGtk::OnCloseButtonClicked( GtkButton *button, BlockedPopupContainerViewGtk* container) { container->model_->set_dismissed(); container->model_->CloseAll(); } gboolean BlockedPopupContainerViewGtk::OnRoundedExposeCallback( GtkWidget* widget, GdkEventExpose* event, BlockedPopupContainerViewGtk* container) { if (!container->theme_provider_->UseGtkTheme()) { int width = widget->allocation.width; int height = widget->allocation.height; // Clip to our damage rect. cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(event->window)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); // TODO(erg): We draw the gradient background only when GTK themes are // off. This isn't a perfect solution as this isn't themed! The views // version doesn't appear to be themed either, so at least for now, // constants are OK. int half_width = width / 2; cairo_pattern_t* pattern = cairo_pattern_create_linear( half_width, 0, half_width, height); cairo_pattern_add_color_stop_rgb( pattern, 0.0, kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]); cairo_pattern_add_color_stop_rgb( pattern, 1.0, kBackgroundColorBottom[0], kBackgroundColorBottom[1], kBackgroundColorBottom[2]); cairo_set_source(cr, pattern); cairo_paint(cr); cairo_pattern_destroy(pattern); cairo_destroy(cr); } return FALSE; } <commit_msg>GTK: The blocked popup notification should obey chrome themes.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. Use of this // source code is governed by a BSD-style license that can be found in the // LICENSE file. #include "chrome/browser/gtk/blocked_popup_container_view_gtk.h" #include "app/gfx/gtk_util.h" #include "app/l10n_util.h" #include "base/string_util.h" #include "chrome/browser/gtk/custom_button.h" #include "chrome/browser/gtk/gtk_chrome_button.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/browser/gtk/rounded_window.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tab_contents/tab_contents_view_gtk.h" #include "chrome/common/gtk_util.h" #include "chrome/common/notification_service.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" namespace { // The minimal border around the edge of the notification. const int kSmallPadding = 2; // Color of the gradient in the background. const double kBackgroundColorTop[] = { 246.0 / 255, 250.0 / 255, 1.0 }; const double kBackgroundColorBottom[] = { 219.0 / 255, 235.0 / 255, 1.0 }; // Rounded corner radius (in pixels). const int kCornerSize = 4; } // namespace // static BlockedPopupContainerView* BlockedPopupContainerView::Create( BlockedPopupContainer* container) { return new BlockedPopupContainerViewGtk(container); } BlockedPopupContainerViewGtk::~BlockedPopupContainerViewGtk() { container_.Destroy(); } TabContentsViewGtk* BlockedPopupContainerViewGtk::ContainingView() { return static_cast<TabContentsViewGtk*>( model_->GetConstrainingContents(NULL)->view()); } void BlockedPopupContainerViewGtk::GetURLAndTitleForPopup( size_t index, string16* url, string16* title) const { DCHECK(url); DCHECK(title); TabContents* tab_contents = model_->GetTabContentsAt(index); const GURL& tab_contents_url = tab_contents->GetURL().GetOrigin(); *url = UTF8ToUTF16(tab_contents_url.possibly_invalid_spec()); *title = tab_contents->GetTitle(); } // Overridden from BlockedPopupContainerView: void BlockedPopupContainerViewGtk::SetPosition() { // No-op. Not required with the GTK version. } void BlockedPopupContainerViewGtk::ShowView() { // TODO(erg): Animate in. gtk_widget_show_all(container_.get()); } void BlockedPopupContainerViewGtk::UpdateLabel() { size_t blocked_notices = model_->GetBlockedNoticeCount(); size_t blocked_items = model_->GetBlockedPopupCount() + blocked_notices; GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_)); if (!label) { label = gtk_label_new(""); gtk_container_add(GTK_CONTAINER(menu_button_), label); } std::string label_text; if (blocked_items == 0) { label_text = l10n_util::GetStringUTF8(IDS_POPUPS_UNBLOCKED); } else if (blocked_notices == 0) { label_text = l10n_util::GetStringFUTF8(IDS_POPUPS_BLOCKED_COUNT, UintToString16(blocked_items)); } else { label_text = l10n_util::GetStringFUTF8(IDS_BLOCKED_NOTICE_COUNT, UintToString16(blocked_items)); } gtk_label_set_text(GTK_LABEL(label), label_text.c_str()); } void BlockedPopupContainerViewGtk::HideView() { // TODO(erg): Animate out. gtk_widget_hide(container_.get()); } void BlockedPopupContainerViewGtk::Destroy() { ContainingView()->RemoveBlockedPopupView(this); delete this; } void BlockedPopupContainerViewGtk::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::BROWSER_THEME_CHANGED); // Make sure the label exists (so we can change its colors). UpdateLabel(); // Update the label's colors. GtkWidget* label = gtk_bin_get_child(GTK_BIN(menu_button_)); if (theme_provider_->UseGtkTheme()) { gtk_util::SetLabelColor(label, NULL); } else { GdkColor color = theme_provider_->GetGdkColor( BrowserThemeProvider::COLOR_BOOKMARK_TEXT); gtk_util::SetLabelColor(label, &color); } GdkColor color = theme_provider_->GetBorderColor(); gtk_util::SetRoundedWindowBorderColor(container_.get(), color); } bool BlockedPopupContainerViewGtk::IsCommandEnabled(int command_id) const { return true; } bool BlockedPopupContainerViewGtk::IsItemChecked(int id) const { // |id| should be > 0 since all index based commands have 1 added to them. DCHECK_GT(id, 0); size_t id_size_t = static_cast<size_t>(id); if (id_size_t > BlockedPopupContainer::kImpossibleNumberOfPopups) { id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1; if (id_size_t < model_->GetPopupHostCount()) return model_->IsHostWhitelisted(id_size_t); } return false; } void BlockedPopupContainerViewGtk::ExecuteCommand(int id) { DCHECK_GT(id, 0); size_t id_size_t = static_cast<size_t>(id); // Is this a click on a popup? if (id_size_t < BlockedPopupContainer::kImpossibleNumberOfPopups) { model_->LaunchPopupAtIndex(id_size_t - 1); return; } // |id| shouldn't be == kImpossibleNumberOfPopups since the popups end before // this and the hosts start after it. (If it is used, it is as a separator.) DCHECK_NE(id_size_t, BlockedPopupContainer::kImpossibleNumberOfPopups); id_size_t -= BlockedPopupContainer::kImpossibleNumberOfPopups + 1; // Is this a click on a host? size_t host_count = model_->GetPopupHostCount(); if (id_size_t < host_count) { model_->ToggleWhitelistingForHost(id_size_t); return; } // |id shouldn't be == host_count since this is the separator between hosts // and notices. DCHECK_NE(id_size_t, host_count); id_size_t -= host_count + 1; // Nothing to do for now for notices. } BlockedPopupContainerViewGtk::BlockedPopupContainerViewGtk( BlockedPopupContainer* container) : model_(container), theme_provider_(GtkThemeProvider::GetFrom(container->profile())), close_button_(CustomDrawButton::CloseButton(theme_provider_)) { Init(); registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, NotificationService::AllSources()); theme_provider_->InitThemesFor(this); } void BlockedPopupContainerViewGtk::Init() { menu_button_ = theme_provider_->BuildChromeButton(); UpdateLabel(); g_signal_connect(menu_button_, "clicked", G_CALLBACK(OnMenuButtonClicked), this); GtkWidget* hbox = gtk_hbox_new(FALSE, 0); gtk_box_pack_start(GTK_BOX(hbox), menu_button_, FALSE, FALSE, kSmallPadding); gtk_util::CenterWidgetInHBox(hbox, close_button_->widget(), true, 0); g_signal_connect(close_button_->widget(), "clicked", G_CALLBACK(OnCloseButtonClicked), this); container_.Own(gtk_util::CreateGtkBorderBin(hbox, NULL, kSmallPadding, kSmallPadding, kSmallPadding, kSmallPadding)); // Connect an expose signal that draws the background. Most connect before // the ActAsRoundedWindow one. g_signal_connect(container_.get(), "expose-event", G_CALLBACK(OnRoundedExposeCallback), this); gtk_util::ActAsRoundedWindow( container_.get(), gfx::kGdkBlack, kCornerSize, gtk_util::ROUNDED_TOP_LEFT | gtk_util::ROUNDED_TOP_RIGHT, gtk_util::BORDER_LEFT | gtk_util::BORDER_TOP | gtk_util::BORDER_RIGHT); ContainingView()->AttachBlockedPopupView(this); } void BlockedPopupContainerViewGtk::OnMenuButtonClicked( GtkButton *button, BlockedPopupContainerViewGtk* container) { container->launch_menu_.reset(new MenuGtk(container, false)); // Set items 1 .. popup_count as individual popups. size_t popup_count = container->model_->GetBlockedPopupCount(); for (size_t i = 0; i < popup_count; ++i) { string16 url, title; container->GetURLAndTitleForPopup(i, &url, &title); // We can't just use the index into container_ here because Menu reserves // the value 0 as the nop command. container->launch_menu_->AppendMenuItemWithLabel(i + 1, l10n_util::GetStringFUTF8(IDS_POPUP_TITLE_FORMAT, url, title)); } // Set items (kImpossibleNumberOfPopups + 1) .. // (kImpossibleNumberOfPopups + hosts.size()) as hosts. std::vector<std::string> hosts(container->model_->GetHosts()); if (!hosts.empty() && (popup_count > 0)) container->launch_menu_->AppendSeparator(); size_t first_host = BlockedPopupContainer::kImpossibleNumberOfPopups + 1; for (size_t i = 0; i < hosts.size(); ++i) { container->launch_menu_->AppendCheckMenuItemWithLabel(first_host + i, l10n_util::GetStringFUTF8(IDS_POPUP_HOST_FORMAT, UTF8ToUTF16(hosts[i]))); } // Set items (kImpossibleNumberOfPopups + hosts.size() + 2) .. // (kImpossibleNumberOfPopups + hosts.size() + 1 + notice_count) as notices. size_t notice_count = container->model_->GetBlockedNoticeCount(); if (notice_count && (!hosts.empty() || (popup_count > 0))) container->launch_menu_->AppendSeparator(); size_t first_notice = first_host + hosts.size() + 1; for (size_t i = 0; i < notice_count; ++i) { std::string host; string16 reason; container->model_->GetHostAndReasonForNotice(i, &host, &reason); container->launch_menu_->AppendMenuItemWithLabel(first_notice + i, l10n_util::GetStringFUTF8(IDS_NOTICE_TITLE_FORMAT, UTF8ToUTF16(host), reason)); } container->launch_menu_->PopupAsContext(gtk_get_current_event_time()); } void BlockedPopupContainerViewGtk::OnCloseButtonClicked( GtkButton *button, BlockedPopupContainerViewGtk* container) { container->model_->set_dismissed(); container->model_->CloseAll(); } gboolean BlockedPopupContainerViewGtk::OnRoundedExposeCallback( GtkWidget* widget, GdkEventExpose* event, BlockedPopupContainerViewGtk* container) { if (!container->theme_provider_->UseGtkTheme()) { int width = widget->allocation.width; int height = widget->allocation.height; // Clip to our damage rect. cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(event->window)); cairo_rectangle(cr, event->area.x, event->area.y, event->area.width, event->area.height); cairo_clip(cr); if (container->theme_provider_->GetThemeID() == BrowserThemeProvider::kDefaultThemeID) { // We are using the default theme. Use a fairly soft gradient for the // background of the blocked popup notification. int half_width = width / 2; cairo_pattern_t* pattern = cairo_pattern_create_linear( half_width, 0, half_width, height); cairo_pattern_add_color_stop_rgb( pattern, 0.0, kBackgroundColorTop[0], kBackgroundColorTop[1], kBackgroundColorTop[2]); cairo_pattern_add_color_stop_rgb( pattern, 1.0, kBackgroundColorBottom[0], kBackgroundColorBottom[1], kBackgroundColorBottom[2]); cairo_set_source(cr, pattern); cairo_paint(cr); cairo_pattern_destroy(pattern); } else { // Use the toolbar color the theme specifies instead. It would be nice to // have a gradient here, but there isn't a second color to use... GdkColor color = container->theme_provider_->GetGdkColor( BrowserThemeProvider::COLOR_TOOLBAR); gdk_cairo_set_source_color(cr, &color); cairo_paint(cr); } cairo_destroy(cr); } return FALSE; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/ui_layout_test.h" // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. //static const char* kTopLevelFiles[] = { //"window-attributes-exist.html" //}; // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. static const char* kSubDirFiles[] = { "clear.html", "delete-removal.html", "enumerate-storage.html", "enumerate-with-length-and-key.html", //"iframe-events.html", //"index-get-and-set.html", //"onstorage-attribute-markup.html", //"onstorage-attribute-setattribute.html", //"localstorage/onstorage-attribute-setwindow.html", //"simple-events.html", "simple-usage.html", //"string-conversion.html", // "window-open.html" }; class DOMStorageTest : public UILayoutTest { protected: DOMStorageTest() : UILayoutTest(), test_dir_(FilePath().AppendASCII("LayoutTests"). AppendASCII("storage").AppendASCII("domstorage")) { } virtual ~DOMStorageTest() { } virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); launch_arguments_.AppendSwitch(switches::kEnableLocalStorage); launch_arguments_.AppendSwitch(switches::kEnableSessionStorage); UILayoutTest::SetUp(); } FilePath test_dir_; }; TEST_F(DOMStorageTest, DISABLED_DOMStorageLayoutTests) { // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. //InitializeForLayoutTest(test_dir_, FilePath(), false); //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i) // RunLayoutTest(kTopLevelFiles[i], false, true); } TEST_F(DOMStorageTest, DISABLED_LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } TEST_F(DOMStorageTest, DISABLED_SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } <commit_msg>Another try to make Valgrind errors go away without figuring out how to do a suppression.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Completely disable for now. #if 0 #include "chrome/common/chrome_switches.h" #include "chrome/test/ui/ui_layout_test.h" // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. //static const char* kTopLevelFiles[] = { //"window-attributes-exist.html" //}; // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. static const char* kSubDirFiles[] = { "clear.html", "delete-removal.html", "enumerate-storage.html", "enumerate-with-length-and-key.html", //"iframe-events.html", //"index-get-and-set.html", //"onstorage-attribute-markup.html", //"onstorage-attribute-setattribute.html", //"localstorage/onstorage-attribute-setwindow.html", //"simple-events.html", "simple-usage.html", //"string-conversion.html", // "window-open.html" }; class DOMStorageTest : public UILayoutTest { protected: DOMStorageTest() : UILayoutTest(), test_dir_(FilePath().AppendASCII("LayoutTests"). AppendASCII("storage").AppendASCII("domstorage")) { } virtual ~DOMStorageTest() { } virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); launch_arguments_.AppendSwitch(switches::kEnableLocalStorage); launch_arguments_.AppendSwitch(switches::kEnableSessionStorage); UILayoutTest::SetUp(); } FilePath test_dir_; }; TEST_F(DOMStorageTest, DISABLED_DOMStorageLayoutTests) { // TODO(jorlow): Enable these tests when we remove them from the // test_exceptions.txt file. //InitializeForLayoutTest(test_dir_, FilePath(), false); //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i) // RunLayoutTest(kTopLevelFiles[i], false, true); } TEST_F(DOMStorageTest, DISABLED_LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } TEST_F(DOMStorageTest, DISABLED_SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } #endif <|endoftext|>
<commit_before>// Resource.hh // Copyright (c) 2002 Henrik Kinnunen (fluxgen@linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id: Resource.hh,v 1.4 2002/04/04 14:26:47 fluxgen Exp $ #ifndef RESOURCE_HH #define RESOURCE_HH #include "NotCopyable.hh" #include <string> #include <list> class Resource_base:private NotCopyable { public: virtual void setFromString(char const *strval)=0; virtual void setDefaultValue()=0; virtual std::string getString()=0; inline const std::string& getAltName() const { return m_altname; } inline const std::string& getName() const { return m_name; } protected: Resource_base(const std::string &name, const std::string &altname): m_name(name), m_altname(altname) { } virtual ~Resource_base(){ }; private: std::string m_name, m_altname; }; class ResourceManager; template <typename T> class Resource:public Resource_base { public: Resource(ResourceManager &rm, T val, const std::string &name, const std::string &altname): Resource_base(name, altname), m_value(val), m_defaultval(val), m_rm(rm) { m_rm.addResource(*this); } ~Resource() { m_rm.removeResource(*this); } inline void setDefaultValue() { m_value = m_defaultval; } void setFromString(const char *strval); inline Resource<T>& operator = (const T& newvalue) { m_value = newvalue; return *this;} std::string getString(); inline T& operator*(void) { return m_value; } inline T *operator->(void) { return &m_value; } private: T m_value, m_defaultval; ResourceManager &m_rm; }; class ResourceManager { public: typedef std::list<Resource_base *> ResourceList; ResourceManager(){ } bool load(const char *filename); bool save(const char *filename, const char *mergefilename=0); template <class T> void addResource(Resource<T> &r) { m_resourcelist.push_back(&r); m_resourcelist.unique(); } template <class T> void removeResource(Resource<T> &r) { m_resourcelist.remove(&r); } private: static inline void ensureXrmIsInitialize(); static bool m_init; ResourceList m_resourcelist; }; #endif //_RESOURCE_HH_ <commit_msg>const-correct on Resource class<commit_after>// Resource.hh // Copyright (c) 2002 Henrik Kinnunen (fluxgen@linuxmail.org) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id: Resource.hh,v 1.5 2002/05/17 10:59:58 fluxgen Exp $ #ifndef RESOURCE_HH #define RESOURCE_HH #include "NotCopyable.hh" #include <string> #include <list> class Resource_base:private NotCopyable { public: virtual void setFromString(char const *strval)=0; virtual void setDefaultValue()=0; virtual std::string getString()=0; inline const std::string& getAltName() const { return m_altname; } inline const std::string& getName() const { return m_name; } protected: Resource_base(const std::string &name, const std::string &altname): m_name(name), m_altname(altname) { } virtual ~Resource_base(){ }; private: std::string m_name, m_altname; }; class ResourceManager; template <typename T> class Resource:public Resource_base { public: Resource(ResourceManager &rm, T val, const std::string &name, const std::string &altname): Resource_base(name, altname), m_value(val), m_defaultval(val), m_rm(rm) { m_rm.addResource(*this); } ~Resource() { m_rm.removeResource(*this); } inline void setDefaultValue() { m_value = m_defaultval; } void setFromString(const char *strval); inline Resource<T>& operator = (const T& newvalue) { m_value = newvalue; return *this;} std::string getString(); inline T& operator*(void) { return m_value; } inline const T& operator*(void) const { return m_value; } inline T *operator->(void) { return &m_value; } inline const T *operator->(void) const { return &m_value; } private: T m_value, m_defaultval; ResourceManager &m_rm; }; class ResourceManager { public: typedef std::list<Resource_base *> ResourceList; ResourceManager(){ } bool load(const char *filename); bool save(const char *filename, const char *mergefilename=0); template <class T> void addResource(Resource<T> &r) { m_resourcelist.push_back(&r); m_resourcelist.unique(); } template <class T> void removeResource(Resource<T> &r) { m_resourcelist.remove(&r); } private: static inline void ensureXrmIsInitialize(); static bool m_init; ResourceList m_resourcelist; }; #endif //_RESOURCE_HH_ <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "googleurl/src/gurl.h" #include "net/base/data_url.h" #include "testing/gtest/include/gtest/gtest.h" namespace { struct ParseTestData { const char* url; bool is_valid; const char* mime_type; const char* charset; const char* data; }; class DataURLTest : public testing::Test { }; } TEST(DataURLTest, Parse) { const ParseTestData tests[] = { { "data:", false, "", "", "" }, { "data:,", true, "text/plain", "US-ASCII", "" }, { "data:;base64,", true, "text/plain", "US-ASCII", "" }, { "data:;charset=,test", true, "text/plain", "US-ASCII", "test" }, { "data:TeXt/HtMl,<b>x</b>", true, "text/html", "US-ASCII", "<b>x</b>" }, { "data:,foo", true, "text/plain", "US-ASCII", "foo" }, { "data:;base64,aGVsbG8gd29ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, { "data:foo/bar;baz=1;charset=kk,boo", true, "foo/bar", "kk", "boo" }, { "data:text/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world" "%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E", true, "text/html", "US-ASCII", "<html><body><b>hello world</b></body></html>" }, { "data:text/html,<html><body><b>hello world</b></body></html>", true, "text/html", "US-ASCII", "<html><body><b>hello world</b></body></html>" }, // the comma cannot be url-escaped! { "data:%2Cblah", false, "", "", "" }, // invalid base64 content { "data:;base64,aGVs_-_-", false, "", "", "" }, // Spaces should be removed from non-text data URLs (we already tested // spaces above). { "data:image/fractal,a b c d e f g", true, "image/fractal", "US-ASCII", "abcdefg" }, // Spaces should also be removed from anything base-64 encoded { "data:;base64,aGVs bG8gd2 9ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, // Other whitespace should also be removed from anything base-64 encoded. { "data:;base64,aGVs bG8gd2 \n9ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, // In base64 encoding, escaped whitespace should be stripped. // (This test was taken from acid3) // http://b/1054495 { "data:text/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207" "%20", true, "text/javascript", "US-ASCII", "d4 = 'four';" }, // Only unescaped whitespace should be stripped in non-base64. // http://b/1157796 { "data:img/png,A B %20 %0A C", true, "img/png", "US-ASCII", "AB \nC" }, // TODO(darin): add more interesting tests }; for (size_t i = 0; i < arraysize(tests); ++i) { std::string mime_type; std::string charset; std::string data; bool ok = net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data); EXPECT_EQ(ok, tests[i].is_valid); if (tests[i].is_valid) { EXPECT_EQ(tests[i].mime_type, mime_type); EXPECT_EQ(tests[i].charset, charset); EXPECT_EQ(tests[i].data, data); } } } <commit_msg>Fix indentation.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "googleurl/src/gurl.h" #include "net/base/data_url.h" #include "testing/gtest/include/gtest/gtest.h" namespace { struct ParseTestData { const char* url; bool is_valid; const char* mime_type; const char* charset; const char* data; }; class DataURLTest : public testing::Test { }; } TEST(DataURLTest, Parse) { const ParseTestData tests[] = { { "data:", false, "", "", "" }, { "data:,", true, "text/plain", "US-ASCII", "" }, { "data:;base64,", true, "text/plain", "US-ASCII", "" }, { "data:;charset=,test", true, "text/plain", "US-ASCII", "test" }, { "data:TeXt/HtMl,<b>x</b>", true, "text/html", "US-ASCII", "<b>x</b>" }, { "data:,foo", true, "text/plain", "US-ASCII", "foo" }, { "data:;base64,aGVsbG8gd29ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, { "data:foo/bar;baz=1;charset=kk,boo", true, "foo/bar", "kk", "boo" }, { "data:text/html,%3Chtml%3E%3Cbody%3E%3Cb%3Ehello%20world" "%3C%2Fb%3E%3C%2Fbody%3E%3C%2Fhtml%3E", true, "text/html", "US-ASCII", "<html><body><b>hello world</b></body></html>" }, { "data:text/html,<html><body><b>hello world</b></body></html>", true, "text/html", "US-ASCII", "<html><body><b>hello world</b></body></html>" }, // the comma cannot be url-escaped! { "data:%2Cblah", false, "", "", "" }, // invalid base64 content { "data:;base64,aGVs_-_-", false, "", "", "" }, // Spaces should be removed from non-text data URLs (we already tested // spaces above). { "data:image/fractal,a b c d e f g", true, "image/fractal", "US-ASCII", "abcdefg" }, // Spaces should also be removed from anything base-64 encoded { "data:;base64,aGVs bG8gd2 9ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, // Other whitespace should also be removed from anything base-64 encoded. { "data:;base64,aGVs bG8gd2 \n9ybGQ=", true, "text/plain", "US-ASCII", "hello world" }, // In base64 encoding, escaped whitespace should be stripped. // (This test was taken from acid3) // http://b/1054495 { "data:text/javascript;base64,%20ZD%20Qg%0D%0APS%20An%20Zm91cic%0D%0A%207" "%20", true, "text/javascript", "US-ASCII", "d4 = 'four';" }, // Only unescaped whitespace should be stripped in non-base64. // http://b/1157796 { "data:img/png,A B %20 %0A C", true, "img/png", "US-ASCII", "AB \nC" }, // TODO(darin): add more interesting tests }; for (size_t i = 0; i < arraysize(tests); ++i) { std::string mime_type; std::string charset; std::string data; bool ok = net::DataURL::Parse(GURL(tests[i].url), &mime_type, &charset, &data); EXPECT_EQ(ok, tests[i].is_valid); if (tests[i].is_valid) { EXPECT_EQ(tests[i].mime_type, mime_type); EXPECT_EQ(tests[i].charset, charset); EXPECT_EQ(tests[i].data, data); } } } <|endoftext|>
<commit_before>// @(#)root/krb5auth:$Id$ // Author: Maarten Ballintijn 27/10/2003 #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <netinet/in.h> #ifndef WIN32 # include <unistd.h> #endif #include "TKSocket.h" #include "TSocket.h" #include "TError.h" extern "C" { // missing from "krb5.h" extern int krb5_net_read(/*IN*/ krb5_context context, int fd, /*OUT*/ char *buf,/*IN*/ int len); extern int krb5_net_write(/*IN*/ krb5_context context, int fd, const char *buf, int len); } #ifdef __APPLE__ #define SOCKET int #define SOCKET_ERRNO errno #define SOCKET_EINTR EINTR #define SOCKET_READ(a,b,c) read(a,b,c) #define SOCKET_WRITE(a,b,c) write(a,b,c) /* * lib/krb5/os/net_read.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_read() reads from the file descriptor "fd" to the buffer * "buf", until either 1) "len" bytes have been read or 2) cannot * read anymore from "fd". It returns the number of bytes read * or a read() error. (The calling interface is identical to * read(2).) * * XXX must not use non-blocking I/O */ int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len) { int cc, len2 = 0; do { cc = SOCKET_READ((SOCKET)fd, buf, len); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); /* errno is already set */ } else if (cc == 0) { return(len2); } else { buf += cc; len2 += cc; len -= cc; } } while (len > 0); return(len2); } /* * lib/krb5/os/net_write.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_write() writes "len" bytes from "buf" to the file * descriptor "fd". It returns the number of bytes written or * a write() error. (The calling interface is identical to * write(2).) * * XXX must not use non-blocking I/O */ int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len) { int cc; register int wrlen = len; do { cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); } else { buf += cc; wrlen -= cc; } } while (wrlen > 0); return(len); } #endif ClassImp(TKSocket) krb5_context TKSocket::fgContext = 0; krb5_ccache TKSocket::fgCCDef = 0; krb5_principal TKSocket::fgClient = 0; //______________________________________________________________________________ TKSocket::TKSocket(TSocket *s) : fSocket(s), fServer(0), fAuthContext(0) { // Constructor } //______________________________________________________________________________ TKSocket::~TKSocket() { // Destructor krb5_free_principal(fgContext, fServer); krb5_auth_con_free(fgContext, fAuthContext); delete fSocket; } //______________________________________________________________________________ TKSocket *TKSocket::Connect(const char *server, Int_t port) { // Connect to 'server' on 'port' Int_t rc; if (fgContext == 0) { rc = krb5_init_context(&fgContext); if (rc != 0) { ::Error("TKSocket::Connect","while initializing krb5 (%d), %s", rc, error_message(rc)); return 0; } rc = krb5_cc_default(fgContext, &fgCCDef); if (rc != 0) { ::Error("TKSocket::Connect","while getting default credential cache (%d), %s", rc, error_message(rc)); krb5_free_context(fgContext); fgContext = 0; return 0; } rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient); if (rc != 0) { ::Error("TKSocket::Connect","while getting client principal from %s (%d), %s", krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc)); krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0; krb5_free_context(fgContext); fgContext = 0; return 0; } } TSocket *s = new TSocket(server, port); if (!s->IsValid()) { ::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port); delete s; return 0; } TKSocket *ks = new TKSocket(s); rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer); if (rc != 0) { ::Error("TKSocket::Connect","while getting server principal (%d), %s", rc, error_message(rc)); delete ks; return 0; } krb5_data cksum_data; cksum_data.data = StrDup(server); cksum_data.length = strlen(server); krb5_error *err_ret; krb5_ap_rep_enc_part *rep_ret; int sock = ks->fSocket->GetDescriptor(); rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock, (char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer, AP_OPTS_MUTUAL_REQUIRED, &cksum_data, 0, /* no creds, use ccache instead */ fgCCDef, &err_ret, &rep_ret, 0); delete [] cksum_data.data; if (rc != 0) { ::Error("TKSocket::Connect","while sendauth (%d), %s", rc, error_message(rc)); delete ks; return 0; } return ks; } //______________________________________________________________________________ Int_t TKSocket::BlockRead(char *&buf, EEncoding &type) { // Read block on information from server. The result is stored in buf. // The number of read bytes is returned; -1 is returned in case of error. Int_t rc; Desc_t desc; Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading descriptor (%d), %s", rc, error_message(rc)); return -1; } type = static_cast<EEncoding>(ntohs(desc.fType)); krb5_data enc; enc.length = ntohs(desc.fLength); enc.data = new char[enc.length+1]; rc = krb5_net_read(fgContext, fd, enc.data, enc.length); enc.data[enc.length] = 0; if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading data (%d), %s", rc, error_message(rc)); delete [] enc.data; return -1; } krb5_data out; switch (type) { case kNone: buf = enc.data; rc = enc.length; break; case kSafe: rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0); break; case kPriv: rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } if (type != kNone) { // copy data to buffer that is new'ed buf = new char[out.length+1]; memcpy(buf, out.data, out.length); buf[out.length] = 0; free(out.data); delete [] enc.data; rc = out.length; } return rc; } //______________________________________________________________________________ Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type) { // Block-send 'length' bytes to server from 'buf'. Desc_t desc; krb5_data in; krb5_data enc; Int_t rc; in.data = const_cast<char*>(buf); in.length = length; switch (type) { case kNone: enc.data = in.data; enc.length = in.length; break; case kSafe: rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0); break; case kPriv: rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } desc.fLength = htons(enc.length); desc.fType = htons(type); Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc <= 0) { Error("BlockWrite","writing descriptor (%d), %s", rc, error_message(rc)); return -1; } rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length); if (rc <= 0) { Error("BlockWrite","writing data (%d), %s", rc, error_message(rc)); return -1; } if (type != kNone) free(enc.data); return rc; } <commit_msg>Silence warning "register deprecated".<commit_after>// @(#)root/krb5auth:$Id$ // Author: Maarten Ballintijn 27/10/2003 #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <netinet/in.h> #ifndef WIN32 # include <unistd.h> #endif #include "TKSocket.h" #include "TSocket.h" #include "TError.h" extern "C" { // missing from "krb5.h" extern int krb5_net_read(/*IN*/ krb5_context context, int fd, /*OUT*/ char *buf,/*IN*/ int len); extern int krb5_net_write(/*IN*/ krb5_context context, int fd, const char *buf, int len); } #ifdef __APPLE__ #define SOCKET int #define SOCKET_ERRNO errno #define SOCKET_EINTR EINTR #define SOCKET_READ(a,b,c) read(a,b,c) #define SOCKET_WRITE(a,b,c) write(a,b,c) /* * lib/krb5/os/net_read.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_read() reads from the file descriptor "fd" to the buffer * "buf", until either 1) "len" bytes have been read or 2) cannot * read anymore from "fd". It returns the number of bytes read * or a read() error. (The calling interface is identical to * read(2).) * * XXX must not use non-blocking I/O */ int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len) { int cc, len2 = 0; do { cc = SOCKET_READ((SOCKET)fd, buf, len); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); /* errno is already set */ } else if (cc == 0) { return(len2); } else { buf += cc; len2 += cc; len -= cc; } } while (len > 0); return(len2); } /* * lib/krb5/os/net_write.c * * Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology. * All Rights Reserved. * * Export of this software from the United States of America may * require a specific license from the United States Government. * It is the responsibility of any person or organization contemplating * export to obtain such a license before exporting. * * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and * distribute this software and its documentation for any purpose and * without fee is hereby granted, provided that the above copyright * notice appear in all copies and that both that copyright notice and * this permission notice appear in supporting documentation, and that * the name of M.I.T. not be used in advertising or publicity pertaining * to distribution of the software without specific, written prior * permission. Furthermore if you modify this software you must label * your software as modified software and not distribute it in such a * fashion that it might be confused with the original M.I.T. software. * M.I.T. makes no representations about the suitability of * this software for any purpose. It is provided "as is" without express * or implied warranty. * */ /* * krb5_net_write() writes "len" bytes from "buf" to the file * descriptor "fd". It returns the number of bytes written or * a write() error. (The calling interface is identical to * write(2).) * * XXX must not use non-blocking I/O */ int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len) { int cc; int wrlen = len; do { cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen); if (cc < 0) { if (SOCKET_ERRNO == SOCKET_EINTR) continue; /* XXX this interface sucks! */ errno = SOCKET_ERRNO; return(cc); } else { buf += cc; wrlen -= cc; } } while (wrlen > 0); return(len); } #endif ClassImp(TKSocket) krb5_context TKSocket::fgContext = 0; krb5_ccache TKSocket::fgCCDef = 0; krb5_principal TKSocket::fgClient = 0; //______________________________________________________________________________ TKSocket::TKSocket(TSocket *s) : fSocket(s), fServer(0), fAuthContext(0) { // Constructor } //______________________________________________________________________________ TKSocket::~TKSocket() { // Destructor krb5_free_principal(fgContext, fServer); krb5_auth_con_free(fgContext, fAuthContext); delete fSocket; } //______________________________________________________________________________ TKSocket *TKSocket::Connect(const char *server, Int_t port) { // Connect to 'server' on 'port' Int_t rc; if (fgContext == 0) { rc = krb5_init_context(&fgContext); if (rc != 0) { ::Error("TKSocket::Connect","while initializing krb5 (%d), %s", rc, error_message(rc)); return 0; } rc = krb5_cc_default(fgContext, &fgCCDef); if (rc != 0) { ::Error("TKSocket::Connect","while getting default credential cache (%d), %s", rc, error_message(rc)); krb5_free_context(fgContext); fgContext = 0; return 0; } rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient); if (rc != 0) { ::Error("TKSocket::Connect","while getting client principal from %s (%d), %s", krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc)); krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0; krb5_free_context(fgContext); fgContext = 0; return 0; } } TSocket *s = new TSocket(server, port); if (!s->IsValid()) { ::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port); delete s; return 0; } TKSocket *ks = new TKSocket(s); rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer); if (rc != 0) { ::Error("TKSocket::Connect","while getting server principal (%d), %s", rc, error_message(rc)); delete ks; return 0; } krb5_data cksum_data; cksum_data.data = StrDup(server); cksum_data.length = strlen(server); krb5_error *err_ret; krb5_ap_rep_enc_part *rep_ret; int sock = ks->fSocket->GetDescriptor(); rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock, (char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer, AP_OPTS_MUTUAL_REQUIRED, &cksum_data, 0, /* no creds, use ccache instead */ fgCCDef, &err_ret, &rep_ret, 0); delete [] cksum_data.data; if (rc != 0) { ::Error("TKSocket::Connect","while sendauth (%d), %s", rc, error_message(rc)); delete ks; return 0; } return ks; } //______________________________________________________________________________ Int_t TKSocket::BlockRead(char *&buf, EEncoding &type) { // Read block on information from server. The result is stored in buf. // The number of read bytes is returned; -1 is returned in case of error. Int_t rc; Desc_t desc; Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading descriptor (%d), %s", rc, error_message(rc)); return -1; } type = static_cast<EEncoding>(ntohs(desc.fType)); krb5_data enc; enc.length = ntohs(desc.fLength); enc.data = new char[enc.length+1]; rc = krb5_net_read(fgContext, fd, enc.data, enc.length); enc.data[enc.length] = 0; if (rc == 0) errno = ECONNABORTED; if (rc <= 0) { SysError("BlockRead","reading data (%d), %s", rc, error_message(rc)); delete [] enc.data; return -1; } krb5_data out; switch (type) { case kNone: buf = enc.data; rc = enc.length; break; case kSafe: rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0); break; case kPriv: rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } if (type != kNone) { // copy data to buffer that is new'ed buf = new char[out.length+1]; memcpy(buf, out.data, out.length); buf[out.length] = 0; free(out.data); delete [] enc.data; rc = out.length; } return rc; } //______________________________________________________________________________ Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type) { // Block-send 'length' bytes to server from 'buf'. Desc_t desc; krb5_data in; krb5_data enc; Int_t rc; in.data = const_cast<char*>(buf); in.length = length; switch (type) { case kNone: enc.data = in.data; enc.length = in.length; break; case kSafe: rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0); break; case kPriv: rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0); break; default: Error("BlockWrite","unknown encoding type (%d)", type); return -1; } desc.fLength = htons(enc.length); desc.fType = htons(type); Int_t fd = fSocket->GetDescriptor(); rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc)); if (rc <= 0) { Error("BlockWrite","writing descriptor (%d), %s", rc, error_message(rc)); return -1; } rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length); if (rc <= 0) { Error("BlockWrite","writing data (%d), %s", rc, error_message(rc)); return -1; } if (type != kNone) free(enc.data); return rc; } <|endoftext|>
<commit_before>/** * @file llpanelvolumepulldown.cpp * @author Tofu Linden * @brief A floater showing the master volume pull-down * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llpanelvolumepulldown.h" // Viewer libs #include "llviewercontrol.h" #include "llstatusbar.h" // Linden libs #include "llbutton.h" #include "lltabcontainer.h" #include "llfloaterreg.h" #include "llfloaterpreference.h" #include "llsliderctrl.h" /* static */ const F32 LLPanelVolumePulldown::sAutoCloseFadeStartTimeSec = 4.0f; /* static */ const F32 LLPanelVolumePulldown::sAutoCloseTotalTimeSec = 5.0f; ///---------------------------------------------------------------------------- /// Class LLPanelVolumePulldown ///---------------------------------------------------------------------------- // Default constructor LLPanelVolumePulldown::LLPanelVolumePulldown() { mHoverTimer.stop(); mCommitCallbackRegistrar.add("Vol.setControlFalse", boost::bind(&LLPanelVolumePulldown::setControlFalse, this, _2)); mCommitCallbackRegistrar.add("Vol.GoAudioPrefs", boost::bind(&LLPanelVolumePulldown::onAdvancedButtonClick, this, _2)); buildFromFile( "panel_volume_pulldown.xml"); } BOOL LLPanelVolumePulldown::postBuild() { // set the initial volume-slider's position to reflect reality LLSliderCtrl* volslider = getChild<LLSliderCtrl>( "mastervolume" ); volslider->setValue(gSavedSettings.getF32("AudioLevelMaster")); return LLPanel::postBuild(); } /*virtual*/ void LLPanelVolumePulldown::onMouseEnter(S32 x, S32 y, MASK mask) { mHoverTimer.stop(); LLPanel::onMouseEnter(x,y,mask); } /*virtual*/ void LLPanelVolumePulldown::onTopLost() { setVisible(FALSE); } /*virtual*/ void LLPanelVolumePulldown::onMouseLeave(S32 x, S32 y, MASK mask) { mHoverTimer.start(); LLPanel::onMouseLeave(x,y,mask); } /*virtual*/ void LLPanelVolumePulldown::handleVisibilityChange ( BOOL new_visibility ) { if (new_visibility) { mHoverTimer.start(); // timer will be stopped when mouse hovers over panel } else { mHoverTimer.stop(); } } void LLPanelVolumePulldown::onAdvancedButtonClick(const LLSD& user_data) { // close the global volume minicontrol, we're bringing up the big one setVisible(FALSE); // bring up the prefs floater LLFloaterPreference* prefsfloater = dynamic_cast<LLFloaterPreference*> (LLFloaterReg::showInstance("preferences")); if (prefsfloater) { // grab the 'audio' panel from the preferences floater and // bring it the front! LLTabContainer* tabcontainer = prefsfloater->getChild<LLTabContainer>("pref core"); LLPanel* audiopanel = prefsfloater->getChild<LLPanel>("audio"); if (tabcontainer && audiopanel) { tabcontainer->selectTabPanel(audiopanel); } } } void LLPanelVolumePulldown::setControlFalse(const LLSD& user_data) { std::string control_name = user_data.asString(); LLControlVariable* control = findControl(control_name); if (control) control->set(LLSD(FALSE)); } //virtual void LLPanelVolumePulldown::draw() { F32 alpha = mHoverTimer.getStarted() ? clamp_rescale(mHoverTimer.getElapsedTimeF32(), sAutoCloseFadeStartTimeSec, sAutoCloseTotalTimeSec, 1.f, 0.f) : 1.0f; LLViewDrawContext context(alpha); LLPanel::draw(); if (alpha == 0.f) { setVisible(FALSE); } } <commit_msg>Fixed warning "LLView::getChild: Making dummy class LLSliderCtrl named "mastervolume" in volumepulldown_floater"<commit_after>/** * @file llpanelvolumepulldown.cpp * @author Tofu Linden * @brief A floater showing the master volume pull-down * * $LicenseInfo:firstyear=2008&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llpanelvolumepulldown.h" // Viewer libs #include "llviewercontrol.h" #include "llstatusbar.h" // Linden libs #include "llbutton.h" #include "lltabcontainer.h" #include "llfloaterreg.h" #include "llfloaterpreference.h" #include "llsliderctrl.h" /* static */ const F32 LLPanelVolumePulldown::sAutoCloseFadeStartTimeSec = 4.0f; /* static */ const F32 LLPanelVolumePulldown::sAutoCloseTotalTimeSec = 5.0f; ///---------------------------------------------------------------------------- /// Class LLPanelVolumePulldown ///---------------------------------------------------------------------------- // Default constructor LLPanelVolumePulldown::LLPanelVolumePulldown() { mHoverTimer.stop(); mCommitCallbackRegistrar.add("Vol.setControlFalse", boost::bind(&LLPanelVolumePulldown::setControlFalse, this, _2)); mCommitCallbackRegistrar.add("Vol.GoAudioPrefs", boost::bind(&LLPanelVolumePulldown::onAdvancedButtonClick, this, _2)); buildFromFile( "panel_volume_pulldown.xml"); } BOOL LLPanelVolumePulldown::postBuild() { // set the initial volume-slider's position to reflect reality // <FS:Ansariel> Was renamed to "System Volume" //LLSliderCtrl* volslider = getChild<LLSliderCtrl>( "mastervolume" ); LLSliderCtrl* volslider = getChild<LLSliderCtrl>( "System Volume" ); volslider->setValue(gSavedSettings.getF32("AudioLevelMaster")); return LLPanel::postBuild(); } /*virtual*/ void LLPanelVolumePulldown::onMouseEnter(S32 x, S32 y, MASK mask) { mHoverTimer.stop(); LLPanel::onMouseEnter(x,y,mask); } /*virtual*/ void LLPanelVolumePulldown::onTopLost() { setVisible(FALSE); } /*virtual*/ void LLPanelVolumePulldown::onMouseLeave(S32 x, S32 y, MASK mask) { mHoverTimer.start(); LLPanel::onMouseLeave(x,y,mask); } /*virtual*/ void LLPanelVolumePulldown::handleVisibilityChange ( BOOL new_visibility ) { if (new_visibility) { mHoverTimer.start(); // timer will be stopped when mouse hovers over panel } else { mHoverTimer.stop(); } } void LLPanelVolumePulldown::onAdvancedButtonClick(const LLSD& user_data) { // close the global volume minicontrol, we're bringing up the big one setVisible(FALSE); // bring up the prefs floater LLFloaterPreference* prefsfloater = dynamic_cast<LLFloaterPreference*> (LLFloaterReg::showInstance("preferences")); if (prefsfloater) { // grab the 'audio' panel from the preferences floater and // bring it the front! LLTabContainer* tabcontainer = prefsfloater->getChild<LLTabContainer>("pref core"); LLPanel* audiopanel = prefsfloater->getChild<LLPanel>("audio"); if (tabcontainer && audiopanel) { tabcontainer->selectTabPanel(audiopanel); } } } void LLPanelVolumePulldown::setControlFalse(const LLSD& user_data) { std::string control_name = user_data.asString(); LLControlVariable* control = findControl(control_name); if (control) control->set(LLSD(FALSE)); } //virtual void LLPanelVolumePulldown::draw() { F32 alpha = mHoverTimer.getStarted() ? clamp_rescale(mHoverTimer.getElapsedTimeF32(), sAutoCloseFadeStartTimeSec, sAutoCloseTotalTimeSec, 1.f, 0.f) : 1.0f; LLViewDrawContext context(alpha); LLPanel::draw(); if (alpha == 0.f) { setVisible(FALSE); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2008 Princeton University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Niket Agarwal */ #include "mem/ruby/network/garnet/flexible-pipeline/GarnetNetwork.hh" #include "mem/ruby/network/garnet/flexible-pipeline/NetworkLink.hh" NetworkLink::NetworkLink(const Params *p) : SimObject(p) { linkBuffer = new flitBuffer(); m_in_port = 0; m_out_port = 0; m_link_utilized = 0; m_latency = p->link_latency; m_id = p->link_id; int num_net = p->virt_nets; int num_vc = p->vcs_per_vnet; m_vc_load.resize(num_net * num_vc); for (int i = 0; i < num_net * num_vc; i++) m_vc_load[i] = 0; } NetworkLink::~NetworkLink() { delete linkBuffer; } int NetworkLink::get_id() { return m_id; } void NetworkLink::setLinkConsumer(FlexibleConsumer *consumer) { link_consumer = consumer; } void NetworkLink::setSourceQueue(flitBuffer *srcQueue) { link_srcQueue = srcQueue; } void NetworkLink::setSource(FlexibleConsumer *source) { link_source = source; } void NetworkLink::request_vc_link(int vc, NetDest destination, Time request_time) { link_consumer->request_vc(vc, m_in_port, destination, request_time); } bool NetworkLink::isBufferNotFull_link(int vc) { return link_consumer->isBufferNotFull(vc, m_in_port); } void NetworkLink::grant_vc_link(int vc, Time grant_time) { link_source->grant_vc(m_out_port, vc, grant_time); } void NetworkLink::release_vc_link(int vc, Time release_time) { link_source->release_vc(m_out_port, vc, release_time); } std::vector<int> NetworkLink::getVcLoad() { return m_vc_load; } double NetworkLink::getLinkUtilization() { Time m_ruby_start = m_net_ptr->getRubyStartTime(); return (double(m_link_utilized)) / (double(g_eventQueue_ptr->getTime()-m_ruby_start)); } bool NetworkLink::isReady() { return linkBuffer->isReady(); } void NetworkLink::setInPort(int port) { m_in_port = port; } void NetworkLink::setOutPort(int port) { m_out_port = port; } void NetworkLink::wakeup() { if (!link_srcQueue->isReady()) return; flit *t_flit = link_srcQueue->getTopFlit(); t_flit->set_time(g_eventQueue_ptr->getTime() + m_latency); linkBuffer->insert(t_flit); g_eventQueue_ptr->scheduleEvent(link_consumer, m_latency); m_link_utilized++; m_vc_load[t_flit->get_vc()]++; } flit* NetworkLink::peekLink() { return linkBuffer->peekTopFlit(); } flit* NetworkLink::consumeLink() { return linkBuffer->getTopFlit(); } NetworkLink * NetworkLinkParams::create() { return new NetworkLink(this); } <commit_msg>Garnet: Correct computation of link utilization The computation for link utilization was incorrect for the flexible network. The utilization was being divided twice by the total time.<commit_after>/* * Copyright (c) 2008 Princeton University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Niket Agarwal */ #include "mem/ruby/network/garnet/flexible-pipeline/GarnetNetwork.hh" #include "mem/ruby/network/garnet/flexible-pipeline/NetworkLink.hh" NetworkLink::NetworkLink(const Params *p) : SimObject(p) { linkBuffer = new flitBuffer(); m_in_port = 0; m_out_port = 0; m_link_utilized = 0; m_latency = p->link_latency; m_id = p->link_id; int num_net = p->virt_nets; int num_vc = p->vcs_per_vnet; m_vc_load.resize(num_net * num_vc); for (int i = 0; i < num_net * num_vc; i++) m_vc_load[i] = 0; } NetworkLink::~NetworkLink() { delete linkBuffer; } int NetworkLink::get_id() { return m_id; } void NetworkLink::setLinkConsumer(FlexibleConsumer *consumer) { link_consumer = consumer; } void NetworkLink::setSourceQueue(flitBuffer *srcQueue) { link_srcQueue = srcQueue; } void NetworkLink::setSource(FlexibleConsumer *source) { link_source = source; } void NetworkLink::request_vc_link(int vc, NetDest destination, Time request_time) { link_consumer->request_vc(vc, m_in_port, destination, request_time); } bool NetworkLink::isBufferNotFull_link(int vc) { return link_consumer->isBufferNotFull(vc, m_in_port); } void NetworkLink::grant_vc_link(int vc, Time grant_time) { link_source->grant_vc(m_out_port, vc, grant_time); } void NetworkLink::release_vc_link(int vc, Time release_time) { link_source->release_vc(m_out_port, vc, release_time); } std::vector<int> NetworkLink::getVcLoad() { return m_vc_load; } double NetworkLink::getLinkUtilization() { return (double(m_link_utilized)); } bool NetworkLink::isReady() { return linkBuffer->isReady(); } void NetworkLink::setInPort(int port) { m_in_port = port; } void NetworkLink::setOutPort(int port) { m_out_port = port; } void NetworkLink::wakeup() { if (!link_srcQueue->isReady()) return; flit *t_flit = link_srcQueue->getTopFlit(); t_flit->set_time(g_eventQueue_ptr->getTime() + m_latency); linkBuffer->insert(t_flit); g_eventQueue_ptr->scheduleEvent(link_consumer, m_latency); m_link_utilized++; m_vc_load[t_flit->get_vc()]++; } flit* NetworkLink::peekLink() { return linkBuffer->peekTopFlit(); } flit* NetworkLink::consumeLink() { return linkBuffer->getTopFlit(); } NetworkLink * NetworkLinkParams::create() { return new NetworkLink(this); } <|endoftext|>
<commit_before>#include "BasicDemoCameraSystem.hh" #include <ComponentsCore/RigidBody.hpp> #include <ComponentsCore/Collider.hpp> #include <ComponentsCore/CameraComponent.hpp> #include <ComponentsCore/Light.hh> #include <ComponentsCore/MeshRenderer.hh> #include <Components/Lifetime.hpp> #include <Entity/Entity.hh> #include <Entity/EntityData.hh> #include <Core/AScene.hh> #include <SystemsCore/PhysicsSystem.hpp> #include <Physics/RaycasterInterface.hpp> #include <Physics/RaycastHit.hpp> #include <Physics/CharacterControllerInterface.hh> #include <Core/Inputs/Input.hh> #include <SystemsCore/RenderCameraSystem.hpp> #include <imgui/imgui.h> #include <AssetManagement/AssetManager.hh> #include <glm/gtx/quaternion.hpp> #include <glm/gtc/matrix_transform.hpp> namespace AGE { BasicDemoCameraSystem::BasicDemoCameraSystem(AScene *scene) : System(scene), _filter(scene) { } bool BasicDemoCameraSystem::initialize() { _filter.requireComponent<CameraComponent>(); return (true); } void BasicDemoCameraSystem::updateBegin(float time) { } void BasicDemoCameraSystem::mainUpdate(float time) { for (Entity const &entity : _filter.getCollection()) { static float trigger = 1.0f; Joystick controller; auto inputs = _scene->getInstance<Input>(); bool controllerEnabled = inputs->getJoystick(0, controller); if ((inputs->getPhysicalKeyPressed(AgeKeys::AGE_SPACE) || (controllerEnabled && controller.getButtonPressed(AgeJoystickButtons::AGE_JOYSTICK_BUTTON_RIGHTSHOULDER))) && trigger >= 0.15f) { trigger = 0.0f; auto e = _scene->createEntity(); e->addComponent<Lifetime>(15.0f); auto &link = e->getLink(); auto &cameraLink = entity->getLink(); const glm::quat &cameraOrientation = cameraLink.getOrientation(); const glm::vec3 cameraForward = glm::vec3(glm::mat4(glm::toMat4(cameraOrientation) * glm::translate(glm::mat4(1), glm::vec3(0.0f, 0.0f, -1.0f)))[3]); link.setPosition(cameraLink.getPosition() + cameraOrientation * glm::vec3(0, 0, -2)); link.setOrientation(cameraOrientation); link.setScale(glm::vec3(1.0f)); e->addComponent<MeshRenderer>(_scene->getInstance<AGE::AssetsManager>()->getMesh("cube/cube.sage"), _scene->getInstance<AGE::AssetsManager>()->getMaterial(OldFile("cube/cube.mage")))->enableRenderMode(RenderModes::AGE_OPAQUE); e->addComponent<RigidBody>()->addForce(10.0f * cameraForward, Physics::ForceMode::Impulse); e->addComponent<Collider>(Physics::ColliderType::Box); auto pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(float(rand() % 100) / 100.0f, float(rand() % 100) / 100.0f, float(rand() % 100) / 100.0f)); } trigger += time; #if defined(EDITOR_ENABLED) entity->getComponent<CameraComponent>()->editorUpdate(); auto camComponent = entity->getComponent<CameraComponent>(); static char const *pipelineNames[RenderType::TOTAL] = { "Debug deferred rendering", "Deferred rendering" }; if (ImGui::ListBox("Pipelines", &_pipelineIndex, pipelineNames, int(RenderType::TOTAL))) { if (camComponent->getPipeline() != (RenderType)_pipelineIndex) { camComponent->setPipeline((RenderType)_pipelineIndex); _scene->getSystem<RenderCameraSystem>()->drawDebugLines(_pipelineIndex == (int)RenderType::DEBUG_DEFERRED ? true : false); } } #endif } } void BasicDemoCameraSystem::updateEnd(float time) { } } <commit_msg>deferred as default pipeline<commit_after>#include "BasicDemoCameraSystem.hh" #include <ComponentsCore/RigidBody.hpp> #include <ComponentsCore/Collider.hpp> #include <ComponentsCore/CameraComponent.hpp> #include <ComponentsCore/Light.hh> #include <ComponentsCore/MeshRenderer.hh> #include <Components/Lifetime.hpp> #include <Entity/Entity.hh> #include <Entity/EntityData.hh> #include <Core/AScene.hh> #include <SystemsCore/PhysicsSystem.hpp> #include <Physics/RaycasterInterface.hpp> #include <Physics/RaycastHit.hpp> #include <Physics/CharacterControllerInterface.hh> #include <Core/Inputs/Input.hh> #include <SystemsCore/RenderCameraSystem.hpp> #include <imgui/imgui.h> #include <AssetManagement/AssetManager.hh> #include <glm/gtx/quaternion.hpp> #include <glm/gtc/matrix_transform.hpp> namespace AGE { BasicDemoCameraSystem::BasicDemoCameraSystem(AScene *scene) : System(scene), _filter(scene) { } bool BasicDemoCameraSystem::initialize() { _filter.requireComponent<CameraComponent>(); return (true); } void BasicDemoCameraSystem::updateBegin(float time) { } void BasicDemoCameraSystem::mainUpdate(float time) { for (Entity const &entity : _filter.getCollection()) { static float trigger = 1.0f; Joystick controller; auto inputs = _scene->getInstance<Input>(); bool controllerEnabled = inputs->getJoystick(0, controller); if ((inputs->getPhysicalKeyPressed(AgeKeys::AGE_SPACE) || (controllerEnabled && controller.getButtonPressed(AgeJoystickButtons::AGE_JOYSTICK_BUTTON_RIGHTSHOULDER))) && trigger >= 0.15f) { trigger = 0.0f; auto e = _scene->createEntity(); e->addComponent<Lifetime>(15.0f); auto &link = e->getLink(); auto &cameraLink = entity->getLink(); const glm::quat &cameraOrientation = cameraLink.getOrientation(); const glm::vec3 cameraForward = glm::vec3(glm::mat4(glm::toMat4(cameraOrientation) * glm::translate(glm::mat4(1), glm::vec3(0.0f, 0.0f, -1.0f)))[3]); link.setPosition(cameraLink.getPosition() + cameraOrientation * glm::vec3(0, 0, -2)); link.setOrientation(cameraOrientation); link.setScale(glm::vec3(1.0f)); e->addComponent<MeshRenderer>(_scene->getInstance<AGE::AssetsManager>()->getMesh("cube/cube.sage"), _scene->getInstance<AGE::AssetsManager>()->getMaterial(OldFile("cube/cube.mage")))->enableRenderMode(RenderModes::AGE_OPAQUE); e->addComponent<RigidBody>()->addForce(10.0f * cameraForward, Physics::ForceMode::Impulse); e->addComponent<Collider>(Physics::ColliderType::Box); auto pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(float(rand() % 100) / 100.0f, float(rand() % 100) / 100.0f, float(rand() % 100) / 100.0f)); } trigger += time; #if defined(EDITOR_ENABLED) entity->getComponent<CameraComponent>()->editorUpdate(); auto camComponent = entity->getComponent<CameraComponent>(); static char const *pipelineNames[RenderType::TOTAL] = { "Debug deferred rendering", "Deferred rendering" }; ImGui::ListBox("Pipelines", &_pipelineIndex, pipelineNames, int(RenderType::TOTAL)); if (camComponent->getPipeline() != (RenderType)_pipelineIndex) { camComponent->setPipeline((RenderType)_pipelineIndex); _scene->getSystem<RenderCameraSystem>()->drawDebugLines(_pipelineIndex == (int)RenderType::DEBUG_DEFERRED ? true : false); } #endif } } void BasicDemoCameraSystem::updateEnd(float time) { } } <|endoftext|>
<commit_before>/* * Seek camera interface * Author: Maarten Vandersteegen */ #include "SeekCam.h" #include "SeekLogging.h" using namespace LibSeek; SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, cv::Rect roi, std::string ffc_filename) : m_offset(0x4000), m_ffc_filename(ffc_filename), m_is_opened(false), m_dev(vendor_id, product_id), m_raw_data(buffer), m_raw_data_size(raw_height * raw_width), m_raw_frame(raw_height, raw_width, CV_16UC1, buffer, cv::Mat::AUTO_STEP), m_flat_field_calibration_frame(), m_additional_ffc(), m_dead_pixel_mask() { /* set ROI to exclude metadata frame regions */ m_raw_frame = m_raw_frame(roi); } SeekCam::~SeekCam() { close(); } bool SeekCam::open() { if (m_ffc_filename != std::string()) { m_additional_ffc = cv::imread(m_ffc_filename, -1); if (m_additional_ffc.type() != m_raw_frame.type()) { error("Error: '%s' not found or it has the wrong type: %d\n", m_ffc_filename.c_str(), m_additional_ffc.type()); return false; } if (m_additional_ffc.size() != m_raw_frame.size()) { error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n", m_ffc_filename.c_str(), m_raw_frame.cols, m_raw_frame.rows, m_additional_ffc.cols, m_additional_ffc.rows); return false; } } return open_cam(); } void SeekCam::close() { if (m_dev.isOpened()) { std::vector<uint8_t> data = { 0x00, 0x00 }; m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); } m_is_opened = false; } bool SeekCam::isOpened() { return m_is_opened; } bool SeekCam::grab() { int i; for (i=0; i<40; i++) { if(!get_frame()) { error("Error: frame acquisition failed\n"); return false; } if (frame_id() == 3) { return true; } else if (frame_id() == 1) { m_raw_frame.copyTo(m_flat_field_calibration_frame); } } return false; } void SeekCam::retrieve(cv::Mat& dst) { /* apply flat field calibration */ m_raw_frame += m_offset - m_flat_field_calibration_frame; /* filter out dead pixels */ apply_dead_pixel_filter(m_raw_frame, dst); /* apply additional flat field calibration for degradient */ if (!m_additional_ffc.empty()) dst += m_offset - m_additional_ffc; } bool SeekCam::read(cv::Mat& dst) { if (!grab()) return false; retrieve(dst); return true; } void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst) { double tmin, tmax, rsize; double rnint = 0; double rnstart = 0; size_t n; size_t num_of_pixels = src.rows * src.cols; cv::minMaxLoc(src, &tmin, &tmax); rsize = (tmax - tmin) / 10.0; for (n=0; n<10; n++) { double min = tmin + n * rsize; cv::Mat mask; cv::Mat temp; rnstart += rnint; cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask); /* num_of_pixels_in_range / total_num_of_pixels * 256 */ rnint = (cv::countNonZero(mask) << 8) / num_of_pixels; temp = ((src - min) * rnint) / rsize + rnstart; temp.copyTo(dst, mask); } dst.convertTo(dst, CV_8UC1); } bool SeekCam::open_cam() { int i; if (!m_dev.open()) { error("Error: open failed\n"); return false; } /* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */ for (i=0; i<3; i++) { /* cam specific configuration */ if (!init_cam()) { error("Error: init_cam failed\n"); return false; } if (!get_frame()) { error("Error: first frame acquisition failed, retry attempt %d\n", i+1); continue; } if (frame_id() != 4) { error("Error: expected first frame to have id 4\n"); return false; } create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list); if (!grab()) { error("Error: first grab failed\n"); return false; } m_is_opened = true; return true; } error("Error: max init retry count exceeded\n"); return false; } bool SeekCam::get_frame() { /* request new frame */ uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size); std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] }; if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data)) return false; /* store frame data */ if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size)) return false; return true; } void SeekCam::print_usb_data(std::vector<uint8_t>& data) { std::stringstream ss; std::string out; ss << "Response: "; for (size_t i = 0; i < data.size(); i++) { ss << " " << std::hex << data[i]; } out = ss.str(); debug("%s\n", out.c_str()); } void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask, std::vector<cv::Point>& dead_pixel_list) { int x, y; bool has_unlisted_pixels; double max_value; cv::Point hist_max_value; cv::Mat tmp, hist; int channels[] = {0}; int histSize[] = {0x4000}; float range[] = {0, 0x4000}; const float* ranges[] = { range }; /* calculate optimal threshold to determine what pixels are dead pixels */ frame.convertTo(tmp, CV_32FC1); cv::minMaxLoc(tmp, nullptr, &max_value); cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, /* the histogram is uniform */ false); hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest, but we don't want this one */ cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value); const double threshold = hist_max_value.y - (max_value - hist_max_value.y); /* calculate the dead pixels mask */ cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY); tmp.convertTo(dead_pixel_mask, CV_8UC1); /* build dead pixel list in a certain order to assure that every dead pixel value * gets an estimated value in the filter stage */ dead_pixel_mask.convertTo(tmp, CV_16UC1); dead_pixel_list.clear(); do { has_unlisted_pixels = false; for (y=0; y<tmp.rows; y++) { for (x=0; x<tmp.cols; x++) { const cv::Point p(x, y); if (tmp.at<uint16_t>(y, x) != 0) continue; /* not a dead pixel */ /* only add pixel to the list if we can estimate its value * directly from its neighbor pixels */ if (calc_mean_value(tmp, p, 0) != 0) { dead_pixel_list.push_back(p); tmp.at<uint16_t>(y, x) = 255; } else has_unlisted_pixels = true; } } } while (has_unlisted_pixels); } void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst) { size_t i; const size_t size = m_dead_pixel_list.size(); const uint32_t dead_pixel_marker = 0xffff; dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */ dst.setTo(dead_pixel_marker); /* value to identify dead pixels */ src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */ /* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */ for (i=0; i<size; i++) { cv::Point p = m_dead_pixel_list[i]; dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker); } } uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker) { uint32_t value = 0, temp; uint32_t div = 0; const int right_border = img.cols - 1; const int lower_border = img.rows - 1; if (p.x != 0) { /* if not on the left border of the image */ temp = img.at<uint16_t>(p.y, p.x-1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.x != right_border) { /* if not on the right border of the image */ temp = img.at<uint16_t>(p.y, p.x+1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != 0) { /* upper */ temp = img.at<uint16_t>(p.y-1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != lower_border) { /* lower */ temp = img.at<uint16_t>(p.y+1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (div) return (value / div); return 0; } <commit_msg>Fix print_usb_data could print out garbage data<commit_after>/* * Seek camera interface * Author: Maarten Vandersteegen */ #include "SeekCam.h" #include "SeekLogging.h" using namespace LibSeek; SeekCam::SeekCam(int vendor_id, int product_id, uint16_t* buffer, size_t raw_height, size_t raw_width, cv::Rect roi, std::string ffc_filename) : m_offset(0x4000), m_ffc_filename(ffc_filename), m_is_opened(false), m_dev(vendor_id, product_id), m_raw_data(buffer), m_raw_data_size(raw_height * raw_width), m_raw_frame(raw_height, raw_width, CV_16UC1, buffer, cv::Mat::AUTO_STEP), m_flat_field_calibration_frame(), m_additional_ffc(), m_dead_pixel_mask() { /* set ROI to exclude metadata frame regions */ m_raw_frame = m_raw_frame(roi); } SeekCam::~SeekCam() { close(); } bool SeekCam::open() { if (m_ffc_filename != std::string()) { m_additional_ffc = cv::imread(m_ffc_filename, -1); if (m_additional_ffc.type() != m_raw_frame.type()) { error("Error: '%s' not found or it has the wrong type: %d\n", m_ffc_filename.c_str(), m_additional_ffc.type()); return false; } if (m_additional_ffc.size() != m_raw_frame.size()) { error("Error: expected '%s' to have size [%d,%d], got [%d,%d]\n", m_ffc_filename.c_str(), m_raw_frame.cols, m_raw_frame.rows, m_additional_ffc.cols, m_additional_ffc.rows); return false; } } return open_cam(); } void SeekCam::close() { if (m_dev.isOpened()) { std::vector<uint8_t> data = { 0x00, 0x00 }; m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); m_dev.request_set(DeviceCommand::SET_OPERATION_MODE, data); } m_is_opened = false; } bool SeekCam::isOpened() { return m_is_opened; } bool SeekCam::grab() { int i; for (i=0; i<40; i++) { if(!get_frame()) { error("Error: frame acquisition failed\n"); return false; } if (frame_id() == 3) { return true; } else if (frame_id() == 1) { m_raw_frame.copyTo(m_flat_field_calibration_frame); } } return false; } void SeekCam::retrieve(cv::Mat& dst) { /* apply flat field calibration */ m_raw_frame += m_offset - m_flat_field_calibration_frame; /* filter out dead pixels */ apply_dead_pixel_filter(m_raw_frame, dst); /* apply additional flat field calibration for degradient */ if (!m_additional_ffc.empty()) dst += m_offset - m_additional_ffc; } bool SeekCam::read(cv::Mat& dst) { if (!grab()) return false; retrieve(dst); return true; } void SeekCam::convertToGreyScale(cv::Mat& src, cv::Mat& dst) { double tmin, tmax, rsize; double rnint = 0; double rnstart = 0; size_t n; size_t num_of_pixels = src.rows * src.cols; cv::minMaxLoc(src, &tmin, &tmax); rsize = (tmax - tmin) / 10.0; for (n=0; n<10; n++) { double min = tmin + n * rsize; cv::Mat mask; cv::Mat temp; rnstart += rnint; cv::inRange(src, cv::Scalar(min), cv::Scalar(min + rsize), mask); /* num_of_pixels_in_range / total_num_of_pixels * 256 */ rnint = (cv::countNonZero(mask) << 8) / num_of_pixels; temp = ((src - min) * rnint) / rsize + rnstart; temp.copyTo(dst, mask); } dst.convertTo(dst, CV_8UC1); } bool SeekCam::open_cam() { int i; if (!m_dev.open()) { error("Error: open failed\n"); return false; } /* init retry loop: sometimes cam skips first 512 bytes of first frame (needed for dead pixel filter) */ for (i=0; i<3; i++) { /* cam specific configuration */ if (!init_cam()) { error("Error: init_cam failed\n"); return false; } if (!get_frame()) { error("Error: first frame acquisition failed, retry attempt %d\n", i+1); continue; } if (frame_id() != 4) { error("Error: expected first frame to have id 4\n"); return false; } create_dead_pixel_list(m_raw_frame, m_dead_pixel_mask, m_dead_pixel_list); if (!grab()) { error("Error: first grab failed\n"); return false; } m_is_opened = true; return true; } error("Error: max init retry count exceeded\n"); return false; } bool SeekCam::get_frame() { /* request new frame */ uint8_t* s = reinterpret_cast<uint8_t*>(&m_raw_data_size); std::vector<uint8_t> data = { s[0], s[1], s[2], s[3] }; if (!m_dev.request_set(DeviceCommand::START_GET_IMAGE_TRANSFER, data)) return false; /* store frame data */ if (!m_dev.fetch_frame(m_raw_data, m_raw_data_size)) return false; return true; } void SeekCam::print_usb_data(std::vector<uint8_t>& data) { std::stringstream ss; std::string out; ss << "Response: "; for (size_t i = 0; i < data.size(); i++) { ss << " " << std::hex << (int)(unsigned char)data[i]; } out = ss.str(); debug("%s\n", out.c_str()); } void SeekCam::create_dead_pixel_list(cv::Mat frame, cv::Mat& dead_pixel_mask, std::vector<cv::Point>& dead_pixel_list) { int x, y; bool has_unlisted_pixels; double max_value; cv::Point hist_max_value; cv::Mat tmp, hist; int channels[] = {0}; int histSize[] = {0x4000}; float range[] = {0, 0x4000}; const float* ranges[] = { range }; /* calculate optimal threshold to determine what pixels are dead pixels */ frame.convertTo(tmp, CV_32FC1); cv::minMaxLoc(tmp, nullptr, &max_value); cv::calcHist(&tmp, 1, channels, cv::Mat(), hist, 1, histSize, ranges, true, /* the histogram is uniform */ false); hist.at<float>(0, 0) = 0; /* suppres 0th bin since its usual the highest, but we don't want this one */ cv::minMaxLoc(hist, nullptr, nullptr, nullptr, &hist_max_value); const double threshold = hist_max_value.y - (max_value - hist_max_value.y); /* calculate the dead pixels mask */ cv::threshold(tmp, tmp, threshold, 255, cv::THRESH_BINARY); tmp.convertTo(dead_pixel_mask, CV_8UC1); /* build dead pixel list in a certain order to assure that every dead pixel value * gets an estimated value in the filter stage */ dead_pixel_mask.convertTo(tmp, CV_16UC1); dead_pixel_list.clear(); do { has_unlisted_pixels = false; for (y=0; y<tmp.rows; y++) { for (x=0; x<tmp.cols; x++) { const cv::Point p(x, y); if (tmp.at<uint16_t>(y, x) != 0) continue; /* not a dead pixel */ /* only add pixel to the list if we can estimate its value * directly from its neighbor pixels */ if (calc_mean_value(tmp, p, 0) != 0) { dead_pixel_list.push_back(p); tmp.at<uint16_t>(y, x) = 255; } else has_unlisted_pixels = true; } } } while (has_unlisted_pixels); } void SeekCam::apply_dead_pixel_filter(cv::Mat& src, cv::Mat& dst) { size_t i; const size_t size = m_dead_pixel_list.size(); const uint32_t dead_pixel_marker = 0xffff; dst.create(src.rows, src.cols, src.type()); /* ensure dst is properly allocated */ dst.setTo(dead_pixel_marker); /* value to identify dead pixels */ src.copyTo(dst, m_dead_pixel_mask); /* only copy non dead pixel values */ /* replace dead pixel values (0xffff) with the mean of its non dead surrounding pixels */ for (i=0; i<size; i++) { cv::Point p = m_dead_pixel_list[i]; dst.at<uint16_t>(p) = calc_mean_value(dst, p, dead_pixel_marker); } } uint16_t SeekCam::calc_mean_value(cv::Mat& img, cv::Point p, uint32_t dead_pixel_marker) { uint32_t value = 0, temp; uint32_t div = 0; const int right_border = img.cols - 1; const int lower_border = img.rows - 1; if (p.x != 0) { /* if not on the left border of the image */ temp = img.at<uint16_t>(p.y, p.x-1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.x != right_border) { /* if not on the right border of the image */ temp = img.at<uint16_t>(p.y, p.x+1); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != 0) { /* upper */ temp = img.at<uint16_t>(p.y-1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (p.y != lower_border) { /* lower */ temp = img.at<uint16_t>(p.y+1, p.x); if (temp != dead_pixel_marker) { value += temp; div++; } } if (div) return (value / div); return 0; } <|endoftext|>
<commit_before>// CNCPoint.cpp /* * Copyright (c) 2009, Dan Heeks, Perttu Ahola * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "CNCPoint.h" #ifdef HEEKSCAD #include "../interface/HeeksCADInterface.h" extern CHeeksCADInterface heekscad_interface; #else #include "interface/HeeksCADInterface.h" #include "heekscnc/src/Program.h" extern CHeeksCADInterface* heeksCAD; #endif CNCPoint::CNCPoint() : gp_Pnt(0.0, 0.0, 0.0) { } CNCPoint::CNCPoint( const double *xyz ) : gp_Pnt(xyz[0], xyz[1], xyz[2]) { } CNCPoint::CNCPoint( const double &x, const double &y, const double &z ) : gp_Pnt(x,y,z) { } CNCPoint::CNCPoint( const gp_Pnt & rhs ) : gp_Pnt(rhs) { } double CNCPoint::Tolerance() const { #ifdef HEEKSCAD return(heekscad_interface.GetTolerance()); #else return(heeksCAD->GetTolerance()); #endif } double CNCPoint::Units() const { #ifdef HEEKSCAD return(wxGetApp().m_view_units); #else return(theApp.m_program->m_units); #endif } double CNCPoint::X(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::X()); else return(gp_Pnt::X() / Units()); } double CNCPoint::Y(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::Y()); else return(gp_Pnt::Y() / Units()); } double CNCPoint::Z(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::Z()); else return(gp_Pnt::Z() / Units()); } CNCPoint & CNCPoint::operator+= ( const CNCPoint & rhs ) { SetX( X() + rhs.X() ); SetY( Y() + rhs.Y() ); SetZ( Z() + rhs.Z() ); return(*this); } CNCPoint CNCPoint::operator- ( const CNCPoint & rhs ) const { CNCPoint result(*this); result.SetX( X() - rhs.X() ); result.SetY( Y() - rhs.Y() ); result.SetZ( Z() - rhs.Z() ); return(result); } bool CNCPoint::operator==( const CNCPoint & rhs ) const { // We use the sum of both point's tolerance values. return(Distance(rhs) < (Tolerance() + rhs.Tolerance())); } // End equivalence operator bool CNCPoint::operator!=( const CNCPoint & rhs ) const { return(! (*this == rhs)); } // End not-equal operator bool CNCPoint::operator<( const CNCPoint & rhs ) const { if (*this == rhs) return(false); if (fabs(X() - rhs.X()) > Tolerance()) { if (X() > rhs.X()) return(false); if (X() < rhs.X()) return(true); } if (fabs(Y() - rhs.Y()) > Tolerance()) { if (Y() > rhs.Y()) return(false); if (Y() < rhs.Y()) return(true); } if (fabs(Z() - rhs.Z()) > Tolerance()) { if (Z() > rhs.Z()) return(false); if (Z() < rhs.Z()) return(true); } return(false); // They're equal } // End equivalence operator void CNCPoint::ToDoubleArray( double *pArrayOfThree ) const { pArrayOfThree[0] = X(); pArrayOfThree[1] = Y(); pArrayOfThree[2] = Z(); } // End ToDoubleArray() method CNCVector::CNCVector() : gp_Vec(0.0, 0.0, 0.0) { } CNCVector::CNCVector( const double *xyz ) : gp_Vec(xyz[0], xyz[1], xyz[2]) { } CNCVector::CNCVector( const double &x, const double &y, const double &z ) : gp_Vec(x,y,z) { } CNCVector::CNCVector( const gp_Vec & rhs ) : gp_Vec(rhs) { } bool CNCVector::operator==( const CNCVector & rhs ) const { return(this->IsEqual(rhs, Tolerance(), Tolerance()) == Standard_True); } // End equivalence operator bool CNCVector::operator!=( const CNCVector & rhs ) const { return(! (*this == rhs)); } // End not-equal operator bool CNCVector::operator<( const CNCVector & rhs ) const { for (int offset=1; offset <=3; offset++) { if (fabs(Coord(offset) - rhs.Coord(offset)) < Tolerance()) continue; if (Coord(offset) > rhs.Coord(offset)) return(false); if (Coord(offset) < rhs.Coord(offset)) return(true); } return(false); // They're equal } // End equivalence operator double CNCVector::Tolerance() const { #ifdef HEEKSCAD return(heekscad_interface.GetTolerance()); #else return(heeksCAD->GetTolerance()); #endif } <commit_msg>removed #include "heekscnc/src/Program.h" I was able to do this, because: I changed theApp.m_program->m_units to heeksCAD->GetViewUnits(). I think that is probably what was wanted anyway.<commit_after>// CNCPoint.cpp /* * Copyright (c) 2009, Dan Heeks, Perttu Ahola * This program is released under the BSD license. See the file COPYING for * details. */ #include "stdafx.h" #include "CNCPoint.h" #ifdef HEEKSCAD #include "../interface/HeeksCADInterface.h" extern CHeeksCADInterface heekscad_interface; #else #include "interface/HeeksCADInterface.h" extern CHeeksCADInterface* heeksCAD; #endif CNCPoint::CNCPoint() : gp_Pnt(0.0, 0.0, 0.0) { } CNCPoint::CNCPoint( const double *xyz ) : gp_Pnt(xyz[0], xyz[1], xyz[2]) { } CNCPoint::CNCPoint( const double &x, const double &y, const double &z ) : gp_Pnt(x,y,z) { } CNCPoint::CNCPoint( const gp_Pnt & rhs ) : gp_Pnt(rhs) { } double CNCPoint::Tolerance() const { #ifdef HEEKSCAD return(heekscad_interface.GetTolerance()); #else return(heeksCAD->GetTolerance()); #endif } double CNCPoint::Units() const { #ifdef HEEKSCAD return(wxGetApp().m_view_units); #else return heeksCAD->GetViewUnits(); #endif } double CNCPoint::X(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::X()); else return(gp_Pnt::X() / Units()); } double CNCPoint::Y(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::Y()); else return(gp_Pnt::Y() / Units()); } double CNCPoint::Z(const bool in_drawing_units /* = false */) const { if (in_drawing_units == false) return(gp_Pnt::Z()); else return(gp_Pnt::Z() / Units()); } CNCPoint & CNCPoint::operator+= ( const CNCPoint & rhs ) { SetX( X() + rhs.X() ); SetY( Y() + rhs.Y() ); SetZ( Z() + rhs.Z() ); return(*this); } CNCPoint CNCPoint::operator- ( const CNCPoint & rhs ) const { CNCPoint result(*this); result.SetX( X() - rhs.X() ); result.SetY( Y() - rhs.Y() ); result.SetZ( Z() - rhs.Z() ); return(result); } bool CNCPoint::operator==( const CNCPoint & rhs ) const { // We use the sum of both point's tolerance values. return(Distance(rhs) < (Tolerance() + rhs.Tolerance())); } // End equivalence operator bool CNCPoint::operator!=( const CNCPoint & rhs ) const { return(! (*this == rhs)); } // End not-equal operator bool CNCPoint::operator<( const CNCPoint & rhs ) const { if (*this == rhs) return(false); if (fabs(X() - rhs.X()) > Tolerance()) { if (X() > rhs.X()) return(false); if (X() < rhs.X()) return(true); } if (fabs(Y() - rhs.Y()) > Tolerance()) { if (Y() > rhs.Y()) return(false); if (Y() < rhs.Y()) return(true); } if (fabs(Z() - rhs.Z()) > Tolerance()) { if (Z() > rhs.Z()) return(false); if (Z() < rhs.Z()) return(true); } return(false); // They're equal } // End equivalence operator void CNCPoint::ToDoubleArray( double *pArrayOfThree ) const { pArrayOfThree[0] = X(); pArrayOfThree[1] = Y(); pArrayOfThree[2] = Z(); } // End ToDoubleArray() method CNCVector::CNCVector() : gp_Vec(0.0, 0.0, 0.0) { } CNCVector::CNCVector( const double *xyz ) : gp_Vec(xyz[0], xyz[1], xyz[2]) { } CNCVector::CNCVector( const double &x, const double &y, const double &z ) : gp_Vec(x,y,z) { } CNCVector::CNCVector( const gp_Vec & rhs ) : gp_Vec(rhs) { } bool CNCVector::operator==( const CNCVector & rhs ) const { return(this->IsEqual(rhs, Tolerance(), Tolerance()) == Standard_True); } // End equivalence operator bool CNCVector::operator!=( const CNCVector & rhs ) const { return(! (*this == rhs)); } // End not-equal operator bool CNCVector::operator<( const CNCVector & rhs ) const { for (int offset=1; offset <=3; offset++) { if (fabs(Coord(offset) - rhs.Coord(offset)) < Tolerance()) continue; if (Coord(offset) > rhs.Coord(offset)) return(false); if (Coord(offset) < rhs.Coord(offset)) return(true); } return(false); // They're equal } // End equivalence operator double CNCVector::Tolerance() const { #ifdef HEEKSCAD return(heekscad_interface.GetTolerance()); #else return(heeksCAD->GetTolerance()); #endif } <|endoftext|>
<commit_before>#include <boost/interprocess/managed_shared_memory.hpp> #include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> #include <liveMedia.hh> #include <GroupsockHelper.hh> #define EventTime server_EventTime #include <BasicUsageEnvironment.hh> #undef EventTime extern "C" { #include <libavcodec/avcodec.h> } #include "AlloShared/concurrent_queue.h" #include "AlloShared/Cubemap.hpp" #include "AlloShared/Binoculars.hpp" #include "AlloShared/config.h" #include "AlloShared/Process.h" #include "config.h" #include "CubemapFaceSource.h" #include "CubemapExtractionPlugin/CubemapExtractionPlugin.h" #include "AlloServer.h" #include "to_human_readable_byte_count.hpp" struct FrameStreamState { RTPSink* sink; Frame* content; FramedSource* source; }; static UsageEnvironment* env; static struct in_addr destinationAddress; static RTSPServer* rtspServer; static char const* descriptionString = "Session streamed by \"AlloUnity\""; static boost::interprocess::managed_shared_memory* shm; static boost::barrier stopStreamingBarrier(3); static boost::uint16_t rtspPort; static int avgBitRate; // Cubemap related static ServerMediaSession* cubemapSMS; static EventTriggerId addFaceSubstreamsTriggerId; static EventTriggerId removeFaceSubstreamsTriggerId; static std::string cubemapStreamName = "cubemap"; static std::vector<FrameStreamState> faceStreams; // Binoculars related static Binoculars* binoculars = nullptr; static ServerMediaSession* binocularsSMS = NULL; static EventTriggerId addBinularsSubstreamTriggerId; static EventTriggerId removeBinularsSubstreamTriggerId; static std::string binocularsStreamName = "binoculars"; static FrameStreamState binocularsStream; static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms, std::string& name) { char* url = rtspServer->rtspURL(sms); std::cout << "Play " << name << " using the URL \"" << url << "\"" << std::endl; delete[] url; } void addFaceSubstreams0(void*) { if (!cubemapSMS) { cubemapSMS = ServerMediaSession::createNew(*env, cubemapStreamName.c_str(), cubemapStreamName.c_str(), descriptionString, True); rtspServer->addServerMediaSession(cubemapSMS); announceStream(rtspServer, cubemapSMS, cubemapStreamName); } for (int i = 0; i < cubemap->getFacesCount(); i++) { faceStreams.push_back(FrameStreamState()); FrameStreamState* state = &faceStreams.back(); state->content = cubemap->getFace(i)->getContent(); Port rtpPort(FACE0_RTP_PORT_NUM + i); Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, TTL); //rtpGroupsock->multicastSendOnly(); // we're a SSM source // Create a 'H264 Video RTP' sink from the RTP 'groupsock': state->sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96); ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink); cubemapSMS->addSubsession(subsession); state->source = H264VideoStreamDiscreteFramer::createNew(*env, RawPixelSource::createNew(*env, state->content, avgBitRate)); state->sink->startPlaying(*state->source, NULL, NULL); std::cout << "Streaming face " << i << " ..." << std::endl; } } void removeFaceSubstreams0(void*) { if (cubemapSMS) { rtspServer->closeAllClientSessionsForServerMediaSession(cubemapSMS); for (int i = 0; i < faceStreams.size(); i++) { FrameStreamState stream = faceStreams[i]; stream.sink->stopPlaying(); Medium::close(stream.sink); Medium::close(stream.source); std::cout << "removed face " << i << std::endl; } faceStreams.clear(); cubemapSMS->deleteAllSubsessions(); } stopStreamingBarrier.wait(); } void addBinocularsSubstream0(void*) { if (!binocularsSMS) { binocularsSMS = ServerMediaSession::createNew(*env, binocularsStreamName.c_str(), binocularsStreamName.c_str(), descriptionString, True); rtspServer->addServerMediaSession(binocularsSMS); announceStream(rtspServer, binocularsSMS, binocularsStreamName); } binocularsStream.content = binoculars->getContent(); Port rtpPort(BINOCULARS_RTP_PORT_NUM); Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, TTL); //rtpGroupsock->multicastSendOnly(); // we're a SSM source // Create a 'H264 Video RTP' sink from the RTP 'groupsock': binocularsStream.sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96); ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*binocularsStream.sink); binocularsSMS->addSubsession(subsession); binocularsStream.source = H264VideoStreamDiscreteFramer::createNew(*env, RawPixelSource::createNew(*env, binocularsStream.content, avgBitRate)); binocularsStream.sink->startPlaying(*binocularsStream.source, NULL, NULL); std::cout << "Streaming binoculars ..." << std::endl; } void removeBinocularsSubstream0(void*) { if (binocularsSMS) { rtspServer->closeAllClientSessionsForServerMediaSession(binocularsSMS); binocularsStream.sink->stopPlaying(); Medium::close(binocularsStream.sink); Medium::close(binocularsStream.source); std::cout << "removed binoculars" << std::endl; binocularsSMS->deleteAllSubsessions(); } stopStreamingBarrier.wait(); } void networkLoop() { env->taskScheduler().doEventLoop(); // does not return } void setupRTSP() { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); char multicastAddressStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(destinationAddress.s_addr), multicastAddressStr, sizeof(multicastAddressStr)); printf("Multicast address: %s\n", multicastAddressStr); // Create the RTSP server: rtspServer = RTSPServer::createNew(*env, rtspPort, NULL); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; exit(1); } // Set up each of the possible streams that can be served by the // RTSP server. Each such stream is implemented using a // "ServerMediaSession" object, plus one or more // "ServerMediaSubsession" objects for each audio/video substream. OutPacketBuffer::maxSize = 400000000; addFaceSubstreamsTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstreams0); removeFaceSubstreamsTriggerId = env->taskScheduler().createEventTrigger(&removeFaceSubstreams0); addBinularsSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addBinocularsSubstream0); removeBinularsSubstreamTriggerId = env->taskScheduler().createEventTrigger(&removeBinocularsSubstream0); } void startStreaming() { // Open already created shared memory object. // Must have read and write access since we are using mutexes // and locking a mutex is a write operation shm = new boost::interprocess::managed_shared_memory(boost::interprocess::open_only, SHM_NAME); auto cubemapPair = shm->find<Cubemap::Ptr>("Cubemap"); if (cubemapPair.first) { cubemap = cubemapPair.first->get(); env->taskScheduler().triggerEvent(addFaceSubstreamsTriggerId, NULL); } else { cubemap = nullptr; } auto binocularsPair = shm->find<Binoculars::Ptr>("Binoculars"); if (binocularsPair.first) { binoculars = binocularsPair.first->get(); env->taskScheduler().triggerEvent(addBinularsSubstreamTriggerId, NULL); } else { binoculars = nullptr; } } void stopStreaming() { env->taskScheduler().triggerEvent(removeFaceSubstreamsTriggerId, NULL); env->taskScheduler().triggerEvent(removeBinularsSubstreamTriggerId, NULL); stopStreamingBarrier.wait(); delete shm; } int main(int argc, char* argv[]) { boost::program_options::options_description desc(""); desc.add_options() ("multicast-address", boost::program_options::value<std::string>(), "") ("interface", boost::program_options::value<std::string>(), "") ("rtsp-port", boost::program_options::value<boost::uint16_t>(), "") ("avg-bit-rate", boost::program_options::value<int>(), ""); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("interface")) { std::string interfaceAddress = vm["interface"].as<std::string>(); NetAddressList addresses(interfaceAddress.c_str()); if (addresses.numAddresses() == 0) { std::cout << "Failed to find network address for \"" << interfaceAddress << "\"" << std::endl; return -1; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); } char sourceAddressStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ReceivingInterfaceAddr), sourceAddressStr, sizeof(sourceAddressStr)); std::cout << "Using source address " << sourceAddressStr << std::endl; if (vm.count("rtsp-port")) { rtspPort = vm["rtsp-port"].as<boost::uint16_t>(); } else { rtspPort = 8555; } std::cout << "Using RTSP port " << rtspPort << std::endl; // Create 'groupsocks' for RTP and RTCP: if(vm.count("multicast-address")) { inet_pton(AF_INET, vm["multicast-address"].as<std::string>().c_str(), &(destinationAddress.s_addr)); } else { inet_pton(AF_INET, "224.0.0.1", &(destinationAddress.s_addr)); } if (vm.count("avg-bit-rate")) { avgBitRate = vm["avg-bit-rate"].as<int>(); } else { avgBitRate = DEFAULT_AVG_BIT_RATE; } std::string bitRateString = to_human_readable_byte_count(avgBitRate, true, false); std::cout << "Using an average encoding bit rate of " << bitRateString << "/s per face" << std::endl; av_log_set_level(AV_LOG_WARNING); avcodec_register_all(); setupRTSP(); boost::thread networkThread = boost::thread(&networkLoop); Process unityProcess(CUBEMAPEXTRACTIONPLUGIN_ID, false); while (true) { std::cout << "Waiting for Unity ..." << std::endl; unityProcess.waitForBirth(); std::cout << "Connected to Unity :)" << std::endl; startStreaming(); unityProcess.join(); std::cout << "Lost connection to Unity :(" << std::endl; stopStreaming(); } return 0; } <commit_msg>Fixed deadlock in AlloServer<commit_after>#include <boost/interprocess/managed_shared_memory.hpp> #include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> #include <liveMedia.hh> #include <GroupsockHelper.hh> #define EventTime server_EventTime #include <BasicUsageEnvironment.hh> #undef EventTime extern "C" { #include <libavcodec/avcodec.h> } #include "AlloShared/concurrent_queue.h" #include "AlloShared/Cubemap.hpp" #include "AlloShared/Binoculars.hpp" #include "AlloShared/config.h" #include "AlloShared/Process.h" #include "config.h" #include "CubemapFaceSource.h" #include "CubemapExtractionPlugin/CubemapExtractionPlugin.h" #include "AlloServer.h" #include "to_human_readable_byte_count.hpp" struct FrameStreamState { RTPSink* sink; Frame* content; FramedSource* source; }; static UsageEnvironment* env; static struct in_addr destinationAddress; static RTSPServer* rtspServer; static char const* descriptionString = "Session streamed by \"AlloUnity\""; static boost::interprocess::managed_shared_memory* shm; static boost::barrier stopStreamingBarrier(3); static boost::uint16_t rtspPort; static int avgBitRate; // Cubemap related static ServerMediaSession* cubemapSMS; static EventTriggerId addFaceSubstreamsTriggerId; static EventTriggerId removeFaceSubstreamsTriggerId; static std::string cubemapStreamName = "cubemap"; static std::vector<FrameStreamState> faceStreams; // Binoculars related static Binoculars* binoculars = nullptr; static ServerMediaSession* binocularsSMS = NULL; static EventTriggerId addBinularsSubstreamTriggerId; static EventTriggerId removeBinularsSubstreamTriggerId; static std::string binocularsStreamName = "binoculars"; static FrameStreamState binocularsStream; static void announceStream(RTSPServer* rtspServer, ServerMediaSession* sms, std::string& name) { char* url = rtspServer->rtspURL(sms); std::cout << "Play " << name << " using the URL \"" << url << "\"" << std::endl; delete[] url; } void addFaceSubstreams0(void*) { if (!cubemapSMS) { cubemapSMS = ServerMediaSession::createNew(*env, cubemapStreamName.c_str(), cubemapStreamName.c_str(), descriptionString, True); rtspServer->addServerMediaSession(cubemapSMS); announceStream(rtspServer, cubemapSMS, cubemapStreamName); } for (int i = 0; i < cubemap->getFacesCount(); i++) { faceStreams.push_back(FrameStreamState()); FrameStreamState* state = &faceStreams.back(); state->content = cubemap->getFace(i)->getContent(); Port rtpPort(FACE0_RTP_PORT_NUM + i); Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, TTL); //rtpGroupsock->multicastSendOnly(); // we're a SSM source // Create a 'H264 Video RTP' sink from the RTP 'groupsock': state->sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96); ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*state->sink); cubemapSMS->addSubsession(subsession); state->source = H264VideoStreamDiscreteFramer::createNew(*env, RawPixelSource::createNew(*env, state->content, avgBitRate)); state->sink->startPlaying(*state->source, NULL, NULL); std::cout << "Streaming face " << i << " ..." << std::endl; } } void removeFaceSubstreams0(void*) { if (cubemapSMS) { rtspServer->closeAllClientSessionsForServerMediaSession(cubemapSMS); for (int i = 0; i < faceStreams.size(); i++) { FrameStreamState stream = faceStreams[i]; stream.sink->stopPlaying(); Medium::close(stream.sink); Medium::close(stream.source); std::cout << "removed face " << i << std::endl; } faceStreams.clear(); cubemapSMS->deleteAllSubsessions(); } boost::thread(boost::bind(&boost::barrier::wait, &stopStreamingBarrier)); } void addBinocularsSubstream0(void*) { if (!binocularsSMS) { binocularsSMS = ServerMediaSession::createNew(*env, binocularsStreamName.c_str(), binocularsStreamName.c_str(), descriptionString, True); rtspServer->addServerMediaSession(binocularsSMS); announceStream(rtspServer, binocularsSMS, binocularsStreamName); } binocularsStream.content = binoculars->getContent(); Port rtpPort(BINOCULARS_RTP_PORT_NUM); Groupsock* rtpGroupsock = new Groupsock(*env, destinationAddress, rtpPort, TTL); //rtpGroupsock->multicastSendOnly(); // we're a SSM source // Create a 'H264 Video RTP' sink from the RTP 'groupsock': binocularsStream.sink = H264VideoRTPSink::createNew(*env, rtpGroupsock, 96); ServerMediaSubsession* subsession = PassiveServerMediaSubsession::createNew(*binocularsStream.sink); binocularsSMS->addSubsession(subsession); binocularsStream.source = H264VideoStreamDiscreteFramer::createNew(*env, RawPixelSource::createNew(*env, binocularsStream.content, avgBitRate)); binocularsStream.sink->startPlaying(*binocularsStream.source, NULL, NULL); std::cout << "Streaming binoculars ..." << std::endl; } void removeBinocularsSubstream0(void*) { if (binocularsSMS) { rtspServer->closeAllClientSessionsForServerMediaSession(binocularsSMS); binocularsStream.sink->stopPlaying(); Medium::close(binocularsStream.sink); Medium::close(binocularsStream.source); std::cout << "removed binoculars" << std::endl; binocularsSMS->deleteAllSubsessions(); } boost::thread(boost::bind(&boost::barrier::wait, &stopStreamingBarrier)); } void networkLoop() { env->taskScheduler().doEventLoop(); // does not return } void setupRTSP() { // Begin by setting up our usage environment: TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); char multicastAddressStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(destinationAddress.s_addr), multicastAddressStr, sizeof(multicastAddressStr)); printf("Multicast address: %s\n", multicastAddressStr); // Create the RTSP server: rtspServer = RTSPServer::createNew(*env, rtspPort, NULL); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; exit(1); } // Set up each of the possible streams that can be served by the // RTSP server. Each such stream is implemented using a // "ServerMediaSession" object, plus one or more // "ServerMediaSubsession" objects for each audio/video substream. OutPacketBuffer::maxSize = 400000000; addFaceSubstreamsTriggerId = env->taskScheduler().createEventTrigger(&addFaceSubstreams0); removeFaceSubstreamsTriggerId = env->taskScheduler().createEventTrigger(&removeFaceSubstreams0); addBinularsSubstreamTriggerId = env->taskScheduler().createEventTrigger(&addBinocularsSubstream0); removeBinularsSubstreamTriggerId = env->taskScheduler().createEventTrigger(&removeBinocularsSubstream0); } void startStreaming() { // Open already created shared memory object. // Must have read and write access since we are using mutexes // and locking a mutex is a write operation shm = new boost::interprocess::managed_shared_memory(boost::interprocess::open_only, SHM_NAME); auto cubemapPair = shm->find<Cubemap::Ptr>("Cubemap"); if (cubemapPair.first) { cubemap = cubemapPair.first->get(); env->taskScheduler().triggerEvent(addFaceSubstreamsTriggerId, NULL); } else { cubemap = nullptr; } auto binocularsPair = shm->find<Binoculars::Ptr>("Binoculars"); if (binocularsPair.first) { binoculars = binocularsPair.first->get(); env->taskScheduler().triggerEvent(addBinularsSubstreamTriggerId, NULL); } else { binoculars = nullptr; } } void stopStreaming() { env->taskScheduler().triggerEvent(removeFaceSubstreamsTriggerId, NULL); env->taskScheduler().triggerEvent(removeBinularsSubstreamTriggerId, NULL); stopStreamingBarrier.wait(); delete shm; } int main(int argc, char* argv[]) { boost::program_options::options_description desc(""); desc.add_options() ("multicast-address", boost::program_options::value<std::string>(), "") ("interface", boost::program_options::value<std::string>(), "") ("rtsp-port", boost::program_options::value<boost::uint16_t>(), "") ("avg-bit-rate", boost::program_options::value<int>(), ""); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm); boost::program_options::notify(vm); if (vm.count("interface")) { std::string interfaceAddress = vm["interface"].as<std::string>(); NetAddressList addresses(interfaceAddress.c_str()); if (addresses.numAddresses() == 0) { std::cout << "Failed to find network address for \"" << interfaceAddress << "\"" << std::endl; return -1; } ReceivingInterfaceAddr = *(unsigned*)(addresses.firstAddress()->data()); } char sourceAddressStr[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &(ReceivingInterfaceAddr), sourceAddressStr, sizeof(sourceAddressStr)); std::cout << "Using source address " << sourceAddressStr << std::endl; if (vm.count("rtsp-port")) { rtspPort = vm["rtsp-port"].as<boost::uint16_t>(); } else { rtspPort = 8555; } std::cout << "Using RTSP port " << rtspPort << std::endl; // Create 'groupsocks' for RTP and RTCP: if(vm.count("multicast-address")) { inet_pton(AF_INET, vm["multicast-address"].as<std::string>().c_str(), &(destinationAddress.s_addr)); } else { inet_pton(AF_INET, "224.0.0.1", &(destinationAddress.s_addr)); } if (vm.count("avg-bit-rate")) { avgBitRate = vm["avg-bit-rate"].as<int>(); } else { avgBitRate = DEFAULT_AVG_BIT_RATE; } std::string bitRateString = to_human_readable_byte_count(avgBitRate, true, false); std::cout << "Using an average encoding bit rate of " << bitRateString << "/s per face" << std::endl; av_log_set_level(AV_LOG_WARNING); avcodec_register_all(); setupRTSP(); boost::thread networkThread = boost::thread(&networkLoop); Process unityProcess(CUBEMAPEXTRACTIONPLUGIN_ID, false); while (true) { std::cout << "Waiting for Unity ..." << std::endl; unityProcess.waitForBirth(); std::cout << "Connected to Unity :)" << std::endl; startStreaming(); unityProcess.join(); std::cout << "Lost connection to Unity :(" << std::endl; stopStreaming(); } return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "EratBig.h" #include "SieveOfEratosthenes.h" #include "WheelFactorization.h" #include "config.h" #include "bithacks.h" #include <stdint.h> #include <stdexcept> #include <cstdlib> #include <cstring> #include <vector> #include <list> namespace soe { EratBig::EratBig(const SieveOfEratosthenes& soe) : Modulo210Wheel_t(soe), stock_(NULL), log2SieveSize_(floorLog2(soe.getSieveSize())), moduloSieveSize_(soe.getSieveSize() - 1) { // EratBig uses bitwise operations that require a power of 2 sieve size if (!isPowerOf2(soe.getSieveSize())) throw std::invalid_argument("EratBig: sieveSize must be a power of 2 (2^n)."); setSize(soe); initBucketLists(); } EratBig::~EratBig() { for (std::list<Bucket*>::iterator it = pointers_.begin(); it != pointers_.end(); ++it) delete[] *it; } /** * Set the size of the lists_ vector. * @remark The size is a power of 2 value which allows use of fast * bitwise operators in sieve(uint8_t*). */ void EratBig::setSize(const SieveOfEratosthenes& soe) { // max values in sieve(uint8_t*) uint32_t maxSievingPrime = soe.getSquareRoot() / SieveOfEratosthenes::NUMBERS_PER_BYTE; uint32_t maxWheelFactor = wheel(0).nextMultipleFactor; uint32_t maxMultipleOffset = maxSievingPrime * maxWheelFactor + maxWheelFactor; uint32_t maxMultipleIndex = (soe.getSieveSize() - 1) + maxMultipleOffset; uint32_t maxSegmentCount = maxMultipleIndex / soe.getSieveSize(); // size must be >= maxSegmentCount + 1 uint32_t size = nextHighestPowerOf2(maxSegmentCount + 1); moduloListsSize_ = size - 1; lists_.resize(size, NULL); } void EratBig::initBucketLists() { // initialize each bucket list with an empty bucket for (uint32_t i = 0; i < lists_.size(); i++) pushBucket(i); } /** * Add a prime number <= sqrt(n) for sieving to EratBig. */ void EratBig::addSievingPrime(uint32_t prime) { uint32_t multipleIndex; uint32_t wheelIndex; if (getWheelPrimeData(&prime, &multipleIndex, &wheelIndex) == true) { // indicates in how many segments the next multiple // of prime needs to be crossed-off uint32_t segmentCount = multipleIndex >> log2SieveSize_; multipleIndex &= moduloSieveSize_; uint32_t next = segmentCount & moduloListsSize_; // add prime to the bucket list related // to its next multiple occurrence if (!lists_[next]->addWheelPrime(prime, multipleIndex, wheelIndex)) pushBucket(next); } } /** * Add an empty bucket from the bucket stock_ to the * front of lists_[index], if the bucket stock_ is * empty new buckets are allocated first. */ void EratBig::pushBucket(uint32_t index) { if (stock_ == NULL) { Bucket* more = new Bucket[BUCKETS_PER_ALLOC]; stock_ = &more[0]; pointers_.push_back(more); for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++) more[i].setNext(&more[i + 1]); more[BUCKETS_PER_ALLOC - 1].setNext(NULL); } Bucket* bucket = stock_; stock_ = stock_->next(); bucket->setNext(lists_[index]); lists_[index] = bucket; } /** * Implementation of Tomas Oliveira e Silva's cache-friendly segmented * sieve of Eratosthenes algorithm, see: * http://www.ieeta.pt/~tos/software/prime_sieve.html * This algorithm is used to remove the multiples of big sieving * primes (i.e. very few multiples per segment) from the sieve array. * My implementation uses a sieve array with 30 numbers per byte and a * modulo 210 wheel that skips multiples of 2, 3, 5 and 7. * @see SieveOfEratosthenes::crossOffMultiples() */ void EratBig::sieve(uint8_t* sieve) { // lists_[0] contains the list of buckets related to the current // segment i.e. its buckets contain all the sieving primes that have // multiple occurrence(s) in the current segment while (!lists_[0]->isEmpty() || lists_[0]->hasNext()) { Bucket* bucket = lists_[0]; lists_[0] = NULL; pushBucket(0); // each loop iteration processes a bucket i.e. removes the next // multiple of its sieving primes do { const WheelPrime* wPrime = bucket->begin(); const WheelPrime* end = bucket->end(); // For out-of-order CPUs this algorithm can be sped up by // processing 2 sieving primes per loop iteration, this breaks // the dependency chain and reduces pipeline stalls for (; wPrime + 2 <= end; wPrime += 2) { uint32_t multipleIndex0 = wPrime[0].getMultipleIndex(); uint32_t wheelIndex0 = wPrime[0].getWheelIndex(); uint32_t sievingPrime0 = wPrime[0].getSievingPrime(); uint32_t multipleIndex1 = wPrime[1].getMultipleIndex(); uint32_t wheelIndex1 = wPrime[1].getWheelIndex(); uint32_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the current multiple (unset corresponding bit) of // sievingPrime0 and sievingPrime1, calculate their next // multipleIndex and the wheel indexes of their next multiples sieve[multipleIndex0] &= wheel(wheelIndex0).unsetBit; multipleIndex0 += wheel(wheelIndex0).nextMultipleFactor * sievingPrime0; multipleIndex0 += wheel(wheelIndex0).correct; wheelIndex0 += wheel(wheelIndex0).next; sieve[multipleIndex1] &= wheel(wheelIndex1).unsetBit; multipleIndex1 += wheel(wheelIndex1).nextMultipleFactor * sievingPrime1; multipleIndex1 += wheel(wheelIndex1).correct; wheelIndex1 += wheel(wheelIndex1).next; uint32_t next0 = (multipleIndex0 >> log2SieveSize_) & moduloListsSize_; multipleIndex0 &= moduloSieveSize_; uint32_t next1 = (multipleIndex1 >> log2SieveSize_) & moduloListsSize_; multipleIndex1 &= moduloSieveSize_; // move sievingPrime0 and sievingPrime1 to the bucket list // related to their next multiple occurrence if (!lists_[next0]->addWheelPrime(sievingPrime0, multipleIndex0, wheelIndex0)) pushBucket(next0); if (!lists_[next1]->addWheelPrime(sievingPrime1, multipleIndex1, wheelIndex1)) pushBucket(next1); } if (wPrime != end) { uint32_t multipleIndex = wPrime->getMultipleIndex(); uint32_t wheelIndex = wPrime->getWheelIndex(); uint32_t sievingPrime = wPrime->getSievingPrime(); sieve[multipleIndex] &= wheel(wheelIndex).unsetBit; multipleIndex += wheel(wheelIndex).nextMultipleFactor * sievingPrime; multipleIndex += wheel(wheelIndex).correct; wheelIndex += wheel(wheelIndex).next; uint32_t next = (multipleIndex >> log2SieveSize_) & moduloListsSize_; multipleIndex &= moduloSieveSize_; if (!lists_[next]->addWheelPrime(sievingPrime, multipleIndex, wheelIndex)) pushBucket(next); } // reset the processed bucket and move it to the bucket stock_ Bucket* old = bucket; bucket = bucket->next(); old->reset(); old->setNext(stock_); stock_ = old; } while (bucket != NULL); } // lists_[0] has been processed, thus the list related to the next // segment lists_[1] moves to lists_[0] and so on Bucket* tmp = lists_[0]; std::copy(lists_.begin() + 1, lists_.end(), lists_.begin()); lists_.back() = tmp; } } // namespace soe <commit_msg>renamed bithacks.h to popcount.h, some functions moved to imath.h<commit_after>// // Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>. // All rights reserved. // // This file is part of primesieve. // Homepage: http://primesieve.googlecode.com // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the author nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "EratBig.h" #include "SieveOfEratosthenes.h" #include "WheelFactorization.h" #include "config.h" #include "imath.h" #include <stdint.h> #include <stdexcept> #include <cstdlib> #include <cstring> #include <vector> #include <list> namespace soe { EratBig::EratBig(const SieveOfEratosthenes& soe) : Modulo210Wheel_t(soe), stock_(NULL), log2SieveSize_(ilog2(soe.getSieveSize())), moduloSieveSize_(soe.getSieveSize() - 1) { // EratBig uses bitwise operations that require a power of 2 sieve size if (!isPowerOf2(soe.getSieveSize())) throw std::invalid_argument("EratBig: sieveSize must be a power of 2 (2^n)."); setSize(soe); initBucketLists(); } EratBig::~EratBig() { for (std::list<Bucket*>::iterator it = pointers_.begin(); it != pointers_.end(); ++it) delete[] *it; } /** * Set the size of the lists_ vector. * @remark The size is a power of 2 value which allows use of fast * bitwise operators in sieve(uint8_t*). */ void EratBig::setSize(const SieveOfEratosthenes& soe) { // max values in sieve(uint8_t*) uint32_t maxSievingPrime = soe.getSquareRoot() / SieveOfEratosthenes::NUMBERS_PER_BYTE; uint32_t maxWheelFactor = wheel(0).nextMultipleFactor; uint32_t maxMultipleOffset = maxSievingPrime * maxWheelFactor + maxWheelFactor; uint32_t maxMultipleIndex = (soe.getSieveSize() - 1) + maxMultipleOffset; uint32_t maxSegmentCount = maxMultipleIndex / soe.getSieveSize(); // size must be >= maxSegmentCount + 1 uint32_t size = nextPowerOf2(maxSegmentCount + 1); moduloListsSize_ = size - 1; lists_.resize(size, NULL); } void EratBig::initBucketLists() { // initialize each bucket list with an empty bucket for (uint32_t i = 0; i < lists_.size(); i++) pushBucket(i); } /** * Add a prime number <= sqrt(n) for sieving to EratBig. */ void EratBig::addSievingPrime(uint32_t prime) { uint32_t multipleIndex; uint32_t wheelIndex; if (getWheelPrimeData(&prime, &multipleIndex, &wheelIndex) == true) { // indicates in how many segments the next multiple // of prime needs to be crossed-off uint32_t segmentCount = multipleIndex >> log2SieveSize_; multipleIndex &= moduloSieveSize_; uint32_t next = segmentCount & moduloListsSize_; // add prime to the bucket list related // to its next multiple occurrence if (!lists_[next]->addWheelPrime(prime, multipleIndex, wheelIndex)) pushBucket(next); } } /** * Add an empty bucket from the bucket stock_ to the * front of lists_[index], if the bucket stock_ is * empty new buckets are allocated first. */ void EratBig::pushBucket(uint32_t index) { if (stock_ == NULL) { Bucket* more = new Bucket[BUCKETS_PER_ALLOC]; stock_ = &more[0]; pointers_.push_back(more); for(int i = 0; i < BUCKETS_PER_ALLOC - 1; i++) more[i].setNext(&more[i + 1]); more[BUCKETS_PER_ALLOC - 1].setNext(NULL); } Bucket* bucket = stock_; stock_ = stock_->next(); bucket->setNext(lists_[index]); lists_[index] = bucket; } /** * Implementation of Tomas Oliveira e Silva's cache-friendly segmented * sieve of Eratosthenes algorithm, see: * http://www.ieeta.pt/~tos/software/prime_sieve.html * This algorithm is used to remove the multiples of big sieving * primes (i.e. very few multiples per segment) from the sieve array. * My implementation uses a sieve array with 30 numbers per byte and a * modulo 210 wheel that skips multiples of 2, 3, 5 and 7. * @see SieveOfEratosthenes::crossOffMultiples() */ void EratBig::sieve(uint8_t* sieve) { // lists_[0] contains the list of buckets related to the current // segment i.e. its buckets contain all the sieving primes that have // multiple occurrence(s) in the current segment while (!lists_[0]->isEmpty() || lists_[0]->hasNext()) { Bucket* bucket = lists_[0]; lists_[0] = NULL; pushBucket(0); // each loop iteration processes a bucket i.e. removes the next // multiple of its sieving primes do { const WheelPrime* wPrime = bucket->begin(); const WheelPrime* end = bucket->end(); // For out-of-order CPUs this algorithm can be sped up by // processing 2 sieving primes per loop iteration, this breaks // the dependency chain and reduces pipeline stalls for (; wPrime + 2 <= end; wPrime += 2) { uint32_t multipleIndex0 = wPrime[0].getMultipleIndex(); uint32_t wheelIndex0 = wPrime[0].getWheelIndex(); uint32_t sievingPrime0 = wPrime[0].getSievingPrime(); uint32_t multipleIndex1 = wPrime[1].getMultipleIndex(); uint32_t wheelIndex1 = wPrime[1].getWheelIndex(); uint32_t sievingPrime1 = wPrime[1].getSievingPrime(); // cross-off the current multiple (unset corresponding bit) of // sievingPrime0 and sievingPrime1, calculate their next // multipleIndex and the wheel indexes of their next multiples sieve[multipleIndex0] &= wheel(wheelIndex0).unsetBit; multipleIndex0 += wheel(wheelIndex0).nextMultipleFactor * sievingPrime0; multipleIndex0 += wheel(wheelIndex0).correct; wheelIndex0 += wheel(wheelIndex0).next; sieve[multipleIndex1] &= wheel(wheelIndex1).unsetBit; multipleIndex1 += wheel(wheelIndex1).nextMultipleFactor * sievingPrime1; multipleIndex1 += wheel(wheelIndex1).correct; wheelIndex1 += wheel(wheelIndex1).next; uint32_t next0 = (multipleIndex0 >> log2SieveSize_) & moduloListsSize_; multipleIndex0 &= moduloSieveSize_; uint32_t next1 = (multipleIndex1 >> log2SieveSize_) & moduloListsSize_; multipleIndex1 &= moduloSieveSize_; // move sievingPrime0 and sievingPrime1 to the bucket list // related to their next multiple occurrence if (!lists_[next0]->addWheelPrime(sievingPrime0, multipleIndex0, wheelIndex0)) pushBucket(next0); if (!lists_[next1]->addWheelPrime(sievingPrime1, multipleIndex1, wheelIndex1)) pushBucket(next1); } if (wPrime != end) { uint32_t multipleIndex = wPrime->getMultipleIndex(); uint32_t wheelIndex = wPrime->getWheelIndex(); uint32_t sievingPrime = wPrime->getSievingPrime(); sieve[multipleIndex] &= wheel(wheelIndex).unsetBit; multipleIndex += wheel(wheelIndex).nextMultipleFactor * sievingPrime; multipleIndex += wheel(wheelIndex).correct; wheelIndex += wheel(wheelIndex).next; uint32_t next = (multipleIndex >> log2SieveSize_) & moduloListsSize_; multipleIndex &= moduloSieveSize_; if (!lists_[next]->addWheelPrime(sievingPrime, multipleIndex, wheelIndex)) pushBucket(next); } // reset the processed bucket and move it to the bucket stock_ Bucket* old = bucket; bucket = bucket->next(); old->reset(); old->setNext(stock_); stock_ = old; } while (bucket != NULL); } // lists_[0] has been processed, thus the list related to the next // segment lists_[1] moves to lists_[0] and so on Bucket* tmp = lists_[0]; std::copy(lists_.begin() + 1, lists_.end(), lists_.begin()); lists_.back() = tmp; } } // namespace soe <|endoftext|>
<commit_before>// Test that (the same) debug info is emitted for an Objective-C++ // module and a C++ precompiled header. // REQUIRES: asserts, shell // Modules: // RUN: rm -rf %t // RUN: %clang_cc1 -x objective-c++ -std=c++11 -g -fmodules -fmodule-format=obj -fimplicit-module-maps -DMODULES -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t.ll -mllvm -debug-only=pchcontainer &>%t-mod.ll // RUN: cat %t-mod.ll | FileCheck %s // PCH: // RUN: %clang_cc1 -x c++ -std=c++11 -emit-pch -fmodule-format=obj -I %S/Inputs -o %t.pch %S/Inputs/DebugCXX.h -mllvm -debug-only=pchcontainer &>%t-pch.ll // RUN: cat %t-pch.ll | FileCheck %s #ifdef MODULES @import DebugCXX; #endif // CHECK: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus, // CHECK-SAME: isOptimized: false, // CHECK-SAME: splitDebugFilename: // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum" // CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE") // CHECK: !DINamespace(name: "DebugCXX" // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct" // CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<long, DebugCXX::traits<long> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIlNS_6traitsIlEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A<void>" // CHECK-SAME: identifier: "_ZTSN8DebugCXX1AIJvEEE") // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "FloatInstatiation" // no mangled name here yet. // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "B", // no mangled name here yet. <commit_msg>clang/test/Modules/ModuleDebugInfo.cpp: Add -triple %itanium to appease ms-targeted builds.<commit_after>// Test that (the same) debug info is emitted for an Objective-C++ // module and a C++ precompiled header. // REQUIRES: asserts, shell // Modules: // RUN: rm -rf %t // RUN: %clang_cc1 -triple %itanium_abi_triple -x objective-c++ -std=c++11 -g -fmodules -fmodule-format=obj -fimplicit-module-maps -DMODULES -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t.ll -mllvm -debug-only=pchcontainer &>%t-mod.ll // RUN: cat %t-mod.ll | FileCheck %s // PCH: // RUN: %clang_cc1 -triple %itanium_abi_triple -x c++ -std=c++11 -emit-pch -fmodule-format=obj -I %S/Inputs -o %t.pch %S/Inputs/DebugCXX.h -mllvm -debug-only=pchcontainer &>%t-pch.ll // RUN: cat %t-pch.ll | FileCheck %s #ifdef MODULES @import DebugCXX; #endif // CHECK: distinct !DICompileUnit(language: DW_LANG_{{.*}}C_plus_plus, // CHECK-SAME: isOptimized: false, // CHECK-SAME: splitDebugFilename: // CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum" // CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE") // CHECK: !DINamespace(name: "DebugCXX" // CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct" // CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, // CHECK-SAME: name: "Template<long, DebugCXX::traits<long> >" // CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIlNS_6traitsIlEEEE") // CHECK: !DICompositeType(tag: DW_TAG_class_type, name: "A<void>" // CHECK-SAME: identifier: "_ZTSN8DebugCXX1AIJvEEE") // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "FloatInstatiation" // no mangled name here yet. // CHECK: !DIDerivedType(tag: DW_TAG_typedef, name: "B", // no mangled name here yet. <|endoftext|>
<commit_before>//======================================================================== // AppWindow.cpp // // Copyright 2005-2009 Sergey Kazenyuk, All Rights Reserved. // Copyright 2018 Janus // Distributed under the terms of the MIT License. //======================================================================== // $Id: AppWindow.cpp 12 2009-02-02 08:51:09Z sergey.kazenyuk $ // $Rev: 12 $ // $Author: sergey.kazenyuk $ // $Date: 2009-02-02 10:51:09 +0200 (Mon, 02 Feb 2009) $ //======================================================================== #include <Catalog.h> #include <Clipboard.h> #include <FindDirectory.h> #include <IconUtils.h> #include <LayoutBuilder.h> #include <Path.h> #include <Resources.h> #include <Roster.h> #include <SeparatorView.h> #include <string> #include "App.h" #include "AppWindow.h" #define PREFS_FILENAME "Randomizer_settings" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "AppWindow" //==================================================================== void Generator(char* password, const int& num, const char* symbols); //==================================================================== AppWindow::AppWindow(BRect frame) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME(App_Name), B_TITLED_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { PassOut = new BTextControl("PassOut", "", NULL, NULL); PassOut->SetEnabled(false); PassLength = new BSpinner("PassLength", B_TRANSLATE("Password length:"), new BMessage(SEQ_LEN_MSG)); PassLength->SetMinValue(1); PassLength->SetValue(10); UpperCaseCB = new BCheckBox( "UpperCaseCB", B_TRANSLATE("Upper case"), new BMessage(UCASE_CB_MSG)); UpperCaseCB->SetValue(B_CONTROL_ON); LowerCaseCB = new BCheckBox( "LowerCaseCB", B_TRANSLATE("Lower case"), new BMessage(LCASE_CB_MSG)); LowerCaseCB->SetValue(B_CONTROL_ON); NumCB = new BCheckBox( "NumCB", B_TRANSLATE("Numbers"), new BMessage(NUMBERS_CB_MSG)); NumCB->SetValue(B_CONTROL_ON); SpecSymbCB = new BCheckBox( "SpecSymbCB", B_TRANSLATE("Symbols"), new BMessage(SPEC_SYMB_CB_MSG)); // Custom symbols checkbox CustSymbCB = new BCheckBox( "CustSymbCB", B_TRANSLATE("Custom:"), new BMessage(CUST_SYMB_CB_MSG)); // Custom symbols input field CustSymb = new BTextControl("CustSymb", "", NULL, new BMessage(CUST_SYMB_MSG)); CustSymb->SetDivider(0); CustSymb->SetEnabled(false); GenerateBtn = new BButton( "GenBtn", B_TRANSLATE("Generate"), new BMessage(GEN_BTN_MSG)); GenerateBtn->MakeDefault(true); font_height fh; PassOut->GetFontHeight(&fh); const float iconSize = ceilf(fh.ascent) - 2.0; CopyToClipboardBtn = new BButton("CopyToClipboardBtn", "", new BMessage(COPY_BTN_MSG)); CopyToClipboardBtn->SetIcon(ResourceVectorToBitmap("CLIPBOARD", iconSize)); CopyToClipboardBtn->SetToolTip(B_TRANSLATE("Copy to clipboard")); BSeparatorView* separatorPasswordView = new BSeparatorView( "generatedPassword", B_TRANSLATE("Generated password"), B_HORIZONTAL, B_FANCY_BORDER, BAlignment(B_ALIGN_LEFT, B_ALIGN_VERTICAL_CENTER)); BLayoutBuilder::Group<>(this, B_VERTICAL, B_USE_SMALL_SPACING) .Add(BuildMenuBar()) .AddGrid() .SetInsets(B_USE_WINDOW_INSETS, B_USE_HALF_ITEM_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(UpperCaseCB, 0, 0) .Add(LowerCaseCB, 0, 1) .Add(NumCB, 1, 0) .Add(SpecSymbCB, 1, 1) .Add(CustSymbCB, 0, 2) .Add(CustSymb, 1, 2) .Add(PassLength, 0, 3, 2) .End() .Add(separatorPasswordView) .AddGroup(B_VERTICAL) .SetInsets( B_USE_WINDOW_INSETS, 0, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .AddGroup(B_HORIZONTAL, 0) .Add(PassOut) .Add(CopyToClipboardBtn) .End() .AddGroup(B_HORIZONTAL) .AddGlue() .Add(GenerateBtn) .End() .End(); SpecSymbCB->SetToolTip("!@#$%^&*"); CustSymbCB->SetToolTip(B_TRANSLATE("Custom set of characters")); UnarchivePreferences(); GeneratePassword(); } //-------------------------------------------------------------------- bool AppWindow::QuitRequested() { ArchivePreferences(); be_app->PostMessage(B_QUIT_REQUESTED); return true; } //-------------------------------------------------------------------- void AppWindow::MessageReceived(BMessage* message) { #ifdef DEBUG printf("AppWindow::MessageReceived: \n"); message->PrintToStream(); #endif switch (message->what) { case GEN_BTN_MSG: { GeneratePassword(); } break; case COPY_BTN_MSG: { PassOut->TextView()->SelectAll(); PassOut->TextView()->Copy(be_clipboard); } break; case CUST_SYMB_CB_MSG: // Custom symbols checkbox set/unset if (CustSymbCB->Value() == B_CONTROL_ON) CustSymb->SetEnabled(true); else CustSymb->SetEnabled(false); break; case B_ABOUT_REQUESTED: be_app->PostMessage(B_ABOUT_REQUESTED); break; default: BWindow::MessageReceived(message); } } //-------------------------------------------------------------------- BMenuBar* AppWindow::BuildMenuBar() { BMenuBar* menuBar = new BMenuBar("menubar"); BMenu* menu = new BMenu(B_TRANSLATE("App")); menuBar->AddItem(menu); menu->AddItem(new BMenuItem( B_TRANSLATE("About"), new BMessage(B_ABOUT_REQUESTED), 0, 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Copy to clipboard"), new BMessage(COPY_BTN_MSG), 'C', 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED), 'Q', 0)); return menuBar; } void AppWindow::GeneratePassword() { const char en_upsymbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char en_lowsymbols[] = "abcdefghijklmnopqrstuvwxyz"; const char num_symbols[] = "0123456789"; const char spec_symbols[] = "!@#$%^&*"; //<------- PassOut->SetText(""); std::string symbols; if (UpperCaseCB->Value() == B_CONTROL_ON) symbols += en_upsymbols; if (LowerCaseCB->Value() == B_CONTROL_ON) symbols += en_lowsymbols; if (NumCB->Value() == B_CONTROL_ON) symbols += num_symbols; if (SpecSymbCB->Value() == B_CONTROL_ON) symbols += spec_symbols; if (CustSymbCB->Value() == B_CONTROL_ON) symbols += CustSymb->Text(); int pass_length = PassLength->Value(); char* password = new char[pass_length]; Generator(password, pass_length, symbols.c_str()); PassOut->SetText(password); delete[] password; } BBitmap* AppWindow::ResourceVectorToBitmap(const char* resName, float iconSize) { BResources res; size_t size; app_info appInfo; be_app->GetAppInfo(&appInfo); BFile appFile(&appInfo.ref, B_READ_ONLY); res.SetTo(&appFile); BBitmap* aBmp = NULL; const uint8* iconData = (const uint8*) res.LoadResource('VICN', resName, &size); if (size > 0) { aBmp = new BBitmap(BRect(0, 0, iconSize, iconSize), 0, B_RGBA32); status_t result = BIconUtils::GetVectorIcon(iconData, size, aBmp); if (result != B_OK) { delete aBmp; aBmp = NULL; } } return aBmp; } BFile AppWindow::PrefsFile(int32 mode) { BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.SetTo(path.Path(), PREFS_FILENAME); return BFile(path.Path(), mode); } void AppWindow::SavePreferences(BMessage& msg) { BFile file = PrefsFile(B_WRITE_ONLY | B_CREATE_FILE); file.SetSize(0); msg.Flatten(&file); } void AppWindow::LoadPreferences(BMessage& msg) { BFile file = PrefsFile(B_READ_ONLY); msg.Unflatten(&file); } void AppWindow::ArchivePreferences() { BMessage message; message.AddInt32("PassLength", PassLength->Value()); message.AddBool("UpperCaseCB", UpperCaseCB->Value() == B_CONTROL_ON); message.AddBool("LowerCaseCB", LowerCaseCB->Value() == B_CONTROL_ON); message.AddBool("NumCB", NumCB->Value() == B_CONTROL_ON); message.AddBool("SpecSymbCB", SpecSymbCB->Value() == B_CONTROL_ON); message.AddBool("CustSymbCB", CustSymbCB->Value() == B_CONTROL_ON); message.AddString("CustSymb", CustSymb->Text()); SavePreferences(message); } void AppWindow::UnarchivePreferences() { BMessage message; LoadPreferences(message); int32 length; if (message.FindInt32("PassLength", &length) == B_OK) PassLength->SetValue(length); bool controlOn; if (message.FindBool("UpperCaseCB", &controlOn) == B_OK) UpperCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("LowerCaseCB", &controlOn) == B_OK) LowerCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("NumCB", &controlOn) == B_OK) NumCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("SpecSymbCB", &controlOn) == B_OK) SpecSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("CustSymbCB", &controlOn) == B_OK) { CustSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); CustSymb->SetEnabled(controlOn); } BString symbols; if (message.FindString("CustSymb", &symbols) == B_OK) CustSymb->SetText(symbols); } <commit_msg>Tweak layouting<commit_after>//======================================================================== // AppWindow.cpp // // Copyright 2005-2009 Sergey Kazenyuk, All Rights Reserved. // Copyright 2018 Janus // Copyright 2019 Humdinger // Distributed under the terms of the MIT License. //======================================================================== // $Id: AppWindow.cpp 12 2009-02-02 08:51:09Z sergey.kazenyuk $ // $Rev: 12 $ // $Author: sergey.kazenyuk $ // $Date: 2009-02-02 10:51:09 +0200 (Mon, 02 Feb 2009) $ //======================================================================== #include <Catalog.h> #include <Clipboard.h> #include <FindDirectory.h> #include <IconUtils.h> #include <LayoutBuilder.h> #include <Path.h> #include <Resources.h> #include <Roster.h> #include <SeparatorView.h> #include <string> #include "App.h" #include "AppWindow.h" #define PREFS_FILENAME "Randomizer_settings" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "AppWindow" //==================================================================== void Generator(char* password, const int& num, const char* symbols); //==================================================================== AppWindow::AppWindow(BRect frame) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME(App_Name), B_TITLED_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { PassOut = new BTextControl("PassOut", "", NULL, NULL); PassOut->SetEnabled(false); PassLength = new BSpinner("PassLength", B_TRANSLATE("Password length:"), new BMessage(SEQ_LEN_MSG)); PassLength->SetMinValue(1); PassLength->SetValue(10); UpperCaseCB = new BCheckBox( "UpperCaseCB", B_TRANSLATE("Upper case"), new BMessage(UCASE_CB_MSG)); UpperCaseCB->SetValue(B_CONTROL_ON); LowerCaseCB = new BCheckBox( "LowerCaseCB", B_TRANSLATE("Lower case"), new BMessage(LCASE_CB_MSG)); LowerCaseCB->SetValue(B_CONTROL_ON); NumCB = new BCheckBox( "NumCB", B_TRANSLATE("Numbers"), new BMessage(NUMBERS_CB_MSG)); NumCB->SetValue(B_CONTROL_ON); SpecSymbCB = new BCheckBox( "SpecSymbCB", B_TRANSLATE("Symbols"), new BMessage(SPEC_SYMB_CB_MSG)); // Custom symbols checkbox CustSymbCB = new BCheckBox( "CustSymbCB", B_TRANSLATE("Custom:"), new BMessage(CUST_SYMB_CB_MSG)); // Custom symbols input field CustSymb = new BTextControl("CustSymb", "", NULL, new BMessage(CUST_SYMB_MSG)); CustSymb->SetDivider(0); CustSymb->SetEnabled(false); GenerateBtn = new BButton( "GenBtn", B_TRANSLATE("Generate"), new BMessage(GEN_BTN_MSG)); GenerateBtn->MakeDefault(true); font_height fh; PassOut->GetFontHeight(&fh); const float iconSize = ceilf(fh.ascent) - 2.0; CopyToClipboardBtn = new BButton("CopyToClipboardBtn", "", new BMessage(COPY_BTN_MSG)); CopyToClipboardBtn->SetIcon(ResourceVectorToBitmap("CLIPBOARD", iconSize)); CopyToClipboardBtn->SetToolTip(B_TRANSLATE("Copy to clipboard")); BSeparatorView* separatorPasswordView = new BSeparatorView( "generatedPassword", B_TRANSLATE("Generated password"), B_HORIZONTAL, B_FANCY_BORDER, BAlignment(B_ALIGN_CENTER, B_ALIGN_VERTICAL_CENTER)); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .Add(BuildMenuBar()) .AddGrid(B_USE_DEFAULT_SPACING, 0, 1) .SetInsets(B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(UpperCaseCB, 0, 0) .Add(LowerCaseCB, 0, 1) .Add(NumCB, 1, 0) .Add(SpecSymbCB, 1, 1) .Add(CustSymbCB, 0, 2) .Add(CustSymb, 1, 2) .End() .AddGroup(B_HORIZONTAL, 0) .SetInsets( B_USE_WINDOW_INSETS, 0, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(PassLength) .End() .AddStrut(B_USE_DEFAULT_SPACING) .Add(separatorPasswordView) .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING) .SetInsets( B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .AddGroup(B_HORIZONTAL, 0) .Add(PassOut) .Add(CopyToClipboardBtn) .End() .AddGroup(B_HORIZONTAL) .AddGlue() .Add(GenerateBtn) .AddGlue() .End() .End(); SpecSymbCB->SetToolTip("!@#$%^&*"); CustSymbCB->SetToolTip(B_TRANSLATE("Custom set of characters")); UnarchivePreferences(); GeneratePassword(); } //-------------------------------------------------------------------- bool AppWindow::QuitRequested() { ArchivePreferences(); be_app->PostMessage(B_QUIT_REQUESTED); return true; } //-------------------------------------------------------------------- void AppWindow::MessageReceived(BMessage* message) { #ifdef DEBUG printf("AppWindow::MessageReceived: \n"); message->PrintToStream(); #endif switch (message->what) { case GEN_BTN_MSG: { GeneratePassword(); } break; case COPY_BTN_MSG: { PassOut->TextView()->SelectAll(); PassOut->TextView()->Copy(be_clipboard); } break; case CUST_SYMB_CB_MSG: // Custom symbols checkbox set/unset if (CustSymbCB->Value() == B_CONTROL_ON) CustSymb->SetEnabled(true); else CustSymb->SetEnabled(false); break; case B_ABOUT_REQUESTED: be_app->PostMessage(B_ABOUT_REQUESTED); break; default: BWindow::MessageReceived(message); } } //-------------------------------------------------------------------- BMenuBar* AppWindow::BuildMenuBar() { BMenuBar* menuBar = new BMenuBar("menubar"); BMenu* menu = new BMenu(B_TRANSLATE("App")); menuBar->AddItem(menu); menu->AddItem(new BMenuItem( B_TRANSLATE("About"), new BMessage(B_ABOUT_REQUESTED), 0, 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Copy to clipboard"), new BMessage(COPY_BTN_MSG), 'C', 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED), 'Q', 0)); return menuBar; } void AppWindow::GeneratePassword() { const char en_upsymbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char en_lowsymbols[] = "abcdefghijklmnopqrstuvwxyz"; const char num_symbols[] = "0123456789"; const char spec_symbols[] = "!@#$%^&*"; //<------- PassOut->SetText(""); std::string symbols; if (UpperCaseCB->Value() == B_CONTROL_ON) symbols += en_upsymbols; if (LowerCaseCB->Value() == B_CONTROL_ON) symbols += en_lowsymbols; if (NumCB->Value() == B_CONTROL_ON) symbols += num_symbols; if (SpecSymbCB->Value() == B_CONTROL_ON) symbols += spec_symbols; if (CustSymbCB->Value() == B_CONTROL_ON) symbols += CustSymb->Text(); int pass_length = PassLength->Value(); char* password = new char[pass_length]; Generator(password, pass_length, symbols.c_str()); PassOut->SetText(password); delete[] password; } BBitmap* AppWindow::ResourceVectorToBitmap(const char* resName, float iconSize) { BResources res; size_t size; app_info appInfo; be_app->GetAppInfo(&appInfo); BFile appFile(&appInfo.ref, B_READ_ONLY); res.SetTo(&appFile); BBitmap* aBmp = NULL; const uint8* iconData = (const uint8*) res.LoadResource('VICN', resName, &size); if (size > 0) { aBmp = new BBitmap(BRect(0, 0, iconSize, iconSize), 0, B_RGBA32); status_t result = BIconUtils::GetVectorIcon(iconData, size, aBmp); if (result != B_OK) { delete aBmp; aBmp = NULL; } } return aBmp; } BFile AppWindow::PrefsFile(int32 mode) { BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.SetTo(path.Path(), PREFS_FILENAME); return BFile(path.Path(), mode); } void AppWindow::SavePreferences(BMessage& msg) { BFile file = PrefsFile(B_WRITE_ONLY | B_CREATE_FILE); file.SetSize(0); msg.Flatten(&file); } void AppWindow::LoadPreferences(BMessage& msg) { BFile file = PrefsFile(B_READ_ONLY); msg.Unflatten(&file); } void AppWindow::ArchivePreferences() { BMessage message; message.AddInt32("PassLength", PassLength->Value()); message.AddBool("UpperCaseCB", UpperCaseCB->Value() == B_CONTROL_ON); message.AddBool("LowerCaseCB", LowerCaseCB->Value() == B_CONTROL_ON); message.AddBool("NumCB", NumCB->Value() == B_CONTROL_ON); message.AddBool("SpecSymbCB", SpecSymbCB->Value() == B_CONTROL_ON); message.AddBool("CustSymbCB", CustSymbCB->Value() == B_CONTROL_ON); message.AddString("CustSymb", CustSymb->Text()); SavePreferences(message); } void AppWindow::UnarchivePreferences() { BMessage message; LoadPreferences(message); int32 length; if (message.FindInt32("PassLength", &length) == B_OK) PassLength->SetValue(length); bool controlOn; if (message.FindBool("UpperCaseCB", &controlOn) == B_OK) UpperCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("LowerCaseCB", &controlOn) == B_OK) LowerCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("NumCB", &controlOn) == B_OK) NumCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("SpecSymbCB", &controlOn) == B_OK) SpecSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("CustSymbCB", &controlOn) == B_OK) { CustSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); CustSymb->SetEnabled(controlOn); } BString symbols; if (message.FindString("CustSymb", &symbols) == B_OK) CustSymb->SetText(symbols); } <|endoftext|>
<commit_before>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Random.h> #include <atomic> #include <unistd.h> #include <sys/time.h> #include <random> #include <array> #include <glog/logging.h> #include <folly/File.h> #include <folly/FileUtil.h> namespace folly { namespace { void readRandomDevice(void* data, size_t size) { // Keep it open for the duration of the program static File randomDevice("/dev/urandom"); auto bytesRead = readFull(randomDevice.fd(), data, size); PCHECK(bytesRead >= 0 && size_t(bytesRead) == size); } class BufferedRandomDevice { public: static constexpr size_t kDefaultBufferSize = 128; explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize); void get(void* data, size_t size) { if (LIKELY(size <= remaining())) { memcpy(data, ptr_, size); ptr_ += size; } else { getSlow(static_cast<unsigned char*>(data), size); } } private: void getSlow(unsigned char* data, size_t size); inline size_t remaining() const { return buffer_.get() + bufferSize_ - ptr_; } const size_t bufferSize_; std::unique_ptr<unsigned char[]> buffer_; unsigned char* ptr_; }; BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize) : bufferSize_(bufferSize), buffer_(new unsigned char[bufferSize]), ptr_(buffer_.get() + bufferSize) { // refill on first use } void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) { DCHECK_GT(size, remaining()); if (size >= bufferSize_) { // Just read directly. readRandomDevice(data, size); return; } size_t copied = remaining(); memcpy(data, ptr_, copied); data += copied; size -= copied; // refill readRandomDevice(buffer_.get(), bufferSize_); ptr_ = buffer_.get(); memcpy(data, ptr_, size); ptr_ += size; } } // namespace void Random::secureRandom(void* data, size_t size) { static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice; bufferedRandomDevice->get(data, size); } ThreadLocalPRNG::ThreadLocalPRNG() { static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance; local_ = localInstance.get(); } class ThreadLocalPRNG::LocalInstancePRNG { public: LocalInstancePRNG() : rng(Random::create()) { } Random::DefaultGenerator rng; }; uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) { return local->rng(); } } <commit_msg>Fix crashes in readRandomDevice()<commit_after>/* * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/Random.h> #include <atomic> #include <unistd.h> #include <sys/time.h> #include <random> #include <array> #include <glog/logging.h> #include <folly/File.h> #include <folly/FileUtil.h> namespace folly { namespace { void readRandomDevice(void* data, size_t size) { // Keep it open for the duration of the program. Note that we leak the File // to ensure the file is indeed open for the duration of the program. static File& randomDevice = *new File("/dev/urandom"); auto bytesRead = readFull(randomDevice.fd(), data, size); PCHECK(bytesRead >= 0 && size_t(bytesRead) == size); } class BufferedRandomDevice { public: static constexpr size_t kDefaultBufferSize = 128; explicit BufferedRandomDevice(size_t bufferSize = kDefaultBufferSize); void get(void* data, size_t size) { if (LIKELY(size <= remaining())) { memcpy(data, ptr_, size); ptr_ += size; } else { getSlow(static_cast<unsigned char*>(data), size); } } private: void getSlow(unsigned char* data, size_t size); inline size_t remaining() const { return buffer_.get() + bufferSize_ - ptr_; } const size_t bufferSize_; std::unique_ptr<unsigned char[]> buffer_; unsigned char* ptr_; }; BufferedRandomDevice::BufferedRandomDevice(size_t bufferSize) : bufferSize_(bufferSize), buffer_(new unsigned char[bufferSize]), ptr_(buffer_.get() + bufferSize) { // refill on first use } void BufferedRandomDevice::getSlow(unsigned char* data, size_t size) { DCHECK_GT(size, remaining()); if (size >= bufferSize_) { // Just read directly. readRandomDevice(data, size); return; } size_t copied = remaining(); memcpy(data, ptr_, copied); data += copied; size -= copied; // refill readRandomDevice(buffer_.get(), bufferSize_); ptr_ = buffer_.get(); memcpy(data, ptr_, size); ptr_ += size; } } // namespace void Random::secureRandom(void* data, size_t size) { static ThreadLocal<BufferedRandomDevice> bufferedRandomDevice; bufferedRandomDevice->get(data, size); } ThreadLocalPRNG::ThreadLocalPRNG() { static folly::ThreadLocal<ThreadLocalPRNG::LocalInstancePRNG> localInstance; local_ = localInstance.get(); } class ThreadLocalPRNG::LocalInstancePRNG { public: LocalInstancePRNG() : rng(Random::create()) { } Random::DefaultGenerator rng; }; uint32_t ThreadLocalPRNG::getImpl(LocalInstancePRNG* local) { return local->rng(); } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/DeviceFilters/PoseIntegrator.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/DataStructures/DataGroupCopier.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::Vector3d; namespace SurgSim { namespace Device { PoseIntegrator::PoseIntegrator(const std::string& name) : CommonDevice(name), m_poseResult(PoseType::Identity()), m_firstInput(true), m_poseIndex(-1), m_linearVelocityIndex(-1), m_angularVelocityIndex(-1) { } const PoseIntegrator::PoseType& PoseIntegrator::integrate(const PoseType& pose) { // Note: we apply translation and rotation separately. This is NOT the same as (m_poseResult * pose)! m_poseResult.pretranslate(pose.translation()); m_poseResult.rotate(pose.rotation()); return m_poseResult; } bool PoseIntegrator::initialize() { return true; } bool PoseIntegrator::finalize() { return true; } void PoseIntegrator::initializeInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) { if (m_firstInput) { m_firstInput = false; if (!inputData.vectors().hasEntry(SurgSim::DataStructures::Names::LINEAR_VELOCITY) || !inputData.vectors().hasEntry(SurgSim::DataStructures::Names::ANGULAR_VELOCITY)) { SurgSim::DataStructures::DataGroupBuilder builder; builder.addEntriesFrom(inputData); builder.addVector(SurgSim::DataStructures::Names::LINEAR_VELOCITY); builder.addVector(SurgSim::DataStructures::Names::ANGULAR_VELOCITY); getInitialInputData() = builder.createData(); getInputData() = getInitialInputData(); m_copier = std::make_shared<SurgSim::DataStructures::DataGroupCopier>(inputData, getInputData()); } } if (m_copier == nullptr) { getInputData() = inputData; } else { m_copier->copy(); } getInitialInputData() = getInputData(); m_poseIndex = inputData.poses().getIndex(SurgSim::DataStructures::Names::POSE); m_linearVelocityIndex = getInputData().vectors().getIndex(SurgSim::DataStructures::Names::LINEAR_VELOCITY); m_angularVelocityIndex = getInputData().vectors().getIndex(SurgSim::DataStructures::Names::ANGULAR_VELOCITY); SurgSim::Math::RigidTransform3d pose; if (inputData.poses().get(SurgSim::DataStructures::Names::POSE, &pose)) { m_poseResult = pose; } } void PoseIntegrator::handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) { if (m_copier == nullptr) { getInputData() = inputData; } else { m_copier->copy(); } if (m_poseIndex >= 0) { SurgSim::Math::RigidTransform3d pose; if (inputData.poses().get(m_poseIndex, &pose)) { m_timer.markFrame(); double rate = m_timer.getAverageFrameRate(); if (m_timer.getNumberOfClockFails() > 0) { m_timer.start(); rate = 0.0; } // Before updating the current pose, use it to calculate the angular velocity. Vector3d rotationAxis; double angle; SurgSim::Math::computeAngleAndAxis(pose.rotation(), &angle, &rotationAxis); rotationAxis = m_poseResult.rotation() * rotationAxis; // rotate the axis into global space // The angular and linear indices must exist because the entries were added in initializeInput. getInputData().vectors().set(m_angularVelocityIndex, rotationAxis * angle * rate); getInputData().poses().set(m_poseIndex, integrate(pose)); getInputData().vectors().set(m_linearVelocityIndex, pose.translation() * rate); } } pushInput(); } bool PoseIntegrator::requestOutput(const std::string& device, SurgSim::DataStructures::DataGroup* outputData) { bool state = pullOutput(); if (state) { *outputData = getOutputData(); } return state; } }; // namespace Device }; // namespace SurgSim <commit_msg>PoseIntegrator logs clock fails with Debug level.<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Devices/DeviceFilters/PoseIntegrator.h" #include "SurgSim/DataStructures/DataGroupBuilder.h" #include "SurgSim/DataStructures/DataGroupCopier.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Matrix.h" #include "SurgSim/Math/Vector.h" using SurgSim::Math::Vector3d; namespace SurgSim { namespace Device { PoseIntegrator::PoseIntegrator(const std::string& name) : CommonDevice(name), m_poseResult(PoseType::Identity()), m_firstInput(true), m_poseIndex(-1), m_linearVelocityIndex(-1), m_angularVelocityIndex(-1) { } const PoseIntegrator::PoseType& PoseIntegrator::integrate(const PoseType& pose) { // Note: we apply translation and rotation separately. This is NOT the same as (m_poseResult * pose)! m_poseResult.pretranslate(pose.translation()); m_poseResult.rotate(pose.rotation()); return m_poseResult; } bool PoseIntegrator::initialize() { return true; } bool PoseIntegrator::finalize() { return true; } void PoseIntegrator::initializeInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) { if (m_firstInput) { m_firstInput = false; if (!inputData.vectors().hasEntry(SurgSim::DataStructures::Names::LINEAR_VELOCITY) || !inputData.vectors().hasEntry(SurgSim::DataStructures::Names::ANGULAR_VELOCITY)) { SurgSim::DataStructures::DataGroupBuilder builder; builder.addEntriesFrom(inputData); builder.addVector(SurgSim::DataStructures::Names::LINEAR_VELOCITY); builder.addVector(SurgSim::DataStructures::Names::ANGULAR_VELOCITY); getInitialInputData() = builder.createData(); getInputData() = getInitialInputData(); m_copier = std::make_shared<SurgSim::DataStructures::DataGroupCopier>(inputData, getInputData()); } } if (m_copier == nullptr) { getInputData() = inputData; } else { m_copier->copy(); } getInitialInputData() = getInputData(); m_poseIndex = inputData.poses().getIndex(SurgSim::DataStructures::Names::POSE); m_linearVelocityIndex = getInputData().vectors().getIndex(SurgSim::DataStructures::Names::LINEAR_VELOCITY); m_angularVelocityIndex = getInputData().vectors().getIndex(SurgSim::DataStructures::Names::ANGULAR_VELOCITY); SurgSim::Math::RigidTransform3d pose; if (inputData.poses().get(SurgSim::DataStructures::Names::POSE, &pose)) { m_poseResult = pose; } } void PoseIntegrator::handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) { if (m_copier == nullptr) { getInputData() = inputData; } else { m_copier->copy(); } if (m_poseIndex >= 0) { SurgSim::Math::RigidTransform3d pose; if (inputData.poses().get(m_poseIndex, &pose)) { m_timer.markFrame(); double rate = m_timer.getAverageFrameRate(); if (m_timer.getNumberOfClockFails() > 0) { m_timer.start(); rate = 0.0; SURGSIM_LOG_DEBUG(SurgSim::Framework::Logger::getLogger("Devices/Filters/PoseIntegrator")) << "The Timer used by " << getName() << " had a clock fail. The calculated velocities will be zero this update."; } // Before updating the current pose, use it to calculate the angular velocity. Vector3d rotationAxis; double angle; SurgSim::Math::computeAngleAndAxis(pose.rotation(), &angle, &rotationAxis); rotationAxis = m_poseResult.rotation() * rotationAxis; // rotate the axis into global space // The angular and linear indices must exist because the entries were added in initializeInput. getInputData().vectors().set(m_angularVelocityIndex, rotationAxis * angle * rate); getInputData().poses().set(m_poseIndex, integrate(pose)); getInputData().vectors().set(m_linearVelocityIndex, pose.translation() * rate); } } pushInput(); } bool PoseIntegrator::requestOutput(const std::string& device, SurgSim::DataStructures::DataGroup* outputData) { bool state = pullOutput(); if (state) { *outputData = getOutputData(); } return state; } }; // namespace Device }; // namespace SurgSim <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qmlprojectrunconfiguration.h" #include "qmlproject.h" #include "qmlprojectmanagerconstants.h" #include "qmlprojectrunconfigurationwidget.h" #include <coreplugin/mimedatabase.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <utils/qtcprocess.h> #include <qt4projectmanager/qtversionmanager.h> #include <qt4projectmanager/qtoutputformatter.h> #include <qt4projectmanager/qt4projectmanagerconstants.h> #ifdef Q_OS_WIN32 #include <utils/winutils.h> #endif using Core::EditorManager; using Core::ICore; using Core::IEditor; using Qt4ProjectManager::QtVersionManager; using namespace QmlProjectManager::Internal; namespace QmlProjectManager { const char * const M_CURRENT_FILE = "CurrentFile"; QmlProjectRunConfiguration::QmlProjectRunConfiguration(QmlProjectTarget *parent) : ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)), m_qtVersionId(-1), m_projectTarget(parent), m_usingCurrentFile(true), m_isEnabled(false) { ctor(); updateQtVersions(); } QmlProjectRunConfiguration::QmlProjectRunConfiguration(QmlProjectTarget *parent, QmlProjectRunConfiguration *source) : ProjectExplorer::RunConfiguration(parent, source), m_qtVersionId(source->m_qtVersionId), m_scriptFile(source->m_scriptFile), m_qmlViewerArgs(source->m_qmlViewerArgs), m_projectTarget(parent), m_usingCurrentFile(source->m_usingCurrentFile), m_userEnvironmentChanges(source->m_userEnvironmentChanges) { ctor(); updateQtVersions(); } bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const { Q_UNUSED(bc); return m_isEnabled; } void QmlProjectRunConfiguration::ctor() { // reset default settings in constructor setUseCppDebugger(false); setUseQmlDebugger(true); EditorManager *em = Core::EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), this, SLOT(changeCurrentFile(Core::IEditor*))); QtVersionManager *qtVersions = QtVersionManager::instance(); connect(qtVersions, SIGNAL(qtVersionsChanged(QList<int>)), this, SLOT(updateQtVersions())); setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name.")); } QmlProjectRunConfiguration::~QmlProjectRunConfiguration() { } QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const { return static_cast<QmlProjectTarget *>(target()); } QString QmlProjectRunConfiguration::viewerPath() const { Qt4ProjectManager::QtVersion *version = qtVersion(); if (!version) { return QString(); } else { return version->qmlviewerCommand(); } } QString QmlProjectRunConfiguration::observerPath() const { Qt4ProjectManager::QtVersion *version = qtVersion(); if (!version) { return QString(); } else { return version->qmlObserverTool(); } } QString QmlProjectRunConfiguration::viewerArguments() const { // arguments in .user file QString args = m_qmlViewerArgs; // arguments from .qmlproject file foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) { Utils::QtcProcess::addArg(&args, "-I"); Utils::QtcProcess::addArg(&args, importPath); } QString s = mainScript(); if (!s.isEmpty()) { s = canonicalCapsPath(s); Utils::QtcProcess::addArg(&args, s); } return args; } QString QmlProjectRunConfiguration::workingDirectory() const { QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName()); return canonicalCapsPath(projectFile.absolutePath()); } int QmlProjectRunConfiguration::qtVersionId() const { return m_qtVersionId; } void QmlProjectRunConfiguration::setQtVersionId(int id) { if (m_qtVersionId == id) return; m_qtVersionId = id; qmlTarget()->qmlProject()->refresh(QmlProject::Configuration); if (m_configurationWidget) m_configurationWidget.data()->updateQtVersionComboBox(); } /* QtDeclarative checks explicitly that the capitalization for any URL / path is exactly like the capitalization on disk. This method is uses the same native Windows API's to get the exact canonical path. */ QString QmlProjectRunConfiguration::canonicalCapsPath(const QString &fileName) { QString canonicalPath = QFileInfo(fileName).canonicalFilePath(); #if defined(Q_OS_WIN32) QString error; // don't know whether the shortpath step is really needed, // but we do this in QtDeclarative too. QString path = Utils::getShortPathName(canonicalPath, &error); if (!path.isEmpty()) path = Utils::getLongPathName(canonicalPath, &error); if (!path.isEmpty()) canonicalPath = path; #endif return canonicalPath; } Qt4ProjectManager::QtVersion *QmlProjectRunConfiguration::qtVersion() const { if (m_qtVersionId == -1) return 0; QtVersionManager *versionManager = QtVersionManager::instance(); Qt4ProjectManager::QtVersion *version = versionManager->version(m_qtVersionId); QTC_ASSERT(version, return 0); return version; } QWidget *QmlProjectRunConfiguration::createConfigurationWidget() { QTC_ASSERT(m_configurationWidget.isNull(), return m_configurationWidget.data()); m_configurationWidget = new QmlProjectRunConfigurationWidget(this); return m_configurationWidget.data(); } ProjectExplorer::OutputFormatter *QmlProjectRunConfiguration::createOutputFormatter() const { return new Qt4ProjectManager::QtOutputFormatter(qmlTarget()->qmlProject()); } QmlProjectRunConfiguration::MainScriptSource QmlProjectRunConfiguration::mainScriptSource() const { if (m_usingCurrentFile) { return FileInEditor; } if (!m_mainScriptFilename.isEmpty()) { return FileInSettings; } return FileInProjectFile; } /** Returns absolute path to main script file. */ QString QmlProjectRunConfiguration::mainScript() const { if (m_usingCurrentFile) { return m_currentFileFilename; } if (!m_mainScriptFilename.isEmpty()) { return m_mainScriptFilename; } QString path = qmlTarget()->qmlProject()->mainFile(); if (QFileInfo(path).isAbsolute()) { return path; } else { return qmlTarget()->qmlProject()->projectDir().absoluteFilePath(path); } } void QmlProjectRunConfiguration::setScriptSource(MainScriptSource source, const QString &settingsPath) { if (source == FileInEditor) { m_scriptFile = M_CURRENT_FILE; m_mainScriptFilename.clear(); m_usingCurrentFile = true; } else if (source == FileInProjectFile) { m_scriptFile.clear(); m_mainScriptFilename.clear(); m_usingCurrentFile = false; } else { // FileInSettings m_scriptFile = settingsPath; m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(m_scriptFile); m_usingCurrentFile = false; } updateEnabled(); if (m_configurationWidget) m_configurationWidget.data()->updateFileComboBox(); } Utils::Environment QmlProjectRunConfiguration::environment() const { Utils::Environment env = baseEnvironment(); env.modify(userEnvironmentChanges()); return env; } QVariantMap QmlProjectRunConfiguration::toMap() const { QVariantMap map(ProjectExplorer::RunConfiguration::toMap()); map.insert(QLatin1String(Constants::QML_VIEWER_QT_KEY), m_qtVersionId); map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs); map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile); map.insert(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges)); return map; } bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map) { setQtVersionId(map.value(QLatin1String(Constants::QML_VIEWER_QT_KEY), -1).toInt()); m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString(); m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString(); m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList( map.value(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY)).toStringList()); updateQtVersions(); if (m_scriptFile == M_CURRENT_FILE) { setScriptSource(FileInEditor); } else if (m_scriptFile.isEmpty()) { setScriptSource(FileInProjectFile); } else { setScriptSource(FileInSettings, m_scriptFile); } return RunConfiguration::fromMap(map); } void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor * /*editor*/) { updateEnabled(); } void QmlProjectRunConfiguration::updateEnabled() { bool qmlFileFound = false; if (m_usingCurrentFile) { Core::IEditor *editor = Core::EditorManager::instance()->currentEditor(); Core::MimeDatabase *db = ICore::instance()->mimeDatabase(); if (editor) { m_currentFileFilename = editor->file()->fileName(); if (db->findByFile(mainScript()).type() == QLatin1String("application/x-qml")) qmlFileFound = true; } if (!editor || db->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) { // find a qml file with lowercase filename. This is slow, but only done // in initialization/other border cases. foreach(const QString &filename, m_projectTarget->qmlProject()->files()) { const QFileInfo fi(filename); if (!filename.isEmpty() && fi.baseName()[0].isLower() && db->findByFile(fi).type() == QLatin1String("application/x-qml")) { m_currentFileFilename = filename; qmlFileFound = true; break; } } } } else { // use default one qmlFileFound = !mainScript().isEmpty(); } bool newValue = (QFileInfo(viewerPath()).exists() || QFileInfo(observerPath()).exists()) && qmlFileFound; // Always emit change signal to force reevaluation of run/debug buttons m_isEnabled = newValue; emit isEnabledChanged(m_isEnabled); } void QmlProjectRunConfiguration::updateQtVersions() { QtVersionManager *qtVersions = QtVersionManager::instance(); // // update m_qtVersionId // if (!qtVersions->isValidId(m_qtVersionId) || !isValidVersion(qtVersions->version(m_qtVersionId))) { int newVersionId = -1; // take first one you find foreach (Qt4ProjectManager::QtVersion *version, qtVersions->validVersions()) { if (isValidVersion(version)) { newVersionId = version->uniqueId(); break; } } setQtVersionId(newVersionId); } updateEnabled(); } bool QmlProjectRunConfiguration::isValidVersion(Qt4ProjectManager::QtVersion *version) { if (version && (version->supportsTargetId(Qt4ProjectManager::Constants::DESKTOP_TARGET_ID) || version->supportsTargetId(Qt4ProjectManager::Constants::QT_SIMULATOR_TARGET_ID)) && !version->qmlviewerCommand().isEmpty()) { return true; } return false; } Utils::Environment QmlProjectRunConfiguration::baseEnvironment() const { Utils::Environment env; if (qtVersion()) env = qtVersion()->qmlToolsEnvironment(); return env; } void QmlProjectRunConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff) { if (m_userEnvironmentChanges != diff) { m_userEnvironmentChanges = diff; if (m_configurationWidget) m_configurationWidget.data()->userEnvironmentChangesChanged(); } } QList<Utils::EnvironmentItem> QmlProjectRunConfiguration::userEnvironmentChanges() const { return m_userEnvironmentChanges; } } // namespace QmlProjectManager <commit_msg>QmlProject: Fix issue where qmlviewer is launched with directory as argument<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qmlprojectrunconfiguration.h" #include "qmlproject.h" #include "qmlprojectmanagerconstants.h" #include "qmlprojectrunconfigurationwidget.h" #include <coreplugin/mimedatabase.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> #include <utils/qtcassert.h> #include <utils/qtcprocess.h> #include <qt4projectmanager/qtversionmanager.h> #include <qt4projectmanager/qtoutputformatter.h> #include <qt4projectmanager/qt4projectmanagerconstants.h> #ifdef Q_OS_WIN32 #include <utils/winutils.h> #endif using Core::EditorManager; using Core::ICore; using Core::IEditor; using Qt4ProjectManager::QtVersionManager; using namespace QmlProjectManager::Internal; namespace QmlProjectManager { const char * const M_CURRENT_FILE = "CurrentFile"; QmlProjectRunConfiguration::QmlProjectRunConfiguration(QmlProjectTarget *parent) : ProjectExplorer::RunConfiguration(parent, QLatin1String(Constants::QML_RC_ID)), m_qtVersionId(-1), m_scriptFile(M_CURRENT_FILE), m_projectTarget(parent), m_usingCurrentFile(true), m_isEnabled(false) { ctor(); updateQtVersions(); } QmlProjectRunConfiguration::QmlProjectRunConfiguration(QmlProjectTarget *parent, QmlProjectRunConfiguration *source) : ProjectExplorer::RunConfiguration(parent, source), m_qtVersionId(source->m_qtVersionId), m_scriptFile(source->m_scriptFile), m_qmlViewerArgs(source->m_qmlViewerArgs), m_projectTarget(parent), m_usingCurrentFile(source->m_usingCurrentFile), m_userEnvironmentChanges(source->m_userEnvironmentChanges) { ctor(); updateQtVersions(); } bool QmlProjectRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *bc) const { Q_UNUSED(bc); return m_isEnabled; } void QmlProjectRunConfiguration::ctor() { // reset default settings in constructor setUseCppDebugger(false); setUseQmlDebugger(true); EditorManager *em = Core::EditorManager::instance(); connect(em, SIGNAL(currentEditorChanged(Core::IEditor*)), this, SLOT(changeCurrentFile(Core::IEditor*))); QtVersionManager *qtVersions = QtVersionManager::instance(); connect(qtVersions, SIGNAL(qtVersionsChanged(QList<int>)), this, SLOT(updateQtVersions())); setDisplayName(tr("QML Viewer", "QMLRunConfiguration display name.")); } QmlProjectRunConfiguration::~QmlProjectRunConfiguration() { } QmlProjectTarget *QmlProjectRunConfiguration::qmlTarget() const { return static_cast<QmlProjectTarget *>(target()); } QString QmlProjectRunConfiguration::viewerPath() const { Qt4ProjectManager::QtVersion *version = qtVersion(); if (!version) { return QString(); } else { return version->qmlviewerCommand(); } } QString QmlProjectRunConfiguration::observerPath() const { Qt4ProjectManager::QtVersion *version = qtVersion(); if (!version) { return QString(); } else { return version->qmlObserverTool(); } } QString QmlProjectRunConfiguration::viewerArguments() const { // arguments in .user file QString args = m_qmlViewerArgs; // arguments from .qmlproject file foreach (const QString &importPath, qmlTarget()->qmlProject()->importPaths()) { Utils::QtcProcess::addArg(&args, "-I"); Utils::QtcProcess::addArg(&args, importPath); } QString s = mainScript(); if (!s.isEmpty()) { s = canonicalCapsPath(s); Utils::QtcProcess::addArg(&args, s); } return args; } QString QmlProjectRunConfiguration::workingDirectory() const { QFileInfo projectFile(qmlTarget()->qmlProject()->file()->fileName()); return canonicalCapsPath(projectFile.absolutePath()); } int QmlProjectRunConfiguration::qtVersionId() const { return m_qtVersionId; } void QmlProjectRunConfiguration::setQtVersionId(int id) { if (m_qtVersionId == id) return; m_qtVersionId = id; qmlTarget()->qmlProject()->refresh(QmlProject::Configuration); if (m_configurationWidget) m_configurationWidget.data()->updateQtVersionComboBox(); } /* QtDeclarative checks explicitly that the capitalization for any URL / path is exactly like the capitalization on disk. This method is uses the same native Windows API's to get the exact canonical path. */ QString QmlProjectRunConfiguration::canonicalCapsPath(const QString &fileName) { QString canonicalPath = QFileInfo(fileName).canonicalFilePath(); #if defined(Q_OS_WIN32) QString error; // don't know whether the shortpath step is really needed, // but we do this in QtDeclarative too. QString path = Utils::getShortPathName(canonicalPath, &error); if (!path.isEmpty()) path = Utils::getLongPathName(canonicalPath, &error); if (!path.isEmpty()) canonicalPath = path; #endif return canonicalPath; } Qt4ProjectManager::QtVersion *QmlProjectRunConfiguration::qtVersion() const { if (m_qtVersionId == -1) return 0; QtVersionManager *versionManager = QtVersionManager::instance(); Qt4ProjectManager::QtVersion *version = versionManager->version(m_qtVersionId); QTC_ASSERT(version, return 0); return version; } QWidget *QmlProjectRunConfiguration::createConfigurationWidget() { QTC_ASSERT(m_configurationWidget.isNull(), return m_configurationWidget.data()); m_configurationWidget = new QmlProjectRunConfigurationWidget(this); return m_configurationWidget.data(); } ProjectExplorer::OutputFormatter *QmlProjectRunConfiguration::createOutputFormatter() const { return new Qt4ProjectManager::QtOutputFormatter(qmlTarget()->qmlProject()); } QmlProjectRunConfiguration::MainScriptSource QmlProjectRunConfiguration::mainScriptSource() const { if (m_usingCurrentFile) { return FileInEditor; } if (!m_mainScriptFilename.isEmpty()) { return FileInSettings; } return FileInProjectFile; } /** Returns absolute path to main script file. */ QString QmlProjectRunConfiguration::mainScript() const { if (m_usingCurrentFile) { return m_currentFileFilename; } if (!m_mainScriptFilename.isEmpty()) { return m_mainScriptFilename; } QString path = qmlTarget()->qmlProject()->mainFile(); if (QFileInfo(path).isAbsolute()) { return path; } else { return qmlTarget()->qmlProject()->projectDir().absoluteFilePath(path); } } void QmlProjectRunConfiguration::setScriptSource(MainScriptSource source, const QString &settingsPath) { if (source == FileInEditor) { m_scriptFile = M_CURRENT_FILE; m_mainScriptFilename.clear(); m_usingCurrentFile = true; } else if (source == FileInProjectFile) { m_scriptFile.clear(); m_mainScriptFilename.clear(); m_usingCurrentFile = false; } else { // FileInSettings m_scriptFile = settingsPath; m_mainScriptFilename = qmlTarget()->qmlProject()->projectDir().absoluteFilePath(m_scriptFile); m_usingCurrentFile = false; } updateEnabled(); if (m_configurationWidget) m_configurationWidget.data()->updateFileComboBox(); } Utils::Environment QmlProjectRunConfiguration::environment() const { Utils::Environment env = baseEnvironment(); env.modify(userEnvironmentChanges()); return env; } QVariantMap QmlProjectRunConfiguration::toMap() const { QVariantMap map(ProjectExplorer::RunConfiguration::toMap()); map.insert(QLatin1String(Constants::QML_VIEWER_QT_KEY), m_qtVersionId); map.insert(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY), m_qmlViewerArgs); map.insert(QLatin1String(Constants::QML_MAINSCRIPT_KEY), m_scriptFile); map.insert(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY), Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges)); return map; } bool QmlProjectRunConfiguration::fromMap(const QVariantMap &map) { setQtVersionId(map.value(QLatin1String(Constants::QML_VIEWER_QT_KEY), -1).toInt()); m_qmlViewerArgs = map.value(QLatin1String(Constants::QML_VIEWER_ARGUMENTS_KEY)).toString(); m_scriptFile = map.value(QLatin1String(Constants::QML_MAINSCRIPT_KEY), M_CURRENT_FILE).toString(); m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList( map.value(QLatin1String(Constants::USER_ENVIRONMENT_CHANGES_KEY)).toStringList()); updateQtVersions(); if (m_scriptFile == M_CURRENT_FILE) { setScriptSource(FileInEditor); } else if (m_scriptFile.isEmpty()) { setScriptSource(FileInProjectFile); } else { setScriptSource(FileInSettings, m_scriptFile); } return RunConfiguration::fromMap(map); } void QmlProjectRunConfiguration::changeCurrentFile(Core::IEditor * /*editor*/) { updateEnabled(); } void QmlProjectRunConfiguration::updateEnabled() { bool qmlFileFound = false; if (m_usingCurrentFile) { Core::IEditor *editor = Core::EditorManager::instance()->currentEditor(); Core::MimeDatabase *db = ICore::instance()->mimeDatabase(); if (editor) { m_currentFileFilename = editor->file()->fileName(); if (db->findByFile(mainScript()).type() == QLatin1String("application/x-qml")) qmlFileFound = true; } if (!editor || db->findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) { // find a qml file with lowercase filename. This is slow, but only done // in initialization/other border cases. foreach(const QString &filename, m_projectTarget->qmlProject()->files()) { const QFileInfo fi(filename); if (!filename.isEmpty() && fi.baseName()[0].isLower() && db->findByFile(fi).type() == QLatin1String("application/x-qml")) { m_currentFileFilename = filename; qmlFileFound = true; break; } } } } else { // use default one qmlFileFound = !mainScript().isEmpty(); } bool newValue = (QFileInfo(viewerPath()).exists() || QFileInfo(observerPath()).exists()) && qmlFileFound; // Always emit change signal to force reevaluation of run/debug buttons m_isEnabled = newValue; emit isEnabledChanged(m_isEnabled); } void QmlProjectRunConfiguration::updateQtVersions() { QtVersionManager *qtVersions = QtVersionManager::instance(); // // update m_qtVersionId // if (!qtVersions->isValidId(m_qtVersionId) || !isValidVersion(qtVersions->version(m_qtVersionId))) { int newVersionId = -1; // take first one you find foreach (Qt4ProjectManager::QtVersion *version, qtVersions->validVersions()) { if (isValidVersion(version)) { newVersionId = version->uniqueId(); break; } } setQtVersionId(newVersionId); } updateEnabled(); } bool QmlProjectRunConfiguration::isValidVersion(Qt4ProjectManager::QtVersion *version) { if (version && (version->supportsTargetId(Qt4ProjectManager::Constants::DESKTOP_TARGET_ID) || version->supportsTargetId(Qt4ProjectManager::Constants::QT_SIMULATOR_TARGET_ID)) && !version->qmlviewerCommand().isEmpty()) { return true; } return false; } Utils::Environment QmlProjectRunConfiguration::baseEnvironment() const { Utils::Environment env; if (qtVersion()) env = qtVersion()->qmlToolsEnvironment(); return env; } void QmlProjectRunConfiguration::setUserEnvironmentChanges(const QList<Utils::EnvironmentItem> &diff) { if (m_userEnvironmentChanges != diff) { m_userEnvironmentChanges = diff; if (m_configurationWidget) m_configurationWidget.data()->userEnvironmentChangesChanged(); } } QList<Utils::EnvironmentItem> QmlProjectRunConfiguration::userEnvironmentChanges() const { return m_userEnvironmentChanges; } } // namespace QmlProjectManager <|endoftext|>
<commit_before>// RUN: %clang_cc1 -o /dev/null -verify %s enum E { one, two, three, four }; int test(enum E e) { switch (e) { case one: return 7; case two ... two + 1: return 42; case four: return 25; default: return 0; } } <commit_msg>Doug's feedback<commit_after>// RUN: %clang_cc1 -verify %s enum E { one, two, three, four }; int test(enum E e) { switch (e) { case one: return 7; case two ... two + 1: return 42; case four: return 25; default: return 0; } } <|endoftext|>
<commit_before>/* This file is part of WME Lite. http://dead-code.org/redir.php?target=wmelite Copyright (c) 2011 Jan Nedoma Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "dcgf.h" #include "BDiskFile.h" #include "PathUtil.h" ////////////////////////////////////////////////////////////////////////// CBDiskFile::CBDiskFile(CBGame* inGame):CBFile(inGame) { m_File = NULL; m_Data = NULL; m_Compressed = false; m_PrefixSize = 0; } ////////////////////////////////////////////////////////////////////////// CBDiskFile::~CBDiskFile() { Close(); } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Open(const char* Filename) { Close(); char FullPath[MAX_PATH]; ops = PathUtil::GetFileAccessMethod(Filename); for(int i=0; i<Game->m_FileManager->m_SinglePaths.GetSize(); i++) { sprintf(FullPath, "%s%s", Game->m_FileManager->m_SinglePaths[i], Filename); CorrectSlashes(FullPath); m_File = ops->file_open(FullPath, "rb"); if(m_File!=NULL) break; } // if we didn't find it in search paths, try to open directly if(!m_File) { strcpy(FullPath, Filename); CorrectSlashes(FullPath); m_File = ops->file_open(FullPath, "rb"); } if(m_File) { DWORD magic1, magic2; ops->file_read((char *) (&magic1), sizeof(DWORD), m_File); ops->file_read((char *) (&magic2), sizeof(DWORD), m_File); if(magic1==DCGF_MAGIC && magic2==COMPRESSED_FILE_MAGIC) m_Compressed = true; if(m_Compressed) { DWORD DataOffset, CompSize, UncompSize; ops->file_read((char *) (&DataOffset), sizeof(DWORD), m_File); ops->file_read((char *) (&CompSize), sizeof(DWORD), m_File); ops->file_read((char *) (&UncompSize), sizeof(DWORD), m_File); BYTE* CompBuffer = new BYTE[CompSize]; if(!CompBuffer) { Game->LOG(0, "Error allocating memory for compressed file '%s'", Filename); Close(); return E_FAIL; } m_Data = new BYTE[UncompSize]; if(!m_Data) { Game->LOG(0, "Error allocating buffer for file '%s'", Filename); delete [] CompBuffer; Close(); return E_FAIL; } ops->file_seek(m_File, DataOffset + m_PrefixSize, SEEK_SET); ops->file_read((char *) CompBuffer, CompSize, m_File); if(uncompress(m_Data, (uLongf*)&UncompSize, CompBuffer, CompSize)!=Z_OK) { Game->LOG(0, "Error uncompressing file '%s'", Filename); delete [] CompBuffer; Close(); return E_FAIL; } delete [] CompBuffer; m_Size = UncompSize; m_Pos = 0; ops->file_close(m_File); m_File = NULL; } else { m_Pos = 0; ops->file_seek(m_File, 0, SEEK_END); m_Size = ops->file_tell(m_File) - m_PrefixSize; ops->file_seek(m_File, m_PrefixSize, SEEK_SET); } return S_OK; } else return E_FAIL; } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Close() { if(m_File) ops->file_close(m_File); m_File = NULL; m_Pos = 0; m_Size = 0; SAFE_DELETE_ARRAY(m_Data); m_Compressed = false; return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Read(void *Buffer, DWORD Size) { if(m_Compressed) { memcpy(Buffer, m_Data+m_Pos, Size); m_Pos+=Size; return S_OK; } else { if(m_File) { size_t count = ops->file_read((char *) Buffer, Size, m_File); m_Pos += count; return S_OK; } else return E_FAIL; } } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Seek(DWORD Pos, TSeek Origin) { if(m_Compressed) { DWORD NewPos=0; switch(Origin) { case SEEK_TO_BEGIN: NewPos = Pos; break; case SEEK_TO_END: NewPos = m_Size + Pos; break; case SEEK_TO_CURRENT: NewPos = m_Pos + Pos; break; } if(NewPos > m_Size) return E_FAIL; else m_Pos = NewPos; return S_OK; } else { if(!m_File) return E_FAIL; int ret=1; switch(Origin) { case SEEK_TO_BEGIN: ret = ops->file_seek(m_File, m_PrefixSize + Pos, SEEK_SET); break; case SEEK_TO_END: ret = ops->file_seek(m_File, Pos, SEEK_END); break; case SEEK_TO_CURRENT: ret = ops->file_seek(m_File, Pos, SEEK_CUR); break; } if(ret==0) { m_Pos = ops->file_tell(m_File) - m_PrefixSize; return S_OK; } else return E_FAIL; } } ////////////////////////////////////////////////////////////////////////// void CBDiskFile::CorrectSlashes(char* fileName) { for (size_t i = 0; i < strlen(fileName); i++) { if (fileName[i] == '\\') fileName[i] = '/'; } } <commit_msg>added fix from Jan Kavan<commit_after>/* This file is part of WME Lite. http://dead-code.org/redir.php?target=wmelite Copyright (c) 2011 Jan Nedoma Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "dcgf.h" #include "BDiskFile.h" #include "PathUtil.h" ////////////////////////////////////////////////////////////////////////// CBDiskFile::CBDiskFile(CBGame* inGame):CBFile(inGame) { m_File = NULL; m_Data = NULL; m_Compressed = false; m_PrefixSize = 0; } ////////////////////////////////////////////////////////////////////////// CBDiskFile::~CBDiskFile() { Close(); } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Open(const char* Filename) { Close(); char FullPath[MAX_PATH]; ops = PathUtil::GetFileAccessMethod(Filename); for(int i=0; i<Game->m_FileManager->m_SinglePaths.GetSize(); i++) { sprintf(FullPath, "%s%s", Game->m_FileManager->m_SinglePaths[i], Filename); CorrectSlashes(FullPath); m_File = ops->file_open(FullPath, "rb"); if(m_File!=NULL) break; } // if we didn't find it in search paths, try to open directly if(!m_File) { strcpy(FullPath, Filename); CorrectSlashes(FullPath); m_File = ops->file_open(FullPath, "rb"); } if(m_File) { DWORD magic1, magic2; ops->file_read((char *) (&magic1), sizeof(DWORD), m_File); ops->file_read((char *) (&magic2), sizeof(DWORD), m_File); if(magic1==DCGF_MAGIC && magic2==COMPRESSED_FILE_MAGIC) m_Compressed = true; if(m_Compressed) { DWORD DataOffset, CompSize, UncompSize; ops->file_read((char *) (&DataOffset), sizeof(DWORD), m_File); ops->file_read((char *) (&CompSize), sizeof(DWORD), m_File); ops->file_read((char *) (&UncompSize), sizeof(DWORD), m_File); BYTE* CompBuffer = new BYTE[CompSize]; if(!CompBuffer) { Game->LOG(0, "Error allocating memory for compressed file '%s'", Filename); Close(); return E_FAIL; } m_Data = new BYTE[UncompSize]; if(!m_Data) { Game->LOG(0, "Error allocating buffer for file '%s'", Filename); delete [] CompBuffer; Close(); return E_FAIL; } ops->file_seek(m_File, DataOffset + m_PrefixSize, SEEK_SET); ops->file_read((char *) CompBuffer, CompSize, m_File); if(uncompress(m_Data, (uLongf*)&UncompSize, CompBuffer, CompSize)!=Z_OK) { Game->LOG(0, "Error uncompressing file '%s'", Filename); delete [] CompBuffer; Close(); return E_FAIL; } delete [] CompBuffer; m_Size = UncompSize; m_Pos = 0; ops->file_close(m_File); m_File = NULL; } else { m_Pos = 0; ops->file_seek(m_File, 0, SEEK_END); m_Size = ops->file_tell(m_File) - m_PrefixSize; ops->file_seek(m_File, m_PrefixSize, SEEK_SET); } return S_OK; } else return E_FAIL; } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Close() { if(m_File) ops->file_close(m_File); m_File = NULL; m_Pos = 0; m_Size = 0; SAFE_DELETE_ARRAY(m_Data); m_Compressed = false; return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Read(void *Buffer, DWORD Size) { if(m_Compressed) { memcpy(Buffer, m_Data+m_Pos, Size); m_Pos+=Size; return S_OK; } else { if(m_File) { size_t count = ops->file_read((char *) Buffer, Size, m_File); if (count == 0) return E_FAIL; m_Pos += count; return S_OK; } else return E_FAIL; } } ////////////////////////////////////////////////////////////////////////// HRESULT CBDiskFile::Seek(DWORD Pos, TSeek Origin) { if(m_Compressed) { DWORD NewPos=0; switch(Origin) { case SEEK_TO_BEGIN: NewPos = Pos; break; case SEEK_TO_END: NewPos = m_Size + Pos; break; case SEEK_TO_CURRENT: NewPos = m_Pos + Pos; break; } if(NewPos > m_Size) return E_FAIL; else m_Pos = NewPos; return S_OK; } else { if(!m_File) return E_FAIL; int ret=1; switch(Origin) { case SEEK_TO_BEGIN: ret = ops->file_seek(m_File, m_PrefixSize + Pos, SEEK_SET); break; case SEEK_TO_END: ret = ops->file_seek(m_File, Pos, SEEK_END); break; case SEEK_TO_CURRENT: ret = ops->file_seek(m_File, Pos, SEEK_CUR); break; } if(ret==0) { m_Pos = ops->file_tell(m_File) - m_PrefixSize; return S_OK; } else return E_FAIL; } } ////////////////////////////////////////////////////////////////////////// void CBDiskFile::CorrectSlashes(char* fileName) { for (size_t i = 0; i < strlen(fileName); i++) { if (fileName[i] == '\\') fileName[i] = '/'; } } <|endoftext|>