text
stringlengths
54
60.6k
<commit_before>/** * * Graph * * Undirected, weighted graph * https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016 * */ #ifndef ALGORITHM_GRAPH_HPP_ #define ALGORITHM_GRAPH_HPP_ 1 /** Includes */ #include <cstddef> /** size_t definition */ #include <vector> /** Containers */ #include <map> /** Containers */ namespace algorithm { /** Undirected, weighted graph class \note Vertex deletion is not implemented \note Edge deletion is not implemented \note Cannot use double as WeightType */ template< class ValueType, /**< Vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< Weight type */ WeightType WeightDefaultValue = 0 /**< Default value of weight */ > class Graph { public: typedef size_t SizeType; typedef std::map<const KeyType, WeightType> EdgeType; /**< Edges of vertex \param KeyType key_dest \param WeightType weight */ /** Test if two keys are equal \return Return true if two keys are equal; otherwise return false \param[in] key_first First key to compare \param[in] key_second Second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) const { return key_first == key_second; } /** Vertex class Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< Key of vertex; same with index in graph_ */ ValueType value; /**< Value of vertex */ EdgeType edges; //SizeType edges_size; /**< Count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) { } /** Test if two values are equal \return Return true if two values are equal; otherwise return false \param[in] value Value to compare */ bool IsValueEqual(const ValueType & value) const { return this->value == value; } }; private: std::vector<VertexNode> graph_; /**< Graph */ public: /** Test whether there is an edge from the vertices src to dest \return Return true if the edge exists; otherwise return false \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** Add a vertex, if a graph not have the vertex with specified value already \return Return the key of vertex if added successfully; otherwise return -1 \param[in] value_of_vertex Value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** Add an edge to connect two vertices \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) \param[in] weight Weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.insert( std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight)) ); } /** Get a key of the vertex with specified value from a graph If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return Return the key of vertex if added successfully; otherwise return the size of graph \param[in] value_of_vertex Value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** Get a value of the vertex with specified key from a graph \return Return the value \param[in] key_of_vertex Key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).value; } /** Set a value of the vertex with specified key from a graph \param[in] key_of_vertex Key of vertex \param[in] value_of_vertex Value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** Get a count of vertices \return Count of vertices */ inline SizeType GetVertexCount(void) const { return graph_.size(); } /** Get a count of edges \return Count of edges \param[in] key_of_vertex Key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).edges.size(); } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_GRAPH_HPP_ */ <commit_msg>Change the private member to protected<commit_after>/** * * Graph * * Undirected, weighted graph * https://github.com/kdzlvaids/algorithm_and_practice-pknu-2016 * */ #ifndef ALGORITHM_GRAPH_HPP_ #define ALGORITHM_GRAPH_HPP_ 1 /** Includes */ #include <cstddef> /** size_t definition */ #include <vector> /** Containers */ #include <map> /** Containers */ namespace algorithm { /** Undirected, weighted graph class \note Vertex deletion is not implemented \note Edge deletion is not implemented \note Cannot use double as WeightType */ template< class ValueType, /**< Vertex value type; operator== should be defined */ class WeightType = unsigned int, /**< Weight type */ WeightType WeightDefaultValue = 0 /**< Default value of weight */ > class Graph { public: typedef size_t SizeType; typedef std::map<const KeyType, WeightType> EdgeType; /**< Edges of vertex \param KeyType key_dest \param WeightType weight */ /** Test if two keys are equal \return Return true if two keys are equal; otherwise return false \param[in] key_first First key to compare \param[in] key_second Second key to compare */ bool IsKeyEqual(const KeyType & key_first, const KeyType & key_second) const { return key_first == key_second; } /** Vertex class Each vertex has an array for its edges as a member. */ struct VertexNode { const KeyType key; /**< Key of vertex; same with index in graph_ */ ValueType value; /**< Value of vertex */ EdgeType edges; //SizeType edges_size; /**< Count of edges; forward_list not support size() function */ /** Constructor */ VertexNode(const KeyType & key, const ValueType & value) : key(key) , value(value) { } /** Test if two values are equal \return Return true if two values are equal; otherwise return false \param[in] value Value to compare */ bool IsValueEqual(const ValueType & value) const { return this->value == value; } }; protected: std::vector<VertexNode> graph_; /**< Graph */ public: /** Test whether there is an edge from the vertices src to dest \return Return true if the edge exists; otherwise return false \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) */ bool Adjacent(const KeyType & key_src, const KeyType & key_dest) { for(auto & edge : graph_.at(key_src)->edges) { if(IsKeyEqual(edge.first, key_dest) == true) /** Found */ return true; } return false; /** Not found */ } /** Add a vertex, if a graph not have the vertex with specified value already \return Return the key of vertex if added successfully; otherwise return -1 \param[in] value_of_vertex Value of vertex */ KeyType AddVertex(const ValueType & value_of_vertex) { KeyType key_of_vertex = GetVertexKey(value_of_vertex); if(key_of_vertex == GetVertexCount()) /** Not found */ graph_.push_back(VertexNode(key_of_vertex, value_of_vertex)); return key_of_vertex; } /** Add an edge to connect two vertices \param[in] key_src Key of source (src) \param[in] key_dest Key of destination (dest) \param[in] weight Weight of the edge */ void AddEdge(const KeyType & key_src, const KeyType & key_dest, const WeightType & weight = WeightDefaultValue) { graph_.at(key_src).edges.insert( std::make_pair<const KeyType, WeightType> (KeyType(key_dest), WeightType(weight)) ); } /** Get a key of the vertex with specified value from a graph If failed to add, return the size of graph which is an invalid key (maximum key + 1). \return Return the key of vertex if added successfully; otherwise return the size of graph \param[in] value_of_vertex Value of vertex */ KeyType GetVertexKey(const ValueType & value_of_vertex) { for(const VertexNode & vertex : graph_) { if(vertex.IsValueEqual(value_of_vertex) == true) return vertex.key; } return GetVertexCount(); } /** Get a value of the vertex with specified key from a graph \return Return the value \param[in] key_of_vertex Key of vertex */ inline ValueType GetVertexValue(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).value; } /** Set a value of the vertex with specified key from a graph \param[in] key_of_vertex Key of vertex \param[in] value_of_vertex Value of vertex */ inline void SetVertexValue(const KeyType & key_of_vertex, const ValueType & value_of_vertex) { graph_.at(key_of_vertex).value = value_of_vertex; } /** Get a count of vertices \return Count of vertices */ inline SizeType GetVertexCount(void) const { return graph_.size(); } /** Get a count of edges \return Count of edges \param[in] key_of_vertex Key of vertex */ inline SizeType GetVertexEdgeCount(const KeyType & key_of_vertex) const { return graph_.at(key_of_vertex).edges.size(); } }; } /** ns: algorithm */ #endif /** ! ALGORITHM_GRAPH_HPP_ */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: langselect.cxx,v $ * * $Revision: 1.13 $ * last change: $Author: obo $ $Date: 2005-01-27 12:27:15 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "app.hxx" #include "langselect.hxx" #include <stdio.h> #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _TOOLS_ISOLANG_HXX #include <tools/isolang.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/lang/XLocalizable.hpp> #include <com/sun/star/lang/Locale.hpp> #include <rtl/locale.hxx> #ifndef INCLUDED_RTL_INSTANCE_HXX #include <rtl/instance.hxx> #endif #include <osl/process.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; using namespace com::sun::star::util; namespace desktop { sal_Bool LanguageSelection::bFoundLanguage = sal_False; OUString LanguageSelection::aFoundLanguage; const OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii("en-US"); Locale LanguageSelection::IsoStringToLocale(const OUString& str) { Locale l; sal_Int32 index=0; l.Language = str.getToken(0, '-', index); if (index >= 0) l.Country = str.getToken(0, '-', index); if (index >= 0) l.Variant = str.getToken(0, '-', index); return l; } bool LanguageSelection::prepareLanguage() { OUString aLocaleString = getLanguageString(); if ( aLocaleString.getLength() > 0 ) { OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); try { Reference< XLocalizable > theConfigProvider( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString); theConfigProvider->setLocale(loc); Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Setup/L10N/", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("ooLocale"), makeAny(aLocaleString)); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); return true; } catch (Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } return false; } OUString LanguageSelection::getLanguageString() { // did we already find a language? if (bFoundLanguage) return aFoundLanguage; // check whether the user has selected a specific language OUString aUserLanguage = getUserLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage)) { // all is well bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } else { // selected language is not/no longer installed resetUserLanguage(); } } // try to use system default aUserLanguage = getSystemLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage, sal_False)) { // great, system default language is available bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } } // fallback 1: en-US OUString usFB = usFallbackLanguage; if (isInstalledLanguage(usFB)) { bFoundLanguage = sal_True; aFoundLanguage = usFallbackLanguage; return aFoundLanguage; } // fallback didn't work use first installed language aUserLanguage = getFirstInstalledLanguage(); bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } Reference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate) { Reference< XNameAccess > xNameAccess; try{ OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); OUString sAccessSrvc; if (bUpdate) sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"); else sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"); OUString sConfigURL = OUString::createFromAscii(pPath); // get configuration provider Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); if (theMSF.is()) { Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > ( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); // access the provider Sequence< Any > theArgs(1); theArgs[ 0 ] <<= sConfigURL; xNameAccess = Reference< XNameAccess > ( theConfigProvider->createInstanceWithArguments( sAccessSrvc, theArgs ), UNO_QUERY_THROW ); } } catch (com::sun::star::uno::Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } return xNameAccess; } Sequence< OUString > LanguageSelection::getInstalledLanguages() { Sequence< OUString > seqLanguages; Reference< XNameAccess > xAccess = getConfigAccess("org.openoffice.Setup/Office/InstalledLocales", sal_False); if (!xAccess.is()) return seqLanguages; seqLanguages = xAccess->getElementNames(); return seqLanguages; } sal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact) { sal_Bool bInstalled = sal_False; Sequence< OUString > seqLanguages = getInstalledLanguages(); for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.equals(seqLanguages[i])) { bInstalled = sal_True; break; } } if (!bInstalled && !bExact) { // no exact match was found, well try to find a substitute Locale aLocale = IsoStringToLocale(usLocale); Locale aInstalledLocale; for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { aInstalledLocale = IsoStringToLocale(seqLanguages[i]); if (aLocale.Language.equals(aInstalledLocale.Language)) { bInstalled = sal_True; usLocale = seqLanguages[i]; break; } } } return bInstalled; } OUString LanguageSelection::getFirstInstalledLanguage() { OUString aLanguage; Sequence< OUString > seqLanguages = getInstalledLanguages(); if (seqLanguages.getLength() > 0) aLanguage = seqLanguages[0]; return aLanguage; } OUString LanguageSelection::getUserLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } OUString LanguageSelection::getSystemLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.System/L10N", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } void LanguageSelection::resetUserLanguage() { try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("UILocale"), makeAny(OUString::createFromAscii(""))); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); } catch ( Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } } // namespace desktop <commit_msg>INTEGRATION: CWS lobeta2 (1.12.14); FILE MERGED 2005/02/07 14:32:48 jl 1.12.14.3: RESYNC: (1.12-1.13); FILE MERGED 2004/12/16 16:35:18 lo 1.12.14.2: #112849# convert file urls to internal form on the command line 2004/12/09 13:36:55 lo 1.12.14.1: #i32939# set CJK and CTL document locale according to user lang, if not yet set<commit_after>/************************************************************************* * * $RCSfile: langselect.cxx,v $ * * $Revision: 1.14 $ * last change: $Author: vg $ $Date: 2005-03-11 10:47:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "app.hxx" #include "langselect.hxx" #include <stdio.h> #ifndef _RTL_STRING_HXX #include <rtl/string.hxx> #endif #ifndef _SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif #ifndef _TOOLS_ISOLANG_HXX #include <tools/isolang.hxx> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/beans/NamedValue.hpp> #include <com/sun/star/util/XChangesBatch.hpp> #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/lang/XLocalizable.hpp> #include <com/sun/star/lang/Locale.hpp> #include <rtl/locale.hxx> #ifndef INCLUDED_RTL_INSTANCE_HXX #include <rtl/instance.hxx> #endif #include <osl/process.h> using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::container; using namespace com::sun::star::beans; using namespace com::sun::star::util; namespace desktop { sal_Bool LanguageSelection::bFoundLanguage = sal_False; OUString LanguageSelection::aFoundLanguage; const OUString LanguageSelection::usFallbackLanguage = OUString::createFromAscii("en-US"); Locale LanguageSelection::IsoStringToLocale(const OUString& str) { Locale l; sal_Int32 index=0; l.Language = str.getToken(0, '-', index); if (index >= 0) l.Country = str.getToken(0, '-', index); if (index >= 0) l.Variant = str.getToken(0, '-', index); return l; } bool LanguageSelection::prepareLanguage() { // get the selected UI language as string OUString aLocaleString = getLanguageString(); if ( aLocaleString.getLength() > 0 ) { OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); try { // prepare default config provider by localizing it to the selected locale // this will ensure localized configuration settings to be selected accoring to the // UI language. Reference< XLocalizable > theConfigProvider( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); Locale loc = LanguageSelection::IsoStringToLocale(aLocaleString); theConfigProvider->setLocale(loc); Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Setup/L10N/", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("ooLocale"), makeAny(aLocaleString)); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); // #i32939# setting of default document locale setDefaultLocale(aLocaleString); return true; } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch (Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } return false; } void LanguageSelection::setDefaultLocale(const OUString& usUILocale) { // #i32939# setting of default document locale // org.openoffice.Office.Linguistic/General/DefaultLocale // org.openoffice.Office.Linguistic/General/DefaultLocale_CJK // org.openoffice.Office.Linguistic/General/DefaultLocale_CTL // determine script type of UI locale LanguageType ltUILocale = ConvertIsoStringToLanguage(usUILocale); sal_uInt16 nScriptType = SvtLanguageOptions::GetScriptTypeOfLanguage(ltUILocale); Reference< XPropertySet > xProp(getConfigAccess( "org.openoffice.Office.Linguistic/General/", sal_True), UNO_QUERY_THROW); OUString usName = OUString::createFromAscii("DefaultLocale"); switch (nScriptType) { case SCRIPTTYPE_ASIAN: usName = OUString::createFromAscii("DefaultLocale_CJK"); break; case SCRIPTTYPE_COMPLEX: usName = OUString::createFromAscii("DefaultLocale_CTL"); break; } OUString usValue; xProp->getPropertyValue(usName) >>= usValue; if (usValue.getLength() == 0) { // there is no document language set, for the script type selected // in the UI // covert the LanguageType we've got from the LanguageTable back to // an iso string and store it OUString usDefault = ConvertLanguageToIsoString(ltUILocale); try { xProp->setPropertyValue(usName, makeAny(usDefault)); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); } catch ( PropertyVetoException ) { // we are not allowed to change this } } } OUString LanguageSelection::getLanguageString() { // did we already find a language? if (bFoundLanguage) return aFoundLanguage; // check whether the user has selected a specific language OUString aUserLanguage = getUserLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage)) { // all is well bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } else { // selected language is not/no longer installed resetUserLanguage(); } } // try to use system default aUserLanguage = getSystemLanguage(); if (aUserLanguage.getLength() > 0 ) { if (isInstalledLanguage(aUserLanguage, sal_False)) { // great, system default language is available bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } } // fallback 1: en-US OUString usFB = usFallbackLanguage; if (isInstalledLanguage(usFB)) { bFoundLanguage = sal_True; aFoundLanguage = usFallbackLanguage; return aFoundLanguage; } // fallback didn't work use first installed language aUserLanguage = getFirstInstalledLanguage(); bFoundLanguage = sal_True; aFoundLanguage = aUserLanguage; return aFoundLanguage; } Reference< XNameAccess > LanguageSelection::getConfigAccess(const sal_Char* pPath, sal_Bool bUpdate) { Reference< XNameAccess > xNameAccess; try{ OUString sConfigSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationProvider"); OUString sAccessSrvc; if (bUpdate) sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationUpdateAccess"); else sAccessSrvc = OUString::createFromAscii("com.sun.star.configuration.ConfigurationAccess"); OUString sConfigURL = OUString::createFromAscii(pPath); // get configuration provider Reference< XMultiServiceFactory > theMSF = comphelper::getProcessServiceFactory(); if (theMSF.is()) { Reference< XMultiServiceFactory > theConfigProvider = Reference< XMultiServiceFactory > ( theMSF->createInstance( sConfigSrvc ),UNO_QUERY_THROW ); // access the provider Sequence< Any > theArgs(1); theArgs[ 0 ] <<= sConfigURL; xNameAccess = Reference< XNameAccess > ( theConfigProvider->createInstanceWithArguments( sAccessSrvc, theArgs ), UNO_QUERY_THROW ); } } catch (com::sun::star::uno::Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } return xNameAccess; } Sequence< OUString > LanguageSelection::getInstalledLanguages() { Sequence< OUString > seqLanguages; Reference< XNameAccess > xAccess = getConfigAccess("org.openoffice.Setup/Office/InstalledLocales", sal_False); if (!xAccess.is()) return seqLanguages; seqLanguages = xAccess->getElementNames(); return seqLanguages; } sal_Bool LanguageSelection::isInstalledLanguage(OUString& usLocale, sal_Bool bExact) { sal_Bool bInstalled = sal_False; Sequence< OUString > seqLanguages = getInstalledLanguages(); for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { if (usLocale.equals(seqLanguages[i])) { bInstalled = sal_True; break; } } if (!bInstalled && !bExact) { // no exact match was found, well try to find a substitute Locale aLocale = IsoStringToLocale(usLocale); Locale aInstalledLocale; for (sal_Int32 i=0; i<seqLanguages.getLength(); i++) { aInstalledLocale = IsoStringToLocale(seqLanguages[i]); if (aLocale.Language.equals(aInstalledLocale.Language)) { bInstalled = sal_True; usLocale = seqLanguages[i]; break; } } } return bInstalled; } OUString LanguageSelection::getFirstInstalledLanguage() { OUString aLanguage; Sequence< OUString > seqLanguages = getInstalledLanguages(); if (seqLanguages.getLength() > 0) aLanguage = seqLanguages[0]; return aLanguage; } OUString LanguageSelection::getUserLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } OUString LanguageSelection::getSystemLanguage() { OUString aUserLanguage; Reference< XNameAccess > xAccess(getConfigAccess("org.openoffice.System/L10N", sal_False)); if (xAccess.is()) { try { xAccess->getByName(OUString::createFromAscii("UILocale")) >>= aUserLanguage; } catch ( NoSuchElementException const & ) { return OUString(); } catch ( WrappedTargetException const & ) { return OUString(); } } return aUserLanguage; } void LanguageSelection::resetUserLanguage() { try { Reference< XPropertySet > xProp(getConfigAccess("org.openoffice.Office.Linguistic/General", sal_True), UNO_QUERY_THROW); xProp->setPropertyValue(OUString::createFromAscii("UILocale"), makeAny(OUString::createFromAscii(""))); Reference< XChangesBatch >(xProp, UNO_QUERY_THROW)->commitChanges(); } catch ( PropertyVetoException& ) { // we are not allowed to change this } catch ( Exception& e) { OString aMsg = OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US); OSL_ENSURE(sal_False, aMsg.getStr()); } } } // namespace desktop <|endoftext|>
<commit_before>/* UselessMine Copyright (C) 2014 Vladimir "allejo" Jimenez This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <memory> #include <stdlib.h> #include <string> #include "bzfsAPI.h" #include "bztoolkit/bzToolkitAPI.h" // Define plugin name const std::string PLUGIN_NAME = "Useless Mine"; // Define plugin version numbering const int MAJOR = 1; const int MINOR = 0; const int REV = 0; const int BUILD = 28; // A function to replace substrings in a string with another substring std::string ReplaceString(std::string subject, const std::string& search, const std::string& replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } class UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler { public: virtual const char* Name (); virtual void Init (const char* config); virtual void Event (bz_EventData *eventData); virtual void Cleanup (void); virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*); virtual int getMineCount (); virtual void removeAllMines (int playerID), removeMine (int mineIndex), setMine (int owner, float pos[3], bz_eTeamType team); virtual std::string formatDeathMessage (std::string msg, std::string victim, std::string owner); // The information each mine will contain struct Mine { int owner; // The owner of the mine and the victim, respectively float x, y, z; // The coordinates of where the mine was placed bz_eTeamType team; // The team of the owner bool detonated; // Whether or not the mine has been detonated; to prepare it for removal from play double detonationTime; // The time the mine was detonated Mine (int _owner, float _pos[3], bz_eTeamType _team) : owner(_owner), x(_pos[0]), y(_pos[1]), z(_pos[2]), team(_team), detonated(false) {} }; std::vector<Mine> activeMines; // A vector that will store all of the mines that are in play std::vector<std::string> deathMessages; // A vector that will store all of the witty death messages std::string deathMessagesFile; double bzdb_SpawnSafetyTime, // The BZDB variable that will store the amount of seconds a player has before a mine is detonated playerSpawnTime[256]; // The time of a player's last spawn time used to calculate their safety from detonation }; BZ_PLUGIN(UselessMine) const char* UselessMine::Name (void) { static std::string pluginBuild = ""; if (!pluginBuild.size()) { std::ostringstream pluginBuildStream; pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")"; pluginBuild = pluginBuildStream.str(); } return pluginBuild.c_str(); } void UselessMine::Init (const char* commandLine) { // Register our events with Register() Register(bz_eFlagGrabbedEvent); Register(bz_ePlayerDieEvent); Register(bz_ePlayerPartEvent); Register(bz_ePlayerSpawnEvent); Register(bz_ePlayerUpdateEvent); // Register our custom slash commands bz_registerCustomSlashCommand("mine", this); // Set some custom BZDB variables bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB("_mineSafetyTime", 5.0); // Save the location of the file so we can reload after deathMessagesFile = commandLine; // Open the file of witty death messages std::ifstream file(commandLine); std::string currentLine; // If the file exists, read each line if (file) { // Push each line into the deathMessages vector while (std::getline(file, currentLine)) { deathMessages.push_back(currentLine); } bz_debugMessagef(2, "DEBUG :: Useless Mine :: %d witty messages were loaded", deathMessages.size()); } else { bz_debugMessage(2, "WARNING :: Useless Mine :: No witty death messages were loaded"); } } void UselessMine::Cleanup (void) { Flush(); // Clean up all the events // Clean up our custom slash commands bz_removeCustomSlashCommand("mine"); } void UselessMine::Event (bz_EventData *eventData) { switch (eventData->eventType) { case bz_eFlagGrabbedEvent: // This event is called each time a flag is grabbed by a player { bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData; // Data // --- // (int) playerID - The player that grabbed the flag // (int) flagID - The flag ID that was grabbed // (bz_ApiString) flagType - The flag abbreviation of the flag that was grabbed // (float[3]) pos - The position at which the flag was grabbed // (double) eventTime - This value is the local server time of the event. // If the user grabbed the Useless flag, let them know they can place a mine if (strcmp(flagGrabData->flagType, "US") == 0) { bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, "You grabbed a Useless flag! Type /mine at any time to set a useless mine!"); } } break; case bz_ePlayerDieEvent: // This event is called each time a tank is killed. { bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData; // Data // --- // (int) playerID - ID of the player who was killed. // (bz_eTeamType) team - The team the killed player was on. // (int) killerID - The owner of the shot that killed the player, or BZ_SERVER for server side kills // (bz_eTeamType) killerTeam - The team the owner of the shot was on. // (bz_ApiString) flagKilledWith - The flag name the owner of the shot had when the shot was fired. // (int) shotID - The shot ID that killed the player, if the player was not killed by a shot, the id will be -1. // (bz_PlayerUpdateState) state - The state record for the killed player at the time of the event // (double) eventTime - Time of the event on the server. int playerID = dieData->playerID; // Loop through all the mines in play for (int i = 0; i < getMineCount(); i++) { // Create a local variable for easy access Mine &detonatedMine = activeMines.at(i); // Check if the mine has already been detonated if (detonatedMine.detonated) { // If they were killed within the time the shockwave explodes, then we can safely say they were killed by the mine if (detonatedMine.detonationTime + bz_getBZDBDouble("_shockAdLife") > bz_getCurrentTime()) { // Check if the player who just died was killed by the server if (dieData->killerID == 253) { // Easy to access variables float deathPos[3] = {dieData->state.pos[0], dieData->state.pos[1], dieData->state.pos[2]}; double shockRange = bz_getBZDBDouble("_shockOutRadius") * 0.75; // Check if the player died inside of the mine radius if ((deathPos[0] > detonatedMine.x - shockRange && deathPos[0] < detonatedMine.x + shockRange) && (deathPos[1] > detonatedMine.y - shockRange && deathPos[1] < detonatedMine.y + shockRange) && (deathPos[2] > detonatedMine.z - shockRange && deathPos[2] < detonatedMine.z + shockRange)) { // Attribute the kill to the mine owner dieData->killerID = detonatedMine.owner; // Only get a death messages if death messages exist and the player who died is now also the mine owner if (!deathMessages.empty() && playerID != detonatedMine.owner) { // The random number used to fetch a random taunting death message int randomNumber = rand() % deathMessages.size(); // Get the callsigns of the players const char* owner = bz_getPlayerCallsign(detonatedMine.owner); const char* victim = bz_getPlayerCallsign(playerID); // Get a random death message std::string deathMessage = deathMessages.at(randomNumber); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str()); } break; } } } else { removeMine(i); } } } } break; case bz_ePlayerPartEvent: // This event is called each time a player leaves a game { bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData; // Data // --- // (int) playerID - The player ID that is leaving // (bz_BasePlayerRecord*) record - The player record for the leaving player // (bz_ApiString) reason - The reason for leaving, such as a kick or a ban // (double) eventTime - Time of event. int playerID = partData->playerID; // Remove all the mines belonging to the player who just left removeAllMines(playerID); } break; case bz_ePlayerSpawnEvent: // This event is called each time a playing tank is being spawned into the world { bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData; // Data // --- // (int) playerID - ID of the player who was added to the world. // (bz_eTeamType) team - The team the player is a member of. // (bz_PlayerUpdateState) state - The state record for the spawning player // (double) eventTime - Time local server time for the event. int playerID = spawnData->playerID; // Save the time the player spawned last playerSpawnTime[playerID] = bz_getCurrentTime(); } break; case bz_ePlayerUpdateEvent: // This event is called each time a player sends an update to the server { bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData; // Data // --- // (int) playerID - ID of the player that sent the update // (bz_PlayerUpdateState) state - The original state the tank was in // (bz_PlayerUpdateState) lastState - The second state the tank is currently in to show there was an update // (double) stateTime - The time the state was updated // (double) eventTime - The current server time int playerID = updateData->playerID; // Loop through all of the players for (int i = 0; i < getMineCount(); i++) { // Make an easy access mine Mine &currentMine = activeMines.at(i); std::shared_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(playerID)); // If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner if (currentMine.owner != playerID && (pr->team == eRogueTeam || pr->team != currentMine.team) && pr->spawned) { // Make easy to access variables float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]}; double shockRange = bz_getBZDBDouble("_shockOutRadius") * 0.75; // Check if the player is in the detonation range if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) && (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) && (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) && playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime()) { // Check that the mine owner exists and is not an observer if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers) { // Get the current mine position float minePos[3] = {currentMine.x, currentMine.y, currentMine.z}; // Only detonate a mine once if (!currentMine.detonated) { currentMine.detonated = true; currentMine.detonationTime = bz_getCurrentTime(); // BOOM! bz_fireWorldWep("SW", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team); } } // Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there else { removeMine(i); } break; } } } } break; default: break; } } bool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString /*message*/, bz_APIStringList *params) { if (command == "mine") { std::shared_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID)); // If the player is not an observer, they let them proceed to the next check if (playerRecord->team != eObservers) { // Check if the player has the Useless flag if (playerRecord->currentFlag == "USeless (+US)") { // Store their current position float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]}; setMine(playerID, currentPosition, playerRecord->team); } else { bz_sendTextMessage(BZ_SERVER, playerID, "You can't place a mine without the Useless flag!"); } } else { bz_sendTextMessage(BZ_SERVER, playerID, "Silly observer, you can't place a mine."); } return true; } return true; } // A function to format death messages in order to replace placeholders with callsigns and values std::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner) { // Replace the %victim% and %owner% placeholders std::string formattedMessage = ReplaceString(ReplaceString(msg, "%victim%", victim), "%owner%", owner); // If the message has a %minecount%, then replace it if (formattedMessage.find("%minecount%") != std::string::npos) { // Subtract one from the mine count because the mine we're announcing hasn't beeb removed yet int minecount = (getMineCount() == 0) ? 0 : getMineCount() - 1; formattedMessage = ReplaceString(formattedMessage, "%minecount%", std::to_string(minecount)); } return formattedMessage; } // A shortcut to get the amount of mines that are in play int UselessMine::getMineCount() { return activeMines.size(); } // Remove all of the mines belonging to a player void UselessMine::removeAllMines(int playerID) { // Go through all of the mines for (int i = 0; i < getMineCount(); i++) { // Quick access mine Mine &currentMine = activeMines.at(i); // If the mine belongs to the player, remove it if (currentMine.owner == playerID) { removeMine(i); } } } // A shortcut to remove a mine from play void UselessMine::removeMine(int mineIndex) { activeMines.erase(activeMines.begin() + mineIndex); } // A shortcut to set a mine void UselessMine::setMine(int owner, float pos[3], bz_eTeamType team) { // Remove their flag because it's going to be a US flag bz_removePlayerFlag(owner); // Push the new mine Mine newMine(owner, pos, team); activeMines.push_back(newMine); }<commit_msg>Make mine detection less sensitive & OpenFFA support<commit_after>/* UselessMine Copyright (C) 2014 Vladimir "allejo" Jimenez This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <fstream> #include <memory> #include <stdlib.h> #include <string> #include "bzfsAPI.h" #include "bztoolkit/bzToolkitAPI.h" // Define plugin name const std::string PLUGIN_NAME = "Useless Mine"; // Define plugin version numbering const int MAJOR = 1; const int MINOR = 0; const int REV = 0; const int BUILD = 28; // A function to replace substrings in a string with another substring std::string ReplaceString(std::string subject, const std::string& search, const std::string& replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } class UselessMine : public bz_Plugin, public bz_CustomSlashCommandHandler { public: virtual const char* Name (); virtual void Init (const char* config); virtual void Event (bz_EventData *eventData); virtual void Cleanup (void); virtual bool SlashCommand (int playerID, bz_ApiString, bz_ApiString, bz_APIStringList*); virtual int getMineCount (); virtual void removeAllMines (int playerID), removeMine (int mineIndex), setMine (int owner, float pos[3], bz_eTeamType team); virtual std::string formatDeathMessage (std::string msg, std::string victim, std::string owner); // The information each mine will contain struct Mine { int owner; // The owner of the mine and the victim, respectively float x, y, z; // The coordinates of where the mine was placed bz_eTeamType team; // The team of the owner bool detonated; // Whether or not the mine has been detonated; to prepare it for removal from play double detonationTime; // The time the mine was detonated Mine (int _owner, float _pos[3], bz_eTeamType _team) : owner(_owner), x(_pos[0]), y(_pos[1]), z(_pos[2]), team(_team), detonated(false) {} }; std::vector<Mine> activeMines; // A vector that will store all of the mines that are in play std::vector<std::string> deathMessages; // A vector that will store all of the witty death messages std::string deathMessagesFile; double bzdb_SpawnSafetyTime, // The BZDB variable that will store the amount of seconds a player has before a mine is detonated playerSpawnTime[256]; // The time of a player's last spawn time used to calculate their safety from detonation bool openFFA; }; BZ_PLUGIN(UselessMine) const char* UselessMine::Name (void) { static std::string pluginBuild = ""; if (!pluginBuild.size()) { std::ostringstream pluginBuildStream; pluginBuildStream << PLUGIN_NAME << " " << MAJOR << "." << MINOR << "." << REV << " (" << BUILD << ")"; pluginBuild = pluginBuildStream.str(); } return pluginBuild.c_str(); } void UselessMine::Init (const char* commandLine) { // Register our events with Register() Register(bz_eFlagGrabbedEvent); Register(bz_ePlayerDieEvent); Register(bz_ePlayerPartEvent); Register(bz_ePlayerSpawnEvent); Register(bz_ePlayerUpdateEvent); // Register our custom slash commands bz_registerCustomSlashCommand("mine", this); // Set some custom BZDB variables bzdb_SpawnSafetyTime = bztk_registerCustomDoubleBZDB("_mineSafetyTime", 5.0); // Save the location of the file so we can reload after deathMessagesFile = commandLine; // We'll ignore team colors if it's an Open FFA game openFFA = (bz_getGameType() == eOpenFFAGame); // Open the file of witty death messages std::ifstream file(commandLine); std::string currentLine; // If the file exists, read each line if (file) { // Push each line into the deathMessages vector while (std::getline(file, currentLine)) { deathMessages.push_back(currentLine); } bz_debugMessagef(2, "DEBUG :: Useless Mine :: %d witty messages were loaded", deathMessages.size()); } else { bz_debugMessage(2, "WARNING :: Useless Mine :: No witty death messages were loaded"); } } void UselessMine::Cleanup (void) { Flush(); // Clean up all the events // Clean up our custom slash commands bz_removeCustomSlashCommand("mine"); } void UselessMine::Event (bz_EventData *eventData) { switch (eventData->eventType) { case bz_eFlagGrabbedEvent: // This event is called each time a flag is grabbed by a player { bz_FlagGrabbedEventData_V1* flagGrabData = (bz_FlagGrabbedEventData_V1*)eventData; // If the user grabbed the Useless flag, let them know they can place a mine if (strcmp(flagGrabData->flagType, "US") == 0) { bz_sendTextMessage(BZ_SERVER, flagGrabData->playerID, "You grabbed a Useless flag! Type /mine at any time to set a useless mine!"); } } break; case bz_ePlayerDieEvent: // This event is called each time a tank is killed. { bz_PlayerDieEventData_V1* dieData = (bz_PlayerDieEventData_V1*)eventData; int playerID = dieData->playerID; // Loop through all the mines in play for (int i = 0; i < getMineCount(); i++) { // Create a local variable for easy access Mine &detonatedMine = activeMines.at(i); // Check if the mine has already been detonated if (detonatedMine.detonated) { // Check if the player who just died was killed by the server if (dieData->killerID == 253) { // Easy to access variables float deathPos[3] = {dieData->state.pos[0], dieData->state.pos[1], dieData->state.pos[2]}; double shockRange = bz_getBZDBDouble("_shockOutRadius") * 0.75; // Check if the player died inside of the mine radius if ((deathPos[0] > detonatedMine.x - shockRange && deathPos[0] < detonatedMine.x + shockRange) && (deathPos[1] > detonatedMine.y - shockRange && deathPos[1] < detonatedMine.y + shockRange) && (deathPos[2] > detonatedMine.z - shockRange && deathPos[2] < detonatedMine.z + shockRange)) { // Attribute the kill to the mine owner dieData->killerID = detonatedMine.owner; // Only get a death messages if death messages exist and the player who died is now also the mine owner if (!deathMessages.empty() && playerID != detonatedMine.owner) { // The random number used to fetch a random taunting death message int randomNumber = rand() % deathMessages.size(); // Get the callsigns of the players const char* owner = bz_getPlayerCallsign(detonatedMine.owner); const char* victim = bz_getPlayerCallsign(playerID); // Get a random death message std::string deathMessage = deathMessages.at(randomNumber); bz_sendTextMessage(BZ_SERVER, BZ_ALLUSERS, formatDeathMessage(deathMessage, victim, owner).c_str()); } break; } } else { removeMine(i); } } } } break; case bz_ePlayerPartEvent: // This event is called each time a player leaves a game { bz_PlayerJoinPartEventData_V1* partData = (bz_PlayerJoinPartEventData_V1*)eventData; int playerID = partData->playerID; // Remove all the mines belonging to the player who just left removeAllMines(playerID); } break; case bz_ePlayerSpawnEvent: // This event is called each time a playing tank is being spawned into the world { bz_PlayerSpawnEventData_V1* spawnData = (bz_PlayerSpawnEventData_V1*)eventData; int playerID = spawnData->playerID; // Save the time the player spawned last playerSpawnTime[playerID] = bz_getCurrentTime(); } break; case bz_ePlayerUpdateEvent: // This event is called each time a player sends an update to the server { bz_PlayerUpdateEventData_V1* updateData = (bz_PlayerUpdateEventData_V1*)eventData; int playerID = updateData->playerID; // Loop through all of the players for (int i = 0; i < getMineCount(); i++) { // Make an easy access mine Mine &currentMine = activeMines.at(i); std::unique_ptr<bz_BasePlayerRecord> pr(bz_getPlayerByIndex(playerID)); // If the mine owner is not the player triggering the mine (so no self kills) and the player is a rogue or does is an enemy team relative to the mine owner if (currentMine.owner != playerID && (pr->team == eRogueTeam || pr->team != currentMine.team || openFFA) && pr->spawned) { // Make easy to access variables float playerPos[3] = {updateData->state.pos[0], updateData->state.pos[1], updateData->state.pos[2]}; double shockRange = bz_getBZDBDouble("_shockOutRadius") * 0.75; // Check if the player is in the detonation range if ((playerPos[0] > currentMine.x - shockRange && playerPos[0] < currentMine.x + shockRange) && (playerPos[1] > currentMine.y - shockRange && playerPos[1] < currentMine.y + shockRange) && (playerPos[2] > currentMine.z - shockRange && playerPos[2] < currentMine.z + shockRange) && playerSpawnTime[playerID] + bzdb_SpawnSafetyTime <= bz_getCurrentTime()) { // Check that the mine owner exists and is not an observer if (bztk_isValidPlayerID(currentMine.owner) && bz_getPlayerTeam(currentMine.owner) != eObservers) { // Get the current mine position float minePos[3] = {currentMine.x, currentMine.y, currentMine.z}; // Only detonate a mine once if (!currentMine.detonated) { currentMine.detonated = true; currentMine.detonationTime = bz_getCurrentTime(); // BOOM! bz_fireWorldWep("SW", 2.0, BZ_SERVER, minePos, 0, 0, 0, currentMine.team); } } // Just in case the player doesn't exist or is an observer, then remove the mine because it shouldn't be there else { removeMine(i); } break; } } } } break; default: break; } } bool UselessMine::SlashCommand(int playerID, bz_ApiString command, bz_ApiString /*message*/, bz_APIStringList *params) { if (command == "mine") { std::unique_ptr<bz_BasePlayerRecord> playerRecord(bz_getPlayerByIndex(playerID)); // If the player is not an observer, they let them proceed to the next check if (playerRecord->team != eObservers) { // Check if the player has the Useless flag if (playerRecord->currentFlag == "USeless (+US)") { // Store their current position float currentPosition[3] = {playerRecord->lastKnownState.pos[0], playerRecord->lastKnownState.pos[1], playerRecord->lastKnownState.pos[2]}; setMine(playerID, currentPosition, playerRecord->team); } else { bz_sendTextMessage(BZ_SERVER, playerID, "You can't place a mine without the Useless flag!"); } } else { bz_sendTextMessage(BZ_SERVER, playerID, "Silly observer, you can't place a mine."); } return true; } return true; } // A function to format death messages in order to replace placeholders with callsigns and values std::string UselessMine::formatDeathMessage(std::string msg, std::string victim, std::string owner) { // Replace the %victim% and %owner% placeholders std::string formattedMessage = ReplaceString(ReplaceString(msg, "%victim%", victim), "%owner%", owner); // If the message has a %minecount%, then replace it if (formattedMessage.find("%minecount%") != std::string::npos) { // Subtract one from the mine count because the mine we're announcing hasn't beeb removed yet int minecount = (getMineCount() == 0) ? 0 : getMineCount() - 1; formattedMessage = ReplaceString(formattedMessage, "%minecount%", std::to_string(minecount)); } return formattedMessage; } // A shortcut to get the amount of mines that are in play int UselessMine::getMineCount() { return activeMines.size(); } // Remove all of the mines belonging to a player void UselessMine::removeAllMines(int playerID) { // Go through all of the mines for (int i = 0; i < getMineCount(); i++) { // Quick access mine Mine &currentMine = activeMines.at(i); // If the mine belongs to the player, remove it if (currentMine.owner == playerID) { removeMine(i); } } } // A shortcut to remove a mine from play void UselessMine::removeMine(int mineIndex) { activeMines.erase(activeMines.begin() + mineIndex); } // A shortcut to set a mine void UselessMine::setMine(int owner, float pos[3], bz_eTeamType team) { // Remove their flag because it's going to be a US flag bz_removePlayerFlag(owner); // Push the new mine Mine newMine(owner, pos, team); activeMines.push_back(newMine); }<|endoftext|>
<commit_before>#pragma once #include <deque> #include <memory> #include <iostream> #include <map> #include <utility> template <typename T> class MessageBusProxy; namespace { using Cursor = long unsigned int; } template <typename MessageType> class MessageBus { public: MessageBus()=default; void push(const MessageType& message); static MessageBus<MessageType>* getBus(); MessageType* next(MessageBusProxy<MessageType>* proxy); private: using MessageQueue = std::deque<MessageType>; friend class MessageBusProxy<MessageType>; void registerProxy(MessageBusProxy<MessageType>* proxy); void unregisterProxy(MessageBusProxy<MessageType>* proxy); MessageQueue m_messages; std::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys; static std::unique_ptr<MessageBus<MessageType>> m_bus; }; #include "messagebusqueue.hpp" #include "messagebusproxy.hpp" template <typename MessageType> void MessageBus<MessageType>::push(const MessageType& message) { if (m_proxys.size() == 0) return; MessageBusQueue::instance()->push<MessageType>(); m_messages.push_back(message); } template <typename MessageType> MessageBus<MessageType>* MessageBus<MessageType>::getBus() { if (m_bus == nullptr) { std::cout << "bus expired"<< std::endl; m_bus.reset(new MessageBus<MessageType>()); } return m_bus.get(); } template <typename MessageType> void MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) { auto cursor = m_messages.begin(); if (m_messages.size() > 0) std::advance(cursor, m_messages.size()-1); m_proxys.emplace(proxy, cursor); } template <typename MessageType> void MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) { auto _search = m_proxys.find(proxy); if (_search == m_proxys.end()) return; m_proxys.erase(_search); if (m_proxys.size() == 0) delete m_bus.release(); } template <typename MessageType> MessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) { // TODO : implement next function auto& iterator = m_proxys.at(proxy); if (iterator == m_messages.end()) return nullptr; return &*(++iterator); } template <typename MessageType> std::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr; template <typename MessageType> void SendMessage(const MessageType& message) { MessageBus<MessageType>::getBus()->push(message); } <commit_msg>Add API to messagebus to send requests.<commit_after>#pragma once #include <deque> #include <memory> #include <iostream> #include <map> #include <utility> template <typename T> class MessageBusProxy; namespace { using Cursor = long unsigned int; } template <typename MessageType> class MessageBus { public: MessageBus()=default; void push(const MessageType& message); template<typename ResponseType> const std::vector<ResponseType>&& request(const MessageType& message); static MessageBus<MessageType>* getBus(); MessageType* next(MessageBusProxy<MessageType>* proxy); private: using MessageQueue = std::deque<MessageType>; friend class MessageBusProxy<MessageType>; void registerProxy(MessageBusProxy<MessageType>* proxy); void unregisterProxy(MessageBusProxy<MessageType>* proxy); MessageQueue m_messages; std::map<MessageBusProxy<MessageType>*, typename MessageQueue::iterator> m_proxys; static std::unique_ptr<MessageBus<MessageType>> m_bus; }; #include "messagebusqueue.hpp" #include "messagebusproxy.hpp" template <typename MessageType> void MessageBus<MessageType>::push(const MessageType& message) { if (m_proxys.size() == 0) return; MessageBusQueue::instance()->push<MessageType>(); m_messages.push_back(message); } template <typename MessageType> MessageBus<MessageType>* MessageBus<MessageType>::getBus() { if (m_bus == nullptr) { std::cout << "bus expired"<< std::endl; m_bus.reset(new MessageBus<MessageType>()); } return m_bus.get(); } template <typename MessageType> void MessageBus<MessageType>::registerProxy(MessageBusProxy<MessageType>* proxy) { auto cursor = m_messages.begin(); if (m_messages.size() > 0) std::advance(cursor, m_messages.size()-1); m_proxys.emplace(proxy, cursor); } template <typename MessageType> void MessageBus<MessageType>::unregisterProxy(MessageBusProxy<MessageType>* proxy) { auto _search = m_proxys.find(proxy); if (_search == m_proxys.end()) return; m_proxys.erase(_search); if (m_proxys.size() == 0) delete m_bus.release(); } template <typename MessageType> MessageType* MessageBus<MessageType>::next(MessageBusProxy<MessageType>* proxy) { // TODO : implement next function auto& iterator = m_proxys.at(proxy); if (iterator == m_messages.end()) return nullptr; return &*(++iterator); } template <typename MessageType> std::unique_ptr<MessageBus<MessageType>> MessageBus<MessageType>::m_bus = nullptr; template <typename MessageType> void SendMessage(const MessageType& message) { MessageBus<MessageType>::getBus()->push(message); } template <typename MessageType, typename ResponseType> const std::vector<ResponseType>&& RequestMessage(const MessageType& message) { MessageBus<MessageType>::getBus()->request(message); } template <typename MessageType, typename ResponseType> const ResponseType& RequestUnique(const MessageType& message) { auto& response = RequestMessage<MessageType, ResponseType>(message); if (response.size() != 1) throw std::runtime_error("More than 1 response"); return response[0]; } <|endoftext|>
<commit_before>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; public: InternalizePass() { if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool runOnModule(Module &M) { // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors"|| I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace ModulePass *llvm::createInternalizePass() { return new InternalizePass(); } <commit_msg>Add an option to this pass. If it is set, we are allowed to internalize all but main. If it's not set, we can still internalize, but only if an explicit symbol list is provided.<commit_after>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; bool DontInternalize; public: InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){ if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else if (!APIList.empty()) // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); else if (!InternalizeEverything) // Finally, if we're allowed to, internalize all but main. DontInternalize = true; } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool runOnModule(Module &M) { if (DontInternalize) return false; // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors"|| I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace ModulePass *llvm::createInternalizePass(bool InternalizeEverything) { return new InternalizePass(InternalizeEverything); } <|endoftext|>
<commit_before>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; bool DontInternalize; public: InternalizePass(bool InternalizeEverything = true) : DontInternalize(false){ if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else if (!APIList.empty()) // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); else if (!InternalizeEverything) // Finally, if we're allowed to, internalize all but main. DontInternalize = true; } void LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } virtual bool runOnModule(Module &M) { if (DontInternalize) return false; // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Mark all global variables with initializers as internal as well... for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName()) && // *never* internalize the llvm.used symbol, used to implement // attribute((used)). I->getName() != "llvm.used") { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors"|| I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace ModulePass *llvm::createInternalizePass(bool InternalizeEverything) { return new InternalizePass(InternalizeEverything); } <commit_msg>Pull inline methods out of the pass class definition to make it easier to read the code.<commit_after>//===-- Internalize.cpp - Mark functions internal -------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass loops over all of the functions in the input module, looking for a // main function. If a main function is found, all other functions and all // global variables with initializers are marked as internal. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Pass.h" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/ADT/Statistic.h" #include <fstream> #include <set> using namespace llvm; namespace { Statistic<> NumFunctions("internalize", "Number of functions internalized"); Statistic<> NumGlobals ("internalize", "Number of global vars internalized"); // APIFile - A file which contains a list of symbols that should not be marked // external. cl::opt<std::string> APIFile("internalize-public-api-file", cl::value_desc("filename"), cl::desc("A file containing list of symbol names to preserve")); // APIList - A list of symbols that should not be marked internal. cl::list<std::string> APIList("internalize-public-api-list", cl::value_desc("list"), cl::desc("A list of symbol names to preserve"), cl::CommaSeparated); class InternalizePass : public ModulePass { std::set<std::string> ExternalNames; bool DontInternalize; public: InternalizePass(bool InternalizeEverything = true); void LoadFile(const char *Filename); virtual bool runOnModule(Module &M); }; RegisterOpt<InternalizePass> X("internalize", "Internalize Global Symbols"); } // end anonymous namespace InternalizePass::InternalizePass(bool InternalizeEverything) : DontInternalize(false){ if (!APIFile.empty()) // If a filename is specified, use it LoadFile(APIFile.c_str()); else if (!APIList.empty()) // Else, if a list is specified, use it. ExternalNames.insert(APIList.begin(), APIList.end()); else if (!InternalizeEverything) // Finally, if we're allowed to, internalize all but main. DontInternalize = true; } void InternalizePass::LoadFile(const char *Filename) { // Load the APIFile... std::ifstream In(Filename); if (!In.good()) { std::cerr << "WARNING: Internalize couldn't load file '" << Filename << "'!\n"; return; // Do not internalize anything... } while (In) { std::string Symbol; In >> Symbol; if (!Symbol.empty()) ExternalNames.insert(Symbol); } } bool InternalizePass::runOnModule(Module &M) { if (DontInternalize) return false; // If no list or file of symbols was specified, check to see if there is a // "main" symbol defined in the module. If so, use it, otherwise do not // internalize the module, it must be a library or something. // if (ExternalNames.empty()) { Function *MainFunc = M.getMainFunction(); if (MainFunc == 0 || MainFunc->isExternal()) return false; // No main found, must be a library... // Preserve main, internalize all else. ExternalNames.insert(MainFunc->getName()); } bool Changed = false; // Found a main function, mark all functions not named main as internal. for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) if (!I->isExternal() && // Function must be defined here !I->hasInternalLinkage() && // Can't already have internal linkage !ExternalNames.count(I->getName())) {// Not marked to keep external? I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumFunctions; DEBUG(std::cerr << "Internalizing func " << I->getName() << "\n"); } // Never internalize the llvm.used symbol. It is used to implement // attribute((used)). ExternalNames.insert("llvm.used"); // Never internalize anchors used by the debugger, else the debugger won't // find them. ExternalNames.insert("llvm.dbg.translation_units"); ExternalNames.insert("llvm.dbg.globals"); // Mark all global variables with initializers as internal as well. for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (!I->isExternal() && !I->hasInternalLinkage() && !ExternalNames.count(I->getName())) { // Special case handling of the global ctor and dtor list. When we // internalize it, we mark it constant, which allows elimination of // the list if it's empty. // if (I->hasAppendingLinkage() && (I->getName() == "llvm.global_ctors" || I->getName() == "llvm.global_dtors")) I->setConstant(true); I->setLinkage(GlobalValue::InternalLinkage); Changed = true; ++NumGlobals; DEBUG(std::cerr << "Internalizing gvar " << I->getName() << "\n"); } return Changed; } ModulePass *llvm::createInternalizePass(bool InternalizeEverything) { return new InternalizePass(InternalizeEverything); } <|endoftext|>
<commit_before>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2018 Michael Fink // /// \file GeoTagTool\MainFrame.cpp GeoTagTool main frame // #include "stdafx.h" #include "res/Ribbon.h" #include "resource.h" #include "AboutDlg.hpp" #include "GeoTagToolView.hpp" #include "MainFrame.hpp" #include "SerialPortDlg.hpp" BOOL MainFrame::PreTranslateMessage(MSG* pMsg) { if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg)) return TRUE; return m_view.PreTranslateMessage(pMsg); } BOOL MainFrame::OnIdle() { return FALSE; } LRESULT MainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { UIAddMenu(GetMenu(), true); m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD); m_cmdBar.AttachMenu(GetMenu()); m_cmdBar.LoadImages(IDR_MAINFRAME); CreateSimpleStatusBar(); m_hWndClient = m_view.Create(m_hWnd); UISetCheck(ID_VIEW_STATUS_BAR, 1); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); ShowRibbonUI(true); return 0; } LRESULT MainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); bHandled = FALSE; return 1; } LRESULT MainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PostMessage(WM_CLOSE); return 0; } LRESULT MainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { AboutDlg dlg; dlg.DoModal(); return 0; } LRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SerialPortDlg dlg; if (IDOK != dlg.DoModal(m_hWnd)) return 0; return 0; } LRESULT MainFrame::OnDataSourceImportTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } LRESULT MainFrame::OnActionsTagImages(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } LRESULT MainFrame::OnActionsSaveLiveTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } <commit_msg>removed ASSERT when starting main frame, due do missing menu resource<commit_after>// // RemotePhotoTool - remote camera control software // Copyright (C) 2008-2018 Michael Fink // /// \file GeoTagTool\MainFrame.cpp GeoTagTool main frame // #include "stdafx.h" #include "res/Ribbon.h" #include "resource.h" #include "AboutDlg.hpp" #include "GeoTagToolView.hpp" #include "MainFrame.hpp" #include "SerialPortDlg.hpp" BOOL MainFrame::PreTranslateMessage(MSG* pMsg) { if (CRibbonFrameWindowImpl<MainFrame>::PreTranslateMessage(pMsg)) return TRUE; return m_view.PreTranslateMessage(pMsg); } BOOL MainFrame::OnIdle() { return FALSE; } LRESULT MainFrame::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { m_cmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD); m_cmdBar.AttachMenu(GetMenu()); m_cmdBar.LoadImages(IDR_MAINFRAME); CreateSimpleStatusBar(); m_hWndClient = m_view.Create(m_hWnd); UISetCheck(ID_VIEW_STATUS_BAR, 1); // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); ShowRibbonUI(true); return 0; } LRESULT MainFrame::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); bHandled = FALSE; return 1; } LRESULT MainFrame::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PostMessage(WM_CLOSE); return 0; } LRESULT MainFrame::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { AboutDlg dlg; dlg.DoModal(); return 0; } LRESULT MainFrame::OnDataSourceOpenGPSReceiver(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { SerialPortDlg dlg; if (IDOK != dlg.DoModal(m_hWnd)) return 0; return 0; } LRESULT MainFrame::OnDataSourceImportTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } LRESULT MainFrame::OnActionsTagImages(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } LRESULT MainFrame::OnActionsSaveLiveTrack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { return 0; } <|endoftext|>
<commit_before>#include <YCommon/Headers/stdincludes.h> #include "AtomicQueue.h" #include <string> #include <YCommon/Headers/AtomicNumberMask.h> #include <YCommon/Headers/Atomics.h> namespace YCommon { namespace YContainers { AtomicQueue::AtomicQueue() : mBuffer(NULL), mItemSize(0), mNumItems(0), mHead(0), mTail(0) { } AtomicQueue::AtomicQueue(void* buffer, size_t buffer_size, size_t item_size, size_t num_items) : mBuffer(NULL), mItemSize(0), mNumItems(0), mHead(0), mTail(0) { Initialize(buffer, buffer_size, item_size, num_items); } AtomicQueue::~AtomicQueue() { } void AtomicQueue::Initialize(void* buffer, size_t buffer_size, size_t item_size, size_t num_items) { mBuffer = buffer; mItemSize = item_size; mNumItems = num_items; mHead = 0; mTail = 0; (void) buffer_size; YASSERT(buffer_size >= (item_size * num_items), "Atomic Queue %u[%u] requires at least %u bytes, supplied %u bytes.", static_cast<uint32_t>(item_size), num_items, static_cast<uint32_t>(item_size * num_items), static_cast<uint32_t>(buffer_size)); } bool AtomicQueue::Enqueue(const void* data_item) { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); const uint64_t cur_head_num = GET_NUM(cur_head); const uint64_t cur_tail_num = GET_NUM(cur_tail); // Check if full (numbers match, but counters do not) if (cur_head_num == cur_tail_num && cur_head != cur_tail) return false; memcpy(static_cast<char*>(mBuffer) + cur_tail_num, data_item, mItemSize); const uint64_t new_tail_num = cur_tail_num + mItemSize; const uint64_t tail_cnt = GET_CNT(cur_tail); // Check if looped through buffer. mTail = (new_tail_num == (mItemSize * mNumItems)) ? CONSTRUCT_NEXT_VALUE(tail_cnt, 0) : CONSTRUCT_VALUE(tail_cnt, new_tail_num); return true; } bool AtomicQueue::Dequeue(void* data_item) { const size_t buffer_size = mItemSize * mNumItems; for (;;) { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); // Check if empty (both counter and numbers match) if (cur_head == cur_tail) return false; const uint64_t cur_head_num = GET_NUM(cur_head); memcpy(data_item, static_cast<char*>(mBuffer) + cur_head_num, mItemSize); const uint64_t new_head_num = cur_head_num + mItemSize; const uint64_t head_cnt = GET_CNT(cur_head); // Check if looped through buffer. const uint64_t new_head_val = (new_head_num == buffer_size) ? CONSTRUCT_NEXT_VALUE(head_cnt, 0) : CONSTRUCT_VALUE(head_cnt, new_head_num); if (AtomicCmpSet64(&mHead, cur_head, new_head_val)) break; } return true; } size_t AtomicQueue::CurrentSize() const { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); const uint64_t cur_head_num = GET_NUM(cur_head); const uint64_t cur_tail_num = GET_NUM(cur_tail); if (cur_head_num == cur_tail_num) { // Empty if the counters match, full otherwise. return (cur_head == cur_tail) ? 0 : mItemSize; } else if (cur_tail_num > cur_head_num) { return (cur_tail_num - cur_head_num) / mItemSize; } else { const uint64_t looped_tail = cur_tail_num + (mItemSize * mNumItems); return (looped_tail - cur_head_num) / mItemSize; } } }} // namespace YCommon { namespace YContainers { <commit_msg>Fixed some type problems<commit_after>#include <YCommon/Headers/stdincludes.h> #include "AtomicQueue.h" #include <string> #include <YCommon/Headers/AtomicNumberMask.h> #include <YCommon/Headers/Atomics.h> namespace YCommon { namespace YContainers { AtomicQueue::AtomicQueue() : mBuffer(NULL), mItemSize(0), mNumItems(0), mHead(0), mTail(0) { } AtomicQueue::AtomicQueue(void* buffer, size_t buffer_size, size_t item_size, size_t num_items) : mBuffer(NULL), mItemSize(0), mNumItems(0), mHead(0), mTail(0) { Initialize(buffer, buffer_size, item_size, num_items); } AtomicQueue::~AtomicQueue() { } void AtomicQueue::Initialize(void* buffer, size_t buffer_size, size_t item_size, size_t num_items) { mBuffer = buffer; mItemSize = item_size; mNumItems = num_items; mHead = 0; mTail = 0; (void) buffer_size; YASSERT(buffer_size >= (item_size * num_items), "Atomic Queue %u[%u] requires at least %u bytes, supplied %u bytes.", static_cast<uint32_t>(item_size), num_items, static_cast<uint32_t>(item_size * num_items), static_cast<uint32_t>(buffer_size)); } bool AtomicQueue::Enqueue(const void* data_item) { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); const uint64_t cur_head_num = GET_NUM(cur_head); const uint64_t cur_tail_num = GET_NUM(cur_tail); // Check if full (numbers match, but counters do not) if (cur_head_num == cur_tail_num && cur_head != cur_tail) return false; memcpy(static_cast<char*>(mBuffer) + cur_tail_num, data_item, mItemSize); const uint64_t new_tail_num = cur_tail_num + mItemSize; const uint64_t tail_cnt = GET_CNT(cur_tail); // Check if looped through buffer. mTail = (new_tail_num == (mItemSize * mNumItems)) ? CONSTRUCT_NEXT_VALUE(tail_cnt, 0) : CONSTRUCT_VALUE(tail_cnt, new_tail_num); return true; } bool AtomicQueue::Dequeue(void* data_item) { const size_t buffer_size = mItemSize * mNumItems; for (;;) { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); // Check if empty (both counter and numbers match) if (cur_head == cur_tail) return false; const uint64_t cur_head_num = GET_NUM(cur_head); memcpy(data_item, static_cast<char*>(mBuffer) + cur_head_num, mItemSize); const uint64_t new_head_num = cur_head_num + mItemSize; const uint64_t head_cnt = GET_CNT(cur_head); // Check if looped through buffer. const uint64_t new_head_val = (new_head_num == buffer_size) ? CONSTRUCT_NEXT_VALUE(head_cnt, 0) : CONSTRUCT_VALUE(head_cnt, new_head_num); if (AtomicCmpSet64(&mHead, cur_head, new_head_val)) break; } return true; } size_t AtomicQueue::CurrentSize() const { const uint64_t cur_head = mHead; const uint64_t cur_tail = mTail; MemoryBarrier(); const uint64_t size = static_cast<uint64_t>(mItemSize); const uint64_t cur_head_num = GET_NUM(cur_head); const uint64_t cur_tail_num = GET_NUM(cur_tail); if (cur_head_num == cur_tail_num) { // Empty if the counters match, full otherwise. return (cur_head == cur_tail) ? 0 : mItemSize; } else if (cur_tail_num > cur_head_num) { return static_cast<size_t>((cur_tail_num - cur_head_num) / size); } else { const uint64_t looped_tail = cur_tail_num + (size * mNumItems); return static_cast<size_t>((looped_tail - cur_head_num) / size); } } }} // namespace YCommon { namespace YContainers { <|endoftext|>
<commit_before>/// /// @file P2_mpi.cpp /// @brief 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <int128.hpp> #include <min_max.hpp> #include <mpi_reduce_sum.hpp> #include <pmath.hpp> #include <print.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// Count the primes inside [prime, stop] template <typename T> int64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop) { int64_t count = 0; for (; prime <= stop; count++) prime = it.next_prime(); return count; } /// Calculate the thread sieving distance. The idea is to /// gradually increase the thread_distance in order to /// keep all CPU cores busy. /// void balanceLoad(int64_t* thread_distance, int64_t low, int64_t z, int threads, double start_time) { double seconds = get_wtime() - start_time; int64_t min_distance = 1 << 20; int64_t max_distance = ceil_div(z - low, threads); if (seconds < 60) *thread_distance *= 2; if (seconds > 60) *thread_distance /= 2; *thread_distance = in_between(min_distance, *thread_distance, max_distance); } template <typename T> T P2_OpenMP_thread(T x, int64_t y, int64_t z, int64_t thread_distance, int64_t thread_num, int64_t low, int64_t& pix, int64_t& pix_count) { pix = 0; pix_count = 0; low += thread_distance * thread_num; z = min(low + thread_distance, z); int64_t start = (int64_t) max(x / z, y); int64_t stop = (int64_t) min(x / low, isqrt(x)); primesieve::iterator rit(stop + 1, start); primesieve::iterator it(low - 1, z); int64_t next = it.next_prime(); int64_t prime = rit.previous_prime(); T P2_thread = 0; // \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i]) while (prime > start && x / prime < z) { pix += count_primes(it, next, x / prime); P2_thread += pix; pix_count++; prime = rit.previous_prime(); } pix += count_primes(it, next, z - 1); return P2_thread; } /// P2(x, y) counts the numbers <= x that have exactly 2 /// prime factors each exceeding the a-th prime. /// Space complexity: O(z^(1/2)). /// template <typename T> T P2_mpi_master(T x, int64_t y, int threads) { #if __cplusplus >= 201103L static_assert(prt::is_signed<T>::value, "P2(T x, ...): T must be signed integer type"); #endif if (x < 4) return 0; T a = pi_legendre(y, threads); T b = pi_legendre((int64_t) isqrt(x), threads); if (a >= b) return 0; int64_t low = 2; int64_t z = (int64_t)(x / max(y, 1)); int64_t min_distance = 1 << 20; int64_t thread_distance = min_distance; int proc_id = mpi_proc_id(); int procs = mpi_num_procs(); int64_t distance = z - low; int64_t proc_distance = ceil_div(distance, procs); low += proc_distance * proc_id; z = min(low + proc_distance, z); T p2 = 0; T pix_total = pi_legendre(low - 1, threads); if (is_mpi_master_proc()) p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; threads = ideal_num_threads(threads, z); aligned_vector<int64_t> pix(threads); aligned_vector<int64_t> pix_counts(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) while (low < z) { int64_t max_threads = ceil_div(z - low, thread_distance); threads = in_between(1, threads, max_threads); double time = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: p2) for (int i = 0; i < threads; i++) p2 += P2_OpenMP_thread(x, y, z, thread_distance, i, low, pix[i], pix_counts[i]); low += thread_distance * threads; balanceLoad(&thread_distance, low, z, threads, time); // Add missing sum contributions in order for (int i = 0; i < threads; i++) { p2 += pix_total * pix_counts[i]; pix_total += pix[i]; } if (print_status()) { double percent = get_percent((double) low, (double) z); cout << "\rStatus: " << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush; } } p2 = mpi_reduce_sum(p2); return p2; } } // namespace namespace primecount { int64_t P2_mpi(int64_t x, int64_t y, int threads) { print(""); print("=== P2_mpi(x, y) ==="); print("Computation of the 2nd partial sieve function"); print(x, y, threads); double time = get_wtime(); int64_t p2 = P2_mpi_master(x, y, threads); print("P2", p2, time); return p2; } #ifdef HAVE_INT128_T int128_t P2_mpi(int128_t x, int64_t y, int threads) { print(""); print("=== P2_mpi(x, y) ==="); print("Computation of the 2nd partial sieve function"); print(x, y, threads); double time = get_wtime(); int128_t p2 = P2_mpi_master(x, y, threads); print("P2", p2, time); return p2; } #endif } // namespace <commit_msg>ideal_num_threads() not needed<commit_after>/// /// @file P2_mpi.cpp /// @brief 2nd partial sieve function. /// P2(x, y) counts the numbers <= x that have exactly 2 prime /// factors each exceeding the a-th prime. /// /// Copyright (C) 2016 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <aligned_vector.hpp> #include <int128.hpp> #include <min_max.hpp> #include <mpi_reduce_sum.hpp> #include <pmath.hpp> #include <print.hpp> #include <stdint.h> #include <algorithm> #include <iostream> #include <iomanip> #ifdef _OPENMP #include <omp.h> #endif using namespace std; using namespace primecount; namespace { /// Count the primes inside [prime, stop] template <typename T> int64_t count_primes(primesieve::iterator& it, int64_t& prime, T stop) { int64_t count = 0; for (; prime <= stop; count++) prime = it.next_prime(); return count; } /// Calculate the thread sieving distance. The idea is to /// gradually increase the thread_distance in order to /// keep all CPU cores busy. /// void balanceLoad(int64_t* thread_distance, int64_t low, int64_t z, int threads, double start_time) { double seconds = get_wtime() - start_time; int64_t min_distance = 1 << 20; int64_t max_distance = ceil_div(z - low, threads); if (seconds < 60) *thread_distance *= 2; if (seconds > 60) *thread_distance /= 2; *thread_distance = in_between(min_distance, *thread_distance, max_distance); } template <typename T> T P2_OpenMP_thread(T x, int64_t y, int64_t z, int64_t thread_distance, int64_t thread_num, int64_t low, int64_t& pix, int64_t& pix_count) { pix = 0; pix_count = 0; low += thread_distance * thread_num; z = min(low + thread_distance, z); int64_t start = (int64_t) max(x / z, y); int64_t stop = (int64_t) min(x / low, isqrt(x)); primesieve::iterator rit(stop + 1, start); primesieve::iterator it(low - 1, z); int64_t next = it.next_prime(); int64_t prime = rit.previous_prime(); T P2_thread = 0; // \sum_{i = pi[start]+1}^{pi[stop]} pi(x / primes[i]) while (prime > start && x / prime < z) { pix += count_primes(it, next, x / prime); P2_thread += pix; pix_count++; prime = rit.previous_prime(); } pix += count_primes(it, next, z - 1); return P2_thread; } /// P2(x, y) counts the numbers <= x that have exactly 2 /// prime factors each exceeding the a-th prime. /// Space complexity: O(z^(1/2)). /// template <typename T> T P2_mpi_master(T x, int64_t y, int threads) { #if __cplusplus >= 201103L static_assert(prt::is_signed<T>::value, "P2(T x, ...): T must be signed integer type"); #endif if (x < 4) return 0; T a = pi_legendre(y, threads); T b = pi_legendre((int64_t) isqrt(x), threads); if (a >= b) return 0; int64_t low = 2; int64_t z = (int64_t)(x / max(y, 1)); int64_t min_distance = 1 << 20; int64_t thread_distance = min_distance; int proc_id = mpi_proc_id(); int procs = mpi_num_procs(); int64_t distance = z - low; int64_t proc_distance = ceil_div(distance, procs); low += proc_distance * proc_id; z = min(low + proc_distance, z); T p2 = 0; T pix_total = pi_legendre(low - 1, threads); if (is_mpi_master_proc()) p2 = (a - 2) * (a + 1) / 2 - (b - 2) * (b + 1) / 2; aligned_vector<int64_t> pix(threads); aligned_vector<int64_t> pix_counts(threads); // \sum_{i=a+1}^{b} pi(x / primes[i]) while (low < z) { int64_t max_threads = ceil_div(z - low, thread_distance); threads = in_between(1, threads, max_threads); double time = get_wtime(); #pragma omp parallel for num_threads(threads) reduction(+: p2) for (int i = 0; i < threads; i++) p2 += P2_OpenMP_thread(x, y, z, thread_distance, i, low, pix[i], pix_counts[i]); low += thread_distance * threads; balanceLoad(&thread_distance, low, z, threads, time); // Add missing sum contributions in order for (int i = 0; i < threads; i++) { p2 += pix_total * pix_counts[i]; pix_total += pix[i]; } if (print_status()) { double percent = get_percent((double) low, (double) z); cout << "\rStatus: " << fixed << setprecision(get_status_precision(x)) << percent << '%' << flush; } } p2 = mpi_reduce_sum(p2); return p2; } } // namespace namespace primecount { int64_t P2_mpi(int64_t x, int64_t y, int threads) { print(""); print("=== P2_mpi(x, y) ==="); print("Computation of the 2nd partial sieve function"); print(x, y, threads); double time = get_wtime(); int64_t p2 = P2_mpi_master(x, y, threads); print("P2", p2, time); return p2; } #ifdef HAVE_INT128_T int128_t P2_mpi(int128_t x, int64_t y, int threads) { print(""); print("=== P2_mpi(x, y) ==="); print("Computation of the 2nd partial sieve function"); print(x, y, threads); double time = get_wtime(); int128_t p2 = P2_mpi_master(x, y, threads); print("P2", p2, time); return p2; } #endif } // namespace <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere ([email protected]) * * This file is part of FlashGraph. * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kmeans.h" #define KM_TEST 1 #define VERBOSE 0 #ifdef PROFILER #include <gperftools/profiler.h> #endif namespace { static unsigned NUM_COLS; static size_t K; static unsigned NUM_ROWS; short OMP_MAX_THREADS; static unsigned g_num_changed = 0; static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max(); static struct timeval start, end; static init_type_t g_init_type; /** * \brief This initializes clusters by randomly choosing sample * membership in a cluster. * See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods * \param cluster_assignments Which cluster each sample falls into. */ static void random_partition_init(unsigned* cluster_assignments, const double* matrix, clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Random init start"; // #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = random() % K; // 0...K clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust); cluster_assignments[row] = asgnd_clust; } // NOTE: M-Step called in compute func to update cluster counts & centers #if VERBOSE printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS); #endif BOOST_LOG_TRIVIAL(info) << "Random init end\n"; } /** * \brief Forgy init takes `K` random samples from the matrix * and uses them as cluster centers. * \param matrix the flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. */ static void forgy_init(const double* matrix, clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Forgy init start"; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1) clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx); } BOOST_LOG_TRIVIAL(info) << "Forgy init end"; } /** * \brief A parallel version of the kmeans++ initialization alg. * See: http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf for algorithm */ static void kmeanspp_init(const double* matrix, clusters::ptr clusters, unsigned* cluster_assignments, std::vector<double>& dist_v) { // Choose c1 uniiformly at random unsigned selected_idx = random() % NUM_ROWS; // 0...(NUM_ROWS-1) clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0); dist_v[selected_idx] = 0.0; #if KM_TEST BOOST_LOG_TRIVIAL(info) << "\nChoosing " << selected_idx << " as center K = 0"; #endif unsigned clust_idx = 0; // The number of clusters assigned // Choose next center c_i with weighted prob while ((clust_idx + 1) < K) { double cum_dist = 0; #pragma omp parallel for reduction(+:cum_dist) shared (dist_v) for (size_t row = 0; row < NUM_ROWS; row++) { double dist = dist_comp_raw(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); if (dist < dist_v[row]) { // Found a closer cluster than before dist_v[row] = dist; cluster_assignments[row] = clust_idx; } cum_dist += dist_v[row]; } cum_dist = (cum_dist * ((double)random())) / (RAND_MAX - 1.0); clust_idx++; for (size_t i=0; i < NUM_ROWS; i++) { cum_dist -= dist_v[i]; if (cum_dist <= 0) { #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Choosing " << i << " as center K = " << clust_idx; #endif clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx); break; } } assert (cum_dist <= 0); } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "\nCluster centers after kmeans++"; clusters->print_means(); #endif } /** * \brief Update the cluster assignments while recomputing distance matrix. * \param matrix The flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. * \param cluster_assignments Which cluster each sample falls into. */ static void EM_step(const double* matrix, clusters::ptr cls, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, const bool prune_init=false) { std::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS); // Per thread changed cluster count. OMP_MAX_THREADS std::vector<size_t> pt_num_change(OMP_MAX_THREADS); for (int i = 0; i < OMP_MAX_THREADS; i++) pt_cl[i] = clusters::create(K, NUM_COLS); #pragma omp parallel for firstprivate(matrix, pt_cl)\ shared(cluster_assignments) schedule(static) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = INVALID_CLUSTER_ID; double best, dist; dist = best = std::numeric_limits<double>::max(); for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { dist = dist_comp_raw(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); if (dist < best) { best = dist; asgnd_clust = clust_idx; } } BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID); if (asgnd_clust != cluster_assignments[row]) { pt_num_change[omp_get_thread_num()]++; } cluster_assignments[row] = asgnd_clust; pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust); // Accumulate for local copies } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts"; BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ..."; #endif cls->clear(); // Serial aggreate of OMP_MAX_THREADS vectors // TODO: Pool these for (int thd = 0; thd < OMP_MAX_THREADS; thd++) { // Updated the changed cluster count g_num_changed += pt_num_change[thd]; // Summation for cluster centers cls->peq(pt_cl[thd]); } unsigned chk_nmemb = 0; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { cls->finalize(clust_idx); cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx); chk_nmemb += cluster_assignment_counts[clust_idx]; } BOOST_VERIFY(chk_nmemb == NUM_ROWS); #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Global number of changes: " << g_num_changed; #endif } } namespace fg { unsigned compute_kmeans(const double* matrix, double* clusters_ptr, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, const unsigned num_rows, const unsigned num_cols, const unsigned k, const unsigned MAX_ITERS, const int max_threads, const std::string init, const double tolerance, const std::string dist_type) { #ifdef PROFILER ProfilerStart("matrix/kmeans.perf"); #endif NUM_COLS = num_cols; K = k; NUM_ROWS = num_rows; assert(max_threads > 0); OMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads()); omp_set_num_threads(OMP_MAX_THREADS); BOOST_LOG_TRIVIAL(info) << "Running on " << OMP_MAX_THREADS << " threads!"; // Check k if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) { BOOST_LOG_TRIVIAL(fatal) << "'k' must be between 2 and the number of rows in the matrix" << "k = " << K; exit(-1); } gettimeofday(&start , NULL); /*** Begin VarInit of data structures ***/ std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1); std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0); clusters::ptr clusters = clusters::create(K, NUM_COLS); if (init == "none") clusters->set_mean(clusters_ptr); // For pruning std::vector<double> dist_v; dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max()); /*** End VarInit ***/ BOOST_LOG_TRIVIAL(info) << "Dist_type is " << dist_type; if (dist_type == "eucl") { g_dist_type = EUCL; } else if (dist_type == "cos") { g_dist_type = COS; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '" << dist_type << "'"; exit(-1); } if (init == "random") { random_partition_init(cluster_assignments, matrix, clusters); g_init_type = RANDOM; } else if (init == "forgy") { forgy_init(matrix, clusters); g_init_type = FORGY; } else if (init == "kmeanspp") { kmeanspp_init(matrix, clusters, cluster_assignments, dist_v); g_init_type = PLUSPLUS; } else if (init == "none") { g_init_type = NONE; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param init must be one of: " "'random', 'forgy', 'kmeanspp'.It is '" << init << "'"; exit(-1); } if (g_init_type == NONE || g_init_type == FORGY || g_init_type == RANDOM) { EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts, true); } BOOST_LOG_TRIVIAL(info) << "Init is '" << init << "'"; BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ..."; bool converged = false; std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ? "until convergence ...": std::to_string(MAX_ITERS) + " iterations ..."; BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters; unsigned iter = 1; while (iter < MAX_ITERS) { // Hold cluster assignment counter BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << ". Computing cluster assignments ..."; EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts); #if KM_TEST printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K); #endif if (g_num_changed == 0 || ((g_num_changed/(double)NUM_ROWS)) <= tolerance) { converged = true; break; } else { g_num_changed = 0; } iter++; } gettimeofday(&end, NULL); BOOST_LOG_TRIVIAL(info) << "\n\nAlgorithmic time taken = " << time_diff(start, end) << " sec\n"; #ifdef PROFILER ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; if (converged) { BOOST_LOG_TRIVIAL(info) << "K-means converged in " << iter << " iterations"; } else { BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in " << iter << " iterations"; } BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; return iter; } } <commit_msg>[Matrix]: removed no-op oerg and added bic & spherical projection code<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Disa Mhembere ([email protected]) * * This file is part of FlashGraph. * * 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 CURRENT_KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "kmeans.h" #define KM_TEST 0 #define VERBOSE 0 #ifdef PROFILER #include <gperftools/profiler.h> #endif namespace { static unsigned NUM_COLS; static size_t K; static unsigned NUM_ROWS; short OMP_MAX_THREADS; static unsigned g_num_changed = 0; static const unsigned INVALID_CLUSTER_ID = std::numeric_limits<unsigned>::max(); static struct timeval start, end; static init_type_t g_init_type; /** * \brief This initializes clusters by randomly choosing sample * membership in a cluster. * See: http://en.wikipedia.org/wiki/K-means_clustering#Initialization_methods * \param cluster_assignments Which cluster each sample falls into. */ static void random_partition_init(unsigned* cluster_assignments, const double* matrix, clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Random init start"; // #pragma omp parallel for firstprivate(cluster_assignments, K) shared(cluster_assignments) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = random() % K; // 0...K clusters->add_member(&matrix[row*NUM_COLS], asgnd_clust); cluster_assignments[row] = asgnd_clust; } // NOTE: M-Step called in compute func to update cluster counts & centers #if VERBOSE printf("After rand paritions cluster_asgns: "); print_arr(cluster_assignments, NUM_ROWS); #endif BOOST_LOG_TRIVIAL(info) << "Random init end\n"; } /** * \brief Forgy init takes `K` random samples from the matrix * and uses them as cluster centers. * \param matrix the flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. */ static void forgy_init(const double* matrix, clusters::ptr clusters) { BOOST_LOG_TRIVIAL(info) << "Forgy init start"; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { // 0...K unsigned rand_idx = random() % (NUM_ROWS - 1); // 0...(n-1) clusters->set_mean(&matrix[rand_idx*NUM_COLS], clust_idx); } BOOST_LOG_TRIVIAL(info) << "Forgy init end"; } /** * \brief A parallel version of the kmeans++ initialization alg. * See: http://ilpubs.stanford.edu:8090/778/1/2006-13.pdf for algorithm */ static void kmeanspp_init(const double* matrix, clusters::ptr clusters, unsigned* cluster_assignments, std::vector<double>& dist_v) { // Choose c1 uniiformly at random unsigned selected_idx = random() % NUM_ROWS; // 0...(NUM_ROWS-1) clusters->set_mean(&matrix[selected_idx*NUM_COLS], 0); dist_v[selected_idx] = 0.0; #if KM_TEST BOOST_LOG_TRIVIAL(info) << "\nChoosing " << selected_idx << " as center K = 0"; #endif unsigned clust_idx = 0; // The number of clusters assigned // Choose next center c_i with weighted prob while ((clust_idx + 1) < K) { double cum_dist = 0; #pragma omp parallel for reduction(+:cum_dist) shared (dist_v) for (size_t row = 0; row < NUM_ROWS; row++) { double dist = dist_comp_raw(&matrix[row*NUM_COLS], &((clusters->get_means())[clust_idx*NUM_COLS]), NUM_COLS); if (dist < dist_v[row]) { // Found a closer cluster than before dist_v[row] = dist; cluster_assignments[row] = clust_idx; } cum_dist += dist_v[row]; } cum_dist = (cum_dist * ((double)random())) / (RAND_MAX - 1.0); clust_idx++; for (size_t i=0; i < NUM_ROWS; i++) { cum_dist -= dist_v[i]; if (cum_dist <= 0) { #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Choosing " << i << " as center K = " << clust_idx; #endif clusters->set_mean(&(matrix[i*NUM_COLS]), clust_idx); break; } } assert (cum_dist <= 0); } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "\nCluster centers after kmeans++"; clusters->print_means(); #endif } /** * \brief Update the cluster assignments while recomputing distance matrix. * \param matrix The flattened matrix who's rows are being clustered. * \param clusters The cluster centers (means) flattened matrix. * \param cluster_assignments Which cluster each sample falls into. */ static void EM_step(const double* matrix, clusters::ptr cls, unsigned* cluster_assignments, unsigned* cluster_assignment_counts) { std::vector<clusters::ptr> pt_cl(OMP_MAX_THREADS); // Per thread changed cluster count. OMP_MAX_THREADS std::vector<size_t> pt_num_change(OMP_MAX_THREADS); for (int i = 0; i < OMP_MAX_THREADS; i++) pt_cl[i] = clusters::create(K, NUM_COLS); #pragma omp parallel for firstprivate(matrix, pt_cl)\ shared(cluster_assignments) schedule(static) for (unsigned row = 0; row < NUM_ROWS; row++) { size_t asgnd_clust = INVALID_CLUSTER_ID; double best, dist; dist = best = std::numeric_limits<double>::max(); for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { dist = dist_comp_raw(&matrix[row*NUM_COLS], &(cls->get_means()[clust_idx*NUM_COLS]), NUM_COLS); if (dist < best) { best = dist; asgnd_clust = clust_idx; } } BOOST_VERIFY(asgnd_clust != INVALID_CLUSTER_ID); if (asgnd_clust != cluster_assignments[row]) { pt_num_change[omp_get_thread_num()]++; } cluster_assignments[row] = asgnd_clust; pt_cl[omp_get_thread_num()]->add_member(&matrix[row*NUM_COLS], asgnd_clust); // Accumulate for local copies } #if VERBOSE BOOST_LOG_TRIVIAL(info) << "Clearing cluster assignment counts"; BOOST_LOG_TRIVIAL(info) << "Clearing cluster centers ..."; #endif cls->clear(); // Serial aggreate of OMP_MAX_THREADS vectors // TODO: Pool these for (int thd = 0; thd < OMP_MAX_THREADS; thd++) { // Updated the changed cluster count g_num_changed += pt_num_change[thd]; // Summation for cluster centers cls->peq(pt_cl[thd]); } unsigned chk_nmemb = 0; for (unsigned clust_idx = 0; clust_idx < K; clust_idx++) { cls->finalize(clust_idx); cluster_assignment_counts[clust_idx] = cls->get_num_members(clust_idx); chk_nmemb += cluster_assignment_counts[clust_idx]; } BOOST_VERIFY(chk_nmemb == NUM_ROWS); #if KM_TEST BOOST_LOG_TRIVIAL(info) << "Global number of changes: " << g_num_changed; #endif } } namespace fg { unsigned compute_kmeans(const double* matrix, double* clusters_ptr, unsigned* cluster_assignments, unsigned* cluster_assignment_counts, const unsigned num_rows, const unsigned num_cols, const unsigned k, const unsigned MAX_ITERS, const int max_threads, const std::string init, const double tolerance, const std::string dist_type) { #ifdef PROFILER ProfilerStart("matrix/kmeans.perf"); #endif NUM_COLS = num_cols; K = k; NUM_ROWS = num_rows; assert(max_threads > 0); OMP_MAX_THREADS = std::min(max_threads, get_num_omp_threads()); omp_set_num_threads(OMP_MAX_THREADS); BOOST_LOG_TRIVIAL(info) << "Running on " << OMP_MAX_THREADS << " threads!"; // Check k if (K > NUM_ROWS || K < 2 || K == (unsigned)-1) { BOOST_LOG_TRIVIAL(fatal) << "'k' must be between 2 and the number of rows in the matrix" << "k = " << K; exit(-1); } /*BOOST_LOG_TRIVIAL(info) << "Projecting onto a sphere:"; spherical_projection(matrix, NUM_ROWS, NUM_COLS);*/ gettimeofday(&start , NULL); /*** Begin VarInit of data structures ***/ std::fill(&cluster_assignments[0], (&cluster_assignments[0])+NUM_ROWS, -1); std::fill(&cluster_assignment_counts[0], (&cluster_assignment_counts[0])+K, 0); clusters::ptr clusters = clusters::create(K, NUM_COLS); if (init == "none") clusters->set_mean(clusters_ptr); std::vector<double> dist_v; dist_v.assign(NUM_ROWS, std::numeric_limits<double>::max()); /*** End VarInit ***/ BOOST_LOG_TRIVIAL(info) << "Dist_type is " << dist_type; if (dist_type == "eucl") { g_dist_type = EUCL; } else if (dist_type == "cos") { g_dist_type = COS; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param dist_type must be one of: 'eucl', 'cos'.It is '" << dist_type << "'"; exit(-1); } if (init == "random") { random_partition_init(cluster_assignments, matrix, clusters); g_init_type = RANDOM; } else if (init == "forgy") { forgy_init(matrix, clusters); g_init_type = FORGY; } else if (init == "kmeanspp") { kmeanspp_init(matrix, clusters, cluster_assignments, dist_v); g_init_type = PLUSPLUS; } else if (init == "none") { g_init_type = NONE; } else { BOOST_LOG_TRIVIAL(fatal) << "[ERROR]: param init must be one of: " "'random', 'forgy', 'kmeanspp'.It is '" << init << "'"; exit(-1); } if (g_init_type == NONE || g_init_type == FORGY || g_init_type == RANDOM) { EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts); } gettimeofday(&end, NULL); BOOST_LOG_TRIVIAL(info) << "\n\nInitialization time taken = " << time_diff(start, end) << " sec\n"; gettimeofday(&start , NULL); BOOST_LOG_TRIVIAL(info) << "Init is '" << init << "'"; BOOST_LOG_TRIVIAL(info) << "Matrix K-means starting ..."; #if 0 FILE* f; BOOST_VERIFY(f = fopen("/mnt/nfs/disa/data/big/friendster-8-10centers", "wb")); fwrite(&((clusters->get_means())[0]), sizeof(double)*NUM_COLS*K, 1, f); fclose(f); printf("\n\nCenters should be:\n"); clusters->print_means(); exit(1); #endif bool converged = false; std::string str_iters = MAX_ITERS == std::numeric_limits<unsigned>::max() ? "until convergence ...": std::to_string(MAX_ITERS) + " iterations ..."; BOOST_LOG_TRIVIAL(info) << "Computing " << str_iters; unsigned iter = 1; while (iter < MAX_ITERS) { // Hold cluster assignment counter BOOST_LOG_TRIVIAL(info) << "E-step Iteration " << iter << ". Computing cluster assignments ..."; EM_step(matrix, clusters, cluster_assignments, cluster_assignment_counts); #if KM_TEST printf("Cluster assignment counts: "); print_arr(cluster_assignment_counts, K); #endif if (g_num_changed == 0 || ((g_num_changed/(double)NUM_ROWS)) <= tolerance) { converged = true; break; } else { g_num_changed = 0; } iter++; } gettimeofday(&end, NULL); BOOST_LOG_TRIVIAL(info) << "\n\nAlgorithmic time taken = " << time_diff(start, end) << " sec\n"; #ifdef PROFILER ProfilerStop(); #endif BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; if (converged) { BOOST_LOG_TRIVIAL(info) << "K-means converged in " << iter << " iterations"; } else { BOOST_LOG_TRIVIAL(warning) << "[Warning]: K-means failed to converge in " << iter << " iterations"; } BOOST_LOG_TRIVIAL(info) << "\n******************************************\n"; #if VERBOSE printf("Computed bic: %f\n", get_bic(dist_v, NUM_ROWS, NUM_COLS, K)); unsigned max_index = (std::max_element(cluster_assignment_counts, cluster_assignment_counts+K) - cluster_assignment_counts); store_cluster(max_index, matrix, cluster_assignment_counts[max_index], cluster_assignments, NUM_ROWS, NUM_COLS, "/mnt/nfs/disa/data/big/"); #endif return iter; } } <|endoftext|>
<commit_before><commit_msg>119 solved<commit_after><|endoftext|>
<commit_before>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # include <strsafe.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::Native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = Path{resourceDirectory.data(), Path::Format::Native}; engine.log(Log::Level::Info) << "Application directory: " << appPath; #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; const auto executablePath = Path{executableDirectory, Path::Format::Native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); Path path = Path{appDataPath, Path::Format::Native}; HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::Native}; DWORD handle; const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle); if (!fileVersionSize) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size"); auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize); if (!GetFileVersionInfoW(executablePath.getNative().c_str(), handle, fileVersionSize, fileVersionBuffer.get())) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version"); LPWSTR companyName = nullptr; LPWSTR productName = nullptr; struct LANGANDCODEPAGE final { WORD wLanguage; WORD wCodePage; }; LPVOID translationPointer; UINT translationLength; if (VerQueryValueW(fileVersionBuffer.get(), L"\\VarFileInfo\\Translation", &translationPointer, &translationLength)) { auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer); for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i) { constexpr size_t subBlockSize = 37; WCHAR subBlock[subBlockSize]; StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\040904b0\\CompanyName", translation[i].wLanguage, translation[i].wCodePage); LPVOID companyNamePointer; UINT companyNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &companyNamePointer, &companyNameLength)) companyName = static_cast<LPWSTR>(companyNamePointer); StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\040904b0\\ProductName", translation[i].wLanguage, translation[i].wCodePage); LPVOID productNamePointer; UINT productNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &productNamePointer, &productNameLength)) productName = static_cast<LPWSTR>(productNamePointer); } } if (companyName) path /= companyName; else path /= OUZEL_DEVELOPER_NAME; if (!path.isDirectory()) createDirectory(path); if (productName) path /= productName; else path /= OUZEL_APPLICATION_NAME; if (!path.isDirectory()) createDirectory(path); return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::Native}; #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::Native}; #elif defined(__ANDROID__) static_cast<void>(user); EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) Path path; const char* homeDirectory = std::getenv("XDG_DATA_HOME"); if (homeDirectory) path = Path{homeDirectory, Path::Format::Native}; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = Path{pwent.pw_dir, Path::Format::Native}; path /= ".local"; if (!directoryExists(path)) createDirectory(path); path /= "share"; if (!directoryExists(path)) createDirectory(path); } path /= OUZEL_DEVELOPER_NAME; if (!directoryExists(path)) createDirectory(path); path /= OUZEL_APPLICATION_NAME; if (!directoryExists(path)) createDirectory(path); return path; #else return Path{}; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!filename.isAbsolute()) { EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + std::string(filename)); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream f(path, std::ios::binary); return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()}; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str()); const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return isDirectory(dirname); } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return isRegular(filename); } } // namespace storage } // namespace ouzel <commit_msg>Fix the Windows build<commit_after>// Copyright 2015-2020 Elviss Strazdins. All rights reserved. #include "../core/Setup.h" #include <algorithm> #include <fstream> #if defined(_WIN32) # pragma push_macro("WIN32_LEAN_AND_MEAN") # pragma push_macro("NOMINMAX") # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif # include <Windows.h> # include <ShlObj.h> # include <Shlwapi.h> # include <strsafe.h> # pragma pop_macro("WIN32_LEAN_AND_MEAN") # pragma pop_macro("NOMINMAX") #elif defined(__APPLE__) # include <TargetConditionals.h> # include <objc/message.h> # include <objc/NSObjCRuntime.h> # include <CoreFoundation/CoreFoundation.h> #elif defined(__ANDROID__) # include "../core/android/EngineAndroid.hpp" #elif defined(__linux__) # include <pwd.h> #endif #include "FileSystem.hpp" #include "Archive.hpp" #include "../core/Engine.hpp" #include "../utils/Log.hpp" #if defined(__APPLE__) # include "CfPointer.hpp" #endif namespace ouzel { namespace storage { FileSystem::FileSystem(Engine& initEngine): engine(initEngine) { #if defined(_WIN32) HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::Native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #elif defined(__APPLE__) CFBundleRef bundle = CFBundleGetMainBundle(); if (!bundle) throw std::runtime_error("Failed to get main bundle"); CfPointer<CFURLRef> relativePath = CFBundleCopyResourcesDirectoryURL(bundle); if (!relativePath) throw std::runtime_error("Failed to get resource directory"); CfPointer<CFURLRef> absolutePath = CFURLCopyAbsoluteURL(relativePath.get()); CfPointer<CFStringRef> path = CFURLCopyFileSystemPath(absolutePath.get(), kCFURLPOSIXPathStyle); const CFIndex maximumSize = CFStringGetMaximumSizeOfFileSystemRepresentation(path.get()); std::vector<char> resourceDirectory(static_cast<std::size_t>(maximumSize)); const Boolean result = CFStringGetFileSystemRepresentation(path.get(), resourceDirectory.data(), maximumSize); if (!result) throw std::runtime_error("Failed to get resource directory"); appPath = Path{resourceDirectory.data(), Path::Format::Native}; engine.log(Log::Level::Info) << "Application directory: " << appPath; #elif defined(__ANDROID__) // not available for Android #elif defined(__linux__) char executableDirectory[PATH_MAX]; ssize_t length; if ((length = readlink("/proc/self/exe", executableDirectory, sizeof(executableDirectory) - 1)) == -1) throw std::system_error(errno, std::system_category(), "Failed to get current directory"); executableDirectory[length] = '\0'; const auto executablePath = Path{executableDirectory, Path::Format::Native}; appPath = executablePath.getDirectory(); engine.log(Log::Level::Info) << "Application directory: " << appPath; #endif } Path FileSystem::getStorageDirectory(const bool user) const { #if defined(_WIN32) WCHAR appDataPath[MAX_PATH]; HRESULT hr; if (FAILED(hr = SHGetFolderPathW(nullptr, (user ? CSIDL_LOCAL_APPDATA : CSIDL_COMMON_APPDATA) | CSIDL_FLAG_CREATE, nullptr, SHGFP_TYPE_CURRENT, appDataPath))) throw std::system_error(hr, std::system_category(), "Failed to get the path of the AppData directory"); Path path = Path{appDataPath, Path::Format::Native}; HINSTANCE instance = GetModuleHandleW(nullptr); if (!instance) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module handle"); std::vector<WCHAR> buffer(MAX_PATH + 1); for (;;) { if (!GetModuleFileNameW(instance, buffer.data(), static_cast<DWORD>(buffer.size()))) throw std::system_error(GetLastError(), std::system_category(), "Failed to get module filename"); if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) buffer.resize(buffer.size() * 2); else break; } const auto executablePath = Path{buffer.data(), Path::Format::Native}; DWORD handle; const DWORD fileVersionSize = GetFileVersionInfoSizeW(executablePath.getNative().c_str(), &handle); if (!fileVersionSize) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version size"); auto fileVersionBuffer = std::make_unique<char[]>(fileVersionSize); if (!GetFileVersionInfoW(executablePath.getNative().c_str(), handle, fileVersionSize, fileVersionBuffer.get())) throw std::system_error(GetLastError(), std::system_category(), "Failed to get file version"); LPWSTR companyName = nullptr; LPWSTR productName = nullptr; struct LANGANDCODEPAGE final { WORD wLanguage; WORD wCodePage; }; LPVOID translationPointer; UINT translationLength; if (VerQueryValueW(fileVersionBuffer.get(), L"\\VarFileInfo\\Translation", &translationPointer, &translationLength)) { auto translation = static_cast<const LANGANDCODEPAGE*>(translationPointer); for (UINT i = 0; i < translationLength / sizeof(LANGANDCODEPAGE); ++i) { constexpr size_t subBlockSize = 37; WCHAR subBlock[subBlockSize]; StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\040904b0\\CompanyName", translation[i].wLanguage, translation[i].wCodePage); LPVOID companyNamePointer; UINT companyNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &companyNamePointer, &companyNameLength)) companyName = static_cast<LPWSTR>(companyNamePointer); StringCchPrintfW(subBlock, subBlockSize, L"\\StringFileInfo\\040904b0\\ProductName", translation[i].wLanguage, translation[i].wCodePage); LPVOID productNamePointer; UINT productNameLength; if (VerQueryValueW(fileVersionBuffer.get(), subBlock, &productNamePointer, &productNameLength)) productName = static_cast<LPWSTR>(productNamePointer); } } if (companyName) path /= companyName; else path /= OUZEL_DEVELOPER_NAME; if (!isDirectory(path)) createDirectory(path); if (productName) path /= productName; else path /= OUZEL_APPLICATION_NAME; if (!isDirectory(path)) createDirectory(path); return path; #elif TARGET_OS_IOS || TARGET_OS_TV id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSDocumentDirectory = 9; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id documentDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSDocumentDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!documentDirectory) throw std::runtime_error("Failed to get document directory"); id documentDirectoryString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(documentDirectory, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(documentDirectoryString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::Native}; #elif TARGET_OS_MAC id fileManager = reinterpret_cast<id (*)(Class, SEL)>(&objc_msgSend)(objc_getClass("NSFileManager"), sel_getUid("defaultManager")); constexpr NSUInteger NSApplicationSupportDirectory = 14; constexpr NSUInteger NSUserDomainMask = 1; constexpr NSUInteger NSLocalDomainMask = 2; id applicationSupportDirectory = reinterpret_cast<id (*)(id, SEL, NSUInteger, NSUInteger, id, BOOL, id*)>(&objc_msgSend)(fileManager, sel_getUid("URLForDirectory:inDomain:appropriateForURL:create:error:"), NSApplicationSupportDirectory, user ? NSUserDomainMask : NSLocalDomainMask, nil, YES, nil); if (!applicationSupportDirectory) throw std::runtime_error("Failed to get application support directory"); CFBundleRef bundle = CFBundleGetMainBundle(); CFStringRef identifier = CFBundleGetIdentifier(bundle); if (!identifier) identifier = CFSTR(OUZEL_DEVELOPER_NAME "." OUZEL_APPLICATION_NAME); id path = reinterpret_cast<id (*)(id, SEL, CFStringRef)>(&objc_msgSend)(applicationSupportDirectory, sel_getUid("URLByAppendingPathComponent:"), identifier); reinterpret_cast<void (*)(id, SEL, id, BOOL, id, id)>(&objc_msgSend)(fileManager, sel_getUid("createDirectoryAtURL:withIntermediateDirectories:attributes:error:"), path, YES, nil, nil); id pathString = reinterpret_cast<id (*)(id, SEL)>(&objc_msgSend)(path, sel_getUid("path")); auto pathUtf8String = reinterpret_cast<const char* (*)(id, SEL)>(&objc_msgSend)(pathString, sel_getUid("UTF8String")); return Path{pathUtf8String, Path::Format::Native}; #elif defined(__ANDROID__) static_cast<void>(user); EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); return engineAndroid.getFilesDirectory(); #elif defined(__linux__) Path path; const char* homeDirectory = std::getenv("XDG_DATA_HOME"); if (homeDirectory) path = Path{homeDirectory, Path::Format::Native}; else { struct passwd pwent; struct passwd* pwentp; std::vector<char> buffer(1024); int e; while ((e = getpwuid_r(getuid(), &pwent, buffer.data(), buffer.size(), &pwentp)) == ERANGE) buffer.resize(buffer.size() * 2); if (e != 0) throw std::runtime_error("Failed to get home directory"); else path = Path{pwent.pw_dir, Path::Format::Native}; path /= ".local"; if (!isDirectory(path)) createDirectory(path); path /= "share"; if (!isDirectory(path)) createDirectory(path); } path /= OUZEL_DEVELOPER_NAME; if (!isDirectory(path)) createDirectory(path); path /= OUZEL_APPLICATION_NAME; if (!isDirectory(path)) createDirectory(path); return path; #else return Path{}; #endif } std::vector<std::uint8_t> FileSystem::readFile(const Path& filename, const bool searchResources) { if (searchResources) for (auto& archive : archives) if (archive.second.fileExists(filename)) return archive.second.readFile(filename); #if defined(__ANDROID__) if (!filename.isAbsolute()) { EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (!asset) throw std::runtime_error("Failed to open file " + std::string(filename)); std::vector<std::uint8_t> data; std::uint8_t buffer[1024]; for (;;) { const int bytesRead = AAsset_read(asset, buffer, sizeof(buffer)); if (bytesRead < 0) throw std::runtime_error("Failed to read from file"); else if (bytesRead == 0) break; data.insert(data.end(), buffer, buffer + bytesRead); } AAsset_close(asset); return data; } #endif const auto path = getPath(filename, searchResources); // file does not exist if (path.isEmpty()) throw std::runtime_error("Failed to find file " + std::string(filename)); std::ifstream f(path, std::ios::binary); return {std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()}; } bool FileSystem::resourceFileExists(const Path& filename) const { if (filename.isAbsolute()) return fileExists(filename); else { Path result = appPath / filename; if (fileExists(result)) return true; else for (const auto& path : resourcePaths) { if (path.isAbsolute()) // if resource path is absolute result = path / filename; else result = appPath / path / filename; if (fileExists(result)) return true; } return false; } } bool FileSystem::directoryExists(const Path& dirname) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAssetDir* assetDir = AAssetManager_openDir(engineAndroid.getAssetManager(), dirname.getNative().c_str()); const bool exists = AAssetDir_getNextFileName(assetDir) != nullptr; AAssetDir_close(assetDir); if (exists) return true; #endif return isDirectory(dirname); } bool FileSystem::fileExists(const Path& filename) const { #if defined(__ANDROID__) EngineAndroid& engineAndroid = static_cast<EngineAndroid&>(engine); AAsset* asset = AAssetManager_open(engineAndroid.getAssetManager(), filename.getNative().c_str(), AASSET_MODE_STREAMING); if (asset) { AAsset_close(asset); return true; } #endif return isRegular(filename); } } // namespace storage } // namespace ouzel <|endoftext|>
<commit_before>typedef unsigned int size_t; void clean(); void funcTest1() { throw ("my exception!",546); // BAD } void DllMain() { try { throw "my exception!"; } // BAD catch (...) { } } void funcTest2() { try { throw "my exception!"; } // GOOD catch (...) { clean(); } } void TestFunc() { funcTest1(); DllMain(); funcTest2(); } <commit_msg>Update test.cpp<commit_after>namespace std { class exception { }; class runtime_error : public exception { public: runtime_error(const char *msg); }; } typedef unsigned int size_t; void clean(); void funcTest1() { throw ("my exception!",546); // BAD } void DllMain() { try { throw "my exception!"; } // BAD catch (...) { } } void funcTest2() { try { throw "my exception!"; } // GOOD catch (...) { clean(); } } void funcTest3() { std::runtime_error("msg error"); // BAD throw std::runtime_error("msg error"); // GOOD } void TestFunc() { funcTest1(); DllMain(); funcTest2(); } <|endoftext|>
<commit_before>/* * Copyright 2018 The Cartographer Authors * * 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 "cartographer/mapping/2d/tsdf_range_data_inserter_2d.h" #include "cartographer/mapping/internal/2d/normal_estimation_2d.h" #include "cartographer/mapping/internal/2d/ray_to_pixel_mask.h" namespace cartographer { namespace mapping { namespace { // Factor for subpixel accuracy of start and end point for ray casts. constexpr int kSubpixelScale = 1000; // Minimum distance between range observation and origin. Otherwise, range // observations are discarded. constexpr float kMinRangeMeters = 1e-6f; const float kSqrtTwoPi = std::sqrt(2.0 * M_PI); void GrowAsNeeded(const sensor::RangeData& range_data, const float truncation_distance, TSDF2D* const tsdf) { Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>()); for (const sensor::RangefinderPoint& hit : range_data.returns) { const Eigen::Vector3f direction = (hit.position - range_data.origin).normalized(); const Eigen::Vector3f end_position = hit.position + truncation_distance * direction; bounding_box.extend(end_position.head<2>()); } // Padding around bounding box to avoid numerical issues at cell boundaries. constexpr float kPadding = 1e-6f; tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones()); tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones()); } float GaussianKernel(const float x, const float sigma) { return 1.0 / (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x / (sigma * sigma)); } std::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay( const Eigen::Vector2f& begin, const Eigen::Vector2f& end, TSDF2D* const tsdf) { const MapLimits& limits = tsdf->limits(); const double superscaled_resolution = limits.resolution() / kSubpixelScale; const MapLimits superscaled_limits( superscaled_resolution, limits.max(), CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale, limits.cell_limits().num_y_cells * kSubpixelScale)); const Eigen::Array2i superscaled_begin = superscaled_limits.GetCellIndex(begin); const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end); return std::make_pair(superscaled_begin, superscaled_end); } struct RangeDataSorter { RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); } bool operator()(const sensor::RangefinderPoint& lhs, const sensor::RangefinderPoint& rhs) { const Eigen::Vector2f delta_lhs = (lhs.position.head<2>() - origin_).normalized(); const Eigen::Vector2f delta_rhs = (lhs.position.head<2>() - origin_).normalized(); if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) { return delta_lhs[1] < 0.f; } else if (delta_lhs[1] < 0.f) { return delta_lhs[0] < delta_rhs[0]; } else { return delta_lhs[0] > delta_rhs[0]; } } private: Eigen::Vector2f origin_; }; float ComputeRangeWeightFactor(float range, int exponent) { float weight = 0.f; if (std::abs(range) > kMinRangeMeters) { weight = 1.f / (std::pow(range, exponent)); } return weight; } } // namespace proto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D( common::LuaParameterDictionary* parameter_dictionary) { proto::TSDFRangeDataInserterOptions2D options; options.set_truncation_distance( parameter_dictionary->GetDouble("truncation_distance")); options.set_maximum_weight(parameter_dictionary->GetDouble("maximum_weight")); options.set_update_free_space( parameter_dictionary->GetBool("update_free_space")); *options .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D( parameter_dictionary->GetDictionary("normal_estimation_options").get()); options.set_project_sdf_distance_to_scan_normal( parameter_dictionary->GetBool("project_sdf_distance_to_scan_normal")); options.set_update_weight_range_exponent( parameter_dictionary->GetInt("update_weight_range_exponent")); options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth( parameter_dictionary->GetDouble( "update_weight_angle_scan_normal_to_ray_kernel_bandwidth")); options.set_update_weight_distance_cell_to_hit_kernel_bandwidth( parameter_dictionary->GetDouble( "update_weight_distance_cell_to_hit_kernel_bandwidth")); return options; } TSDFRangeDataInserter2D::TSDFRangeDataInserter2D( const proto::TSDFRangeDataInserterOptions2D& options) : options_(options) {} // Casts a ray from origin towards hit for each hit in range data. // If 'options.update_free_space' is 'true', all cells along the ray // until 'truncation_distance' behind hit are updated. Otherwise, only the cells // within 'truncation_distance' around hit are updated. void TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data, GridInterface* grid) const { const float truncation_distance = static_cast<float>(options_.truncation_distance()); TSDF2D* tsdf = static_cast<TSDF2D*>(grid); GrowAsNeeded(range_data, truncation_distance, tsdf); // Compute normals if needed. bool scale_update_weight_angle_scan_normal_to_ray = options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f; sensor::RangeData sorted_range_data = range_data; std::vector<float> normals; if (options_.project_sdf_distance_to_scan_normal() || scale_update_weight_angle_scan_normal_to_ray) { std::sort(sorted_range_data.returns.begin(), sorted_range_data.returns.end(), RangeDataSorter(sorted_range_data.origin)); normals = EstimateNormals(sorted_range_data, options_.normal_estimation_options()); } const Eigen::Vector2f origin = sorted_range_data.origin.head<2>(); for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size(); ++hit_index) { const Eigen::Vector2f hit = sorted_range_data.returns[hit_index].position.head<2>(); const float normal = normals.empty() ? std::numeric_limits<float>::quiet_NaN() : normals[hit_index]; InsertHit(options_, hit, origin, normal, tsdf); } tsdf->FinishUpdate(); } void TSDFRangeDataInserter2D::InsertHit( const proto::TSDFRangeDataInserterOptions2D& options, const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal, TSDF2D* tsdf) const { const Eigen::Vector2f ray = hit - origin; const float range = ray.norm(); const float truncation_distance = static_cast<float>(options_.truncation_distance()); if (range < truncation_distance) return; const float truncation_ratio = truncation_distance / range; const Eigen::Vector2f ray_begin = options_.update_free_space() ? origin : origin + (1.0f - truncation_ratio) * ray; const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray; std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray = SuperscaleRay(ray_begin, ray_end, tsdf); std::vector<Eigen::Array2i> ray_mask = RayToPixelMask( superscaled_ray.first, superscaled_ray.second, kSubpixelScale); // Precompute weight factors. float weight_factor_angle_ray_normal = 1.f; if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f) { const Eigen::Vector2f negative_ray = -ray; float angle_ray_normal = common::NormalizeAngleDifference(normal - common::atan2(negative_ray)); weight_factor_angle_ray_normal = GaussianKernel( angle_ray_normal, options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth()); } float weight_factor_range = 1.f; if (options_.update_weight_range_exponent() != 0) { weight_factor_range = ComputeRangeWeightFactor( range, options_.update_weight_range_exponent()); } // Update Cells. for (const Eigen::Array2i& cell_index : ray_mask) { if (tsdf->CellIsUpdated(cell_index)) continue; Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index); float distance_cell_to_origin = (cell_center - origin).norm(); float update_tsd = range - distance_cell_to_origin; if (options_.project_sdf_distance_to_scan_normal()) { float normal_orientation = normal; update_tsd = (cell_center - hit) .dot(Eigen::Vector2f{std::cos(normal_orientation), std::sin(normal_orientation)}); } update_tsd = common::Clamp(update_tsd, -truncation_distance, truncation_distance); float update_weight = weight_factor_range * weight_factor_angle_ray_normal; if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) { update_weight *= GaussianKernel( update_tsd, options_.update_weight_distance_cell_to_hit_kernel_bandwidth()); } UpdateCell(cell_index, update_tsd, update_weight, tsdf); } } void TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell, float update_sdf, float update_weight, TSDF2D* tsdf) const { if (update_weight == 0.f) return; const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell); float updated_weight = tsd_and_weight.second + update_weight; float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second + update_sdf * update_weight) / updated_weight; updated_weight = std::min(updated_weight, static_cast<float>(options_.maximum_weight())); tsdf->SetCell(cell, updated_sdf, updated_weight); } } // namespace mapping } // namespace cartographer <commit_msg>Fix typo in tsdf_range_data_inserter_2d.cc (#1612)<commit_after>/* * Copyright 2018 The Cartographer Authors * * 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 "cartographer/mapping/2d/tsdf_range_data_inserter_2d.h" #include "cartographer/mapping/internal/2d/normal_estimation_2d.h" #include "cartographer/mapping/internal/2d/ray_to_pixel_mask.h" namespace cartographer { namespace mapping { namespace { // Factor for subpixel accuracy of start and end point for ray casts. constexpr int kSubpixelScale = 1000; // Minimum distance between range observation and origin. Otherwise, range // observations are discarded. constexpr float kMinRangeMeters = 1e-6f; const float kSqrtTwoPi = std::sqrt(2.0 * M_PI); void GrowAsNeeded(const sensor::RangeData& range_data, const float truncation_distance, TSDF2D* const tsdf) { Eigen::AlignedBox2f bounding_box(range_data.origin.head<2>()); for (const sensor::RangefinderPoint& hit : range_data.returns) { const Eigen::Vector3f direction = (hit.position - range_data.origin).normalized(); const Eigen::Vector3f end_position = hit.position + truncation_distance * direction; bounding_box.extend(end_position.head<2>()); } // Padding around bounding box to avoid numerical issues at cell boundaries. constexpr float kPadding = 1e-6f; tsdf->GrowLimits(bounding_box.min() - kPadding * Eigen::Vector2f::Ones()); tsdf->GrowLimits(bounding_box.max() + kPadding * Eigen::Vector2f::Ones()); } float GaussianKernel(const float x, const float sigma) { return 1.0 / (kSqrtTwoPi * sigma) * std::exp(-0.5 * x * x / (sigma * sigma)); } std::pair<Eigen::Array2i, Eigen::Array2i> SuperscaleRay( const Eigen::Vector2f& begin, const Eigen::Vector2f& end, TSDF2D* const tsdf) { const MapLimits& limits = tsdf->limits(); const double superscaled_resolution = limits.resolution() / kSubpixelScale; const MapLimits superscaled_limits( superscaled_resolution, limits.max(), CellLimits(limits.cell_limits().num_x_cells * kSubpixelScale, limits.cell_limits().num_y_cells * kSubpixelScale)); const Eigen::Array2i superscaled_begin = superscaled_limits.GetCellIndex(begin); const Eigen::Array2i superscaled_end = superscaled_limits.GetCellIndex(end); return std::make_pair(superscaled_begin, superscaled_end); } struct RangeDataSorter { RangeDataSorter(Eigen::Vector3f origin) { origin_ = origin.head<2>(); } bool operator()(const sensor::RangefinderPoint& lhs, const sensor::RangefinderPoint& rhs) { const Eigen::Vector2f delta_lhs = (lhs.position.head<2>() - origin_).normalized(); const Eigen::Vector2f delta_rhs = (rhs.position.head<2>() - origin_).normalized(); if ((delta_lhs[1] < 0.f) != (delta_rhs[1] < 0.f)) { return delta_lhs[1] < 0.f; } else if (delta_lhs[1] < 0.f) { return delta_lhs[0] < delta_rhs[0]; } else { return delta_lhs[0] > delta_rhs[0]; } } private: Eigen::Vector2f origin_; }; float ComputeRangeWeightFactor(float range, int exponent) { float weight = 0.f; if (std::abs(range) > kMinRangeMeters) { weight = 1.f / (std::pow(range, exponent)); } return weight; } } // namespace proto::TSDFRangeDataInserterOptions2D CreateTSDFRangeDataInserterOptions2D( common::LuaParameterDictionary* parameter_dictionary) { proto::TSDFRangeDataInserterOptions2D options; options.set_truncation_distance( parameter_dictionary->GetDouble("truncation_distance")); options.set_maximum_weight(parameter_dictionary->GetDouble("maximum_weight")); options.set_update_free_space( parameter_dictionary->GetBool("update_free_space")); *options .mutable_normal_estimation_options() = CreateNormalEstimationOptions2D( parameter_dictionary->GetDictionary("normal_estimation_options").get()); options.set_project_sdf_distance_to_scan_normal( parameter_dictionary->GetBool("project_sdf_distance_to_scan_normal")); options.set_update_weight_range_exponent( parameter_dictionary->GetInt("update_weight_range_exponent")); options.set_update_weight_angle_scan_normal_to_ray_kernel_bandwidth( parameter_dictionary->GetDouble( "update_weight_angle_scan_normal_to_ray_kernel_bandwidth")); options.set_update_weight_distance_cell_to_hit_kernel_bandwidth( parameter_dictionary->GetDouble( "update_weight_distance_cell_to_hit_kernel_bandwidth")); return options; } TSDFRangeDataInserter2D::TSDFRangeDataInserter2D( const proto::TSDFRangeDataInserterOptions2D& options) : options_(options) {} // Casts a ray from origin towards hit for each hit in range data. // If 'options.update_free_space' is 'true', all cells along the ray // until 'truncation_distance' behind hit are updated. Otherwise, only the cells // within 'truncation_distance' around hit are updated. void TSDFRangeDataInserter2D::Insert(const sensor::RangeData& range_data, GridInterface* grid) const { const float truncation_distance = static_cast<float>(options_.truncation_distance()); TSDF2D* tsdf = static_cast<TSDF2D*>(grid); GrowAsNeeded(range_data, truncation_distance, tsdf); // Compute normals if needed. bool scale_update_weight_angle_scan_normal_to_ray = options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f; sensor::RangeData sorted_range_data = range_data; std::vector<float> normals; if (options_.project_sdf_distance_to_scan_normal() || scale_update_weight_angle_scan_normal_to_ray) { std::sort(sorted_range_data.returns.begin(), sorted_range_data.returns.end(), RangeDataSorter(sorted_range_data.origin)); normals = EstimateNormals(sorted_range_data, options_.normal_estimation_options()); } const Eigen::Vector2f origin = sorted_range_data.origin.head<2>(); for (size_t hit_index = 0; hit_index < sorted_range_data.returns.size(); ++hit_index) { const Eigen::Vector2f hit = sorted_range_data.returns[hit_index].position.head<2>(); const float normal = normals.empty() ? std::numeric_limits<float>::quiet_NaN() : normals[hit_index]; InsertHit(options_, hit, origin, normal, tsdf); } tsdf->FinishUpdate(); } void TSDFRangeDataInserter2D::InsertHit( const proto::TSDFRangeDataInserterOptions2D& options, const Eigen::Vector2f& hit, const Eigen::Vector2f& origin, float normal, TSDF2D* tsdf) const { const Eigen::Vector2f ray = hit - origin; const float range = ray.norm(); const float truncation_distance = static_cast<float>(options_.truncation_distance()); if (range < truncation_distance) return; const float truncation_ratio = truncation_distance / range; const Eigen::Vector2f ray_begin = options_.update_free_space() ? origin : origin + (1.0f - truncation_ratio) * ray; const Eigen::Vector2f ray_end = origin + (1.0f + truncation_ratio) * ray; std::pair<Eigen::Array2i, Eigen::Array2i> superscaled_ray = SuperscaleRay(ray_begin, ray_end, tsdf); std::vector<Eigen::Array2i> ray_mask = RayToPixelMask( superscaled_ray.first, superscaled_ray.second, kSubpixelScale); // Precompute weight factors. float weight_factor_angle_ray_normal = 1.f; if (options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth() != 0.f) { const Eigen::Vector2f negative_ray = -ray; float angle_ray_normal = common::NormalizeAngleDifference(normal - common::atan2(negative_ray)); weight_factor_angle_ray_normal = GaussianKernel( angle_ray_normal, options_.update_weight_angle_scan_normal_to_ray_kernel_bandwidth()); } float weight_factor_range = 1.f; if (options_.update_weight_range_exponent() != 0) { weight_factor_range = ComputeRangeWeightFactor( range, options_.update_weight_range_exponent()); } // Update Cells. for (const Eigen::Array2i& cell_index : ray_mask) { if (tsdf->CellIsUpdated(cell_index)) continue; Eigen::Vector2f cell_center = tsdf->limits().GetCellCenter(cell_index); float distance_cell_to_origin = (cell_center - origin).norm(); float update_tsd = range - distance_cell_to_origin; if (options_.project_sdf_distance_to_scan_normal()) { float normal_orientation = normal; update_tsd = (cell_center - hit) .dot(Eigen::Vector2f{std::cos(normal_orientation), std::sin(normal_orientation)}); } update_tsd = common::Clamp(update_tsd, -truncation_distance, truncation_distance); float update_weight = weight_factor_range * weight_factor_angle_ray_normal; if (options_.update_weight_distance_cell_to_hit_kernel_bandwidth() != 0.f) { update_weight *= GaussianKernel( update_tsd, options_.update_weight_distance_cell_to_hit_kernel_bandwidth()); } UpdateCell(cell_index, update_tsd, update_weight, tsdf); } } void TSDFRangeDataInserter2D::UpdateCell(const Eigen::Array2i& cell, float update_sdf, float update_weight, TSDF2D* tsdf) const { if (update_weight == 0.f) return; const std::pair<float, float> tsd_and_weight = tsdf->GetTSDAndWeight(cell); float updated_weight = tsd_and_weight.second + update_weight; float updated_sdf = (tsd_and_weight.first * tsd_and_weight.second + update_sdf * update_weight) / updated_weight; updated_weight = std::min(updated_weight, static_cast<float>(options_.maximum_weight())); tsdf->SetCell(cell, updated_sdf, updated_weight); } } // namespace mapping } // namespace cartographer <|endoftext|>
<commit_before>#include <osg/Notify> #include <string> using namespace std; osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE; std::auto_ptr<ofstream> osg::g_NotifyNulStream; bool osg::g_NotifyInit = false; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { if (g_NotifyInit) return true; g_NotifyInit = true; // set up global notify null stream for inline notify #if defined(WIN32) && !defined(__CYGWIN__) g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul")); #else g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null")); #endif // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; } return true; } <commit_msg>Changed the Windows gauard around so that it only works for VisualStudio and not Cygwin/Mingw.<commit_after>#include <osg/Notify> #include <string> using namespace std; osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE; std::auto_ptr<ofstream> osg::g_NotifyNulStream; bool osg::g_NotifyInit = false; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { if (g_NotifyInit) return true; g_NotifyInit = true; // set up global notify null stream for inline notify #if defined(WIN32) && !(defined(__CYGWIN__) || defined(__MINGW32__)) g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul")); #else g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null")); #endif // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; } return true; } <|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. * * Modified by ScyllaDB * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <deque> namespace utils { /** * bounded threadsafe deque */ class bounded_stats_deque { private: std::deque<long> _deque; long _sum = 0; int _max_size; public: bounded_stats_deque(int size) : _max_size(size) { } int size() { return _deque.size(); } void add(long i) { if (size() >= _max_size) { auto removed = _deque.front(); _deque.pop_front(); _sum -= removed; } _deque.push_back(i); _sum += i; } long sum() { return _sum; } double mean() { return size() > 0 ? ((double) sum()) / size() : 0; } const std::deque<long>& deque() const { return _deque; } }; } <commit_msg>bounded_stats_queue: add missing const qualifiers<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. * * Modified by ScyllaDB * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <deque> namespace utils { /** * bounded threadsafe deque */ class bounded_stats_deque { private: std::deque<long> _deque; long _sum = 0; int _max_size; public: bounded_stats_deque(int size) : _max_size(size) { } int size() const { return _deque.size(); } void add(long i) { if (size() >= _max_size) { auto removed = _deque.front(); _deque.pop_front(); _sum -= removed; } _deque.push_back(i); _sum += i; } long sum() const { return _sum; } double mean() const { return size() > 0 ? ((double) sum()) / size() : 0; } const std::deque<long>& deque() const { return _deque; } }; } <|endoftext|>
<commit_before>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RANDOM_H #define RANDOM_H #if defined(_MSC_VER) && !defined(__GNUC__) #pragma warning (disable:4786) #endif #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> %} #else #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> using namespace boost::numeric; #endif namespace csound { /** * A random value will be sampled from the specified distribution, * translated and scaled as specified, * and set in the specified row and column of the local coordinates. * The resulting matrix will be used in place of the local coordinates * when traversing the music graph. * If eventCount is greater than zero, a new event will be created * for each of eventCount samples, * which will be transformed by the newly sampled local coordinates. */ class SILENCE_PUBLIC Random : public Node { protected: #if !defined(SWIG) void *generator_; boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator; boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator; boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator; boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator; boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator; boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator; boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator; boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator; boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator; public: static boost::mt19937 mersenneTwister; #endif std::string distribution; int row; int column; int eventCount; bool incrementTime; double minimum; double maximum; double q; double a; double b; double c; double Lambda; double mean; double sigma; Random(); virtual ~Random(); virtual double sample() const; virtual ublas::matrix<double> getLocalCoordinates() const; virtual void createDistribution(std::string distribution); virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates); static void seed(int s); }; } #endif <commit_msg>Restore necessary functions to "public".<commit_after>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RANDOM_H #define RANDOM_H #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "Node.hpp" %} #else #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> using namespace boost::numeric; #endif namespace csound { /** * A random value will be sampled from the specified distribution, * translated and scaled as specified, * and set in the specified row and column of the local coordinates. * The resulting matrix will be used in place of the local coordinates * when traversing the music graph. * If eventCount is greater than zero, a new event will be created * for each of eventCount samples, * which will be transformed by the newly sampled local coordinates. */ class SILENCE_PUBLIC Random : public Node { protected: #if !defined(SWIG) void *generator_; boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator; boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator; boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator; boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator; boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator; boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator; boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator; boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator; boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator; public: static boost::mt19937 mersenneTwister; #endif public: std::string distribution; int row; int column; int eventCount; bool incrementTime; double minimum; double maximum; double q; double a; double b; double c; double Lambda; double mean; double sigma; Random(); virtual ~Random(); virtual double sample() const; virtual ublas::matrix<double> getLocalCoordinates() const; virtual void createDistribution(std::string distribution); virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates); static void seed(int s); }; } #endif <|endoftext|>
<commit_before>/* syslog.cpp :-) */ /* Revision: 1.14 25.07.2001 $ */ /* Modify: 25.07.2001 SVS - VC 24.07.2001 SVS + (IsDebuggerPresent), LOG- (OutputDebugString) ! 98- . 04.07.2001 SVS ! LOG- :-) + 27.06.2001 SVS ! LOG- :-) %FAR%\$Log Far.YYYYMMDD.BILD.log - BILD=%05d 25.06.2001 SVS ! StrFTime . 16.05.2001 SVS ! DumpExceptionInfo -> farexcpt.cpp + _SYSLOG_KM() 09.05.2001 OT ! , _D(x), 07.05.2001 SVS + DumpExceptionInfo FAR_VERSION 06.05.2001 DJ ! #include 06.05.2001 SVS ! SysLog* ;-) 29.04.2001 + NWZ 28.04.2001 SVS - , CONTEXT_INTEGER CONTEXT_SEGMENTS ! SysLog() + SysLogDump() = NULL, , . 26.01.2001 SVS ! DumpExeptionInfo -> DumpExceptionInfo ;-) 23.01.2001 SVS + DumpExeptionInfo() 22.12.2000 SVS + */ #include "headers.hpp" #pragma hdrstop #include "plugin.hpp" #include "global.hpp" #include "fn.hpp" #include "plugins.hpp" #if !defined(SYSLOG) #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM) #define SYSLOG #endif #endif #if defined(SYSLOG) char LogFileName[MAX_FILE]; static FILE *LogStream=0; static int Indent=0; static char *PrintTime(char *timebuf); extern "C" { WINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID); }; #endif #if defined(SYSLOG) char *MakeSpace(void) { static char Buf[60]=" "; if(Indent) memset(Buf+1,0xB3,Indent); Buf[1+Indent]=0; return Buf; } #endif FILE * OpenLogStream(char *file) { #if defined(SYSLOG) time_t t; struct tm *time_now; char RealLogName[NM*2]; SYSTEMTIME st; GetLocalTime(&st); sprintf(RealLogName,"%s\\Far.%04d%02d%02d.%05d.log", file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION)); return _fsopen(RealLogName,"a+t",SH_DENYWR); #else return NULL; #endif } void OpenSysLog() { #if defined(SYSLOG) if ( LogStream ) fclose(LogStream); DWORD Attr; GetModuleFileName(NULL,LogFileName,sizeof(LogFileName)); char *Ptr=strrchr(LogFileName,'\\'); strcpy(Ptr,"\\$Log"); Attr=GetFileAttributes(LogFileName); if(Attr == -1) { if(!CreateDirectory(LogFileName,NULL)) *Ptr=0; } else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY)) *Ptr=0; LogStream=OpenLogStream(LogFileName); //if ( !LogStream ) //{ // fprintf(stderr,"Can't open log file '%s'\n",LogFileName); //} #endif } void CloseSysLog(void) { #if defined(SYSLOG) fclose(LogStream); LogStream=0; #endif } void ShowHeap() { #if defined(SYSLOG) && defined(HEAPLOG) _HEAPINFO hi; SysLog( " Size Status" ); SysLog( " ---- ------" ); DWORD Sz=0; hi._pentry=NULL; // int *__pentry; while( _rtl_heapwalk( &hi ) == _HEAPOK ) { SysLog( "%7u %s (%p)", hi._size, (hi._useflag ? "used" : "free"),hi.__pentry); Sz+=hi._useflag?hi._size:0; } SysLog( " ---- ------" ); SysLog( "%7u ", Sz); #endif } void CheckHeap(int NumLine) { #if defined(SYSLOG) && defined(HEAPLOG) if (_heapchk()==_HEAPBADNODE) { SysLog("Error: Heap broken, Line=%d",NumLine); } #endif } void SysLog(int i) { #if defined(SYSLOG) Indent+=i; if ( Indent<0 ) Indent=0; #endif } #if defined(SYSLOG) static char *PrintTime(char *timebuf) { SYSTEMTIME st; GetLocalTime(&st); // sprintf(timebuf,"%02d.%02d.%04d %2d:%02d:%02d.%03d", // st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); sprintf(timebuf,"%02d:%02d:%02d.%03d",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); return timebuf; } #endif void SysLog(char *fmt,...) { #if defined(SYSLOG) char msg[MAX_LOG_LINE]; va_list argptr; va_start( argptr, fmt ); vsprintf( msg, fmt, argptr ); va_end(argptr); OpenSysLog(); if ( LogStream ) { char timebuf[64]; fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg); fflush(LogStream); } CloseSysLog(); if(IsDebuggerPresent()) { OutputDebugString(msg); } #endif } /// void SysLog(int l,char *fmt,...) { #if defined(SYSLOG) char msg[MAX_LOG_LINE]; va_list argptr; va_start( argptr, fmt ); vsprintf( msg, fmt, argptr ); va_end(argptr); SysLog(l); OpenSysLog(); if ( LogStream ) { char timebuf[64]; fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg); fflush(LogStream); } CloseSysLog(); if(IsDebuggerPresent()) { OutputDebugString(msg); } #endif } /// void SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp) { #if defined(SYSLOG) int CY=(SizeBuf+15)/16; int X,Y; int InternalLog=fp==NULL?TRUE:FALSE; // char msg[MAX_LOG_LINE]; if(InternalLog) { OpenSysLog(); fp=LogStream; if(fp) { char timebuf[64]; fprintf(fp,"%s %s(%s)\n",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title)); } } if (fp) { char TmpBuf[17]; int I; TmpBuf[16]=0; if(!InternalLog && Title && *Title) fprintf(fp,"%s\n",Title); for(Y=0; Y < CY; ++Y) { memset(TmpBuf,' ',16); fprintf(fp, " %08X: ",StartAddress+Y*16); for(X=0; X < 16; ++X) { if((I=Y*16+X < SizeBuf) != 0) fprintf(fp,"%02X ",Buf[Y*16+X]&0xFF); else fprintf(fp," "); TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' '; if(X == 7) fprintf(fp, " "); } fprintf(fp,"| %s\n",TmpBuf); } fprintf(fp,"\n"); fflush(fp); } if(InternalLog) CloseSysLog(); #endif } <commit_msg>FAR patch 00903.OutputDebugString Дата : 15.08.2001 Сделал : Oleg Taranenko Описание : "Перевод строки" в дебагере среды VC Измененные файлы : syslog.cpp Новые файлы : Удаленные файлы : Состав : 00903.OutputDebugString.txt syslog.cpp.903.diff Основан на патче : 902 Дополнение :<commit_after>/* syslog.cpp :-) */ /* Revision: 1.15 15.08.2001 $ */ /* Modify: 15.08.2001 OT - " " VC 25.07.2001 SVS - VC 24.07.2001 SVS + (IsDebuggerPresent), LOG- (OutputDebugString) ! 98- . 04.07.2001 SVS ! LOG- :-) + 27.06.2001 SVS ! LOG- :-) %FAR%\$Log Far.YYYYMMDD.BILD.log - BILD=%05d 25.06.2001 SVS ! StrFTime . 16.05.2001 SVS ! DumpExceptionInfo -> farexcpt.cpp + _SYSLOG_KM() 09.05.2001 OT ! , _D(x), 07.05.2001 SVS + DumpExceptionInfo FAR_VERSION 06.05.2001 DJ ! #include 06.05.2001 SVS ! SysLog* ;-) 29.04.2001 + NWZ 28.04.2001 SVS - , CONTEXT_INTEGER CONTEXT_SEGMENTS ! SysLog() + SysLogDump() = NULL, , . 26.01.2001 SVS ! DumpExeptionInfo -> DumpExceptionInfo ;-) 23.01.2001 SVS + DumpExeptionInfo() 22.12.2000 SVS + */ #include "headers.hpp" #pragma hdrstop #include "plugin.hpp" #include "global.hpp" #include "fn.hpp" #include "plugins.hpp" #if !defined(SYSLOG) #if defined(SYSLOG_OT) || defined(SYSLOG_SVS) || defined(SYSLOG_DJ) || defined(VVM) || defined(SYSLOG_AT) || defined(SYSLOG_IS) || defined(SYSLOG_tran) || defined(SYSLOG_SKV) || defined(SYSLOG_NWZ) || defined(SYSLOG_KM) #define SYSLOG #endif #endif #if defined(SYSLOG) char LogFileName[MAX_FILE]; static FILE *LogStream=0; static int Indent=0; static char *PrintTime(char *timebuf); extern "C" { WINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID); }; #endif #if defined(SYSLOG) char *MakeSpace(void) { static char Buf[60]=" "; if(Indent) memset(Buf+1,0xB3,Indent); Buf[1+Indent]=0; return Buf; } #endif FILE * OpenLogStream(char *file) { #if defined(SYSLOG) time_t t; struct tm *time_now; char RealLogName[NM*2]; SYSTEMTIME st; GetLocalTime(&st); sprintf(RealLogName,"%s\\Far.%04d%02d%02d.%05d.log", file,st.wYear,st.wMonth,st.wDay,HIWORD(FAR_VERSION)); return _fsopen(RealLogName,"a+t",SH_DENYWR); #else return NULL; #endif } void OpenSysLog() { #if defined(SYSLOG) if ( LogStream ) fclose(LogStream); DWORD Attr; GetModuleFileName(NULL,LogFileName,sizeof(LogFileName)); char *Ptr=strrchr(LogFileName,'\\'); strcpy(Ptr,"\\$Log"); Attr=GetFileAttributes(LogFileName); if(Attr == -1) { if(!CreateDirectory(LogFileName,NULL)) *Ptr=0; } else if(!(Attr&FILE_ATTRIBUTE_DIRECTORY)) *Ptr=0; LogStream=OpenLogStream(LogFileName); //if ( !LogStream ) //{ // fprintf(stderr,"Can't open log file '%s'\n",LogFileName); //} #endif } void CloseSysLog(void) { #if defined(SYSLOG) fclose(LogStream); LogStream=0; #endif } void ShowHeap() { #if defined(SYSLOG) && defined(HEAPLOG) _HEAPINFO hi; SysLog( " Size Status" ); SysLog( " ---- ------" ); DWORD Sz=0; hi._pentry=NULL; // int *__pentry; while( _rtl_heapwalk( &hi ) == _HEAPOK ) { SysLog( "%7u %s (%p)", hi._size, (hi._useflag ? "used" : "free"),hi.__pentry); Sz+=hi._useflag?hi._size:0; } SysLog( " ---- ------" ); SysLog( "%7u ", Sz); #endif } void CheckHeap(int NumLine) { #if defined(SYSLOG) && defined(HEAPLOG) if (_heapchk()==_HEAPBADNODE) { SysLog("Error: Heap broken, Line=%d",NumLine); } #endif } void SysLog(int i) { #if defined(SYSLOG) Indent+=i; if ( Indent<0 ) Indent=0; #endif } #if defined(SYSLOG) static char *PrintTime(char *timebuf) { SYSTEMTIME st; GetLocalTime(&st); // sprintf(timebuf,"%02d.%02d.%04d %2d:%02d:%02d.%03d", // st.wDay,st.wMonth,st.wYear,st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); sprintf(timebuf,"%02d:%02d:%02d.%03d",st.wHour,st.wMinute,st.wSecond,st.wMilliseconds); return timebuf; } #endif void SysLog(char *fmt,...) { #if defined(SYSLOG) char msg[MAX_LOG_LINE]; va_list argptr; va_start( argptr, fmt ); vsprintf( msg, fmt, argptr ); va_end(argptr); OpenSysLog(); if ( LogStream ) { char timebuf[64]; fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg); fflush(LogStream); } CloseSysLog(); if(IsDebuggerPresent()) { OutputDebugString(msg); #ifdef _MSC_VER OutputDebugString("\n"); #endif _MSC_VER } #endif } /// void SysLog(int l,char *fmt,...) { #if defined(SYSLOG) char msg[MAX_LOG_LINE]; va_list argptr; va_start( argptr, fmt ); vsprintf( msg, fmt, argptr ); va_end(argptr); SysLog(l); OpenSysLog(); if ( LogStream ) { char timebuf[64]; fprintf(LogStream,"%s %s%s\n",PrintTime(timebuf),MakeSpace(),msg); fflush(LogStream); } CloseSysLog(); if(IsDebuggerPresent()) { OutputDebugString(msg); } #endif } /// void SysLogDump(char *Title,DWORD StartAddress,LPBYTE Buf,int SizeBuf,FILE *fp) { #if defined(SYSLOG) int CY=(SizeBuf+15)/16; int X,Y; int InternalLog=fp==NULL?TRUE:FALSE; // char msg[MAX_LOG_LINE]; if(InternalLog) { OpenSysLog(); fp=LogStream; if(fp) { char timebuf[64]; fprintf(fp,"%s %s(%s)\n",PrintTime(timebuf),MakeSpace(),NullToEmpty(Title)); } } if (fp) { char TmpBuf[17]; int I; TmpBuf[16]=0; if(!InternalLog && Title && *Title) fprintf(fp,"%s\n",Title); for(Y=0; Y < CY; ++Y) { memset(TmpBuf,' ',16); fprintf(fp, " %08X: ",StartAddress+Y*16); for(X=0; X < 16; ++X) { if((I=Y*16+X < SizeBuf) != 0) fprintf(fp,"%02X ",Buf[Y*16+X]&0xFF); else fprintf(fp," "); TmpBuf[X]=I?(Buf[Y*16+X] < 32?'.':Buf[Y*16+X]):' '; if(X == 7) fprintf(fp, " "); } fprintf(fp,"| %s\n",TmpBuf); } fprintf(fp,"\n"); fflush(fp); } if(InternalLog) CloseSysLog(); #endif } <|endoftext|>
<commit_before>#include <osg/Notify> #include <string> using namespace std; osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE; std::auto_ptr<ofstream> osg::g_NotifyNulStream; bool osg::g_NotifyInit = false; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { if (g_NotifyInit) return true; g_NotifyInit = true; // set up global notify null stream for inline notify #if defined(WIN32) && !defined(__CYGWIN__) g_NotifyNulStream.reset(osgNew std::ofstream ("nul")); #else g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null")); #endif // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; } return true; } <commit_msg>Fix for VisualStudio's lack of auto_ptr::reset.<commit_after>#include <osg/Notify> #include <string> using namespace std; osg::NotifySeverity osg::g_NotifyLevel = osg::NOTICE; std::auto_ptr<ofstream> osg::g_NotifyNulStream; bool osg::g_NotifyInit = false; void osg::setNotifyLevel(osg::NotifySeverity severity) { osg::initNotifyLevel(); g_NotifyLevel = severity; } osg::NotifySeverity osg::getNotifyLevel() { osg::initNotifyLevel(); return g_NotifyLevel; } bool osg::initNotifyLevel() { if (g_NotifyInit) return true; g_NotifyInit = true; // set up global notify null stream for inline notify #if defined(WIN32) && !defined(__CYGWIN__) g_NotifyNulStream = std::auto_ptr<ofstream>(osgNew std::ofstream ("nul")); #else g_NotifyNulStream.reset(osgNew std::ofstream ("/dev/null")); #endif // g_NotifyLevel // ============= g_NotifyLevel = osg::NOTICE; // Default value char *OSGNOTIFYLEVEL=getenv("OSGNOTIFYLEVEL"); if(OSGNOTIFYLEVEL) { std::string stringOSGNOTIFYLEVEL(OSGNOTIFYLEVEL); // Convert to upper case for(std::string::iterator i=stringOSGNOTIFYLEVEL.begin(); i!=stringOSGNOTIFYLEVEL.end(); ++i) { *i=toupper(*i); } if(stringOSGNOTIFYLEVEL.find("ALWAYS")!=std::string::npos) g_NotifyLevel=osg::ALWAYS; else if(stringOSGNOTIFYLEVEL.find("FATAL")!=std::string::npos) g_NotifyLevel=osg::FATAL; else if(stringOSGNOTIFYLEVEL.find("WARN")!=std::string::npos) g_NotifyLevel=osg::WARN; else if(stringOSGNOTIFYLEVEL.find("NOTICE")!=std::string::npos) g_NotifyLevel=osg::NOTICE; else if(stringOSGNOTIFYLEVEL.find("INFO")!=std::string::npos) g_NotifyLevel=osg::INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_INFO")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; else if(stringOSGNOTIFYLEVEL.find("DEBUG_FP")!=std::string::npos) g_NotifyLevel=osg::DEBUG_FP; else if(stringOSGNOTIFYLEVEL.find("DEBUG")!=std::string::npos) g_NotifyLevel=osg::DEBUG_INFO; } return true; } <|endoftext|>
<commit_before>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RANDOM_H #define RANDOM_H #if defined(_MSC_VER) && !defined(__GNUC__) #pragma warning (disable:4786) #endif #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> %} #else #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> using namespace boost::numeric; #endif namespace csound { /** * A random value will be sampled from the specified distribution, * translated and scaled as specified, * and set in the specified row and column of the local coordinates. * The resulting matrix will be used in place of the local coordinates * when traversing the music graph. * If eventCount is greater than zero, a new event will be created * for each of eventCount samples, * which will be transformed by the newly sampled local coordinates. */ class SILENCE_PUBLIC Random : public Node { protected: #if !defined(SWIG) void *generator_; boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator; boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator; boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator; boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator; boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator; boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator; boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator; boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator; boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator; public: static boost::mt19937 mersenneTwister; #endif std::string distribution; int row; int column; int eventCount; bool incrementTime; double minimum; double maximum; double q; double a; double b; double c; double Lambda; double mean; double sigma; Random(); virtual ~Random(); virtual double sample() const; virtual ublas::matrix<double> getLocalCoordinates() const; virtual void createDistribution(std::string distribution); virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates); static void seed(int s); }; } #endif <commit_msg>Restore necessary functions to "public".<commit_after>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software 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 software 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 software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef RANDOM_H #define RANDOM_H #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "Node.hpp" %} #else #include "Node.hpp" #include <boost/random.hpp> #include <boost/random/variate_generator.hpp> #include <cmath> using namespace boost::numeric; #endif namespace csound { /** * A random value will be sampled from the specified distribution, * translated and scaled as specified, * and set in the specified row and column of the local coordinates. * The resulting matrix will be used in place of the local coordinates * when traversing the music graph. * If eventCount is greater than zero, a new event will be created * for each of eventCount samples, * which will be transformed by the newly sampled local coordinates. */ class SILENCE_PUBLIC Random : public Node { protected: #if !defined(SWIG) void *generator_; boost::variate_generator<boost::mt19937, boost::uniform_smallint<> > *uniform_smallint_generator; boost::variate_generator<boost::mt19937, boost::uniform_int<> > *uniform_int_generator; boost::variate_generator<boost::mt19937, boost::uniform_real<> > *uniform_real_generator; boost::variate_generator<boost::mt19937, boost::bernoulli_distribution<> > *bernoulli_distribution_generator; boost::variate_generator<boost::mt19937, boost::geometric_distribution<> > *geometric_distribution_generator; boost::variate_generator<boost::mt19937, boost::triangle_distribution<> > *triangle_distribution_generator; boost::variate_generator<boost::mt19937, boost::exponential_distribution<> > *exponential_distribution_generator; boost::variate_generator<boost::mt19937, boost::normal_distribution<> > *normal_distribution_generator; boost::variate_generator<boost::mt19937, boost::lognormal_distribution<> > *lognormal_distribution_generator; public: static boost::mt19937 mersenneTwister; #endif public: std::string distribution; int row; int column; int eventCount; bool incrementTime; double minimum; double maximum; double q; double a; double b; double c; double Lambda; double mean; double sigma; Random(); virtual ~Random(); virtual double sample() const; virtual ublas::matrix<double> getLocalCoordinates() const; virtual void createDistribution(std::string distribution); virtual void produceOrTransform(Score &score, size_t beginAt, size_t endAt, const ublas::matrix<double> &globalCoordinates); static void seed(int s); }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FileAPI) { ASSERT_TRUE(RunExtensionTest("fileapi")) << message_; } <commit_msg>mark FileAPI failing for the moment to continue triaging webkit roll.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FAILS_FileAPI) { ASSERT_TRUE(RunExtensionTest("fileapi")) << 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, FLAKY_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" 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. // TODO(jorlow): Reenable when https://bugs.webkit.org/show_bug.cgi?id=28094 // is fixed. Until then, this will cause crashes even if the // individual tests are disabled. #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, 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, LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } TEST_F(DOMStorageTest, SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } #endif <commit_msg>Another attempt to enable the local storage ui test based layout tests.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "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, 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, LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } TEST_F(DOMStorageTest, SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), false); for (size_t i=0; i<arraysize(kSubDirFiles); ++i) RunLayoutTest(kSubDirFiles[i], false); } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2017, Balazs Racz * 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. * * \file HwInit.cxx * This file represents the hardware initialization for the TI CC3220SF Wireless MCU. * * @author Balazs Racz * @date 29 March 2017 */ #include <new> #include <cstdint> #include "inc/hw_types.h" #include "inc/hw_memmap.h" #include "inc/hw_ints.h" #include "inc/hw_nvic.h" #include "inc/hw_gpio.h" #include "driverlib/rom.h" #include "driverlib/rom_map.h" #include "driverlib/gpio.h" #include "driverlib/timer.h" #include "driverlib/interrupt.h" #include "driverlib/pin.h" #include "driverlib/utils.h" #include "os/OS.hxx" #include "DummyGPIO.hxx" #include "CC32xxUart.hxx" #include "CC32xxSPI.hxx" #include "CC32xxWiFi.hxx" #include "MCP2515Can.hxx" #include "CC32xxEEPROMEmulation.hxx" #include "hardware.hxx" #include "bootloader_hal.h" /** override stdin */ const char *STDIN_DEVICE = "/dev/ser0"; /** override stdout */ const char *STDOUT_DEVICE = "/dev/ser0"; /** override stderr */ const char *STDERR_DEVICE = "/dev/ser0"; /** Assert the RS-485 transmit enable line. */ static void rs485_enable_assert() { RS485_TX_EN_Pin::set(true); UtilsDelay(100); } /** Deassert the RS-485 transmit enable line. */ static void rs485_enable_deassert() { RS485_TX_EN_Pin::set(false); } /** UART 0 serial driver instance */ static CC32xxUart uart0("/dev/ser0", UARTA0_BASE, INT_UARTA0, 250000, CC32xxUart::CS8, true, rs485_enable_assert, rs485_enable_deassert); /** Wi-Fi instance */ CC32xxWiFi wifi; static CC32xxEEPROMEmulation eeprom("/usr/dmxeeprom", 1500); /** Assert the chip select for the MCP2515 CAN controller. */ static void mcp2515_cs_assert() { MCP2515_CS_N_Pin::set(false); } /** Deassert the chip select for the MCP2515 CAN controller. */ static void mcp2515_cs_deassert() { MCP2515_CS_N_Pin::set(true); } /** Enable MCP2515 CAN controller interrupt. */ static void mcp2515_int_enable() { GPIOIntEnable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN); } /** Disable MCP2515 CAN controller interrupt. */ static void mcp2515_int_disable() { GPIOIntDisable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN); } /** SPI 0.0 driver instance */ static CC32xxSPI spi0_0("/dev/spidev0.0", GSPI_BASE, INT_GSPI, mcp2515_cs_assert, mcp2515_cs_deassert); static MCP2515Can can0("/dev/can0", mcp2515_int_enable, mcp2515_int_disable); extern void eeprom_flush() { eeprom.flush(); } extern "C" { void __attribute__((__weak__)) eeprom_updated_notification() { eeprom_flush(); } extern void (* const __interrupt_vector[])(void); void hw_set_to_safe(void); static uint32_t nsec_per_clock = 0; /// Calculate partial timing information from the tick counter. long long hw_get_partial_tick_time_nsec(void) { volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018; long long tick_val = *tick_current_reg; tick_val *= nsec_per_clock; long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val; if (elapsed < 0) elapsed = 0; return elapsed; } /** Blink LED */ uint32_t blinker_pattern = 0; static volatile uint32_t rest_pattern = 0; void dcc_generator_init(void); void hw_set_to_safe(void) { GpioInit::hw_set_to_safe(); } void resetblink(uint32_t pattern) { blinker_pattern = pattern; } void setblink(uint32_t pattern) { resetblink(pattern); } void timer1a_interrupt_handler(void) { // // Clear the timer interrupt. // MAP_TimerIntClear(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT); // Set output LED. BLINKER_RAW_Pin::set((rest_pattern & 1)); // Shift and maybe reset pattern. rest_pattern >>= 1; if (!rest_pattern) rest_pattern = blinker_pattern; } void diewith(uint32_t pattern) { /* Globally disables interrupts. */ asm("cpsid i\n"); hw_set_to_safe(); resetblink(pattern); while (1) { if (MAP_TimerIntStatus(BLINKER_TIMER_BASE, true) & BLINKER_TIMER_TIMEOUT) { timer1a_interrupt_handler(); } } } /** Initialize the processor hardware pre C runtime init. */ void hw_preinit(void) { /* Globally disables interrupts until the FreeRTOS scheduler is up. */ asm("cpsid i\n"); nsec_per_clock = 1000000000 / cm3_cpu_clock_hz; /* Setup the interrupt vector table */ MAP_IntVTableBaseSet((unsigned long)&__interrupt_vector[0]); // Disables all interrupts that the bootloader might have enabled. HWREG(NVIC_DIS0) = 0xffffffffU; HWREG(NVIC_DIS1) = 0xffffffffU; HWREG(NVIC_DIS2) = 0xffffffffU; HWREG(NVIC_DIS3) = 0xffffffffU; HWREG(NVIC_DIS4) = 0xffffffffU; HWREG(NVIC_DIS5) = 0xffffffffU; /* Setup the system clock. */ PRCMCC3200MCUInit(); // initilize pin modes: init_pinmux<0>(); GpioInit::hw_init(); /* Blinker timer initialization. */ MAP_PRCMPeripheralClkEnable(PRCM_TIMERA1, PRCM_RUN_MODE_CLK); MAP_TimerConfigure(BLINKER_TIMER_BASE, TIMER_CFG_PERIODIC); MAP_TimerLoadSet(BLINKER_TIMER_BASE, BLINKER_TIMER, cm3_cpu_clock_hz / 8); MAP_IntEnable(BLINKER_TIMER_INT); /* This interrupt should hit even during kernel operations. */ MAP_IntPrioritySet(BLINKER_TIMER_INT, 0); MAP_TimerIntEnable(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT); MAP_TimerEnable(BLINKER_TIMER_BASE, BLINKER_TIMER); /* MCP2515 CAN Controller reset hold */ MCP2515_RESET_N_Pin::set(false); /* MCP2515 CAN Controller clock timer initialization. */ MAP_PRCMPeripheralClkEnable(PRCM_TIMERA2, PRCM_RUN_MODE_CLK); MAP_TimerConfigure(TIMERA2_BASE, TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_PWM | TIMER_CFG_A_PERIODIC); MAP_TimerLoadSet(TIMERA2_BASE, TIMER_B, 3); MAP_TimerMatchSet(TIMERA2_BASE, TIMER_B, 1); MAP_TimerEnable(TIMERA2_BASE, TIMER_B); /* MCP2515 CAN Controller gpio interrupt initialization */ GPIOIntTypeSet(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN, GPIO_LOW_LEVEL); MAP_IntPrioritySet(MCP2515_INT_N_Pin::GPIO_INT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(MCP2515_INT_N_Pin::GPIO_INT); /* MCP2515 CAN Controller reset release */ MCP2515_RESET_N_Pin::set(true); /* Checks the SW2 pin at boot time in case we want to allow for a debugger * to connect. asm volatile ("cpsie i\n"); do { if (SW2_Pin::get()) { blinker_pattern = 0xAAAA; } else { blinker_pattern = 0; } } while (blinker_pattern || rest_pattern); asm volatile ("cpsid i\n"); */ } /** PORTA0 interrupt handler. */ void porta0_interrupt_handler(void) { long status = GPIOIntStatus(GPIOA0_BASE, true); if (status & GPIO_INT_PIN_7) { /* MCP2515 CAN Controller interrupt */ can0.interrupt_handler(); } } /** Initialize the processor hardware post C runtime init. */ void hw_init(void) { // Initialize the SPI driver for the CC32xx network processor connection. extern void SPI_init(void); SPI_init(); wifi.instance()->start(); } /** Initialize the processor hardware post platform init. */ void hw_postinit(void) { can0.init("/dev/spidev0.0", 20000000, config_nmranet_can_bitrate()); SyncNotifiable n; wifi.run_on_network_thread([&n]() { eeprom.mount(); n.notify(); }); n.wait_for_notification(); } } /* extern "C" */ <commit_msg>removes automatic rs485 mode.<commit_after>/** \copyright * Copyright (c) 2017, Balazs Racz * 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. * * \file HwInit.cxx * This file represents the hardware initialization for the TI CC3220SF Wireless MCU. * * @author Balazs Racz * @date 29 March 2017 */ #include <new> #include <cstdint> #include "inc/hw_types.h" #include "inc/hw_memmap.h" #include "inc/hw_ints.h" #include "inc/hw_nvic.h" #include "inc/hw_gpio.h" #include "driverlib/rom.h" #include "driverlib/rom_map.h" #include "driverlib/gpio.h" #include "driverlib/timer.h" #include "driverlib/interrupt.h" #include "driverlib/pin.h" #include "driverlib/utils.h" #include "os/OS.hxx" #include "DummyGPIO.hxx" #include "CC32xxUart.hxx" #include "CC32xxSPI.hxx" #include "CC32xxWiFi.hxx" #include "MCP2515Can.hxx" #include "CC32xxEEPROMEmulation.hxx" #include "hardware.hxx" #include "bootloader_hal.h" /** override stdin */ const char *STDIN_DEVICE = "/dev/ser0"; /** override stdout */ const char *STDOUT_DEVICE = "/dev/ser0"; /** override stderr */ const char *STDERR_DEVICE = "/dev/ser0"; /* // Assert the RS-485 transmit enable line. static void rs485_enable_assert() { RS485_TX_EN_Pin::set(true); UtilsDelay(100); } // Deassert the RS-485 transmit enable line. static void rs485_enable_deassert() { RS485_TX_EN_Pin::set(false); }*/ /** UART 0 serial driver instance */ static CC32xxUart uart0("/dev/ser0", UARTA0_BASE, INT_UARTA0, 250000, CC32xxUart::CS8 | CC32xxUart::CSTOPB, true); /** Wi-Fi instance */ CC32xxWiFi wifi; static CC32xxEEPROMEmulation eeprom("/usr/dmxeeprom", 1500); /** Assert the chip select for the MCP2515 CAN controller. */ static void mcp2515_cs_assert() { MCP2515_CS_N_Pin::set(false); } /** Deassert the chip select for the MCP2515 CAN controller. */ static void mcp2515_cs_deassert() { MCP2515_CS_N_Pin::set(true); } /** Enable MCP2515 CAN controller interrupt. */ static void mcp2515_int_enable() { GPIOIntEnable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN); } /** Disable MCP2515 CAN controller interrupt. */ static void mcp2515_int_disable() { GPIOIntDisable(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN); } /** SPI 0.0 driver instance */ static CC32xxSPI spi0_0("/dev/spidev0.0", GSPI_BASE, INT_GSPI, mcp2515_cs_assert, mcp2515_cs_deassert); static MCP2515Can can0("/dev/can0", mcp2515_int_enable, mcp2515_int_disable); extern void eeprom_flush() { eeprom.flush(); } extern "C" { void __attribute__((__weak__)) eeprom_updated_notification() { eeprom_flush(); } extern void (* const __interrupt_vector[])(void); void hw_set_to_safe(void); static uint32_t nsec_per_clock = 0; /// Calculate partial timing information from the tick counter. long long hw_get_partial_tick_time_nsec(void) { volatile uint32_t * tick_current_reg = (volatile uint32_t *)0xe000e018; long long tick_val = *tick_current_reg; tick_val *= nsec_per_clock; long long elapsed = (1ULL << NSEC_TO_TICK_SHIFT) - tick_val; if (elapsed < 0) elapsed = 0; return elapsed; } /** Blink LED */ uint32_t blinker_pattern = 0; static volatile uint32_t rest_pattern = 0; void dcc_generator_init(void); void hw_set_to_safe(void) { GpioInit::hw_set_to_safe(); } void resetblink(uint32_t pattern) { blinker_pattern = pattern; } void setblink(uint32_t pattern) { resetblink(pattern); } void timer1a_interrupt_handler(void) { // // Clear the timer interrupt. // MAP_TimerIntClear(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT); // Set output LED. BLINKER_RAW_Pin::set((rest_pattern & 1)); // Shift and maybe reset pattern. rest_pattern >>= 1; if (!rest_pattern) rest_pattern = blinker_pattern; } void diewith(uint32_t pattern) { /* Globally disables interrupts. */ asm("cpsid i\n"); hw_set_to_safe(); resetblink(pattern); while (1) { if (MAP_TimerIntStatus(BLINKER_TIMER_BASE, true) & BLINKER_TIMER_TIMEOUT) { timer1a_interrupt_handler(); } } } /** Initialize the processor hardware pre C runtime init. */ void hw_preinit(void) { /* Globally disables interrupts until the FreeRTOS scheduler is up. */ asm("cpsid i\n"); nsec_per_clock = 1000000000 / cm3_cpu_clock_hz; /* Setup the interrupt vector table */ MAP_IntVTableBaseSet((unsigned long)&__interrupt_vector[0]); // Disables all interrupts that the bootloader might have enabled. HWREG(NVIC_DIS0) = 0xffffffffU; HWREG(NVIC_DIS1) = 0xffffffffU; HWREG(NVIC_DIS2) = 0xffffffffU; HWREG(NVIC_DIS3) = 0xffffffffU; HWREG(NVIC_DIS4) = 0xffffffffU; HWREG(NVIC_DIS5) = 0xffffffffU; /* Setup the system clock. */ PRCMCC3200MCUInit(); // initilize pin modes: init_pinmux<0>(); GpioInit::hw_init(); /* Blinker timer initialization. */ MAP_PRCMPeripheralClkEnable(PRCM_TIMERA1, PRCM_RUN_MODE_CLK); MAP_TimerConfigure(BLINKER_TIMER_BASE, TIMER_CFG_PERIODIC); MAP_TimerLoadSet(BLINKER_TIMER_BASE, BLINKER_TIMER, cm3_cpu_clock_hz / 8); MAP_IntEnable(BLINKER_TIMER_INT); /* This interrupt should hit even during kernel operations. */ MAP_IntPrioritySet(BLINKER_TIMER_INT, 0); MAP_TimerIntEnable(BLINKER_TIMER_BASE, BLINKER_TIMER_TIMEOUT); MAP_TimerEnable(BLINKER_TIMER_BASE, BLINKER_TIMER); /* MCP2515 CAN Controller reset hold */ MCP2515_RESET_N_Pin::set(false); /* MCP2515 CAN Controller clock timer initialization. */ MAP_PRCMPeripheralClkEnable(PRCM_TIMERA2, PRCM_RUN_MODE_CLK); MAP_TimerConfigure(TIMERA2_BASE, TIMER_CFG_SPLIT_PAIR | TIMER_CFG_B_PWM | TIMER_CFG_A_PERIODIC); MAP_TimerLoadSet(TIMERA2_BASE, TIMER_B, 3); MAP_TimerMatchSet(TIMERA2_BASE, TIMER_B, 1); MAP_TimerEnable(TIMERA2_BASE, TIMER_B); /* MCP2515 CAN Controller gpio interrupt initialization */ GPIOIntTypeSet(MCP2515_INT_N_Pin::GPIO_BASE, MCP2515_INT_N_Pin::GPIO_PIN, GPIO_LOW_LEVEL); MAP_IntPrioritySet(MCP2515_INT_N_Pin::GPIO_INT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(MCP2515_INT_N_Pin::GPIO_INT); /* MCP2515 CAN Controller reset release */ MCP2515_RESET_N_Pin::set(true); /* Checks the SW2 pin at boot time in case we want to allow for a debugger * to connect. asm volatile ("cpsie i\n"); do { if (SW2_Pin::get()) { blinker_pattern = 0xAAAA; } else { blinker_pattern = 0; } } while (blinker_pattern || rest_pattern); asm volatile ("cpsid i\n"); */ } /** PORTA0 interrupt handler. */ void porta0_interrupt_handler(void) { long status = GPIOIntStatus(GPIOA0_BASE, true); if (status & GPIO_INT_PIN_7) { /* MCP2515 CAN Controller interrupt */ can0.interrupt_handler(); } } /** Initialize the processor hardware post C runtime init. */ void hw_init(void) { // Initialize the SPI driver for the CC32xx network processor connection. extern void SPI_init(void); SPI_init(); wifi.instance()->start(); } /** Initialize the processor hardware post platform init. */ void hw_postinit(void) { can0.init("/dev/spidev0.0", 20000000, config_nmranet_can_bitrate()); SyncNotifiable n; wifi.run_on_network_thread([&n]() { eeprom.mount(); n.notify(); }); n.wait_for_notification(); } } /* extern "C" */ <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/format.hpp> #include "IECore/DataPromoteOp.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/ObjectParameter.h" #include "IECore/CompoundParameter.h" #include "IECore/CompoundObject.h" #include "IECore/Object.h" #include "IECore/NullObject.h" #include "IECore/DespatchTypedData.h" #include <cassert> using namespace IECore; using namespace Imath; using namespace std; using namespace boost; DataPromoteOp::DataPromoteOp() : Op( staticTypeName(), "Promotes scalar data types to compound data types.", new ObjectParameter( "result", "Promoted Data object.", new NullObject(), DataTypeId ) ) { m_objectParameter = new ObjectParameter( "object", "The Data object that will be promoted.", new NullObject(), DataTypeId ); m_targetTypeParameter = new IntParameter( "targetType", "The target Data typeId.", InvalidTypeId, 0, Imath::limits<int>::max() ); parameters()->addParameter( m_objectParameter ); parameters()->addParameter( m_targetTypeParameter ); } DataPromoteOp::~DataPromoteOp() { } namespace IECore { template<typename T> struct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsVectorTypedData<T> >::type > { typedef DataPtr ReturnType; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); typename T::Ptr result = new T; typename T::ValueType &vt = result->writable(); const typename F::ValueType &vf = d->readable(); vt.resize( vf.size() ); typename T::ValueType::iterator tIt = vt.begin(); for ( typename F::ValueType::const_iterator it = vf.begin(); it!=vf.end(); it++ ) { *tIt++ = typename T::ValueType::value_type( *it ); } return result; } }; template<typename T> struct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsSimpleTypedData<T> >::type > { typedef DataPtr ReturnType; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); typename T::Ptr result = new T; result->writable() = typename T::ValueType( d->readable() ); return result; } }; struct DataPromoteOp::Promote1Fn { typedef DataPtr ReturnType; TypeId m_targetType; Promote1Fn( TypeId targetType ) : m_targetType( targetType ) { } template<typename T, typename Enable = void > struct Func { ReturnType operator()( typename T::ConstPtr d, TypeId ) const { assert( d ); throw Exception( "DataPromoteOp: Unsupported source data type \"" + d->typeName() + "\"." ); } }; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); Func<F> f; return f(d, m_targetType); } }; template<typename F > struct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericVectorTypedData<F> >::type > { ReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const { assert( d ); switch ( targetType ) { case V2fVectorDataTypeId : { Promote2Fn<V2fVectorData> fn; return fn.template operator()<F>( d ); } case V2dVectorDataTypeId : { Promote2Fn<V2dVectorData> fn; return fn.template operator()<F>( d ); } case V3fVectorDataTypeId : { Promote2Fn<V3fVectorData> fn; return fn.template operator()<F>( d ); } case V3dVectorDataTypeId : { Promote2Fn<V3dVectorData> fn; return fn.template operator()<F>( d ); } case Color3fVectorDataTypeId : { Promote2Fn<Color3fVectorData> fn; return fn.template operator()<F>( d ); } default : throw Exception( "DataPromoteOp: Unsupported target data type \"" + Object::typeNameFromTypeId( targetType ) + "\"." ); } } }; template<typename F > struct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericSimpleTypedData<F> >::type > { ReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const { assert( d ); switch ( targetType ) { case V2fDataTypeId : { Promote2Fn<V2fData> fn; return fn.template operator()<F>( d ); } case V2dDataTypeId : { Promote2Fn<V2dData> fn; return fn.template operator()<F>( d ); } case V3fDataTypeId : { Promote2Fn<V3fData> fn; return fn.template operator()<F>( d ); } case V3dDataTypeId : { Promote2Fn<V3dData> fn; return fn.template operator()<F>( d ); } case Color3fDataTypeId : { Promote2Fn<Color3fData> fn; return fn.template operator()<F>( d ); } default : throw Exception( "DataPromoteOp: Unsupported target data type \"" + Object::typeNameFromTypeId( targetType ) + "\"." ); } } }; } // namespace IECore ObjectPtr DataPromoteOp::doOperation( ConstCompoundObjectPtr operands ) { assert( operands ); const TypeId targetType = (TypeId)m_targetTypeParameter->getNumericValue(); DataPtr srcData = static_pointer_cast<Data>( m_objectParameter->getValue() ); assert( srcData ); Promote1Fn fn( targetType ); DataPtr targetData = despatchTypedData< Promote1Fn, TypeTraits::IsNumericTypedData >( srcData, fn ); assert( targetData ); #ifndef NDEBUG size_t srcSize = despatchTypedData< TypedDataSize >( srcData ) ; size_t targetSize = despatchTypedData< TypedDataSize >( targetData ) ; /// This post-condition is stated in the class documentation assert( srcSize == targetSize ); #endif return targetData; } <commit_msg>Added assert<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2007-2008, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Image Engine Design nor the names of any // other contributors to this software 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 <boost/format.hpp> #include "IECore/DataPromoteOp.h" #include "IECore/SimpleTypedData.h" #include "IECore/VectorTypedData.h" #include "IECore/ObjectParameter.h" #include "IECore/CompoundParameter.h" #include "IECore/CompoundObject.h" #include "IECore/Object.h" #include "IECore/NullObject.h" #include "IECore/DespatchTypedData.h" #include <cassert> using namespace IECore; using namespace Imath; using namespace std; using namespace boost; DataPromoteOp::DataPromoteOp() : Op( staticTypeName(), "Promotes scalar data types to compound data types.", new ObjectParameter( "result", "Promoted Data object.", new NullObject(), DataTypeId ) ) { m_objectParameter = new ObjectParameter( "object", "The Data object that will be promoted.", new NullObject(), DataTypeId ); m_targetTypeParameter = new IntParameter( "targetType", "The target Data typeId.", InvalidTypeId, 0, Imath::limits<int>::max() ); parameters()->addParameter( m_objectParameter ); parameters()->addParameter( m_targetTypeParameter ); } DataPromoteOp::~DataPromoteOp() { } namespace IECore { template<typename T> struct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsVectorTypedData<T> >::type > { typedef DataPtr ReturnType; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); typename T::Ptr result = new T; typename T::ValueType &vt = result->writable(); const typename F::ValueType &vf = d->readable(); vt.resize( vf.size() ); typename T::ValueType::iterator tIt = vt.begin(); for ( typename F::ValueType::const_iterator it = vf.begin(); it!=vf.end(); it++ ) { *tIt++ = typename T::ValueType::value_type( *it ); } return result; } }; template<typename T> struct DataPromoteOp::Promote2Fn<T, typename boost::enable_if< TypeTraits::IsSimpleTypedData<T> >::type > { typedef DataPtr ReturnType; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); typename T::Ptr result = new T; result->writable() = typename T::ValueType( d->readable() ); return result; } }; struct DataPromoteOp::Promote1Fn { typedef DataPtr ReturnType; TypeId m_targetType; Promote1Fn( TypeId targetType ) : m_targetType( targetType ) { } template<typename T, typename Enable = void > struct Func { ReturnType operator()( typename T::ConstPtr d, TypeId ) const { assert( d ); throw Exception( "DataPromoteOp: Unsupported source data type \"" + d->typeName() + "\"." ); } }; template<typename F> ReturnType operator()( typename F::ConstPtr d ) const { assert( d ); Func<F> f; return f(d, m_targetType); } }; template<typename F > struct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericVectorTypedData<F> >::type > { ReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const { assert( d ); switch ( targetType ) { case V2fVectorDataTypeId : { Promote2Fn<V2fVectorData> fn; return fn.template operator()<F>( d ); } case V2dVectorDataTypeId : { Promote2Fn<V2dVectorData> fn; return fn.template operator()<F>( d ); } case V3fVectorDataTypeId : { Promote2Fn<V3fVectorData> fn; return fn.template operator()<F>( d ); } case V3dVectorDataTypeId : { Promote2Fn<V3dVectorData> fn; return fn.template operator()<F>( d ); } case Color3fVectorDataTypeId : { Promote2Fn<Color3fVectorData> fn; return fn.template operator()<F>( d ); } default : throw Exception( "DataPromoteOp: Unsupported target data type \"" + Object::typeNameFromTypeId( targetType ) + "\"." ); } } }; template<typename F > struct DataPromoteOp::Promote1Fn::Func< F, typename boost::enable_if< TypeTraits::IsNumericSimpleTypedData<F> >::type > { ReturnType operator()( typename F::ConstPtr d, TypeId targetType ) const { assert( d ); switch ( targetType ) { case V2fDataTypeId : { Promote2Fn<V2fData> fn; return fn.template operator()<F>( d ); } case V2dDataTypeId : { Promote2Fn<V2dData> fn; return fn.template operator()<F>( d ); } case V3fDataTypeId : { Promote2Fn<V3fData> fn; return fn.template operator()<F>( d ); } case V3dDataTypeId : { Promote2Fn<V3dData> fn; return fn.template operator()<F>( d ); } case Color3fDataTypeId : { Promote2Fn<Color3fData> fn; return fn.template operator()<F>( d ); } default : throw Exception( "DataPromoteOp: Unsupported target data type \"" + Object::typeNameFromTypeId( targetType ) + "\"." ); } } }; } // namespace IECore ObjectPtr DataPromoteOp::doOperation( ConstCompoundObjectPtr operands ) { assert( operands ); const TypeId targetType = (TypeId)m_targetTypeParameter->getNumericValue(); DataPtr srcData = static_pointer_cast<Data>( m_objectParameter->getValue() ); assert( srcData ); Promote1Fn fn( targetType ); DataPtr targetData = despatchTypedData< Promote1Fn, TypeTraits::IsNumericTypedData >( srcData, fn ); assert( targetData ); assert( targetData->typeId() == targetType ); #ifndef NDEBUG size_t srcSize = despatchTypedData< TypedDataSize >( srcData ) ; size_t targetSize = despatchTypedData< TypedDataSize >( targetData ) ; /// This post-condition is stated in the class documentation assert( srcSize == targetSize ); #endif return targetData; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SchWhichPairs.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: bm $ $Date: 2003-12-09 16:30:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef CHART_SCHWHICHPAIRS_HXX #define CHART_SCHWHICHPAIRS_HXX #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _XDEF_HXX #include <svx/xdef.hxx> #endif #ifndef _SVDDEF_HXX #include <svx/svddef.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #include "SchSfxItemIds.hxx" #include "SchSlotIds.hxx" namespace { const USHORT nTitleWhichPairs[] = { // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx 0 }; const USHORT nAxisWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx SID_ATTR_NUMBERFORMAT_VALUE, SID_ATTR_NUMBERFORMAT_VALUE, // 10585 - 10585 svx/svxids.hrc SID_ATTR_NUMBERFORMAT_SOURCE, SID_ATTR_NUMBERFORMAT_SOURCE, // 11432 svx/svxids.hrc SCHATTR_AXISTYPE, SCHATTR_AXISTYPE, // 39 sch/schattr.hxx SCHATTR_TEXT_START, SCHATTR_TEXT_END, // 4 - 6 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, // 54 sch/schattr.hxx SCHATTR_AXIS_START, SCHATTR_AXIS_END, // 70 - 95 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx // SID_TEXTBREAK, SID_TEXTBREAK, // 30587 sch/app.hrc SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, // 30587 sch/schattr.hxx 0 }; const USHORT nAllAxisWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_START, SCHATTR_TEXT_END, // 4 - 6 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, // 54 sch/schattr.hxx SCHATTR_AXIS_SHOWDESCR, SCHATTR_AXIS_SHOWDESCR, // 85 sch/schattr.hxx // SID_TEXTBREAK, SID_TEXTBREAK, // 30587 sch/app.hrc SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, // 30587 sch/schattr.hxx 0 }; const USHORT nGridWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nChartWhichPairs[] = { SCHATTR_STYLE_START,SCHATTR_STYLE_END, // 59 - 68 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nDiagramAreaWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nAreaAndChartWhichPairs[] = // pairs for chart AND area { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SCHATTR_STYLE_START,SCHATTR_STYLE_END, // 59 - 68 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nLegendWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx SCHATTR_LEGEND_START, SCHATTR_LEGEND_END, // 3 - 3 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nDataLabelWhichPairs[] = { SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, 0 }; #define CHART_POINT_WHICHPAIRS \ XATTR_LINE_FIRST, XATTR_LINE_LAST, /* 1000 - 1016 svx/xdef.hxx */ \ XATTR_FILL_FIRST, XATTR_FILL_LAST, /* 1018 - 1046 svx/xdef.hxx */ \ EE_ITEMS_START, EE_ITEMS_END, /* 3994 - 4037 svx/eeitem.hxx */ \ SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, /* 1 - 2 sch/schattr.hxx*/ \ SCHATTR_DUMMY0, SCHATTR_DUMMY0, /* 40 sch/schattr.hxx*/ \ SCHATTR_DUMMY1, SCHATTR_DUMMY1, /* 41 sch/schattr.hxx*/ \ SCHATTR_STYLE_START,SCHATTR_STYLE_END, /* 59 - 68 sch/schattr.hxx*/ \ SCHATTR_SYMBOL_BRUSH,SCHATTR_SYMBOL_BRUSH, /* 96 sch/schattr.hxx*/ \ SCHATTR_SYMBOL_SIZE,SCHATTR_USER_DEFINED_ATTR, /* 99 - 100 sch/schattr.hxx*/ \ SDRATTR_3D_FIRST, SDRATTR_3D_LAST /* 1244 - 1334 svx/svddef.hxx */ const USHORT nDataPointWhichPairs[] = { CHART_POINT_WHICHPAIRS, 0 }; const USHORT nRowWhichPairs[] = { CHART_POINT_WHICHPAIRS, SCHATTR_STAT_START, SCHATTR_STAT_END, /* 45 - 52 sch/schattr.hxx*/ \ SCHATTR_AXIS,SCHATTR_AXIS, /* 69 sch/schattr.hxx*/ \ 0 }; const USHORT nAreaWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nTextWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nTextOrientWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx 0 }; const USHORT nStatWhichPairs[]= { SCHATTR_STAT_START, SCHATTR_STAT_END, // 45 - 52 sch/schattr.hxx 0 }; // for CharacterProperties const USHORT nCharacterPropertyWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx 0 }; const USHORT nLinePropertyWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx 0 }; const USHORT nFillPropertyWhichPairs[] = { XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx 0 }; const USHORT nLineAndFillPropertyWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx 0 }; const USHORT nChartStyleWhichPairs[] = { SCHATTR_DIAGRAM_STYLE, SCHATTR_DIAGRAM_STYLE, SCHATTR_STYLE_SHAPE, SCHATTR_STYLE_SHAPE, SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_RESOLUTION, SCHATTR_SPLINE_RESOLUTION, 0 }; } // anonymous namespace // CHART_SCHWHICHPAIRS_HXX #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.2.110); FILE MERGED 2005/09/05 18:42:40 rt 1.2.110.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SchWhichPairs.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 00:30:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CHART_SCHWHICHPAIRS_HXX #define CHART_SCHWHICHPAIRS_HXX #ifndef _SVX_SVXIDS_HRC #include <svx/svxids.hrc> #endif #ifndef _XDEF_HXX #include <svx/xdef.hxx> #endif #ifndef _SVDDEF_HXX #include <svx/svddef.hxx> #endif #ifndef _EEITEM_HXX #include <svx/eeitem.hxx> #endif #include "SchSfxItemIds.hxx" #include "SchSlotIds.hxx" namespace { const USHORT nTitleWhichPairs[] = { // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx 0 }; const USHORT nAxisWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx SID_ATTR_NUMBERFORMAT_VALUE, SID_ATTR_NUMBERFORMAT_VALUE, // 10585 - 10585 svx/svxids.hrc SID_ATTR_NUMBERFORMAT_SOURCE, SID_ATTR_NUMBERFORMAT_SOURCE, // 11432 svx/svxids.hrc SCHATTR_AXISTYPE, SCHATTR_AXISTYPE, // 39 sch/schattr.hxx SCHATTR_TEXT_START, SCHATTR_TEXT_END, // 4 - 6 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, // 54 sch/schattr.hxx SCHATTR_AXIS_START, SCHATTR_AXIS_END, // 70 - 95 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx // SID_TEXTBREAK, SID_TEXTBREAK, // 30587 sch/app.hrc SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, // 30587 sch/schattr.hxx 0 }; const USHORT nAllAxisWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_START, SCHATTR_TEXT_END, // 4 - 6 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_TEXT_OVERLAP, SCHATTR_TEXT_OVERLAP, // 54 sch/schattr.hxx SCHATTR_AXIS_SHOWDESCR, SCHATTR_AXIS_SHOWDESCR, // 85 sch/schattr.hxx // SID_TEXTBREAK, SID_TEXTBREAK, // 30587 sch/app.hrc SCHATTR_TEXTBREAK, SCHATTR_TEXTBREAK, // 30587 sch/schattr.hxx 0 }; const USHORT nGridWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nChartWhichPairs[] = { SCHATTR_STYLE_START,SCHATTR_STYLE_END, // 59 - 68 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nDiagramAreaWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nAreaAndChartWhichPairs[] = // pairs for chart AND area { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SCHATTR_STYLE_START,SCHATTR_STYLE_END, // 59 - 68 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nLegendWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1018 - 1046 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx SCHATTR_LEGEND_START, SCHATTR_LEGEND_END, // 3 - 3 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nDataLabelWhichPairs[] = { SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, 0 }; #define CHART_POINT_WHICHPAIRS \ XATTR_LINE_FIRST, XATTR_LINE_LAST, /* 1000 - 1016 svx/xdef.hxx */ \ XATTR_FILL_FIRST, XATTR_FILL_LAST, /* 1018 - 1046 svx/xdef.hxx */ \ EE_ITEMS_START, EE_ITEMS_END, /* 3994 - 4037 svx/eeitem.hxx */ \ SCHATTR_DATADESCR_START, SCHATTR_DATADESCR_END, /* 1 - 2 sch/schattr.hxx*/ \ SCHATTR_DUMMY0, SCHATTR_DUMMY0, /* 40 sch/schattr.hxx*/ \ SCHATTR_DUMMY1, SCHATTR_DUMMY1, /* 41 sch/schattr.hxx*/ \ SCHATTR_STYLE_START,SCHATTR_STYLE_END, /* 59 - 68 sch/schattr.hxx*/ \ SCHATTR_SYMBOL_BRUSH,SCHATTR_SYMBOL_BRUSH, /* 96 sch/schattr.hxx*/ \ SCHATTR_SYMBOL_SIZE,SCHATTR_USER_DEFINED_ATTR, /* 99 - 100 sch/schattr.hxx*/ \ SDRATTR_3D_FIRST, SDRATTR_3D_LAST /* 1244 - 1334 svx/svddef.hxx */ const USHORT nDataPointWhichPairs[] = { CHART_POINT_WHICHPAIRS, 0 }; const USHORT nRowWhichPairs[] = { CHART_POINT_WHICHPAIRS, SCHATTR_STAT_START, SCHATTR_STAT_END, /* 45 - 52 sch/schattr.hxx*/ \ SCHATTR_AXIS,SCHATTR_AXIS, /* 69 sch/schattr.hxx*/ \ 0 }; const USHORT nAreaWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nTextWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx SCHATTR_USER_DEFINED_ATTR, SCHATTR_USER_DEFINED_ATTR, // 100 sch/schattr.hxx 0 }; const USHORT nTextOrientWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx // SCHATTR_TEXT_ORIENT, SCHATTR_TEXT_ORIENT, // 4 sch/schattr.hxx SCHATTR_TEXT_STACKED, SCHATTR_TEXT_STACKED, // 4 sch/schattr.hxx SCHATTR_TEXT_DEGREES,SCHATTR_TEXT_DEGREES, // 53 sch/schattr.hxx 0 }; const USHORT nStatWhichPairs[]= { SCHATTR_STAT_START, SCHATTR_STAT_END, // 45 - 52 sch/schattr.hxx 0 }; // for CharacterProperties const USHORT nCharacterPropertyWhichPairs[] = { EE_ITEMS_START, EE_ITEMS_END, // 3994 - 4037 svx/eeitem.hxx 0 }; const USHORT nLinePropertyWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx 0 }; const USHORT nFillPropertyWhichPairs[] = { XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx 0 }; const USHORT nLineAndFillPropertyWhichPairs[] = { XATTR_LINE_FIRST, XATTR_LINE_LAST, // 1000 - 1016 svx/xdef.hxx XATTR_FILL_FIRST, XATTR_FILL_LAST, // 1000 - 1016 svx/xdef.hxx SDRATTR_SHADOW_FIRST, SDRATTR_SHADOW_LAST, // 1067 - 1078 svx/svddef.hxx 0 }; const USHORT nChartStyleWhichPairs[] = { SCHATTR_DIAGRAM_STYLE, SCHATTR_DIAGRAM_STYLE, SCHATTR_STYLE_SHAPE, SCHATTR_STYLE_SHAPE, SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_NUM_OF_LINES_FOR_BAR, SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_ORDER, SCHATTR_SPLINE_RESOLUTION, SCHATTR_SPLINE_RESOLUTION, 0 }; } // anonymous namespace // CHART_SCHWHICHPAIRS_HXX #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/browser_notification_observers.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/notification_service.h" namespace { // Static function that records uptime in /proc/uptime to tmp for metrics use. void RecordUptime() { system("cat /proc/uptime > /tmp/uptime-chrome-first-render &"); } } // namespace namespace chromeos { InitialTabNotificationObserver::InitialTabNotificationObserver() { registrar_.Add(this, NotificationType::LOAD_START, NotificationService::AllSources()); } InitialTabNotificationObserver::~InitialTabNotificationObserver() { } void InitialTabNotificationObserver::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Only log for first tab to render. Make sure this is only done once. if (type == NotificationType::LOAD_START && num_tabs_.GetNext() == 0) { // If we can't post it, it doesn't matter. ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction(RecordUptime)); registrar_.Remove(this, NotificationType::LOAD_START, NotificationService::AllSources()); } } } // namespace chromeos <commit_msg>ChromiumOS: read /proc/uptime without using system().<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/browser_notification_observers.h" #include <string> #include "base/file_util.h" #include "chrome/browser/chrome_thread.h" #include "chrome/common/notification_service.h" namespace { // Static function that records uptime in /proc/uptime to tmp for metrics use. void RecordUptime() { std::string uptime; const FilePath proc_uptime = FilePath("/proc/uptime"); const FilePath uptime_output = FilePath("/tmp/uptime-chrome-first-render"); if (file_util::ReadFileToString(proc_uptime, &uptime)) file_util::WriteFile(uptime_output, uptime.data(), uptime.size()); } } // namespace namespace chromeos { InitialTabNotificationObserver::InitialTabNotificationObserver() { registrar_.Add(this, NotificationType::LOAD_START, NotificationService::AllSources()); } InitialTabNotificationObserver::~InitialTabNotificationObserver() { } void InitialTabNotificationObserver::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { // Only log for first tab to render. Make sure this is only done once. if (type == NotificationType::LOAD_START && num_tabs_.GetNext() == 0) { // If we can't post it, it doesn't matter. ChromeThread::PostTask( ChromeThread::FILE, FROM_HERE, NewRunnableFunction(RecordUptime)); registrar_.Remove(this, NotificationType::LOAD_START, NotificationService::AllSources()); } } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <commit_msg>Added check when unpacking extensions for a null key.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/sandboxed_extension_unpacker.h" #include <set> #include "base/base64.h" #include "base/crypto/signature_verifier.h" #include "base/file_util.h" #include "base/message_loop.h" #include "base/scoped_handle.h" #include "base/task.h" #include "base/utf_string_conversions.h" // TODO(viettrungluu): delete me. #include "chrome/browser/chrome_thread.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/renderer_host/resource_dispatcher_host.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_file_util.h" #include "chrome/common/extensions/extension_l10n_util.h" #include "chrome/common/extensions/extension_unpacker.h" #include "chrome/common/json_value_serializer.h" #include "gfx/codec/png_codec.h" #include "third_party/skia/include/core/SkBitmap.h" const char SandboxedExtensionUnpacker::kExtensionHeaderMagic[] = "Cr24"; SandboxedExtensionUnpacker::SandboxedExtensionUnpacker( const FilePath& crx_path, const FilePath& temp_path, ResourceDispatcherHost* rdh, SandboxedExtensionUnpackerClient* client) : crx_path_(crx_path), temp_path_(temp_path), thread_identifier_(ChromeThread::ID_COUNT), rdh_(rdh), client_(client), got_response_(false) { } void SandboxedExtensionUnpacker::Start() { // We assume that we are started on the thread that the client wants us to do // file IO on. CHECK(ChromeThread::GetCurrentThreadIdentifier(&thread_identifier_)); // Create a temporary directory to work in. if (!temp_dir_.CreateUniqueTempDirUnderPath(temp_path_)) { ReportFailure("Could not create temporary directory."); return; } // Initialize the path that will eventually contain the unpacked extension. extension_root_ = temp_dir_.path().AppendASCII( extension_filenames::kTempExtensionName); // Extract the public key and validate the package. if (!ValidateSignature()) return; // ValidateSignature() already reported the error. // Copy the crx file into our working directory. FilePath temp_crx_path = temp_dir_.path().Append(crx_path_.BaseName()); if (!file_util::CopyFile(crx_path_, temp_crx_path)) { ReportFailure("Failed to copy extension file to temporary directory."); return; } // If we are supposed to use a subprocess, kick off the subprocess. // // TODO(asargent) we shouldn't need to do this branch here - instead // UtilityProcessHost should handle it for us. (http://crbug.com/19192) bool use_utility_process = rdh_ && !CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); if (use_utility_process) { // The utility process will have access to the directory passed to // SandboxedExtensionUnpacker. That directory should not contain a // symlink or NTFS reparse point. When the path is used, following // the link/reparse point will cause file system access outside the // sandbox path, and the sandbox will deny the operation. FilePath link_free_crx_path; if (!file_util::NormalizeFilePath(temp_crx_path, &link_free_crx_path)) { LOG(ERROR) << "Could not get the normalized path of " << temp_crx_path.value(); #if defined (OS_WIN) // On windows, it is possible to mount a disk without the root of that // disk having a drive letter. The sandbox does not support this. // See crbug/49530 . ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that starts " "with a drive letter and does not contain a junction, mount " "point, or symlink. No such path exists for your profile."); #else ReportFailure( "Can not unpack extension. To safely unpack an extension, " "there must be a path to your profile directory that does " "not contain a symlink. No such path exists for your profile."); #endif return; } ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableMethod( this, &SandboxedExtensionUnpacker::StartProcessOnIOThread, link_free_crx_path)); } else { // Otherwise, unpack the extension in this process. ExtensionUnpacker unpacker(temp_crx_path); if (unpacker.Run() && unpacker.DumpImagesToFile() && unpacker.DumpMessageCatalogsToFile()) { OnUnpackExtensionSucceeded(*unpacker.parsed_manifest()); } else { OnUnpackExtensionFailed(unpacker.error_message()); } } } void SandboxedExtensionUnpacker::StartProcessOnIOThread( const FilePath& temp_crx_path) { UtilityProcessHost* host = new UtilityProcessHost( rdh_, this, thread_identifier_); host->StartExtensionUnpacker(temp_crx_path); } void SandboxedExtensionUnpacker::OnUnpackExtensionSucceeded( const DictionaryValue& manifest) { // Skip check for unittests. if (thread_identifier_ != ChromeThread::ID_COUNT) DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; scoped_ptr<DictionaryValue> final_manifest(RewriteManifestFile(manifest)); if (!final_manifest.get()) return; // Create an extension object that refers to the temporary location the // extension was unpacked to. We use this until the extension is finally // installed. For example, the install UI shows images from inside the // extension. extension_.reset(new Extension(extension_root_)); // Localize manifest now, so confirm UI gets correct extension name. std::string error; if (!extension_l10n_util::LocalizeExtension(extension_.get(), final_manifest.get(), &error)) { ReportFailure(error); return; } if (!extension_->InitFromValue(*final_manifest, true, &error)) { ReportFailure(std::string("Manifest is invalid: ") + error); return; } if (!RewriteImageFiles()) return; if (!RewriteCatalogFiles()) return; ReportSuccess(); } void SandboxedExtensionUnpacker::OnUnpackExtensionFailed( const std::string& error) { DCHECK(ChromeThread::CurrentlyOn(thread_identifier_)); got_response_ = true; ReportFailure(error); } void SandboxedExtensionUnpacker::OnProcessCrashed() { // Don't report crashes if they happen after we got a response. if (got_response_) return; ReportFailure("Utility process crashed while trying to install."); } bool SandboxedExtensionUnpacker::ValidateSignature() { ScopedStdioHandle file(file_util::OpenFile(crx_path_, "rb")); if (!file.get()) { ReportFailure("Could not open crx file for reading"); return false; } // Read and verify the header. ExtensionHeader header; size_t len; // TODO(erikkay): Yuck. I'm not a big fan of this kind of code, but it // appears that we don't have any endian/alignment aware serialization // code in the code base. So for now, this assumes that we're running // on a little endian machine with 4 byte alignment. len = fread(&header, 1, sizeof(ExtensionHeader), file.get()); if (len < sizeof(ExtensionHeader)) { ReportFailure("Invalid crx header"); return false; } if (strncmp(kExtensionHeaderMagic, header.magic, sizeof(header.magic))) { ReportFailure("Bad magic number"); return false; } if (header.version != kCurrentVersion) { ReportFailure("Bad version number"); return false; } if (header.key_size > kMaxPublicKeySize || header.signature_size > kMaxSignatureSize) { ReportFailure("Excessively large key or signature"); return false; } if (header.key_size == 0) { ReportFailure("Key length is zero"); return false; } std::vector<uint8> key; key.resize(header.key_size); len = fread(&key.front(), sizeof(uint8), header.key_size, file.get()); if (len < header.key_size) { ReportFailure("Invalid public key"); return false; } std::vector<uint8> signature; signature.resize(header.signature_size); len = fread(&signature.front(), sizeof(uint8), header.signature_size, file.get()); if (len < header.signature_size) { ReportFailure("Invalid signature"); return false; } base::SignatureVerifier verifier; if (!verifier.VerifyInit(extension_misc::kSignatureAlgorithm, sizeof(extension_misc::kSignatureAlgorithm), &signature.front(), signature.size(), &key.front(), key.size())) { ReportFailure("Signature verification initialization failed. " "This is most likely caused by a public key in " "the wrong format (should encode algorithm)."); return false; } unsigned char buf[1 << 12]; while ((len = fread(buf, 1, sizeof(buf), file.get())) > 0) verifier.VerifyUpdate(buf, len); if (!verifier.VerifyFinal()) { ReportFailure("Signature verification failed"); return false; } base::Base64Encode(std::string(reinterpret_cast<char*>(&key.front()), key.size()), &public_key_); return true; } void SandboxedExtensionUnpacker::ReportFailure(const std::string& error) { client_->OnUnpackFailure(error); } void SandboxedExtensionUnpacker::ReportSuccess() { // Client takes ownership of temporary directory and extension. client_->OnUnpackSuccess(temp_dir_.Take(), extension_root_, extension_.release()); } DictionaryValue* SandboxedExtensionUnpacker::RewriteManifestFile( const DictionaryValue& manifest) { // Add the public key extracted earlier to the parsed manifest and overwrite // the original manifest. We do this to ensure the manifest doesn't contain an // exploitable bug that could be used to compromise the browser. scoped_ptr<DictionaryValue> final_manifest( static_cast<DictionaryValue*>(manifest.DeepCopy())); final_manifest->SetString(extension_manifest_keys::kPublicKey, public_key_); std::string manifest_json; JSONStringValueSerializer serializer(&manifest_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*final_manifest)) { ReportFailure("Error serializing manifest.json."); return NULL; } FilePath manifest_path = extension_root_.Append(Extension::kManifestFilename); if (!file_util::WriteFile(manifest_path, manifest_json.data(), manifest_json.size())) { ReportFailure("Error saving manifest.json."); return NULL; } return final_manifest.release(); } bool SandboxedExtensionUnpacker::RewriteImageFiles() { ExtensionUnpacker::DecodedImages images; if (!ExtensionUnpacker::ReadImagesFromFile(temp_dir_.path(), &images)) { ReportFailure("Couldn't read image data from disk."); return false; } // Delete any images that may be used by the browser. We're going to write // out our own versions of the parsed images, and we want to make sure the // originals are gone for good. std::set<FilePath> image_paths = extension_->GetBrowserImages(); if (image_paths.size() != images.size()) { ReportFailure("Decoded images don't match what's in the manifest."); return false; } for (std::set<FilePath>::iterator it = image_paths.begin(); it != image_paths.end(); ++it) { FilePath path = *it; if (path.IsAbsolute() || path.ReferencesParent()) { ReportFailure("Invalid path for browser image."); return false; } if (!file_util::Delete(extension_root_.Append(path), false)) { ReportFailure("Error removing old image file."); return false; } } // Write our parsed images back to disk as well. for (size_t i = 0; i < images.size(); ++i) { const SkBitmap& image = images[i].a; FilePath path_suffix = images[i].b; if (path_suffix.IsAbsolute() || path_suffix.ReferencesParent()) { ReportFailure("Invalid path for bitmap image."); return false; } FilePath path = extension_root_.Append(path_suffix); std::vector<unsigned char> image_data; // TODO(mpcomplete): It's lame that we're encoding all images as PNG, even // though they may originally be .jpg, etc. Figure something out. // http://code.google.com/p/chromium/issues/detail?id=12459 if (!gfx::PNGCodec::EncodeBGRASkBitmap(image, false, &image_data)) { ReportFailure("Error re-encoding theme image."); return false; } // Note: we're overwriting existing files that the utility process wrote, // so we can be sure the directory exists. const char* image_data_ptr = reinterpret_cast<const char*>(&image_data[0]); if (!file_util::WriteFile(path, image_data_ptr, image_data.size())) { ReportFailure("Error saving theme image."); return false; } } return true; } bool SandboxedExtensionUnpacker::RewriteCatalogFiles() { DictionaryValue catalogs; if (!ExtensionUnpacker::ReadMessageCatalogsFromFile(temp_dir_.path(), &catalogs)) { ReportFailure("Could not read catalog data from disk."); return false; } // Write our parsed catalogs back to disk. for (DictionaryValue::key_iterator key_it = catalogs.begin_keys(); key_it != catalogs.end_keys(); ++key_it) { DictionaryValue* catalog; if (!catalogs.GetDictionaryWithoutPathExpansion(*key_it, &catalog)) { ReportFailure("Invalid catalog data."); return false; } // TODO(viettrungluu): Fix the |FilePath::FromWStringHack(UTF8ToWide())| // hack and remove the corresponding #include. FilePath relative_path = FilePath::FromWStringHack(UTF8ToWide(*key_it)); relative_path = relative_path.Append(Extension::kMessagesFilename); if (relative_path.IsAbsolute() || relative_path.ReferencesParent()) { ReportFailure("Invalid path for catalog."); return false; } FilePath path = extension_root_.Append(relative_path); std::string catalog_json; JSONStringValueSerializer serializer(&catalog_json); serializer.set_pretty_print(true); if (!serializer.Serialize(*catalog)) { ReportFailure("Error serializing catalog."); return false; } // Note: we're overwriting existing files that the utility process read, // so we can be sure the directory exists. if (!file_util::WriteFile(path, catalog_json.c_str(), catalog_json.size())) { ReportFailure("Error saving catalog."); return false; } } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/touch/frame/keyboard_container_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/navigation_controller.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "ui/base/animation/slide_animation.h" #include "ui/gfx/rect.h" #include "ui/gfx/transform.h" #include "views/controls/button/image_button.h" #include "views/controls/textfield/textfield.h" #include "views/focus/focus_manager.h" namespace { const int kKeyboardHeight = 300; const int kKeyboardSlideDuration = 500; // In milliseconds PropertyAccessor<bool>* GetFocusedStateAccessor() { static PropertyAccessor<bool> state; return &state; } bool TabContentsHasFocus(const TabContents* contents) { views::View* view = static_cast<TabContentsViewTouch*>(contents->view()); return view->Contains(view->GetFocusManager()->GetFocusedView()); } } // namespace // static const char TouchBrowserFrameView::kViewClassName[] = "browser/ui/touch/frame/TouchBrowserFrameView"; /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, public: TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame, BrowserView* browser_view) : OpaqueBrowserFrameView(frame, browser_view), keyboard_showing_(false), focus_listener_added_(false), keyboard_(NULL) { registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::FOCUS_CHANGED_IN_PAGE, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); browser_view->browser()->tabstrip_model()->AddObserver(this); animation_.reset(new ui::SlideAnimation(this)); animation_->SetTweenType(ui::Tween::LINEAR); animation_->SetSlideDuration(kKeyboardSlideDuration); } TouchBrowserFrameView::~TouchBrowserFrameView() { browser_view()->browser()->tabstrip_model()->RemoveObserver(this); } std::string TouchBrowserFrameView::GetClassName() const { return kViewClassName; } void TouchBrowserFrameView::Layout() { OpaqueBrowserFrameView::Layout(); if (!keyboard_) return; keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating()); gfx::Rect bounds = GetBoundsForReservedArea(); if (animation_->is_animating() && !keyboard_showing_) { // The keyboard is in the process of hiding. So pretend it still has the // same bounds as when the keyboard is visible. But // |GetBoundsForReservedArea| should not take this into account so that the // render view gets the entire area to relayout itself. bounds.set_y(bounds.y() - kKeyboardHeight); bounds.set_height(kKeyboardHeight); } keyboard_->SetBoundsRect(bounds); } void TouchBrowserFrameView::FocusWillChange(views::View* focused_before, views::View* focused_now) { VirtualKeyboardType before = DecideKeyboardStateForView(focused_before); VirtualKeyboardType now = DecideKeyboardStateForView(focused_now); if (before != now) { // TODO(varunjain): support other types of keyboard. UpdateKeyboardAndLayout(now == GENERIC); } } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, protected: int TouchBrowserFrameView::GetReservedHeight() const { return keyboard_showing_ ? kKeyboardHeight : 0; } void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child); if (!GetFocusManager()) return; if (is_add && !focus_listener_added_) { // Add focus listener when this view is added to the hierarchy. GetFocusManager()->AddFocusChangeListener(this); focus_listener_added_ = true; } else if (!is_add && focus_listener_added_) { // Remove focus listener when this view is removed from the hierarchy. GetFocusManager()->RemoveFocusChangeListener(this); focus_listener_added_ = false; } } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, private: void TouchBrowserFrameView::InitVirtualKeyboard() { if (keyboard_) return; Profile* keyboard_profile = browser_view()->browser()->profile(); DCHECK(keyboard_profile) << "Profile required for virtual keyboard."; keyboard_ = new KeyboardContainerView(keyboard_profile, browser_view()->browser()); keyboard_->SetVisible(false); AddChildView(keyboard_); } void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) { if (should_show_keyboard) InitVirtualKeyboard(); if (should_show_keyboard == keyboard_showing_) return; DCHECK(keyboard_); keyboard_showing_ = should_show_keyboard; if (keyboard_showing_) { animation_->Show(); // We don't re-layout the client view until the animation ends (see // AnimationEnded below) because we want the client view to occupy the // entire height during the animation. Layout(); } else { animation_->Hide(); browser_view()->set_clip_y(ui::Tween::ValueBetween( animation_->GetCurrentValue(), 0, kKeyboardHeight)); parent()->Layout(); } } TouchBrowserFrameView::VirtualKeyboardType TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) { if (!view) return NONE; std::string cname = view->GetClassName(); if (cname == views::Textfield::kViewClassName) { return GENERIC; } else if (cname == RenderWidgetHostViewViews::kViewClassName) { TabContents* contents = browser_view()->browser()->GetSelectedTabContents(); bool* editable = contents ? GetFocusedStateAccessor()->GetProperty( contents->property_bag()) : NULL; if (editable && *editable) return GENERIC; } return NONE; } bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const { if (OpaqueBrowserFrameView::HitTest(point)) return true; if (close_button()->IsVisible() && close_button()->GetMirroredBounds().Contains(point)) return true; if (restore_button()->IsVisible() && restore_button()->GetMirroredBounds().Contains(point)) return true; if (maximize_button()->IsVisible() && maximize_button()->GetMirroredBounds().Contains(point)) return true; if (minimize_button()->IsVisible() && minimize_button()->GetMirroredBounds().Contains(point)) return true; return false; } void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents, TabContentsWrapper* new_contents, int index, bool user_gesture) { if (new_contents == old_contents) return; TabContents* contents = new_contents->tab_contents(); if (!TabContentsHasFocus(contents)) return; bool* editable = GetFocusedStateAccessor()->GetProperty( contents->property_bag()); UpdateKeyboardAndLayout(editable ? *editable : false); } void TouchBrowserFrameView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { Browser* browser = browser_view()->browser(); if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the currently active tab sent the // notification. const TabContents* current_tab = browser->GetSelectedTabContents(); TabContents* source_tab = Source<TabContents>(source).ptr(); const bool editable = *Details<const bool>(details).ptr(); if (current_tab == source_tab && TabContentsHasFocus(source_tab)) UpdateKeyboardAndLayout(editable); // Save the state of the focused field so that the keyboard visibility // can be determined after tab switching. GetFocusedStateAccessor()->SetProperty( source_tab->property_bag(), editable); } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* controller = Source<NavigationController>(source).ptr(); Browser* source_browser = Browser::GetBrowserForController( controller, NULL); // If the Browser for the keyboard has navigated, re-evaluate the visibility // of the keyboard. TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE; views::View* view = GetFocusManager()->GetFocusedView(); if (view) { if (view->GetClassName() == views::Textfield::kViewClassName) keyboard_type = GENERIC; if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) { // Reset the state of the focused field in the current tab. GetFocusedStateAccessor()->SetProperty( controller->tab_contents()->property_bag(), false); } } if (source_browser == browser) UpdateKeyboardAndLayout(keyboard_type == GENERIC); } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) { GetFocusedStateAccessor()->DeleteProperty( Source<TabContents>(source).ptr()->property_bag()); } else if (type == NotificationType::PREF_CHANGED) { OpaqueBrowserFrameView::Observe(type, source, details); } } /////////////////////////////////////////////////////////////////////////////// // ui::AnimationDelegate implementation void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) { ui::Transform transform; transform.SetTranslateY( ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0)); keyboard_->SetTransform(transform); browser_view()->set_clip_y( ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight)); SchedulePaint(); } void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) { browser_view()->set_clip_y(0); if (keyboard_showing_) { // Because the NonClientFrameView is a sibling of the ClientView, we rely on // the parent to resize the ClientView instead of resizing it directly. parent()->Layout(); // The keyboard that pops up may end up hiding the text entry. So make sure // the renderer scrolls when necessary to keep the textfield visible. RenderViewHost* host = browser_view()->browser()->GetSelectedTabContents()->render_view_host(); host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView( host->routing_id())); } SchedulePaint(); } <commit_msg>Add a missing head to fix touch compile.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/touch/frame/touch_browser_frame_view.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_host/render_widget_host_view_views.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h" #include "chrome/browser/ui/touch/frame/keyboard_container_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/tab_contents/tab_contents_view_touch.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/navigation_controller.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/common/notification_service.h" #include "content/common/notification_type.h" #include "content/common/view_messages.h" #include "ui/base/animation/slide_animation.h" #include "ui/gfx/rect.h" #include "ui/gfx/transform.h" #include "views/controls/button/image_button.h" #include "views/controls/textfield/textfield.h" #include "views/focus/focus_manager.h" namespace { const int kKeyboardHeight = 300; const int kKeyboardSlideDuration = 500; // In milliseconds PropertyAccessor<bool>* GetFocusedStateAccessor() { static PropertyAccessor<bool> state; return &state; } bool TabContentsHasFocus(const TabContents* contents) { views::View* view = static_cast<TabContentsViewTouch*>(contents->view()); return view->Contains(view->GetFocusManager()->GetFocusedView()); } } // namespace // static const char TouchBrowserFrameView::kViewClassName[] = "browser/ui/touch/frame/TouchBrowserFrameView"; /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, public: TouchBrowserFrameView::TouchBrowserFrameView(BrowserFrame* frame, BrowserView* browser_view) : OpaqueBrowserFrameView(frame, browser_view), keyboard_showing_(false), focus_listener_added_(false), keyboard_(NULL) { registrar_.Add(this, NotificationType::NAV_ENTRY_COMMITTED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::FOCUS_CHANGED_IN_PAGE, NotificationService::AllSources()); registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, NotificationService::AllSources()); browser_view->browser()->tabstrip_model()->AddObserver(this); animation_.reset(new ui::SlideAnimation(this)); animation_->SetTweenType(ui::Tween::LINEAR); animation_->SetSlideDuration(kKeyboardSlideDuration); } TouchBrowserFrameView::~TouchBrowserFrameView() { browser_view()->browser()->tabstrip_model()->RemoveObserver(this); } std::string TouchBrowserFrameView::GetClassName() const { return kViewClassName; } void TouchBrowserFrameView::Layout() { OpaqueBrowserFrameView::Layout(); if (!keyboard_) return; keyboard_->SetVisible(keyboard_showing_ || animation_->is_animating()); gfx::Rect bounds = GetBoundsForReservedArea(); if (animation_->is_animating() && !keyboard_showing_) { // The keyboard is in the process of hiding. So pretend it still has the // same bounds as when the keyboard is visible. But // |GetBoundsForReservedArea| should not take this into account so that the // render view gets the entire area to relayout itself. bounds.set_y(bounds.y() - kKeyboardHeight); bounds.set_height(kKeyboardHeight); } keyboard_->SetBoundsRect(bounds); } void TouchBrowserFrameView::FocusWillChange(views::View* focused_before, views::View* focused_now) { VirtualKeyboardType before = DecideKeyboardStateForView(focused_before); VirtualKeyboardType now = DecideKeyboardStateForView(focused_now); if (before != now) { // TODO(varunjain): support other types of keyboard. UpdateKeyboardAndLayout(now == GENERIC); } } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, protected: int TouchBrowserFrameView::GetReservedHeight() const { return keyboard_showing_ ? kKeyboardHeight : 0; } void TouchBrowserFrameView::ViewHierarchyChanged(bool is_add, View* parent, View* child) { OpaqueBrowserFrameView::ViewHierarchyChanged(is_add, parent, child); if (!GetFocusManager()) return; if (is_add && !focus_listener_added_) { // Add focus listener when this view is added to the hierarchy. GetFocusManager()->AddFocusChangeListener(this); focus_listener_added_ = true; } else if (!is_add && focus_listener_added_) { // Remove focus listener when this view is removed from the hierarchy. GetFocusManager()->RemoveFocusChangeListener(this); focus_listener_added_ = false; } } /////////////////////////////////////////////////////////////////////////////// // TouchBrowserFrameView, private: void TouchBrowserFrameView::InitVirtualKeyboard() { if (keyboard_) return; Profile* keyboard_profile = browser_view()->browser()->profile(); DCHECK(keyboard_profile) << "Profile required for virtual keyboard."; keyboard_ = new KeyboardContainerView(keyboard_profile, browser_view()->browser()); keyboard_->SetVisible(false); AddChildView(keyboard_); } void TouchBrowserFrameView::UpdateKeyboardAndLayout(bool should_show_keyboard) { if (should_show_keyboard) InitVirtualKeyboard(); if (should_show_keyboard == keyboard_showing_) return; DCHECK(keyboard_); keyboard_showing_ = should_show_keyboard; if (keyboard_showing_) { animation_->Show(); // We don't re-layout the client view until the animation ends (see // AnimationEnded below) because we want the client view to occupy the // entire height during the animation. Layout(); } else { animation_->Hide(); browser_view()->set_clip_y(ui::Tween::ValueBetween( animation_->GetCurrentValue(), 0, kKeyboardHeight)); parent()->Layout(); } } TouchBrowserFrameView::VirtualKeyboardType TouchBrowserFrameView::DecideKeyboardStateForView(views::View* view) { if (!view) return NONE; std::string cname = view->GetClassName(); if (cname == views::Textfield::kViewClassName) { return GENERIC; } else if (cname == RenderWidgetHostViewViews::kViewClassName) { TabContents* contents = browser_view()->browser()->GetSelectedTabContents(); bool* editable = contents ? GetFocusedStateAccessor()->GetProperty( contents->property_bag()) : NULL; if (editable && *editable) return GENERIC; } return NONE; } bool TouchBrowserFrameView::HitTest(const gfx::Point& point) const { if (OpaqueBrowserFrameView::HitTest(point)) return true; if (close_button()->IsVisible() && close_button()->GetMirroredBounds().Contains(point)) return true; if (restore_button()->IsVisible() && restore_button()->GetMirroredBounds().Contains(point)) return true; if (maximize_button()->IsVisible() && maximize_button()->GetMirroredBounds().Contains(point)) return true; if (minimize_button()->IsVisible() && minimize_button()->GetMirroredBounds().Contains(point)) return true; return false; } void TouchBrowserFrameView::TabSelectedAt(TabContentsWrapper* old_contents, TabContentsWrapper* new_contents, int index, bool user_gesture) { if (new_contents == old_contents) return; TabContents* contents = new_contents->tab_contents(); if (!TabContentsHasFocus(contents)) return; bool* editable = GetFocusedStateAccessor()->GetProperty( contents->property_bag()); UpdateKeyboardAndLayout(editable ? *editable : false); } void TouchBrowserFrameView::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { Browser* browser = browser_view()->browser(); if (type == NotificationType::FOCUS_CHANGED_IN_PAGE) { // Only modify the keyboard state if the currently active tab sent the // notification. const TabContents* current_tab = browser->GetSelectedTabContents(); TabContents* source_tab = Source<TabContents>(source).ptr(); const bool editable = *Details<const bool>(details).ptr(); if (current_tab == source_tab && TabContentsHasFocus(source_tab)) UpdateKeyboardAndLayout(editable); // Save the state of the focused field so that the keyboard visibility // can be determined after tab switching. GetFocusedStateAccessor()->SetProperty( source_tab->property_bag(), editable); } else if (type == NotificationType::NAV_ENTRY_COMMITTED) { NavigationController* controller = Source<NavigationController>(source).ptr(); Browser* source_browser = Browser::GetBrowserForController( controller, NULL); // If the Browser for the keyboard has navigated, re-evaluate the visibility // of the keyboard. TouchBrowserFrameView::VirtualKeyboardType keyboard_type = NONE; views::View* view = GetFocusManager()->GetFocusedView(); if (view) { if (view->GetClassName() == views::Textfield::kViewClassName) keyboard_type = GENERIC; if (view->GetClassName() == RenderWidgetHostViewViews::kViewClassName) { // Reset the state of the focused field in the current tab. GetFocusedStateAccessor()->SetProperty( controller->tab_contents()->property_bag(), false); } } if (source_browser == browser) UpdateKeyboardAndLayout(keyboard_type == GENERIC); } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) { GetFocusedStateAccessor()->DeleteProperty( Source<TabContents>(source).ptr()->property_bag()); } else if (type == NotificationType::PREF_CHANGED) { OpaqueBrowserFrameView::Observe(type, source, details); } } /////////////////////////////////////////////////////////////////////////////// // ui::AnimationDelegate implementation void TouchBrowserFrameView::AnimationProgressed(const ui::Animation* anim) { ui::Transform transform; transform.SetTranslateY( ui::Tween::ValueBetween(anim->GetCurrentValue(), kKeyboardHeight, 0)); keyboard_->SetTransform(transform); browser_view()->set_clip_y( ui::Tween::ValueBetween(anim->GetCurrentValue(), 0, kKeyboardHeight)); SchedulePaint(); } void TouchBrowserFrameView::AnimationEnded(const ui::Animation* animation) { browser_view()->set_clip_y(0); if (keyboard_showing_) { // Because the NonClientFrameView is a sibling of the ClientView, we rely on // the parent to resize the ClientView instead of resizing it directly. parent()->Layout(); // The keyboard that pops up may end up hiding the text entry. So make sure // the renderer scrolls when necessary to keep the textfield visible. RenderViewHost* host = browser_view()->browser()->GetSelectedTabContents()->render_view_host(); host->Send(new ViewMsg_ScrollFocusedEditableNodeIntoView( host->routing_id())); } SchedulePaint(); } <|endoftext|>
<commit_before>/** * File : F.cpp * Author : Kazune Takahashi * Created : 11/25/2018, 12:58:28 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; int N, M, K; int P[310]; int root = 0; vector<int> children[310]; int cnt_c[310]; int cnt_sum[310]; int S[310]; vector<int> T[310]; bool used[310]; bool ok = true; vector<int> ans; int mini = 0; int calc_S(int v) { if (S[v] != -1) { return S[v]; } if (v == root) { return S[v] = 1; } return S[v] = calc_S(P[v]) + 1; } void flush() { if (ok) { assert((int)ans.size() == M); for (auto i = 0; i < M; i++) { cout << ans[i] + 1; if (i < M - 1) { cout << " "; } } } else { cout << -1 << endl; } } int calc_c(int v) { cnt_c[v] = 0; for (auto x : children[v]) { cnt_c[v] += calc_c(x); } return cnt_c[v] + 1; } int calc_sum(int v) { cnt_sum[v] = 0; for (auto x : children[v]) { cnt_sum[v] += calc_sum(x); } return cnt_sum[v]; } int calc_mini(int remain) { mini = 0; for (auto i = 0; i < 310; i++) { if (remain <= 0) { break; } int x = min((int)T[i].size(), remain); mini += i * x; remain -= x; } return mini; } void init() { fill(S, S + N, -1); for (auto i = 0; i < 310; i++) { T[i].clear(); } for (auto i = 0; i < N; i++) { T[calc_S(i)].push_back(i); } calc_c(root); calc_sum(root); calc_mini(M - (int)ans.size()); } void make_used(int v) { used[v] = true; for (auto x : children[v]) { make_used(x); } } bool erasable(int v) { int cost = S[v]; if (P[v] == -1) { if (K == 1 && (int)ans.size() == M - 1) { ans.push_back(v); return true; } return false; } ans.push_back(v); auto it = children[P[v]].begin(); while (it != children[P[v]].end()) { if (*it == v) { children[P[v]].erase(it); break; } } init(); if ((int)ans.size() == M - 1) { if (cost == K) { return true; } } else if (cnt_c[root] >= M - (int)ans.size() - 1 && mini <= K - cost && K - cost <= cnt_sum[root]) { K -= cost; make_used(v); return true; } children[P[v]].push_back(v); it = ans.end(); it--; ans.erase(it); return false; } int main() { cin >> N >> M >> K; for (auto i = 0; i < N; i++) { cin >> P[i]; P[i]--; } for (auto i = 0; i < N; i++) { if (P[i] == -1) { root = i; } else { children[P[i]].push_back(i); } } init(); fill(used, used + N, false); for (auto i = 0; i < M; i++) { bool valid = false; for (auto j = 0; j < N; j++) { if (used[j]) { continue; } if (erasable(j)) { cerr << "erase: " << j << endl; valid = true; break; } } if (!valid) { ok = false; break; } } flush(); }<commit_msg>tried F.cpp to 'F'<commit_after>/** * File : F.cpp * Author : Kazune Takahashi * Created : 11/25/2018, 12:58:28 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; int N, M, K; int P[310]; int root = 0; vector<int> children[310]; int cnt_c[310]; int cnt_sum[310]; int S[310]; vector<int> T[310]; bool used[310]; bool ok = true; vector<int> ans; int mini = 0; int calc_S(int v) { if (S[v] != -1) { return S[v]; } if (v == root) { return S[v] = 1; } return S[v] = calc_S(P[v]) + 1; } void flush() { if (ok) { assert((int)ans.size() == M); for (auto i = 0; i < M; i++) { cout << ans[i] + 1; if (i < M - 1) { cout << " "; } } } else { cout << -1 << endl; } } int calc_c(int v) { cnt_c[v] = 0; for (auto x : children[v]) { cnt_c[v] += calc_c(x); } return cnt_c[v] + 1; } int calc_sum(int v) { cnt_sum[v] = 0; for (auto x : children[v]) { cnt_sum[v] += calc_sum(x); } return cnt_sum[v]; } int calc_mini(int remain) { mini = 0; for (auto i = 0; i < 310; i++) { if (remain <= 0) { break; } int x = min((int)T[i].size(), remain); mini += i * x; remain -= x; } return mini; } void init() { fill(S, S + N, -1); for (auto i = 0; i < 310; i++) { T[i].clear(); } for (auto i = 0; i < N; i++) { T[calc_S(i)].push_back(i); } calc_c(root); calc_sum(root); calc_mini(M - (int)ans.size()); cerr << "cnt_c[" << root << "] = " << cnt_c[root] << endl; cerr << "cnt_sum[" << root << "] = " << cnt_sum[root] << endl; cerr << "mini = " << mini << endl; } void make_used(int v) { used[v] = true; for (auto x : children[v]) { make_used(x); } } bool erasable(int v) { int cost = S[v]; if (P[v] == -1) { if (K == 1 && (int)ans.size() == M - 1) { ans.push_back(v); return true; } return false; } ans.push_back(v); auto it = children[P[v]].begin(); while (it != children[P[v]].end()) { if (*it == v) { children[P[v]].erase(it); break; } } init(); if ((int)ans.size() == M - 1) { if (cost == K) { return true; } } else if (cnt_c[root] >= M - (int)ans.size() - 1 && mini <= K - cost && K - cost <= cnt_sum[root]) { K -= cost; make_used(v); return true; } children[P[v]].push_back(v); it = ans.end(); it--; ans.erase(it); return false; } int main() { cin >> N >> M >> K; for (auto i = 0; i < N; i++) { cin >> P[i]; P[i]--; } for (auto i = 0; i < N; i++) { if (P[i] == -1) { root = i; } else { children[P[i]].push_back(i); } } init(); fill(used, used + N, false); for (auto i = 0; i < M; i++) { bool valid = false; for (auto j = 0; j < N; j++) { if (used[j]) { continue; } if (erasable(j)) { cerr << "erase: " << j << endl; valid = true; break; } } if (!valid) { ok = false; break; } } flush(); }<|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkObjectToObjectMetric.h" namespace itk { //------------------------------------------------------------------- ObjectToObjectMetric ::ObjectToObjectMetric() { // Don't call SetGradientSource, to avoid valgrind warning. this->m_GradientSource = this->GRADIENT_SOURCE_MOVING; } //------------------------------------------------------------------- ObjectToObjectMetric ::~ObjectToObjectMetric() {} //------------------------------------------------------------------- bool ObjectToObjectMetric ::GetGradientSourceIncludesFixed() const { return m_GradientSource == GRADIENT_SOURCE_FIXED || m_GradientSource == GRADIENT_SOURCE_BOTH; } //------------------------------------------------------------------- bool ObjectToObjectMetric ::GetGradientSourceIncludesMoving() const { return m_GradientSource == GRADIENT_SOURCE_MOVING || m_GradientSource == GRADIENT_SOURCE_BOTH; } //------------------------------------------------------------------- void ObjectToObjectMetric ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "TODO..."; } }//namespace itk <commit_msg>ENH: Populate ObjectToObjectMetric PrintSelf ITK-2634<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkObjectToObjectMetric.h" namespace itk { //------------------------------------------------------------------- ObjectToObjectMetric ::ObjectToObjectMetric() { // Don't call SetGradientSource, to avoid valgrind warning. this->m_GradientSource = this->GRADIENT_SOURCE_MOVING; } //------------------------------------------------------------------- ObjectToObjectMetric ::~ObjectToObjectMetric() {} //------------------------------------------------------------------- bool ObjectToObjectMetric ::GetGradientSourceIncludesFixed() const { return m_GradientSource == GRADIENT_SOURCE_FIXED || m_GradientSource == GRADIENT_SOURCE_BOTH; } //------------------------------------------------------------------- bool ObjectToObjectMetric ::GetGradientSourceIncludesMoving() const { return m_GradientSource == GRADIENT_SOURCE_MOVING || m_GradientSource == GRADIENT_SOURCE_BOTH; } //------------------------------------------------------------------- void ObjectToObjectMetric ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "GradientSourceType: "; switch( m_GradientSource ) { case GRADIENT_SOURCE_FIXED: os << "GRADIENT_SOURCE_FIXED"; break; case GRADIENT_SOURCE_MOVING: os << "GRADIENT_SOURCE_MOVING"; break; case GRADIENT_SOURCE_BOTH: os << "GRADIENT_SOURCE_BOTH"; break; default: itkExceptionMacro(<< "Unknown GradientSource."); } os << std::endl; } }//namespace itk <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkImageFilterToVideoFilterWrapper.h" #include "itkImage.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkVideoFileReader.h" #include "itkVideoFileWriter.h" #include "itkFileListVideoIOFactory.h" /** * Main test */ int itkImageFilterToVideoFilterWrapperTest( int argc, char* argv[] ) { // Check parameters if (argc < 3) { std::cerr << "Usage: " << argv[0] << " input_video output_video" << std::endl; return EXIT_FAILURE; } // Typedefs typedef unsigned char PixelType; typedef itk::Image<PixelType, 2> FrameType; typedef itk::VideoStream< FrameType > VideoType; typedef itk::RecursiveGaussianImageFilter< FrameType, FrameType > GaussianImageFilterType; typedef itk::ImageFilterToVideoFilterWrapper< GaussianImageFilterType > GaussianVideoFilterType; typedef itk::VideoFileReader< VideoType > VideoReaderType; typedef itk::VideoFileWriter< VideoType > VideoWriterType; // Register FileListIO with the factory -- shouldn't have to do this. Needs fixing itk::ObjectFactoryBase::RegisterFactory( itk::FileListVideoIOFactory::New() ); // Set up reader and writer VideoReaderType::Pointer reader = VideoReaderType::New(); VideoWriterType::Pointer writer = VideoWriterType::New(); reader->SetFileName(argv[1]); writer->SetFileName(argv[2]); // Instantiate a new video filter and an image filter GaussianImageFilterType::Pointer imgGauss = GaussianImageFilterType::New(); GaussianVideoFilterType::Pointer vidGauss = GaussianVideoFilterType::New(); // Set the parameters on the image filter and plug it into the video filter imgGauss->SetSigma(3); vidGauss->SetImageFilter(imgGauss); // String the pipeline together vidGauss->SetInput(reader->GetOutput()); writer->SetInput(vidGauss->GetOutput()); // Run the pipeline writer->Update(); ////// // Return successfully ////// return EXIT_SUCCESS; } <commit_msg>ENH: Test output frames<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkImageFilterToVideoFilterWrapper.h" #include "itkImage.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkVideoFileReader.h" #include "itkVideoFileWriter.h" #include "itkImageFileReader.h" #include "itkFileListVideoIO.h" #include "itkFileListVideoIOFactory.h" #include "itkDifferenceImageFilter.h" /** * Main test */ int itkImageFilterToVideoFilterWrapperTest( int argc, char* argv[] ) { // Check parameters if (argc < 3) { std::cerr << "Usage: " << argv[0] << " input_video output_video" << std::endl; return EXIT_FAILURE; } // Get the lists of input and output files std::vector<std::string> inputFiles = itk::FileListVideoIO::SplitFileNames(argv[1]); std::vector<std::string> outputFiles = itk::FileListVideoIO::SplitFileNames(argv[2]); if (inputFiles.size() != outputFiles.size()) { std::cerr << "Must specify the same number of input and output frames" << std::endl; return EXIT_FAILURE; } // Typedefs typedef unsigned char PixelType; typedef itk::Image<PixelType, 2> FrameType; typedef itk::VideoStream< FrameType > VideoType; typedef itk::RecursiveGaussianImageFilter< FrameType, FrameType > GaussianImageFilterType; typedef itk::ImageFilterToVideoFilterWrapper< GaussianImageFilterType > GaussianVideoFilterType; typedef itk::VideoFileReader< VideoType > VideoReaderType; typedef itk::VideoFileWriter< VideoType > VideoWriterType; // Register FileListIO with the factory -- shouldn't have to do this. Needs fixing itk::ObjectFactoryBase::RegisterFactory( itk::FileListVideoIOFactory::New() ); // Set up reader and writer VideoReaderType::Pointer reader = VideoReaderType::New(); VideoWriterType::Pointer writer = VideoWriterType::New(); reader->SetFileName(argv[1]); writer->SetFileName(argv[2]); // Instantiate a new video filter and an image filter GaussianImageFilterType::Pointer imgGauss = GaussianImageFilterType::New(); GaussianVideoFilterType::Pointer vidGauss = GaussianVideoFilterType::New(); // Set the parameters on the image filter and plug it into the video filter imgGauss->SetSigma(3); vidGauss->SetImageFilter(imgGauss); // String the pipeline together vidGauss->SetInput(reader->GetOutput()); writer->SetInput(vidGauss->GetOutput()); // Run the pipeline writer->Update(); // // Check output // typedef itk::ImageFileReader< FrameType > ImageReaderType; typedef itk::DifferenceImageFilter< FrameType, FrameType > DifferenceFilterType; ImageReaderType::Pointer imReader1 = ImageReaderType::New(); ImageReaderType::Pointer imReader2 = ImageReaderType::New(); DifferenceFilterType::Pointer differ = DifferenceFilterType::New(); imgGauss->SetInput(imReader1->GetOutput()); differ->SetValidInput(imgGauss->GetOutput()); differ->SetTestInput(imReader2->GetOutput()); for (unsigned int i = 0; i < inputFiles.size(); ++i) { imReader1->SetFileName(inputFiles[i]); imReader2->SetFileName(outputFiles[i]); differ->Update(); if (differ->GetTotalDifference() != 0) { std::cerr << "Frame " << i << " didn't produce the correct output. Difference = " << differ->GetTotalDifference() << std::endl; return EXIT_FAILURE; } } ////// // Return successfully ////// return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryCTKPluginActivator.h" #include <berryIApplication.h> #include <berryIConfigurationElement.h> #include <berryIContributor.h> #include "berryApplicationContainer.h" #include "berryPlatform.h" #include "berryInternalPlatform.h" #include "berryErrorApplication.h" #include "berryPreferencesService.h" #include "berryExtensionRegistry.h" #include "berryRegistryConstants.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include "berryRegistryContributor.h" #include <QCoreApplication> #include <QDebug> namespace berry { static const QString XP_APPLICATIONS = "org.blueberry.osgi.applications"; ctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr; QScopedPointer<ApplicationContainer> org_blueberry_core_runtime_Activator::appContainer; const bool org_blueberry_core_runtime_Activator::DEBUG = false; void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context) { this->context = context; BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context) RegistryProperties::SetContext(context); //ProcessCommandLine(); this->startRegistry(); preferencesService.reset(new PreferencesService(context->getDataFile("").absolutePath())); prefServiceReg = context->registerService<IPreferencesService>(preferencesService.data()); // // register a listener to catch new plugin installations/resolutions. // pluginListener.reset(new CTKPluginListener(m_ExtensionPointService)); // context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // // populate the registry with all the currently installed plugins. // // There is a small window here while processPlugins is being // // called where the pluginListener may receive a ctkPluginEvent // // to add/remove a plugin from the registry. This is ok since // // the registry is a synchronized object and will not add the // // same bundle twice. // pluginListener->processPlugins(context->getPlugins()); this->startAppContainer(); InternalPlatform::GetInstance()->Start(context); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { InternalPlatform::GetInstance()->Stop(context); //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); prefServiceReg.unregister(); preferencesService->ShutDown(); preferencesService.reset(); prefServiceReg = 0; this->stopRegistry(); RegistryProperties::SetContext(nullptr); stopAppContainer(); this->context = nullptr; } ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext() { return context; } ApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer() { return appContainer.data(); } #if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW) #include <dlfcn.h> QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); Dl_info info = {nullptr,nullptr,nullptr,nullptr}; if(dladdr(symbol, &info) == 0) { return QString(); } else if(info.dli_fname) { QFile soPath(info.dli_fname); int index = soPath.fileName().lastIndexOf('.'); QString pluginId = soPath.fileName().left(index); if (pluginId.startsWith("lib")) pluginId = pluginId.mid(3); return pluginId.replace('_', '.'); } return QString(); } #elif defined(Q_CC_MSVC) #include <ctkBackTrace.h> #include <windows.h> #include <dbghelp.h> QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); if (ctk::DebugSymInitialize()) { std::vector<char> moduleBuffer(sizeof(IMAGEHLP_MODULE64)); PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) { QString pluginId = pModuleInfo->ModuleName; return pluginId.replace('_', '.'); } } return QString(); } #endif QSharedPointer<ctkPlugin> org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer<IContributor>& contributor) { if (RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>()) { bool okay = false; long id = regContributor->GetActualId().toLong(&okay); if (okay) { if (context != nullptr) { return context->getPlugin(id); } } else { // try using the name of the contributor below } } auto plugins = context->getPlugins(); //Return the first plugin that is not installed or uninstalled for (auto plugin : plugins) { if (!(plugin->getState() == ctkPlugin::INSTALLED || plugin->getState() == ctkPlugin::UNINSTALLED)) { return plugin; } } return QSharedPointer<ctkPlugin>(); } org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() : userRegistryKey(new QObject()) , masterRegistryKey(new QObject()) { } org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() { } void org_blueberry_core_runtime_Activator::startRegistry() { // see if the customer suppressed the creation of default registry QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString(); if (property.compare("false", Qt::CaseInsensitive) == 0) return; // check to see if we need to use null as a userToken if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0) { userRegistryKey.reset(nullptr); } // Determine primary and alternative registry locations. BlueBerry extension registry cache // can be found in one of the two locations: // a) in the local configuration area (standard location passed in by the platform) -> priority // b) in the shared configuration area (typically, shared install is used) QList<QString> registryLocations; QList<bool> readOnlyLocations; RegistryStrategy* strategy = nullptr; //Location configuration = OSGIUtils.getDefault().getConfigurationLocation(); QString configuration = context->getDataFile("").absoluteFilePath(); if (configuration.isEmpty()) { RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true"); RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, "true"); strategy = new RegistryStrategy(QList<QString>(), QList<bool>(), masterRegistryKey.data()); } else { //File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR); //bool primaryReadOnly = configuration.isReadOnly(); QString primaryDir = configuration; bool primaryReadOnly = false; //Location parentLocation = configuration.getParentLocation(); QString parentLocation; if (!parentLocation.isEmpty()) { // File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME); // registryLocations << primaryDir << secondaryDir; // readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only } else { registryLocations << primaryDir; readOnlyLocations << primaryReadOnly; } strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data()); } auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data()); defaultRegistry.reset(registry); registryServiceReg = context->registerService<IExtensionRegistry>(registry); //commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext()); } void org_blueberry_core_runtime_Activator::stopRegistry() { if (!defaultRegistry.isNull()) { registryServiceReg.unregister(); defaultRegistry->Stop(masterRegistryKey.data()); } // if (!commandRegistration.isNull()) // { // commandRegistration.unregister(); // } } void org_blueberry_core_runtime_Activator::startAppContainer() { appContainer.reset(new ApplicationContainer(context, defaultRegistry.data())); appContainer->Start(); } void org_blueberry_core_runtime_Activator::stopAppContainer() { appContainer->Stop(); } } <commit_msg>Fix external warning in dbghelp.h<commit_after>/*=================================================================== BlueBerry Platform Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef NOMINMAX #define NOMINMAX #endif #include "berryCTKPluginActivator.h" #include <berryIApplication.h> #include <berryIConfigurationElement.h> #include <berryIContributor.h> #include "berryApplicationContainer.h" #include "berryPlatform.h" #include "berryInternalPlatform.h" #include "berryErrorApplication.h" #include "berryPreferencesService.h" #include "berryExtensionRegistry.h" #include "berryRegistryConstants.h" #include "berryRegistryProperties.h" #include "berryRegistryStrategy.h" #include "berryRegistryContributor.h" #include <QCoreApplication> #include <QDebug> namespace berry { static const QString XP_APPLICATIONS = "org.blueberry.osgi.applications"; ctkPluginContext* org_blueberry_core_runtime_Activator::context = nullptr; QScopedPointer<ApplicationContainer> org_blueberry_core_runtime_Activator::appContainer; const bool org_blueberry_core_runtime_Activator::DEBUG = false; void org_blueberry_core_runtime_Activator::start(ctkPluginContext* context) { this->context = context; BERRY_REGISTER_EXTENSION_CLASS(ErrorApplication, context) RegistryProperties::SetContext(context); //ProcessCommandLine(); this->startRegistry(); preferencesService.reset(new PreferencesService(context->getDataFile("").absolutePath())); prefServiceReg = context->registerService<IPreferencesService>(preferencesService.data()); // // register a listener to catch new plugin installations/resolutions. // pluginListener.reset(new CTKPluginListener(m_ExtensionPointService)); // context->connectPluginListener(pluginListener.data(), SLOT(pluginChanged(ctkPluginEvent)), Qt::DirectConnection); // // populate the registry with all the currently installed plugins. // // There is a small window here while processPlugins is being // // called where the pluginListener may receive a ctkPluginEvent // // to add/remove a plugin from the registry. This is ok since // // the registry is a synchronized object and will not add the // // same bundle twice. // pluginListener->processPlugins(context->getPlugins()); this->startAppContainer(); InternalPlatform::GetInstance()->Start(context); } void org_blueberry_core_runtime_Activator::stop(ctkPluginContext* context) { InternalPlatform::GetInstance()->Stop(context); //pluginListener.reset(); //Platform::GetServiceRegistry().UnRegisterService(IExtensionPointService::SERVICE_ID); prefServiceReg.unregister(); preferencesService->ShutDown(); preferencesService.reset(); prefServiceReg = 0; this->stopRegistry(); RegistryProperties::SetContext(nullptr); stopAppContainer(); this->context = nullptr; } ctkPluginContext* org_blueberry_core_runtime_Activator::getPluginContext() { return context; } ApplicationContainer* org_blueberry_core_runtime_Activator::GetContainer() { return appContainer.data(); } #if defined(Q_OS_LINUX) || defined(Q_OS_DARWIN) || defined(Q_CC_MINGW) #include <dlfcn.h> QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); Dl_info info = {nullptr,nullptr,nullptr,nullptr}; if(dladdr(symbol, &info) == 0) { return QString(); } else if(info.dli_fname) { QFile soPath(info.dli_fname); int index = soPath.fileName().lastIndexOf('.'); QString pluginId = soPath.fileName().left(index); if (pluginId.startsWith("lib")) pluginId = pluginId.mid(3); return pluginId.replace('_', '.'); } return QString(); } #elif defined(Q_CC_MSVC) #include <ctkBackTrace.h> #include <windows.h> #ifdef _MSC_VER # pragma warning(push) # pragma warning(disable: 4091) #endif #include <dbghelp.h> #ifdef _MSC_VER # pragma warning(pop) #endif QString org_blueberry_core_runtime_Activator::getPluginId(void *symbol) { if (symbol == nullptr) return QString(); if (ctk::DebugSymInitialize()) { std::vector<char> moduleBuffer(sizeof(IMAGEHLP_MODULE64)); PIMAGEHLP_MODULE64 pModuleInfo = (PIMAGEHLP_MODULE64)&moduleBuffer.front(); pModuleInfo->SizeOfStruct = sizeof(IMAGEHLP_MODULE64); if (SymGetModuleInfo64(GetCurrentProcess(), (DWORD64)symbol, pModuleInfo)) { QString pluginId = pModuleInfo->ModuleName; return pluginId.replace('_', '.'); } } return QString(); } #endif QSharedPointer<ctkPlugin> org_blueberry_core_runtime_Activator::GetPlugin(const SmartPointer<IContributor>& contributor) { if (RegistryContributor::Pointer regContributor = contributor.Cast<RegistryContributor>()) { bool okay = false; long id = regContributor->GetActualId().toLong(&okay); if (okay) { if (context != nullptr) { return context->getPlugin(id); } } else { // try using the name of the contributor below } } auto plugins = context->getPlugins(); //Return the first plugin that is not installed or uninstalled for (auto plugin : plugins) { if (!(plugin->getState() == ctkPlugin::INSTALLED || plugin->getState() == ctkPlugin::UNINSTALLED)) { return plugin; } } return QSharedPointer<ctkPlugin>(); } org_blueberry_core_runtime_Activator::org_blueberry_core_runtime_Activator() : userRegistryKey(new QObject()) , masterRegistryKey(new QObject()) { } org_blueberry_core_runtime_Activator::~org_blueberry_core_runtime_Activator() { } void org_blueberry_core_runtime_Activator::startRegistry() { // see if the customer suppressed the creation of default registry QString property = context->getProperty(RegistryConstants::PROP_DEFAULT_REGISTRY).toString(); if (property.compare("false", Qt::CaseInsensitive) == 0) return; // check to see if we need to use null as a userToken if (context->getProperty(RegistryConstants::PROP_REGISTRY_nullptr_USER_TOKEN).toString().compare("true", Qt::CaseInsensitive) == 0) { userRegistryKey.reset(nullptr); } // Determine primary and alternative registry locations. BlueBerry extension registry cache // can be found in one of the two locations: // a) in the local configuration area (standard location passed in by the platform) -> priority // b) in the shared configuration area (typically, shared install is used) QList<QString> registryLocations; QList<bool> readOnlyLocations; RegistryStrategy* strategy = nullptr; //Location configuration = OSGIUtils.getDefault().getConfigurationLocation(); QString configuration = context->getDataFile("").absoluteFilePath(); if (configuration.isEmpty()) { RegistryProperties::SetProperty(RegistryConstants::PROP_NO_REGISTRY_CACHE, "true"); RegistryProperties::SetProperty(RegistryConstants::PROP_NO_LAZY_REGISTRY_CACHE_LOADING, "true"); strategy = new RegistryStrategy(QList<QString>(), QList<bool>(), masterRegistryKey.data()); } else { //File primaryDir = new File(configuration.getURL().getPath() + '/' + STORAGE_DIR); //bool primaryReadOnly = configuration.isReadOnly(); QString primaryDir = configuration; bool primaryReadOnly = false; //Location parentLocation = configuration.getParentLocation(); QString parentLocation; if (!parentLocation.isEmpty()) { // File secondaryDir = new File(parentLocation.getURL().getFile() + '/' + IRegistryConstants.RUNTIME_NAME); // registryLocations << primaryDir << secondaryDir; // readOnlyLocations << primaryReadOnly << true; // secondary BlueBerry location is always read only } else { registryLocations << primaryDir; readOnlyLocations << primaryReadOnly; } strategy = new RegistryStrategy(registryLocations, readOnlyLocations, masterRegistryKey.data()); } auto registry = new ExtensionRegistry(strategy, masterRegistryKey.data(), userRegistryKey.data()); defaultRegistry.reset(registry); registryServiceReg = context->registerService<IExtensionRegistry>(registry); //commandRegistration = EquinoxUtils.registerCommandProvider(Activator.getContext()); } void org_blueberry_core_runtime_Activator::stopRegistry() { if (!defaultRegistry.isNull()) { registryServiceReg.unregister(); defaultRegistry->Stop(masterRegistryKey.data()); } // if (!commandRegistration.isNull()) // { // commandRegistration.unregister(); // } } void org_blueberry_core_runtime_Activator::startAppContainer() { appContainer.reset(new ApplicationContainer(context, defaultRegistry.data())); appContainer->Start(); } void org_blueberry_core_runtime_Activator::stopAppContainer() { appContainer->Stop(); } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * SimTK Core: SimTK Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK Core biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2007 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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, CONTRIBUTORS 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 "SimTKmath.h" #include "simbody/internal/MobilizedBody.h" #include "simbody/internal/MultibodySystem.h" #include "simbody/internal/LocalEnergyMinimizer.h" #include "simbody/internal/SimbodyMatterSubsystem.h" #include <vector> #include <map> using namespace SimTK; using namespace std; /** * This class defines the objective function which is passed to the Optimizer. */ class LocalEnergyMinimizer::OptimizerFunction : public OptimizerSystem { public: // stateIn must be realized to Model stage already. OptimizerFunction(const MultibodySystem& system, const State& stateIn) : OptimizerSystem(stateIn.getNQ()), system(system), state(stateIn) { state.updU() = 0; // no velocities system.realize(state, Stage::Time); // we'll only change Position stage and above setNumEqualityConstraints(state.getNQErr()); } int objectiveFunc(const Vector& parameters, const bool new_parameters, Real& f) const { if (new_parameters) state.updQ() = parameters; system.realize(state, Stage::Dynamics); f = system.calcPotentialEnergy(state); return 0; } int gradientFunc(const Vector& parameters, const bool new_parameters, Vector& gradient) const { if (new_parameters) state.updQ() = parameters; system.realize(state, Stage::Dynamics); Vector_<SpatialVec> dEdR = system.getRigidBodyForces(state, Stage::Dynamics); const SimbodyMatterSubsystem& matter = system.getMatterSubsystem(); Vector dEdU; matter.calcInternalGradientFromSpatial(state, dEdR, dEdU); dEdU -= system.getMobilityForces(state, Stage::Dynamics); matter.multiplyByNInv(state, true, -1.0*dEdU, gradient); return 0; } int constraintFunc(const Vector& parameters, const bool new_parameters, Vector& constraints) const { state.updQ() = parameters; system.realize(state, Stage::Position); constraints = state.getQErr(); return 0; } void optimize(Vector& q, Real tolerance) { Optimizer opt(*this); opt.useNumericalJacobian(true); opt.setConvergenceTolerance(tolerance); opt.optimize(q); } private: const MultibodySystem& system; mutable State state; }; void LocalEnergyMinimizer::minimizeEnergy(const MultibodySystem& system, State& state, Real tolerance) { const SimbodyMatterSubsystem& matter = system.getMatterSubsystem(); State tempState = state; matter.setUseEulerAngles(tempState, true); system.realizeModel(tempState); if (!matter.getUseEulerAngles(state)) matter.convertToEulerAngles(state, tempState); OptimizerFunction optimizer(system, tempState); Vector q = tempState.getQ(); optimizer.optimize(q, tolerance); if (matter.getUseEulerAngles(state)) state.updQ() = q; else { tempState.updQ() = q; matter.convertToQuaternions(tempState, state); } } <commit_msg>Make LocalEnergyMinimizer do a final realize.<commit_after>/* -------------------------------------------------------------------------- * * SimTK Core: SimTK Simbody(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK Core biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2007 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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, CONTRIBUTORS 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 "SimTKmath.h" #include "simbody/internal/MobilizedBody.h" #include "simbody/internal/MultibodySystem.h" #include "simbody/internal/LocalEnergyMinimizer.h" #include "simbody/internal/SimbodyMatterSubsystem.h" #include <vector> #include <map> using namespace SimTK; using namespace std; /** * This class defines the objective function which is passed to the Optimizer. */ class LocalEnergyMinimizer::OptimizerFunction : public OptimizerSystem { public: // stateIn must be realized to Model stage already. OptimizerFunction(const MultibodySystem& system, const State& stateIn) : OptimizerSystem(stateIn.getNQ()), system(system), state(stateIn) { state.updU() = 0; // no velocities system.realize(state, Stage::Time); // we'll only change Position stage and above setNumEqualityConstraints(state.getNQErr()); } int objectiveFunc(const Vector& parameters, const bool new_parameters, Real& f) const { if (new_parameters) state.updQ() = parameters; system.realize(state, Stage::Dynamics); f = system.calcPotentialEnergy(state); return 0; } int gradientFunc(const Vector& parameters, const bool new_parameters, Vector& gradient) const { if (new_parameters) state.updQ() = parameters; system.realize(state, Stage::Dynamics); Vector_<SpatialVec> dEdR = system.getRigidBodyForces(state, Stage::Dynamics); const SimbodyMatterSubsystem& matter = system.getMatterSubsystem(); Vector dEdU; matter.calcInternalGradientFromSpatial(state, dEdR, dEdU); dEdU -= system.getMobilityForces(state, Stage::Dynamics); matter.multiplyByNInv(state, true, -1.0*dEdU, gradient); return 0; } int constraintFunc(const Vector& parameters, const bool new_parameters, Vector& constraints) const { state.updQ() = parameters; system.realize(state, Stage::Position); constraints = state.getQErr(); return 0; } void optimize(Vector& q, Real tolerance) { Optimizer opt(*this); opt.useNumericalJacobian(true); opt.setConvergenceTolerance(tolerance); opt.optimize(q); } private: const MultibodySystem& system; mutable State state; }; void LocalEnergyMinimizer::minimizeEnergy(const MultibodySystem& system, State& state, Real tolerance) { const SimbodyMatterSubsystem& matter = system.getMatterSubsystem(); State tempState = state; matter.setUseEulerAngles(tempState, true); system.realizeModel(tempState); if (!matter.getUseEulerAngles(state)) matter.convertToEulerAngles(state, tempState); OptimizerFunction optimizer(system, tempState); Vector q = tempState.getQ(); optimizer.optimize(q, tolerance); if (matter.getUseEulerAngles(state)) state.updQ() = q; else { tempState.updQ() = q; matter.convertToQuaternions(tempState, state); } system.realize(state, Stage::Dynamics); } <|endoftext|>
<commit_before>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/containers.hh ** \brief Some syntactic sugar to look for things in STL containers. */ #ifndef LIBPORT_CONTAINERS_HH # define LIBPORT_CONTAINERS_HH # include <deque> # include <iosfwd> # include <list> # include <set> # include <vector> namespace libport { /// Invoke delete on all the members of \a c, and clear it. template<typename Container> void deep_clear(Container& c); /// Find \a v in the whole \a c. template<typename Container> inline typename Container::const_iterator find(const Container& c, const typename Container::value_type& v); /// Find \a v in the whole \a c. template<typename Container> inline typename Container::iterator find(Container& c, const typename Container::value_type& v); /// Look up for \c k in \a c, return its value, or 0 if unknown. /// /// For associative containers mapping pointers. template<typename Container> inline typename Container::mapped_type find0(Container& c, const typename Container::key_type& k); /// Apply \a f to all the members of \a c, and return it. template<typename Container, typename Functor> inline Functor& for_each(Container& c, Functor& v); /// Is \a v member of \a c? template<typename Container> inline bool has(const Container& c, const typename Container::value_type& v); /// Is \a v member of \a c? Use member find (set, map, hash_map). template<typename Container> inline bool mhas(const Container& c, const typename Container::key_type& v); /// Insert or update \a key -> \a value in \a map, return iterator to it. template<typename Map> typename Map::iterator put(Map& map, const typename Map::key_type& key, const typename Map::mapped_type& value); // Does at least one member of \a c satisfy predicate \a f ? template<typename Container, typename Functor> bool has_if(const Container& c, const Functor& f); // Erase members of \a c satisfying predicate \a f. This does not // preserve the order of the members in the container. template<typename Container, typename Functor> void erase_if(Container& c, const Functor& f); } // namespace libport namespace std { /*---------------------. | Container << Value. | `---------------------*/ #define APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) \ Macro(::std::deque); \ Macro(::std::list); \ Macro(::std::vector); // Push back with '<<'. #define INSERT(Container) \ template<typename Lhs, typename Alloc, \ typename Rhs> \ Container<Lhs, Alloc>& \ operator<<(Container<Lhs, Alloc>& c, const Rhs& v) APPLY_ON_BACK_INSERTION_CONTAINERS(INSERT) #undef INSERT /*---------------------------------. | Associative Container << Value. | `---------------------------------*/ #define APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \ Macro(::std::set); // Insert with '<<'. #define INSERT(Container) \ template<typename Lhs, typename Alloc, \ typename Rhs> \ Container<Lhs, Alloc>& \ operator<<(Container<Lhs, Alloc>& c, const Rhs& v) APPLY_ON_ASSOCIATIVE_CONTAINERS(INSERT) #undef INSERT /*-------------------------. | Container == Container. | `-------------------------*/ namespace libport { #define APPLY_ON_CONTAINERS(Macro) \ APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \ APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) // ::std::list already provides this. #define APPLY_ON_EQUAL_CONTAINERS(Macro) \ Macro(::std::deque); \ Macro(::std::vector); \ Macro(::std::set); // Compare two containers. #define LIBPORT_CONTAINERS_DECLARE_EQUAL(Container) \ template <typename E, typename A> \ bool operator==(const Container<E, A>& lhs, \ const Container<E, A>& rhs); APPLY_ON_EQUAL_CONTAINERS(LIBPORT_CONTAINERS_DECLARE_EQUAL) #undef LIBPORT_CONTAINERS_DECLARE_EQUAL } /*-------------------------. | Container << Container. | `-------------------------*/ #define APPLY_ON_CONTAINERS_CONTAINERS(Macro) \ Macro(::std::deque, ::std::deque); \ Macro(::std::list, ::std::list); \ Macro(::std::list, ::std::set); \ Macro(::std::set, ::std::set); \ Macro(::std::set, ::std::vector); \ Macro(::std::vector, ::std::set); \ Macro(::std::vector, ::std::vector); // Concatenate with '<<'. // Arguably concatenation should be `+='. Consider the case // of appending a container to a container of containers. Or use // an intermediate function, say 'c1 << contents(c2)'. #define INSERT(Cont1, Cont2) \ template<typename Lhs, typename Alloc1, \ typename Rhs, typename Alloc2> \ Cont1<Lhs, Alloc1>& \ operator<< (Cont1<Lhs, Alloc1>& c, \ const Cont2<Rhs, Alloc2>& vs) APPLY_ON_CONTAINERS_CONTAINERS(INSERT) #undef INSERT } // namespace std # include <libport/containers.hxx> #endif // !LIBPORT_CONTAINERS_HH <commit_msg>Add << operator to print vectors.<commit_after>/* * Copyright (C) 2009, 2010, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file libport/containers.hh ** \brief Some syntactic sugar to look for things in STL containers. */ #ifndef LIBPORT_CONTAINERS_HH # define LIBPORT_CONTAINERS_HH # include <deque> # include <iosfwd> # include <list> # include <set> # include <vector> # include <libport/foreach.hh> namespace libport { /// Invoke delete on all the members of \a c, and clear it. template<typename Container> void deep_clear(Container& c); /// Find \a v in the whole \a c. template<typename Container> inline typename Container::const_iterator find(const Container& c, const typename Container::value_type& v); /// Find \a v in the whole \a c. template<typename Container> inline typename Container::iterator find(Container& c, const typename Container::value_type& v); /// Look up for \c k in \a c, return its value, or 0 if unknown. /// /// For associative containers mapping pointers. template<typename Container> inline typename Container::mapped_type find0(Container& c, const typename Container::key_type& k); /// Apply \a f to all the members of \a c, and return it. template<typename Container, typename Functor> inline Functor& for_each(Container& c, Functor& v); /// Is \a v member of \a c? template<typename Container> inline bool has(const Container& c, const typename Container::value_type& v); /// Is \a v member of \a c? Use member find (set, map, hash_map). template<typename Container> inline bool mhas(const Container& c, const typename Container::key_type& v); /// Insert or update \a key -> \a value in \a map, return iterator to it. template<typename Map> typename Map::iterator put(Map& map, const typename Map::key_type& key, const typename Map::mapped_type& value); // Does at least one member of \a c satisfy predicate \a f ? template<typename Container, typename Functor> bool has_if(const Container& c, const Functor& f); // Erase members of \a c satisfying predicate \a f. This does not // preserve the order of the members in the container. template<typename Container, typename Functor> void erase_if(Container& c, const Functor& f); } // namespace libport namespace std { /*---------------------. | Container << Value. | `---------------------*/ #define APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) \ Macro(::std::deque); \ Macro(::std::list); \ Macro(::std::vector); // Push back with '<<'. #define INSERT(Container) \ template<typename Lhs, typename Alloc, \ typename Rhs> \ Container<Lhs, Alloc>& \ operator<<(Container<Lhs, Alloc>& c, const Rhs& v) APPLY_ON_BACK_INSERTION_CONTAINERS(INSERT) #undef INSERT /*---------------------------------. | Associative Container << Value. | `---------------------------------*/ #define APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \ Macro(::std::set); // Insert with '<<'. #define INSERT(Container) \ template<typename Lhs, typename Alloc, \ typename Rhs> \ Container<Lhs, Alloc>& \ operator<<(Container<Lhs, Alloc>& c, const Rhs& v) APPLY_ON_ASSOCIATIVE_CONTAINERS(INSERT) #undef INSERT /*-------------------------. | Container == Container. | `-------------------------*/ namespace libport { #define APPLY_ON_CONTAINERS(Macro) \ APPLY_ON_ASSOCIATIVE_CONTAINERS(Macro) \ APPLY_ON_BACK_INSERTION_CONTAINERS(Macro) // ::std::list already provides this. #define APPLY_ON_EQUAL_CONTAINERS(Macro) \ Macro(::std::deque); \ Macro(::std::vector); \ Macro(::std::set); // Compare two containers. #define LIBPORT_CONTAINERS_DECLARE_EQUAL(Container) \ template <typename E, typename A> \ bool operator==(const Container<E, A>& lhs, \ const Container<E, A>& rhs); APPLY_ON_EQUAL_CONTAINERS(LIBPORT_CONTAINERS_DECLARE_EQUAL) #undef LIBPORT_CONTAINERS_DECLARE_EQUAL } /*-------------------------. | Container << Container. | `-------------------------*/ #define APPLY_ON_CONTAINERS_CONTAINERS(Macro) \ Macro(::std::deque, ::std::deque); \ Macro(::std::list, ::std::list); \ Macro(::std::list, ::std::set); \ Macro(::std::set, ::std::set); \ Macro(::std::set, ::std::vector); \ Macro(::std::vector, ::std::set); \ Macro(::std::vector, ::std::vector); // Concatenate with '<<'. // Arguably concatenation should be `+='. Consider the case // of appending a container to a container of containers. Or use // an intermediate function, say 'c1 << contents(c2)'. #define INSERT(Cont1, Cont2) \ template<typename Lhs, typename Alloc1, \ typename Rhs, typename Alloc2> \ Cont1<Lhs, Alloc1>& \ operator<< (Cont1<Lhs, Alloc1>& c, \ const Cont2<Rhs, Alloc2>& vs) APPLY_ON_CONTAINERS_CONTAINERS(INSERT) #undef INSERT /*--------------------. | ostream << vector. | `--------------------*/ template <typename T, typename Alloc> std::ostream& operator<< (std::ostream& out, const std::vector<T, Alloc>& c) { out << "["; typedef typename std::vector<T, Alloc>::value_type value_type; foreach (const value_type& v, c) out << v << ", "; out << "]"; return out; } } // namespace std # include <libport/containers.hxx> #endif // !LIBPORT_CONTAINERS_HH <|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_ASSERT #include "libtorrent/config.hpp" #include <string> #ifdef __GNUC__ std::string demangle(char const* name); #endif #if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG) TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function); #define TORRENT_ASSERT(x) if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__) #else #include <cassert> #define TORRENT_ASSERT(x) assert(x) #endif #endif <commit_msg>fixed warning on gcc 4.3<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_ASSERT #include "libtorrent/config.hpp" #include <string> #ifdef __GNUC__ std::string demangle(char const* name); #endif #if (defined __linux__ || defined __MACH__) && defined __GNUC__ && !defined(NDEBUG) TORRENT_EXPORT void assert_fail(const char* expr, int line, char const* file, char const* function); #define TORRENT_ASSERT(x) do { if (x) {} else assert_fail(#x, __LINE__, __FILE__, __PRETTY_FUNCTION__); } while (false) #else #include <cassert> #define TORRENT_ASSERT(x) assert(x) #endif #endif <|endoftext|>
<commit_before>/* Copyright (c) 2003, 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_SOCKET_WIN_HPP_INCLUDED #define TORRENT_SOCKET_WIN_HPP_INCLUDED // TODO: remove the dependency of // platform specific headers here. // sockaddr_in is hard to get rid of in a nice way #if defined(_WIN32) #include <winsock2.h> #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <arpa/inet.h> #endif #include <boost/smart_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <vector> #include <exception> #include <string> namespace libtorrent { class network_error : public std::exception { public: network_error(int error_code): m_error_code(error_code) {} virtual const char* what() const throw(); private: int m_error_code; }; class socket; class address { friend class socket; public: address(); address(unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port); address(unsigned int addr, unsigned short port); address(const std::string& addr, unsigned short port); address(const address& a); ~address(); std::string as_string() const; unsigned int ip() const { return m_sockaddr.sin_addr.s_addr; } unsigned short port() const { return htons(m_sockaddr.sin_port); } bool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); } bool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); } bool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); } private: sockaddr_in m_sockaddr; }; class socket: public boost::noncopyable { friend class address; friend class selector; public: enum type { tcp = 0, udp }; socket(type t, bool blocking = true, unsigned short receive_port = 0); virtual ~socket(); void connect(const address& addr); void close(); void set_blocking(bool blocking); bool is_blocking() { return m_blocking; } const address& sender() const { return m_sender; } address name() const; void listen(unsigned short port, int queue); boost::shared_ptr<libtorrent::socket> accept(); template<class T> int send(const T& buffer); template<class T> int send_to(const address& addr, const T& buffer); template<class T> int receive(T& buf); int send(const char* buffer, int size); int send_to(const address& addr, const char* buffer, int size); int receive(char* buffer, int size); void set_receive_bufsize(int size); void set_send_bufsize(int size); bool is_readable() const; bool is_writable() const; enum error_code { netdown, fault, access, address_in_use, address_not_available, in_progress, interrupted, invalid, net_reset, not_connected, no_buffers, operation_not_supported, not_socket, shutdown, would_block, connection_reset, timed_out, connection_aborted, message_size, not_ready, no_support, connection_refused, is_connected, net_unreachable, not_initialized, unknown_error }; error_code last_error() const; private: socket(int sock, const address& sender); int m_socket; address m_sender; bool m_blocking; #ifndef NDEBUG bool m_connected; // indicates that this socket has been connected type m_type; #endif }; template<class T> inline int socket::send(const T& buf) { return send(reinterpret_cast<const char*>(&buf), sizeof(buf)); } template<class T> inline int socket::send_to(const address& addr, const T& buf) { return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf)); } template<class T> inline int socket::receive(T& buf) { return receive(reinterpret_cast<char*>(&buf), sizeof(T)); } // timeout is given in microseconds // modified is cleared and filled with the sockets that is ready for reading or writing // or have had an error class selector { public: void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); } void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); } void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); } /* void clear_readable() { m_readable.clear(); } void clear_writable() { m_writable.clear(); } */ void remove(boost::shared_ptr<socket> s); void remove_writable(boost::shared_ptr<socket> s) { m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); } bool is_writability_monitored(boost::shared_ptr<socket> s) { return std::find(m_writable.begin(), m_writable.end(), s) != m_writable.end(); } void wait(int timeout , std::vector<boost::shared_ptr<socket> >& readable , std::vector<boost::shared_ptr<socket> >& writable , std::vector<boost::shared_ptr<socket> >& error); int count_read_monitors() const { return m_readable.size(); } private: std::vector<boost::shared_ptr<socket> > m_readable; std::vector<boost::shared_ptr<socket> > m_writable; std::vector<boost::shared_ptr<socket> > m_error; }; } #endif // TORRENT_SOCKET_WIN_HPP_INCLUDED <commit_msg>Made the socket.hpp platform independent<commit_after>/* Copyright (c) 2003, 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_SOCKET_HPP_INCLUDED #define TORRENT_SOCKET_HPP_INCLUDED // TODO: remove the dependency of // platform specific headers here. // sockaddr_in is hard to get rid of in a nice way #if defined(_WIN32) #include <winsock2.h> #else #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <errno.h> #include <pthread.h> #include <fcntl.h> #include <arpa/inet.h> #endif #include <boost/smart_ptr.hpp> #include <boost/function.hpp> #include <boost/noncopyable.hpp> #include <vector> #include <exception> #include <string> namespace libtorrent { class network_error : public std::exception { public: network_error(int error_code): m_error_code(error_code) {} virtual const char* what() const throw(); private: int m_error_code; }; class socket; class address { friend class socket; public: address(); address( unsigned char a , unsigned char b , unsigned char c , unsigned char d , unsigned short port); address(unsigned int addr, unsigned short port); address(const std::string& addr, unsigned short port); address(const address& a); ~address(); std::string as_string() const; unsigned int ip() const { return m_ip; } unsigned short port() const { return m_port; } bool operator<(const address& a) const { if (ip() == a.ip()) return port() < a.port(); else return ip() < a.ip(); } bool operator!=(const address& a) const { return (ip() != a.ip()) || port() != a.port(); } bool operator==(const address& a) const { return (ip() == a.ip()) && port() == a.port(); } private: unsigned int m_ip; unsigned short m_port; }; class socket: public boost::noncopyable { friend class address; friend class selector; public: enum type { tcp = 0, udp }; socket(type t, bool blocking = true, unsigned short receive_port = 0); virtual ~socket(); void connect(const address& addr); void close(); void set_blocking(bool blocking); bool is_blocking() { return m_blocking; } const address& sender() const { return m_sender; } address name() const; void listen(unsigned short port, int queue); boost::shared_ptr<libtorrent::socket> accept(); template<class T> int send(const T& buffer); template<class T> int send_to(const address& addr, const T& buffer); template<class T> int receive(T& buf); int send(const char* buffer, int size); int send_to(const address& addr, const char* buffer, int size); int receive(char* buffer, int size); void set_receive_bufsize(int size); void set_send_bufsize(int size); bool is_readable() const; bool is_writable() const; enum error_code { netdown, fault, access, address_in_use, address_not_available, in_progress, interrupted, invalid, net_reset, not_connected, no_buffers, operation_not_supported, not_socket, shutdown, would_block, connection_reset, timed_out, connection_aborted, message_size, not_ready, no_support, connection_refused, is_connected, net_unreachable, not_initialized, unknown_error }; error_code last_error() const; private: socket(int sock, const address& sender); int m_socket; address m_sender; bool m_blocking; #ifndef NDEBUG bool m_connected; // indicates that this socket has been connected type m_type; #endif }; template<class T> inline int socket::send(const T& buf) { return send(reinterpret_cast<const char*>(&buf), sizeof(buf)); } template<class T> inline int socket::send_to(const address& addr, const T& buf) { return send_to(addr, reinterpret_cast<const unsigned char*>(&buf), sizeof(buf)); } template<class T> inline int socket::receive(T& buf) { return receive(reinterpret_cast<char*>(&buf), sizeof(T)); } // timeout is given in microseconds // modified is cleared and filled with the sockets that is ready for reading or writing // or have had an error class selector { public: void monitor_readability(boost::shared_ptr<socket> s) { m_readable.push_back(s); } void monitor_writability(boost::shared_ptr<socket> s) { m_writable.push_back(s); } void monitor_errors(boost::shared_ptr<socket> s) { m_error.push_back(s); } /* void clear_readable() { m_readable.clear(); } void clear_writable() { m_writable.clear(); } */ void remove(boost::shared_ptr<socket> s); void remove_writable(boost::shared_ptr<socket> s) { m_writable.erase(std::find(m_writable.begin(), m_writable.end(), s)); } bool is_writability_monitored(boost::shared_ptr<socket> s) { return std::find(m_writable.begin(), m_writable.end(), s) != m_writable.end(); } void wait(int timeout , std::vector<boost::shared_ptr<socket> >& readable , std::vector<boost::shared_ptr<socket> >& writable , std::vector<boost::shared_ptr<socket> >& error); int count_read_monitors() const { return m_readable.size(); } private: std::vector<boost::shared_ptr<socket> > m_readable; std::vector<boost::shared_ptr<socket> > m_writable; std::vector<boost::shared_ptr<socket> > m_error; }; } #endif // TORRENT_SOCKET_WIN_INCLUDED <|endoftext|>
<commit_before>/* Copyright (c) 2009, 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_THREAD_HPP_INCLUDED #define TORRENT_THREAD_HPP_INCLUDED #include "libtorrent/config.hpp" #include <memory> #if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN // asio assumes that the windows error codes are defined already #include <winsock2.h> #endif #include <memory> // for auto_ptr required by asio #include <boost/asio/detail/thread.hpp> #include <boost/asio/detail/mutex.hpp> #include <boost/asio/detail/event.hpp> #if TORRENT_USE_POSIX_SEMAPHORE #include <semaphore.h> // sem_* #endif #if TORRENT_USE_MACH_SEMAPHORE #include <mach/semaphore.h> // semaphore_signal, semaphore_wait #include <mach/task.h> // semaphore_create, semaphore_destroy #include <mach/mach_init.h> // current_task #endif namespace libtorrent { typedef boost::asio::detail::thread thread; typedef boost::asio::detail::mutex mutex; typedef boost::asio::detail::event event; TORRENT_EXPORT void sleep(int milliseconds); struct TORRENT_EXPORT condition { condition(); ~condition(); void wait(mutex::scoped_lock& l); void signal_all(mutex::scoped_lock& l); private: #ifdef BOOST_HAS_PTHREADS pthread_cond_t m_cond; #elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN HANDLE m_sem; mutex m_mutex; int m_num_waiters; #else #error not implemented #endif }; // #error these semaphores needs to release all threads that are waiting for the semaphore when signalled #if TORRENT_USE_POSIX_SEMAPHORE struct TORRENT_EXPORT semaphore { semaphore() { sem_init(&m_sem, 0, 0); } ~semaphore() { sem_destroy(&m_sem); } void signal() { sem_post(&m_sem); } void signal_all() { int waiters = 0; do { // when anyone is waiting, waiters will be // 0 or negative. 0 means one might be waiting // -1 means 2 are waiting. Keep posting as long // we see negative values or 0 sem_getvalue(&m_sem, &waiters); sem_post(&m_sem); } while (waiters < 0) } void wait() { sem_wait(&m_sem); } void timed_wait(int ms) { timespec sp = { ms / 1000, (ms % 1000) * 1000000 }; sem_timedwait(&m_sem, &sp); } sem_t m_sem; }; #elif TORRENT_USE_MACH_SEMAPHORE struct TORRENT_EXPORT semaphore { semaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); } ~semaphore() { semaphore_destroy(current_task(), m_sem); } void signal() { semaphore_signal(m_sem); } void signal_all() { semaphore_signal_all(m_sem); } void wait() { semaphore_wait(m_sem); } void timed_wait(int ms) { mach_timespec_t sp = { ms / 1000, (ms % 1000) * 100000}; semaphore_timedwait(m_sem, sp); } semaphore_t m_sem; }; #elif defined TORRENT_WINDOWS struct TORRENT_EXPORT semaphore { semaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); } ~semaphore() { CloseHandle(m_sem); } void signal() { ReleaseSemaphore(m_sem, 1, 0); } void signal_all() { LONG prev = 0; do { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1); } void wait() { WaitForSingleObject(m_sem, INFINITE); } void timed_wait(int ms) { WaitForSingleObject(m_sem, ms); } HANDLE m_sem; }; #endif } #endif <commit_msg>fixed typo<commit_after>/* Copyright (c) 2009, 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_THREAD_HPP_INCLUDED #define TORRENT_THREAD_HPP_INCLUDED #include "libtorrent/config.hpp" #include <memory> #if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN // asio assumes that the windows error codes are defined already #include <winsock2.h> #endif #include <memory> // for auto_ptr required by asio #include <boost/asio/detail/thread.hpp> #include <boost/asio/detail/mutex.hpp> #include <boost/asio/detail/event.hpp> #if TORRENT_USE_POSIX_SEMAPHORE #include <semaphore.h> // sem_* #endif #if TORRENT_USE_MACH_SEMAPHORE #include <mach/semaphore.h> // semaphore_signal, semaphore_wait #include <mach/task.h> // semaphore_create, semaphore_destroy #include <mach/mach_init.h> // current_task #endif namespace libtorrent { typedef boost::asio::detail::thread thread; typedef boost::asio::detail::mutex mutex; typedef boost::asio::detail::event event; TORRENT_EXPORT void sleep(int milliseconds); struct TORRENT_EXPORT condition { condition(); ~condition(); void wait(mutex::scoped_lock& l); void signal_all(mutex::scoped_lock& l); private: #ifdef BOOST_HAS_PTHREADS pthread_cond_t m_cond; #elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN HANDLE m_sem; mutex m_mutex; int m_num_waiters; #else #error not implemented #endif }; // #error these semaphores needs to release all threads that are waiting for the semaphore when signalled #if TORRENT_USE_POSIX_SEMAPHORE struct TORRENT_EXPORT semaphore { semaphore() { sem_init(&m_sem, 0, 0); } ~semaphore() { sem_destroy(&m_sem); } void signal() { sem_post(&m_sem); } void signal_all() { int waiters = 0; do { // when anyone is waiting, waiters will be // 0 or negative. 0 means one might be waiting // -1 means 2 are waiting. Keep posting as long // we see negative values or 0 sem_getvalue(&m_sem, &waiters); sem_post(&m_sem); } while (waiters < 0); } void wait() { sem_wait(&m_sem); } void timed_wait(int ms) { timespec sp = { ms / 1000, (ms % 1000) * 1000000 }; sem_timedwait(&m_sem, &sp); } sem_t m_sem; }; #elif TORRENT_USE_MACH_SEMAPHORE struct TORRENT_EXPORT semaphore { semaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); } ~semaphore() { semaphore_destroy(current_task(), m_sem); } void signal() { semaphore_signal(m_sem); } void signal_all() { semaphore_signal_all(m_sem); } void wait() { semaphore_wait(m_sem); } void timed_wait(int ms) { mach_timespec_t sp = { ms / 1000, (ms % 1000) * 100000}; semaphore_timedwait(m_sem, sp); } semaphore_t m_sem; }; #elif defined TORRENT_WINDOWS struct TORRENT_EXPORT semaphore { semaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); } ~semaphore() { CloseHandle(m_sem); } void signal() { ReleaseSemaphore(m_sem, 1, 0); } void signal_all() { LONG prev = 0; do { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1); } void wait() { WaitForSingleObject(m_sem, INFINITE); } void timed_wait(int ms) { WaitForSingleObject(m_sem, ms); } HANDLE m_sem; }; #endif } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/plugin_updater.h" #include <string> #include <vector> #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/plugin_group.h" #include "chrome/common/pref_names.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" namespace plugin_updater { // Convert to a List of Groups static void GetPluginGroups( std::vector<linked_ptr<PluginGroup> >* plugin_groups) { // Read all plugins and convert them to plugin groups std::vector<WebPluginInfo> web_plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins); // We first search for an existing group that matches our name, // and only create a new group if we can't find any. for (size_t i = 0; i < web_plugins.size(); ++i) { const WebPluginInfo& web_plugin = web_plugins[i]; PluginGroup* group = PluginGroup::FindGroupMatchingPlugin( *plugin_groups, web_plugin); if (!group) { group = PluginGroup::FindHardcodedPluginGroup(web_plugin); plugin_groups->push_back(linked_ptr<PluginGroup>(group)); } group->AddPlugin(web_plugin, i); } } static DictionaryValue* CreatePluginFileSummary( const WebPluginInfo& plugin) { DictionaryValue* data = new DictionaryValue(); data->SetString(L"path", plugin.path.value()); data->SetStringFromUTF16(L"name", plugin.name); data->SetStringFromUTF16(L"version", plugin.version); data->SetBoolean(L"enabled", plugin.enabled); return data; } ListValue* GetPluginGroupsData() { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); // Construct DictionaryValues to return to the UI ListValue* plugin_groups_data = new ListValue(); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { plugin_groups_data->Append((*it)->GetDataForUI()); } return plugin_groups_data; } void EnablePluginGroup(bool enable, const string16& group_name) { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->GetGroupName() == group_name) { (*it)->Enable(enable); } } } void EnablePluginFile(bool enable, const FilePath::StringType& path) { FilePath file_path(path); if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path)) NPAPI::PluginList::Singleton()->EnablePlugin(file_path); else NPAPI::PluginList::Singleton()->DisablePlugin(file_path); } static bool enable_internal_pdf_ = true; void DisablePluginGroupsFromPrefs(Profile* profile) { bool update_internal_dir = false; FilePath last_internal_dir = profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory); FilePath cur_internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) && cur_internal_dir != last_internal_dir) { update_internal_dir = true; profile->GetPrefs()->SetFilePath( prefs::kPluginsLastInternalDirectory, cur_internal_dir); } bool found_internal_pdf = false; bool force_enable_internal_pdf = false; FilePath pdf_path; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); FilePath::StringType pdf_path_str = pdf_path.value(); if (enable_internal_pdf_ && !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) { // We switched to the internal pdf plugin being on by default, and so we // need to force it to be enabled. We only want to do it this once though, // i.e. we don't want to enable it again if the user disables it afterwards. profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true); force_enable_internal_pdf = true; } if (ListValue* saved_plugins_list = profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) { for (ListValue::const_iterator it = saved_plugins_list->begin(); it != saved_plugins_list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "Invalid entry in " << prefs::kPluginsPluginsList; continue; // Oops, don't know what to do with this item. } DictionaryValue* plugin = static_cast<DictionaryValue*>(*it); string16 group_name; bool enabled = true; plugin->GetBoolean(L"enabled", &enabled); FilePath::StringType path; // The plugin list constains all the plugin files in addition to the // plugin groups. if (plugin->GetString(L"path", &path)) { // Files have a path attribute, groups don't. FilePath plugin_path(path); if (update_internal_dir && FilePath::CompareIgnoreCase(plugin_path.DirName().value(), last_internal_dir.value()) == 0) { // If the internal plugin directory has changed and if the plugin // looks internal, update its path in the prefs. plugin_path = cur_internal_dir.Append(plugin_path.BaseName()); path = plugin_path.value(); plugin->SetString(L"path", path); } if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) { found_internal_pdf = true; if (!enabled && force_enable_internal_pdf) { enabled = true; plugin->SetBoolean(L"enabled", true); } } if (!enabled) NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path); } else if (!enabled && plugin->GetStringAsUTF16(L"name", &group_name)) { // Otherwise this is a list of groups. EnablePluginGroup(false, group_name); } } } // Build the set of policy-disabled plugins once and cache it. // Don't do this in the constructor, there's no profile available there. std::set<string16> policy_disabled_plugins; const ListValue* plugin_blacklist = profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist); if (plugin_blacklist) { ListValue::const_iterator end(plugin_blacklist->end()); for (ListValue::const_iterator current(plugin_blacklist->begin()); current != end; ++current) { string16 plugin_name; if ((*current)->GetAsUTF16(&plugin_name)) { policy_disabled_plugins.insert(plugin_name); } } } PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins); // Disable all of the plugins and plugin groups that are disabled by policy. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (PluginGroup::IsPluginNameDisabledByPolicy(it->name)) NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); std::vector<linked_ptr<PluginGroup> >::const_iterator it; for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { string16 current_group_name = (*it)->GetGroupName(); if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name)) EnablePluginGroup(false, current_group_name); } if (!enable_internal_pdf_ && !found_internal_pdf) { // The internal PDF plugin is disabled by default, and the user hasn't // overridden the default. NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path); } } void UpdatePreferences(Profile* profile) { ListValue* plugins_list = profile->GetPrefs()->GetMutableList( prefs::kPluginsPluginsList); plugins_list->Clear(); FilePath internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir)) profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory, internal_dir); // Add the plugin files. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { plugins_list->Append(CreatePluginFileSummary(*it)); } // Add the groups as well. std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { // Don't save preferences for vulnerable pugins. if (!(*it)->IsVulnerable()) { plugins_list->Append((*it)->GetSummary()); } } } } // namespace plugin_updater <commit_msg>Disabled internal PDF by default. BUG=None TEST=Verify that the internal PDF plugin is disabled by default.s<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/plugin_updater.h" #include <string> #include <vector> #include "base/path_service.h" #include "base/scoped_ptr.h" #include "base/values.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/plugin_group.h" #include "chrome/common/pref_names.h" #include "webkit/glue/plugins/plugin_list.h" #include "webkit/glue/plugins/webplugininfo.h" namespace plugin_updater { // Convert to a List of Groups static void GetPluginGroups( std::vector<linked_ptr<PluginGroup> >* plugin_groups) { // Read all plugins and convert them to plugin groups std::vector<WebPluginInfo> web_plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &web_plugins); // We first search for an existing group that matches our name, // and only create a new group if we can't find any. for (size_t i = 0; i < web_plugins.size(); ++i) { const WebPluginInfo& web_plugin = web_plugins[i]; PluginGroup* group = PluginGroup::FindGroupMatchingPlugin( *plugin_groups, web_plugin); if (!group) { group = PluginGroup::FindHardcodedPluginGroup(web_plugin); plugin_groups->push_back(linked_ptr<PluginGroup>(group)); } group->AddPlugin(web_plugin, i); } } static DictionaryValue* CreatePluginFileSummary( const WebPluginInfo& plugin) { DictionaryValue* data = new DictionaryValue(); data->SetString(L"path", plugin.path.value()); data->SetStringFromUTF16(L"name", plugin.name); data->SetStringFromUTF16(L"version", plugin.version); data->SetBoolean(L"enabled", plugin.enabled); return data; } ListValue* GetPluginGroupsData() { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); // Construct DictionaryValues to return to the UI ListValue* plugin_groups_data = new ListValue(); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { plugin_groups_data->Append((*it)->GetDataForUI()); } return plugin_groups_data; } void EnablePluginGroup(bool enable, const string16& group_name) { std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { if ((*it)->GetGroupName() == group_name) { (*it)->Enable(enable); } } } void EnablePluginFile(bool enable, const FilePath::StringType& path) { FilePath file_path(path); if (enable && !PluginGroup::IsPluginPathDisabledByPolicy(file_path)) NPAPI::PluginList::Singleton()->EnablePlugin(file_path); else NPAPI::PluginList::Singleton()->DisablePlugin(file_path); } static bool enable_internal_pdf_ = false; void DisablePluginGroupsFromPrefs(Profile* profile) { bool update_internal_dir = false; FilePath last_internal_dir = profile->GetPrefs()->GetFilePath(prefs::kPluginsLastInternalDirectory); FilePath cur_internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &cur_internal_dir) && cur_internal_dir != last_internal_dir) { update_internal_dir = true; profile->GetPrefs()->SetFilePath( prefs::kPluginsLastInternalDirectory, cur_internal_dir); } bool found_internal_pdf = false; bool force_enable_internal_pdf = false; FilePath pdf_path; PathService::Get(chrome::FILE_PDF_PLUGIN, &pdf_path); FilePath::StringType pdf_path_str = pdf_path.value(); if (enable_internal_pdf_ && !profile->GetPrefs()->GetBoolean(prefs::kPluginsEnabledInternalPDF)) { // We switched to the internal pdf plugin being on by default, and so we // need to force it to be enabled. We only want to do it this once though, // i.e. we don't want to enable it again if the user disables it afterwards. profile->GetPrefs()->SetBoolean(prefs::kPluginsEnabledInternalPDF, true); force_enable_internal_pdf = true; } if (ListValue* saved_plugins_list = profile->GetPrefs()->GetMutableList(prefs::kPluginsPluginsList)) { for (ListValue::const_iterator it = saved_plugins_list->begin(); it != saved_plugins_list->end(); ++it) { if (!(*it)->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "Invalid entry in " << prefs::kPluginsPluginsList; continue; // Oops, don't know what to do with this item. } DictionaryValue* plugin = static_cast<DictionaryValue*>(*it); string16 group_name; bool enabled = true; plugin->GetBoolean(L"enabled", &enabled); FilePath::StringType path; // The plugin list constains all the plugin files in addition to the // plugin groups. if (plugin->GetString(L"path", &path)) { // Files have a path attribute, groups don't. FilePath plugin_path(path); if (update_internal_dir && FilePath::CompareIgnoreCase(plugin_path.DirName().value(), last_internal_dir.value()) == 0) { // If the internal plugin directory has changed and if the plugin // looks internal, update its path in the prefs. plugin_path = cur_internal_dir.Append(plugin_path.BaseName()); path = plugin_path.value(); plugin->SetString(L"path", path); } if (FilePath::CompareIgnoreCase(path, pdf_path_str) == 0) { found_internal_pdf = true; if (!enabled && force_enable_internal_pdf) { enabled = true; plugin->SetBoolean(L"enabled", true); } } if (!enabled) NPAPI::PluginList::Singleton()->DisablePlugin(plugin_path); } else if (!enabled && plugin->GetStringAsUTF16(L"name", &group_name)) { // Otherwise this is a list of groups. EnablePluginGroup(false, group_name); } } } // Build the set of policy-disabled plugins once and cache it. // Don't do this in the constructor, there's no profile available there. std::set<string16> policy_disabled_plugins; const ListValue* plugin_blacklist = profile->GetPrefs()->GetList(prefs::kPluginsPluginsBlacklist); if (plugin_blacklist) { ListValue::const_iterator end(plugin_blacklist->end()); for (ListValue::const_iterator current(plugin_blacklist->begin()); current != end; ++current) { string16 plugin_name; if ((*current)->GetAsUTF16(&plugin_name)) { policy_disabled_plugins.insert(plugin_name); } } } PluginGroup::SetPolicyDisabledPluginSet(policy_disabled_plugins); // Disable all of the plugins and plugin groups that are disabled by policy. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { if (PluginGroup::IsPluginNameDisabledByPolicy(it->name)) NPAPI::PluginList::Singleton()->DisablePlugin(it->path); } std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); std::vector<linked_ptr<PluginGroup> >::const_iterator it; for (it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { string16 current_group_name = (*it)->GetGroupName(); if (PluginGroup::IsPluginNameDisabledByPolicy(current_group_name)) EnablePluginGroup(false, current_group_name); } if (!enable_internal_pdf_ && !found_internal_pdf) { // The internal PDF plugin is disabled by default, and the user hasn't // overridden the default. NPAPI::PluginList::Singleton()->DisablePlugin(pdf_path); } } void UpdatePreferences(Profile* profile) { ListValue* plugins_list = profile->GetPrefs()->GetMutableList( prefs::kPluginsPluginsList); plugins_list->Clear(); FilePath internal_dir; if (PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir)) profile->GetPrefs()->SetFilePath(prefs::kPluginsLastInternalDirectory, internal_dir); // Add the plugin files. std::vector<WebPluginInfo> plugins; NPAPI::PluginList::Singleton()->GetPlugins(false, &plugins); for (std::vector<WebPluginInfo>::const_iterator it = plugins.begin(); it != plugins.end(); ++it) { plugins_list->Append(CreatePluginFileSummary(*it)); } // Add the groups as well. std::vector<linked_ptr<PluginGroup> > plugin_groups; GetPluginGroups(&plugin_groups); for (std::vector<linked_ptr<PluginGroup> >::iterator it = plugin_groups.begin(); it != plugin_groups.end(); ++it) { // Don't save preferences for vulnerable pugins. if (!(*it)->IsVulnerable()) { plugins_list->Append((*it)->GetSummary()); } } } } // namespace plugin_updater <|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 "chrome/browser/ssl/ssl_policy.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/singleton.h" #include "base/string_piece.h" #include "base/string_util.h" #include "chrome/browser/cert_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/ssl/ssl_cert_error_handler.h" #include "chrome/browser/ssl/ssl_error_info.h" #include "chrome/browser/ssl/ssl_mixed_content_handler.h" #include "chrome/browser/ssl/ssl_request_info.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/time_format.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "net/base/cert_status_flags.h" #include "net/base/ssl_info.h" #include "webkit/glue/resource_type.h" using WebKit::WebConsoleMessage; class SSLPolicy::ShowMixedContentTask : public Task { public: ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler); virtual ~ShowMixedContentTask(); virtual void Run(); private: SSLPolicy* policy_; scoped_refptr<SSLMixedContentHandler> handler_; DISALLOW_COPY_AND_ASSIGN(ShowMixedContentTask); }; SSLPolicy::ShowMixedContentTask::ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler) : policy_(policy), handler_(handler) { } SSLPolicy::ShowMixedContentTask::~ShowMixedContentTask() { } void SSLPolicy::ShowMixedContentTask::Run() { policy_->AllowMixedContentForOrigin(handler_->frame_origin()); policy_->AllowMixedContentForOrigin(handler_->main_frame_origin()); policy_->backend()->Reload(); } SSLPolicy::SSLPolicy(SSLPolicyBackend* backend) : backend_(backend) { DCHECK(backend_); } void SSLPolicy::OnCertError(SSLCertErrorHandler* handler) { // First we check if we know the policy for this error. net::X509Certificate::Policy::Judgment judgment = backend_->QueryPolicy(handler->ssl_info().cert, handler->request_url().host()); if (judgment == net::X509Certificate::Policy::ALLOWED) { handler->ContinueRequest(); return; } // The judgment is either DENIED or UNKNOWN. // For now we handle the DENIED as the UNKNOWN, which means a blocking // page is shown to the user every time he comes back to the page. switch(handler->cert_error()) { case net::ERR_CERT_COMMON_NAME_INVALID: case net::ERR_CERT_DATE_INVALID: case net::ERR_CERT_AUTHORITY_INVALID: OnOverridableCertError(handler); break; case net::ERR_CERT_NO_REVOCATION_MECHANISM: // Ignore this error. handler->ContinueRequest(); break; case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION: // We ignore this error and display an infobar. handler->ContinueRequest(); backend_->ShowMessage(l10n_util::GetString( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_INFO_BAR)); break; case net::ERR_CERT_CONTAINS_ERRORS: case net::ERR_CERT_REVOKED: case net::ERR_CERT_INVALID: OnFatalCertError(handler); break; default: NOTREACHED(); handler->CancelRequest(); break; } } void SSLPolicy::OnMixedContent(SSLMixedContentHandler* handler) { // Get the user's mixed content preference. PrefService* prefs = handler->GetTabContents()->profile()->GetPrefs(); FilterPolicy::Type filter_policy = FilterPolicy::FromInt(prefs->GetInteger(prefs::kMixedContentFiltering)); // If the user has added an exception, doctor the |filter_policy|. std::string host = GURL(handler->main_frame_origin()).host(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceHTTPS) && backend_->IsForceTLSEnabledForHost(host)) { // We're supposed to block all mixed content for this host. filter_policy = FilterPolicy::FILTER_ALL; } else if (backend_->DidAllowMixedContentForHost(host) || backend_->DidMarkHostAsBroken(host, handler->pid())) { // Let the mixed content through. filter_policy = FilterPolicy::DONT_FILTER; } else if (filter_policy != FilterPolicy::DONT_FILTER) { backend_->ShowMessageWithLink( l10n_util::GetString(IDS_SSL_INFO_BAR_FILTERED_CONTENT), l10n_util::GetString(IDS_SSL_INFO_BAR_SHOW_CONTENT), new ShowMixedContentTask(this, handler)); } handler->StartRequest(filter_policy); AddMixedContentWarningToConsole(handler); } void SSLPolicy::OnRequestStarted(SSLRequestInfo* info) { if (net::IsCertStatusError(info->ssl_cert_status())) UpdateStateForUnsafeContent(info); if (IsMixedContent(info->url(), info->resource_type(), info->filter_policy(), info->frame_origin())) UpdateStateForMixedContent(info); } void SSLPolicy::UpdateEntry(NavigationEntry* entry) { DCHECK(entry); InitializeEntryIfNeeded(entry); if (!entry->url().SchemeIsSecure()) return; // An HTTPS response may not have a certificate for some reason. When that // happens, use the unauthenticated (HTTP) rather than the authentication // broken security style so that we can detect this error condition. if (!entry->ssl().cert_id()) { entry->ssl().set_security_style(SECURITY_STYLE_UNAUTHENTICATED); return; } if (net::IsCertStatusError(entry->ssl().cert_status())) { entry->ssl().set_security_style(SECURITY_STYLE_AUTHENTICATION_BROKEN); return; } if (backend_->DidMarkHostAsBroken(entry->url().host(), entry->site_instance()->GetProcess()->pid())) entry->ssl().set_has_mixed_content(); } // static bool SSLPolicy::IsMixedContent(const GURL& url, ResourceType::Type resource_type, FilterPolicy::Type filter_policy, const std::string& frame_origin) { //////////////////////////////////////////////////////////////////////////// // WARNING: This function is called from both the IO and UI threads. Do // // not touch any non-thread-safe objects! You have been warned. // //////////////////////////////////////////////////////////////////////////// // We can't possibly have mixed content when loading the main frame. if (resource_type == ResourceType::MAIN_FRAME) return false; // If we've filtered the resource, then it's no longer dangerous. if (filter_policy != FilterPolicy::DONT_FILTER) return false; // If the frame doing the loading is already insecure, then we must have // already dealt with whatever mixed content might be going on. if (!GURL(frame_origin).SchemeIsSecure()) return false; // We aren't worried about mixed content if we're loading an HTTPS URL. if (url.SchemeIsSecure()) return false; return true; } //////////////////////////////////////////////////////////////////////////////// // SSLBlockingPage::Delegate methods SSLErrorInfo SSLPolicy::GetSSLErrorInfo(SSLCertErrorHandler* handler) { return SSLErrorInfo::CreateError( SSLErrorInfo::NetErrorToErrorType(handler->cert_error()), handler->ssl_info().cert, handler->request_url()); } void SSLPolicy::OnDenyCertificate(SSLCertErrorHandler* handler) { // Default behavior for rejecting a certificate. // // While DenyCertForHost() executes synchronously on this thread, // CancelRequest() gets posted to a different thread. Calling // DenyCertForHost() first ensures deterministic ordering. backend_->DenyCertForHost(handler->ssl_info().cert, handler->request_url().host()); handler->CancelRequest(); } void SSLPolicy::OnAllowCertificate(SSLCertErrorHandler* handler) { // Default behavior for accepting a certificate. // Note that we should not call SetMaxSecurityStyle here, because the active // NavigationEntry has just been deleted (in HideInterstitialPage) and the // new NavigationEntry will not be set until DidNavigate. This is ok, // because the new NavigationEntry will have its max security style set // within DidNavigate. // // While AllowCertForHost() executes synchronously on this thread, // ContinueRequest() gets posted to a different thread. Calling // AllowCertForHost() first ensures deterministic ordering. backend_->AllowCertForHost(handler->ssl_info().cert, handler->request_url().host()); handler->ContinueRequest(); } //////////////////////////////////////////////////////////////////////////////// // Certificate Error Routines void SSLPolicy::OnOverridableCertError(SSLCertErrorHandler* handler) { if (handler->resource_type() != ResourceType::MAIN_FRAME) { // A sub-resource has a certificate error. The user doesn't really // have a context for making the right decision, so block the // request hard, without an info bar to allow showing the insecure // content. handler->DenyRequest(); return; } // We need to ask the user to approve this certificate. SSLBlockingPage* blocking_page = new SSLBlockingPage(handler, this); blocking_page->Show(); } void SSLPolicy::OnFatalCertError(SSLCertErrorHandler* handler) { if (handler->resource_type() != ResourceType::MAIN_FRAME) { handler->DenyRequest(); return; } handler->CancelRequest(); ShowErrorPage(handler); // No need to degrade our security indicators because we didn't continue. } void SSLPolicy::ShowErrorPage(SSLCertErrorHandler* handler) { SSLErrorInfo error_info = GetSSLErrorInfo(handler); // Let's build the html error page. DictionaryValue strings; strings.SetString(L"title", l10n_util::GetString(IDS_SSL_ERROR_PAGE_TITLE)); strings.SetString(L"headLine", error_info.title()); strings.SetString(L"description", error_info.details()); strings.SetString(L"moreInfoTitle", l10n_util::GetString(IDS_CERT_ERROR_EXTRA_INFO_TITLE)); SSLBlockingPage::SetExtraInfo(&strings, error_info.extra_information()); strings.SetString(L"back", l10n_util::GetString(IDS_SSL_ERROR_PAGE_BACK)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); static const StringPiece html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_SSL_ERROR_HTML)); std::string html_text(jstemplate_builder::GetTemplateHtml(html, &strings, "template_root")); TabContents* tab = handler->GetTabContents(); int cert_id = CertStore::GetSharedInstance()->StoreCert( handler->ssl_info().cert, tab->render_view_host()->process()->pid()); std::string security_info = SSLManager::SerializeSecurityInfo(cert_id, handler->ssl_info().cert_status, handler->ssl_info().security_bits); tab->render_view_host()->LoadAlternateHTMLString(html_text, true, handler->request_url(), security_info); tab->controller().GetActiveEntry()->set_page_type( NavigationEntry::ERROR_PAGE); } void SSLPolicy::AddMixedContentWarningToConsole( SSLMixedContentHandler* handler) { const std::wstring& text = l10n_util::GetStringF( IDS_MIXED_CONTENT_LOG_MESSAGE, UTF8ToWide(handler->frame_origin()), UTF8ToWide(handler->request_url().spec())); backend_->AddMessageToConsole( WideToUTF16Hack(text), WebConsoleMessage::LevelWarning); } void SSLPolicy::InitializeEntryIfNeeded(NavigationEntry* entry) { if (entry->ssl().security_style() != SECURITY_STYLE_UNKNOWN) return; entry->ssl().set_security_style(entry->url().SchemeIsSecure() ? SECURITY_STYLE_AUTHENTICATED : SECURITY_STYLE_UNAUTHENTICATED); } void SSLPolicy::MarkOriginAsBroken(const std::string& origin, int pid) { GURL parsed_origin(origin); if (!parsed_origin.SchemeIsSecure()) return; backend_->MarkHostAsBroken(parsed_origin.host(), pid); } void SSLPolicy::AllowMixedContentForOrigin(const std::string& origin) { GURL parsed_origin(origin); if (!parsed_origin.SchemeIsSecure()) return; backend_->AllowMixedContentForHost(parsed_origin.host()); } void SSLPolicy::UpdateStateForMixedContent(SSLRequestInfo* info) { if (info->resource_type() != ResourceType::MAIN_FRAME || info->resource_type() != ResourceType::SUB_FRAME) { // The frame's origin now contains mixed content and therefore is broken. MarkOriginAsBroken(info->frame_origin(), info->pid()); } if (info->resource_type() != ResourceType::MAIN_FRAME) { // The main frame now contains a frame with mixed content. Therefore, we // mark the main frame's origin as broken too. MarkOriginAsBroken(info->main_frame_origin(), info->pid()); } } void SSLPolicy::UpdateStateForUnsafeContent(SSLRequestInfo* info) { // This request as a broken cert, which means its host is broken. backend_->MarkHostAsBroken(info->url().host(), info->pid()); UpdateStateForMixedContent(info); } <commit_msg>Fix crash when updating a navigation entry without a site_instance.<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 "chrome/browser/ssl/ssl_policy.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/singleton.h" #include "base/string_piece.h" #include "base/string_util.h" #include "chrome/browser/cert_store.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/ssl/ssl_cert_error_handler.h" #include "chrome/browser/ssl/ssl_error_info.h" #include "chrome/browser/ssl/ssl_mixed_content_handler.h" #include "chrome/browser/ssl/ssl_request_info.h" #include "chrome/browser/tab_contents/navigation_entry.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/jstemplate_builder.h" #include "chrome/common/notification_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/time_format.h" #include "chrome/common/url_constants.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" #include "net/base/cert_status_flags.h" #include "net/base/ssl_info.h" #include "webkit/glue/resource_type.h" using WebKit::WebConsoleMessage; class SSLPolicy::ShowMixedContentTask : public Task { public: ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler); virtual ~ShowMixedContentTask(); virtual void Run(); private: SSLPolicy* policy_; scoped_refptr<SSLMixedContentHandler> handler_; DISALLOW_COPY_AND_ASSIGN(ShowMixedContentTask); }; SSLPolicy::ShowMixedContentTask::ShowMixedContentTask(SSLPolicy* policy, SSLMixedContentHandler* handler) : policy_(policy), handler_(handler) { } SSLPolicy::ShowMixedContentTask::~ShowMixedContentTask() { } void SSLPolicy::ShowMixedContentTask::Run() { policy_->AllowMixedContentForOrigin(handler_->frame_origin()); policy_->AllowMixedContentForOrigin(handler_->main_frame_origin()); policy_->backend()->Reload(); } SSLPolicy::SSLPolicy(SSLPolicyBackend* backend) : backend_(backend) { DCHECK(backend_); } void SSLPolicy::OnCertError(SSLCertErrorHandler* handler) { // First we check if we know the policy for this error. net::X509Certificate::Policy::Judgment judgment = backend_->QueryPolicy(handler->ssl_info().cert, handler->request_url().host()); if (judgment == net::X509Certificate::Policy::ALLOWED) { handler->ContinueRequest(); return; } // The judgment is either DENIED or UNKNOWN. // For now we handle the DENIED as the UNKNOWN, which means a blocking // page is shown to the user every time he comes back to the page. switch(handler->cert_error()) { case net::ERR_CERT_COMMON_NAME_INVALID: case net::ERR_CERT_DATE_INVALID: case net::ERR_CERT_AUTHORITY_INVALID: OnOverridableCertError(handler); break; case net::ERR_CERT_NO_REVOCATION_MECHANISM: // Ignore this error. handler->ContinueRequest(); break; case net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION: // We ignore this error and display an infobar. handler->ContinueRequest(); backend_->ShowMessage(l10n_util::GetString( IDS_CERT_ERROR_UNABLE_TO_CHECK_REVOCATION_INFO_BAR)); break; case net::ERR_CERT_CONTAINS_ERRORS: case net::ERR_CERT_REVOKED: case net::ERR_CERT_INVALID: OnFatalCertError(handler); break; default: NOTREACHED(); handler->CancelRequest(); break; } } void SSLPolicy::OnMixedContent(SSLMixedContentHandler* handler) { // Get the user's mixed content preference. PrefService* prefs = handler->GetTabContents()->profile()->GetPrefs(); FilterPolicy::Type filter_policy = FilterPolicy::FromInt(prefs->GetInteger(prefs::kMixedContentFiltering)); // If the user has added an exception, doctor the |filter_policy|. std::string host = GURL(handler->main_frame_origin()).host(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kForceHTTPS) && backend_->IsForceTLSEnabledForHost(host)) { // We're supposed to block all mixed content for this host. filter_policy = FilterPolicy::FILTER_ALL; } else if (backend_->DidAllowMixedContentForHost(host) || backend_->DidMarkHostAsBroken(host, handler->pid())) { // Let the mixed content through. filter_policy = FilterPolicy::DONT_FILTER; } else if (filter_policy != FilterPolicy::DONT_FILTER) { backend_->ShowMessageWithLink( l10n_util::GetString(IDS_SSL_INFO_BAR_FILTERED_CONTENT), l10n_util::GetString(IDS_SSL_INFO_BAR_SHOW_CONTENT), new ShowMixedContentTask(this, handler)); } handler->StartRequest(filter_policy); AddMixedContentWarningToConsole(handler); } void SSLPolicy::OnRequestStarted(SSLRequestInfo* info) { if (net::IsCertStatusError(info->ssl_cert_status())) UpdateStateForUnsafeContent(info); if (IsMixedContent(info->url(), info->resource_type(), info->filter_policy(), info->frame_origin())) UpdateStateForMixedContent(info); } void SSLPolicy::UpdateEntry(NavigationEntry* entry) { DCHECK(entry); InitializeEntryIfNeeded(entry); if (!entry->url().SchemeIsSecure()) return; // An HTTPS response may not have a certificate for some reason. When that // happens, use the unauthenticated (HTTP) rather than the authentication // broken security style so that we can detect this error condition. if (!entry->ssl().cert_id()) { entry->ssl().set_security_style(SECURITY_STYLE_UNAUTHENTICATED); return; } if (net::IsCertStatusError(entry->ssl().cert_status())) { entry->ssl().set_security_style(SECURITY_STYLE_AUTHENTICATION_BROKEN); return; } SiteInstance* site_instance = entry->site_instance(); // Note that |site_instance| can be NULL here because NavigationEntries don't // necessarily have site instances. Without a process, the entry can't // possibly have mixed content. See bug http://crbug.com/12423. if (site_instance && backend_->DidMarkHostAsBroken(entry->url().host(), site_instance->GetProcess()->pid())) entry->ssl().set_has_mixed_content(); } // static bool SSLPolicy::IsMixedContent(const GURL& url, ResourceType::Type resource_type, FilterPolicy::Type filter_policy, const std::string& frame_origin) { //////////////////////////////////////////////////////////////////////////// // WARNING: This function is called from both the IO and UI threads. Do // // not touch any non-thread-safe objects! You have been warned. // //////////////////////////////////////////////////////////////////////////// // We can't possibly have mixed content when loading the main frame. if (resource_type == ResourceType::MAIN_FRAME) return false; // If we've filtered the resource, then it's no longer dangerous. if (filter_policy != FilterPolicy::DONT_FILTER) return false; // If the frame doing the loading is already insecure, then we must have // already dealt with whatever mixed content might be going on. if (!GURL(frame_origin).SchemeIsSecure()) return false; // We aren't worried about mixed content if we're loading an HTTPS URL. if (url.SchemeIsSecure()) return false; return true; } //////////////////////////////////////////////////////////////////////////////// // SSLBlockingPage::Delegate methods SSLErrorInfo SSLPolicy::GetSSLErrorInfo(SSLCertErrorHandler* handler) { return SSLErrorInfo::CreateError( SSLErrorInfo::NetErrorToErrorType(handler->cert_error()), handler->ssl_info().cert, handler->request_url()); } void SSLPolicy::OnDenyCertificate(SSLCertErrorHandler* handler) { // Default behavior for rejecting a certificate. // // While DenyCertForHost() executes synchronously on this thread, // CancelRequest() gets posted to a different thread. Calling // DenyCertForHost() first ensures deterministic ordering. backend_->DenyCertForHost(handler->ssl_info().cert, handler->request_url().host()); handler->CancelRequest(); } void SSLPolicy::OnAllowCertificate(SSLCertErrorHandler* handler) { // Default behavior for accepting a certificate. // Note that we should not call SetMaxSecurityStyle here, because the active // NavigationEntry has just been deleted (in HideInterstitialPage) and the // new NavigationEntry will not be set until DidNavigate. This is ok, // because the new NavigationEntry will have its max security style set // within DidNavigate. // // While AllowCertForHost() executes synchronously on this thread, // ContinueRequest() gets posted to a different thread. Calling // AllowCertForHost() first ensures deterministic ordering. backend_->AllowCertForHost(handler->ssl_info().cert, handler->request_url().host()); handler->ContinueRequest(); } //////////////////////////////////////////////////////////////////////////////// // Certificate Error Routines void SSLPolicy::OnOverridableCertError(SSLCertErrorHandler* handler) { if (handler->resource_type() != ResourceType::MAIN_FRAME) { // A sub-resource has a certificate error. The user doesn't really // have a context for making the right decision, so block the // request hard, without an info bar to allow showing the insecure // content. handler->DenyRequest(); return; } // We need to ask the user to approve this certificate. SSLBlockingPage* blocking_page = new SSLBlockingPage(handler, this); blocking_page->Show(); } void SSLPolicy::OnFatalCertError(SSLCertErrorHandler* handler) { if (handler->resource_type() != ResourceType::MAIN_FRAME) { handler->DenyRequest(); return; } handler->CancelRequest(); ShowErrorPage(handler); // No need to degrade our security indicators because we didn't continue. } void SSLPolicy::ShowErrorPage(SSLCertErrorHandler* handler) { SSLErrorInfo error_info = GetSSLErrorInfo(handler); // Let's build the html error page. DictionaryValue strings; strings.SetString(L"title", l10n_util::GetString(IDS_SSL_ERROR_PAGE_TITLE)); strings.SetString(L"headLine", error_info.title()); strings.SetString(L"description", error_info.details()); strings.SetString(L"moreInfoTitle", l10n_util::GetString(IDS_CERT_ERROR_EXTRA_INFO_TITLE)); SSLBlockingPage::SetExtraInfo(&strings, error_info.extra_information()); strings.SetString(L"back", l10n_util::GetString(IDS_SSL_ERROR_PAGE_BACK)); strings.SetString(L"textdirection", (l10n_util::GetTextDirection() == l10n_util::RIGHT_TO_LEFT) ? L"rtl" : L"ltr"); static const StringPiece html( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_SSL_ERROR_HTML)); std::string html_text(jstemplate_builder::GetTemplateHtml(html, &strings, "template_root")); TabContents* tab = handler->GetTabContents(); int cert_id = CertStore::GetSharedInstance()->StoreCert( handler->ssl_info().cert, tab->render_view_host()->process()->pid()); std::string security_info = SSLManager::SerializeSecurityInfo(cert_id, handler->ssl_info().cert_status, handler->ssl_info().security_bits); tab->render_view_host()->LoadAlternateHTMLString(html_text, true, handler->request_url(), security_info); tab->controller().GetActiveEntry()->set_page_type( NavigationEntry::ERROR_PAGE); } void SSLPolicy::AddMixedContentWarningToConsole( SSLMixedContentHandler* handler) { const std::wstring& text = l10n_util::GetStringF( IDS_MIXED_CONTENT_LOG_MESSAGE, UTF8ToWide(handler->frame_origin()), UTF8ToWide(handler->request_url().spec())); backend_->AddMessageToConsole( WideToUTF16Hack(text), WebConsoleMessage::LevelWarning); } void SSLPolicy::InitializeEntryIfNeeded(NavigationEntry* entry) { if (entry->ssl().security_style() != SECURITY_STYLE_UNKNOWN) return; entry->ssl().set_security_style(entry->url().SchemeIsSecure() ? SECURITY_STYLE_AUTHENTICATED : SECURITY_STYLE_UNAUTHENTICATED); } void SSLPolicy::MarkOriginAsBroken(const std::string& origin, int pid) { GURL parsed_origin(origin); if (!parsed_origin.SchemeIsSecure()) return; backend_->MarkHostAsBroken(parsed_origin.host(), pid); } void SSLPolicy::AllowMixedContentForOrigin(const std::string& origin) { GURL parsed_origin(origin); if (!parsed_origin.SchemeIsSecure()) return; backend_->AllowMixedContentForHost(parsed_origin.host()); } void SSLPolicy::UpdateStateForMixedContent(SSLRequestInfo* info) { if (info->resource_type() != ResourceType::MAIN_FRAME || info->resource_type() != ResourceType::SUB_FRAME) { // The frame's origin now contains mixed content and therefore is broken. MarkOriginAsBroken(info->frame_origin(), info->pid()); } if (info->resource_type() != ResourceType::MAIN_FRAME) { // The main frame now contains a frame with mixed content. Therefore, we // mark the main frame's origin as broken too. MarkOriginAsBroken(info->main_frame_origin(), info->pid()); } } void SSLPolicy::UpdateStateForUnsafeContent(SSLRequestInfo* info) { // This request as a broken cert, which means its host is broken. backend_->MarkHostAsBroken(info->url().host(), info->pid()); UpdateStateForMixedContent(info); } <|endoftext|>
<commit_before>#ifndef PROTOCOL_MESSAGES_HPP_ #define PROTOCOL_MESSAGES_HPP_ #include <cstdint> namespace protocol { namespace message { struct heartbeat_message_t { enum { ID = 0x00 }; std::uint8_t seq; } __attribute__((packed)); struct log_message_t { enum { ID = 0x01 }; char data[100]; } __attribute__((packed)); struct attitude_message_t { enum { ID = 0x02 }; float dcm[9]; } __attribute__((packed)); struct set_arm_state_message_t { enum { ID = 0x03 }; bool armed; } __attribute__((packed)); struct set_control_mode_message_t { enum { ID = 0x04 }; enum class ControlMode { MANUAL, OFFBOARD }; ControlMode mode; } __attribute__((packed)); struct offboard_attitude_control_message_t { enum { ID = 0x05 }; float roll; float pitch; float yaw; float throttle; uint16_t buttons; // Bitfield of buttons uint8_t mode; } __attribute__((packed)); struct motor_throttle_message_t { enum { ID = 0x06 }; float throttles[4]; } __attribute__((packed)); struct sensor_calibration_request_message_t { enum { ID = 0x07 }; } __attribute__((packed)); struct sensor_calibration_response_message_t { enum { ID = 0x08 }; enum class SensorType { ACCEL, GYRO, MAG }; SensorType type; float offsets[3]; } __attribute__((packed)); struct location_message_t { enum { ID = 0x09 }; float lat; float lon; float alt; } __attribute__((packed)); inline std::uint16_t length(int id) { // TODO(kyle): sizeof(empty struct) is 1 in C++... switch(id) { case heartbeat_message_t::ID: return sizeof(heartbeat_message_t); case log_message_t::ID: return sizeof(log_message_t); case attitude_message_t::ID: return sizeof(attitude_message_t); case set_arm_state_message_t::ID: return sizeof(set_arm_state_message_t); case set_control_mode_message_t::ID: return sizeof(set_control_mode_message_t); case offboard_attitude_control_message_t::ID: return sizeof(offboard_attitude_control_message_t); case motor_throttle_message_t::ID: return sizeof(motor_throttle_message_t); case sensor_calibration_request_message_t::ID: return sizeof(sensor_calibration_request_message_t); case sensor_calibration_response_message_t::ID: return sizeof(sensor_calibration_response_message_t); case location_message_t::ID: return sizeof(location_message_t); } return 0; // TODO(kyle): Return something more meaningful? } } } #endif // MESSAGES_HPP_ <commit_msg>Add message types.<commit_after>#ifndef PROTOCOL_MESSAGES_HPP_ #define PROTOCOL_MESSAGES_HPP_ #include <cstdint> namespace protocol { namespace message { struct heartbeat_message_t { enum { ID = 0x00 }; std::uint8_t seq; } __attribute__((packed)); struct log_message_t { enum { ID = 0x01 }; char data[100]; } __attribute__((packed)); struct attitude_message_t { enum { ID = 0x02 }; float dcm[9]; } __attribute__((packed)); struct set_arm_state_message_t { enum { ID = 0x03 }; bool armed; } __attribute__((packed)); struct set_control_mode_message_t { enum { ID = 0x04 }; enum class ControlMode { MANUAL, OFFBOARD }; ControlMode mode; } __attribute__((packed)); struct offboard_attitude_control_message_t { enum { ID = 0x05 }; float roll; float pitch; float yaw; float throttle; uint16_t buttons; // Bitfield of buttons uint8_t mode; } __attribute__((packed)); struct motor_throttle_message_t { enum { ID = 0x06 }; float throttles[4]; } __attribute__((packed)); struct sensor_calibration_request_message_t { enum { ID = 0x07 }; } __attribute__((packed)); struct sensor_calibration_response_message_t { enum { ID = 0x08 }; enum class SensorType { ACCEL, GYRO, MAG }; SensorType type; float offsets[3]; } __attribute__((packed)); struct location_message_t { enum { ID = 0x09 }; float lat; float lon; float alt; } __attribute__((packed)); struct imu_message_t { enum { ID = 0x0a }; float gyro[3]; float accel[3]; } __attribute__((packed)); struct system_message_t { enum { ID = 0x0b }; uint8_t state; float motorDC; // TODO(yoos): Hack for esra test launch } __attribute__((packed)); inline std::uint16_t length(int id) { // TODO(kyle): sizeof(empty struct) is 1 in C++... switch(id) { case heartbeat_message_t::ID: return sizeof(heartbeat_message_t); case log_message_t::ID: return sizeof(log_message_t); case attitude_message_t::ID: return sizeof(attitude_message_t); case set_arm_state_message_t::ID: return sizeof(set_arm_state_message_t); case set_control_mode_message_t::ID: return sizeof(set_control_mode_message_t); case offboard_attitude_control_message_t::ID: return sizeof(offboard_attitude_control_message_t); case motor_throttle_message_t::ID: return sizeof(motor_throttle_message_t); case sensor_calibration_request_message_t::ID: return sizeof(sensor_calibration_request_message_t); case sensor_calibration_response_message_t::ID: return sizeof(sensor_calibration_response_message_t); case location_message_t::ID: return sizeof(location_message_t); case imu_message_t::ID: return sizeof(imu_message_t); case system_message_t::ID: return sizeof(system_message_t); } return 0; // TODO(kyle): Return something more meaningful? } } } #endif // MESSAGES_HPP_ <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <vector> #include "base/command_line.h" #include "base/memory/ref_counted.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "content/common/clipboard_messages.h" #include "content/common/socket_stream_dispatcher.h" #include "content/common/view_messages.h" #include "content/plugin/npobject_util.h" #include "content/renderer/render_thread.h" #include "googleurl/src/url_util.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKitClient.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/websocketstreamhandle_bridge.h" #if !defined(DISABLE_NACL) #include "native_client/src/shared/imc/nacl_imc.h" #include "native_client/src/trusted/plugin/nacl_entry_points.h" #endif #if defined(OS_LINUX) #include "content/renderer/renderer_sandbox_support_linux.h" #endif // This definition of WriteBitmapFromPixels uses shared memory to communicate // across processes. void ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels, const gfx::Size& size) { // Do not try to write a bitmap more than once if (shared_buf_) return; uint32 buf_size = 4 * size.width() * size.height(); // Allocate a shared memory buffer to hold the bitmap bits. #if defined(OS_POSIX) // On POSIX, we need to ask the browser to create the shared memory for us, // since this is blocked by the sandbox. base::SharedMemoryHandle shared_mem_handle; ViewHostMsg_AllocateSharedMemoryBuffer *msg = new ViewHostMsg_AllocateSharedMemoryBuffer(buf_size, &shared_mem_handle); if (RenderThread::current()->Send(msg)) { if (base::SharedMemory::IsHandleValid(shared_mem_handle)) { shared_buf_ = new base::SharedMemory(shared_mem_handle, false); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED() << "Map failed"; return; } } else { NOTREACHED() << "Browser failed to allocate shared memory"; return; } } else { NOTREACHED() << "Browser allocation request message failed"; return; } #else // !OS_POSIX shared_buf_ = new base::SharedMemory; if (!shared_buf_->CreateAndMapAnonymous(buf_size)) { NOTREACHED(); return; } #endif // Copy the bits into shared memory memcpy(shared_buf_->memory(), pixels, buf_size); shared_buf_->Unmap(); ui::Clipboard::ObjectMapParam size_param; const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof(gfx::Size); ++i) size_param.push_back(size_data[i]); ui::Clipboard::ObjectMapParams params; // The first parameter is replaced on the receiving end with a pointer to // a shared memory object containing the bitmap. We reserve space for it here. ui::Clipboard::ObjectMapParam place_holder_param; params.push_back(place_holder_param); params.push_back(size_param); objects_[ui::Clipboard::CBF_SMBITMAP] = params; } // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; if (shared_buf_) { RenderThread::current()->Send( new ClipboardHostMsg_WriteObjectsSync(objects_, shared_buf_->handle())); delete shared_buf_; return; } RenderThread::current()->Send( new ClipboardHostMsg_WriteObjectsAsync(objects_)); } namespace webkit_glue { void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } base::StringPiece GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue ui::Clipboard* ClipboardGetClipboard() { return NULL; } bool ClipboardIsFormatAvailable(const ui::Clipboard::FormatType& format, ui::Clipboard::Buffer buffer) { bool result; RenderThread::current()->Send( new ClipboardHostMsg_IsFormatAvailable(format, buffer, &result)); return result; } void ClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, std::vector<string16>* types, bool* contains_filenames) { RenderThread::current()->Send(new ClipboardHostMsg_ReadAvailableTypes( buffer, types, contains_filenames)); } void ClipboardReadText(ui::Clipboard::Buffer buffer, string16* result) { RenderThread::current()->Send(new ClipboardHostMsg_ReadText(buffer, result)); } void ClipboardReadAsciiText(ui::Clipboard::Buffer buffer, std::string* result) { RenderThread::current()->Send( new ClipboardHostMsg_ReadAsciiText(buffer, result)); } void ClipboardReadHTML(ui::Clipboard::Buffer buffer, string16* markup, GURL* url) { RenderThread::current()->Send( new ClipboardHostMsg_ReadHTML(buffer, markup, url)); } void ClipboardReadImage(ui::Clipboard::Buffer buffer, std::string* data) { RenderThread::current()->Send(new ClipboardHostMsg_ReadImage(buffer, data)); } bool ClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, string16* data, string16* metadata) { bool result = false; RenderThread::current()->Send(new ClipboardHostMsg_ReadData( buffer, type, &result, data, metadata)); return result; } bool ClipboardReadFilenames(ui::Clipboard::Buffer buffer, std::vector<string16>* filenames) { bool result; RenderThread::current()->Send(new ClipboardHostMsg_ReadFilenames( buffer, &result, filenames)); return result; } void GetPlugins(bool refresh, std::vector<webkit::npapi::WebPluginInfo>* plugins) { if (!RenderThread::current()->plugin_refresh_allowed()) refresh = false; RenderThread::current()->Send(new ViewHostMsg_GetPlugins(refresh, plugins)); } bool IsProtocolSupportedForMedia(const GURL& url) { // If new protocol is to be added here, we need to make sure the response is // validated accordingly in the media engine. if (url.SchemeIsFile() || url.SchemeIs(chrome::kHttpScheme) || url.SchemeIs(chrome::kHttpsScheme) || url.SchemeIs(chrome::kDataScheme) || url.SchemeIs(chrome::kExtensionScheme) || url.SchemeIs(chrome::kBlobScheme)) return true; return false; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( const ResourceLoaderBridge::RequestInfo& request_info) { return ChildThread::current()->CreateBridge(request_info); } // static factory function WebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create( WebKit::WebSocketStreamHandle* handle, WebSocketStreamHandleDelegate* delegate) { SocketStreamDispatcher* dispatcher = ChildThread::current()->socket_stream_dispatcher(); return dispatcher->CreateBridge(handle, delegate); } void CloseCurrentConnections() { RenderThread::current()->CloseCurrentConnections(); } void SetCacheMode(bool enabled) { RenderThread::current()->SetCacheMode(enabled); } void ClearCache(bool preserve_ssl_host_info) { RenderThread::current()->ClearCache(preserve_ssl_host_info); } void ClearHostResolverCache() { RenderThread::current()->ClearHostResolverCache(); } void ClearPredictorCache() { RenderThread::current()->ClearPredictorCache(); } std::string GetProductVersion() { chrome::VersionInfo version_info; std::string product("Chrome/"); product += version_info.is_valid() ? version_info.Version() : "0.0.0.0"; return product; } bool IsSingleProcess() { return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); } void EnableSpdy(bool enable) { RenderThread::current()->EnableSpdy(enable); } void UserMetricsRecordAction(const std::string& action) { RenderThread::current()->Send( new ViewHostMsg_UserMetricsRecordAction(action)); } #if !defined(DISABLE_NACL) bool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles, void* nacl_process_handle, int* nacl_process_id) { std::vector<nacl::FileDescriptor> sockets; base::ProcessHandle nacl_process; if (!RenderThread::current()->Send( new ViewHostMsg_LaunchNaCl( ASCIIToWide(alleged_url), socket_count, &sockets, &nacl_process, reinterpret_cast<base::ProcessId*>(nacl_process_id)))) { return false; } CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } *static_cast<nacl::Handle*>(nacl_process_handle) = nacl_process; return true; } #endif #if defined(OS_LINUX) int MatchFontWithFallback(const std::string& face, bool bold, bool italic, int charset) { return renderer_sandbox_support::MatchFontWithFallback( face, bold, italic, charset); } bool GetFontTable(int fd, uint32_t table, uint8_t* output, size_t* output_length) { return renderer_sandbox_support::GetFontTable( fd, table, output, output_length); } #endif } // namespace webkit_glue <commit_msg>Enabled media source content from filesystem: schema.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file provides the embedder's side of random webkit glue functions. #include "build/build_config.h" #if defined(OS_WIN) #include <windows.h> #endif #include <vector> #include "base/command_line.h" #include "base/memory/ref_counted.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/render_messages.h" #include "chrome/common/url_constants.h" #include "content/common/clipboard_messages.h" #include "content/common/socket_stream_dispatcher.h" #include "content/common/view_messages.h" #include "content/plugin/npobject_util.h" #include "content/renderer/render_thread.h" #include "googleurl/src/url_util.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebKitClient.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebString.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/resource/resource_bundle.h" #include "webkit/glue/scoped_clipboard_writer_glue.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/websocketstreamhandle_bridge.h" #if !defined(DISABLE_NACL) #include "native_client/src/shared/imc/nacl_imc.h" #include "native_client/src/trusted/plugin/nacl_entry_points.h" #endif #if defined(OS_LINUX) #include "content/renderer/renderer_sandbox_support_linux.h" #endif // This definition of WriteBitmapFromPixels uses shared memory to communicate // across processes. void ScopedClipboardWriterGlue::WriteBitmapFromPixels(const void* pixels, const gfx::Size& size) { // Do not try to write a bitmap more than once if (shared_buf_) return; uint32 buf_size = 4 * size.width() * size.height(); // Allocate a shared memory buffer to hold the bitmap bits. #if defined(OS_POSIX) // On POSIX, we need to ask the browser to create the shared memory for us, // since this is blocked by the sandbox. base::SharedMemoryHandle shared_mem_handle; ViewHostMsg_AllocateSharedMemoryBuffer *msg = new ViewHostMsg_AllocateSharedMemoryBuffer(buf_size, &shared_mem_handle); if (RenderThread::current()->Send(msg)) { if (base::SharedMemory::IsHandleValid(shared_mem_handle)) { shared_buf_ = new base::SharedMemory(shared_mem_handle, false); if (!shared_buf_ || !shared_buf_->Map(buf_size)) { NOTREACHED() << "Map failed"; return; } } else { NOTREACHED() << "Browser failed to allocate shared memory"; return; } } else { NOTREACHED() << "Browser allocation request message failed"; return; } #else // !OS_POSIX shared_buf_ = new base::SharedMemory; if (!shared_buf_->CreateAndMapAnonymous(buf_size)) { NOTREACHED(); return; } #endif // Copy the bits into shared memory memcpy(shared_buf_->memory(), pixels, buf_size); shared_buf_->Unmap(); ui::Clipboard::ObjectMapParam size_param; const char* size_data = reinterpret_cast<const char*>(&size); for (size_t i = 0; i < sizeof(gfx::Size); ++i) size_param.push_back(size_data[i]); ui::Clipboard::ObjectMapParams params; // The first parameter is replaced on the receiving end with a pointer to // a shared memory object containing the bitmap. We reserve space for it here. ui::Clipboard::ObjectMapParam place_holder_param; params.push_back(place_holder_param); params.push_back(size_param); objects_[ui::Clipboard::CBF_SMBITMAP] = params; } // Define a destructor that makes IPCs to flush the contents to the // system clipboard. ScopedClipboardWriterGlue::~ScopedClipboardWriterGlue() { if (objects_.empty()) return; if (shared_buf_) { RenderThread::current()->Send( new ClipboardHostMsg_WriteObjectsSync(objects_, shared_buf_->handle())); delete shared_buf_; return; } RenderThread::current()->Send( new ClipboardHostMsg_WriteObjectsAsync(objects_)); } namespace webkit_glue { void AppendToLog(const char* file, int line, const char* msg) { logging::LogMessage(file, line).stream() << msg; } base::StringPiece GetDataResource(int resource_id) { return ResourceBundle::GetSharedInstance().GetRawDataResource(resource_id); } #if defined(OS_WIN) HCURSOR LoadCursor(int cursor_id) { return ResourceBundle::GetSharedInstance().LoadCursor(cursor_id); } #endif // Clipboard glue ui::Clipboard* ClipboardGetClipboard() { return NULL; } bool ClipboardIsFormatAvailable(const ui::Clipboard::FormatType& format, ui::Clipboard::Buffer buffer) { bool result; RenderThread::current()->Send( new ClipboardHostMsg_IsFormatAvailable(format, buffer, &result)); return result; } void ClipboardReadAvailableTypes(ui::Clipboard::Buffer buffer, std::vector<string16>* types, bool* contains_filenames) { RenderThread::current()->Send(new ClipboardHostMsg_ReadAvailableTypes( buffer, types, contains_filenames)); } void ClipboardReadText(ui::Clipboard::Buffer buffer, string16* result) { RenderThread::current()->Send(new ClipboardHostMsg_ReadText(buffer, result)); } void ClipboardReadAsciiText(ui::Clipboard::Buffer buffer, std::string* result) { RenderThread::current()->Send( new ClipboardHostMsg_ReadAsciiText(buffer, result)); } void ClipboardReadHTML(ui::Clipboard::Buffer buffer, string16* markup, GURL* url) { RenderThread::current()->Send( new ClipboardHostMsg_ReadHTML(buffer, markup, url)); } void ClipboardReadImage(ui::Clipboard::Buffer buffer, std::string* data) { RenderThread::current()->Send(new ClipboardHostMsg_ReadImage(buffer, data)); } bool ClipboardReadData(ui::Clipboard::Buffer buffer, const string16& type, string16* data, string16* metadata) { bool result = false; RenderThread::current()->Send(new ClipboardHostMsg_ReadData( buffer, type, &result, data, metadata)); return result; } bool ClipboardReadFilenames(ui::Clipboard::Buffer buffer, std::vector<string16>* filenames) { bool result; RenderThread::current()->Send(new ClipboardHostMsg_ReadFilenames( buffer, &result, filenames)); return result; } void GetPlugins(bool refresh, std::vector<webkit::npapi::WebPluginInfo>* plugins) { if (!RenderThread::current()->plugin_refresh_allowed()) refresh = false; RenderThread::current()->Send(new ViewHostMsg_GetPlugins(refresh, plugins)); } bool IsProtocolSupportedForMedia(const GURL& url) { // If new protocol is to be added here, we need to make sure the response is // validated accordingly in the media engine. if (url.SchemeIsFile() || url.SchemeIs(chrome::kHttpScheme) || url.SchemeIs(chrome::kHttpsScheme) || url.SchemeIs(chrome::kDataScheme) || url.SchemeIs(chrome::kExtensionScheme) || url.SchemeIs(chrome::kFileSystemScheme) || url.SchemeIs(chrome::kBlobScheme)) return true; return false; } // static factory function ResourceLoaderBridge* ResourceLoaderBridge::Create( const ResourceLoaderBridge::RequestInfo& request_info) { return ChildThread::current()->CreateBridge(request_info); } // static factory function WebSocketStreamHandleBridge* WebSocketStreamHandleBridge::Create( WebKit::WebSocketStreamHandle* handle, WebSocketStreamHandleDelegate* delegate) { SocketStreamDispatcher* dispatcher = ChildThread::current()->socket_stream_dispatcher(); return dispatcher->CreateBridge(handle, delegate); } void CloseCurrentConnections() { RenderThread::current()->CloseCurrentConnections(); } void SetCacheMode(bool enabled) { RenderThread::current()->SetCacheMode(enabled); } void ClearCache(bool preserve_ssl_host_info) { RenderThread::current()->ClearCache(preserve_ssl_host_info); } void ClearHostResolverCache() { RenderThread::current()->ClearHostResolverCache(); } void ClearPredictorCache() { RenderThread::current()->ClearPredictorCache(); } std::string GetProductVersion() { chrome::VersionInfo version_info; std::string product("Chrome/"); product += version_info.is_valid() ? version_info.Version() : "0.0.0.0"; return product; } bool IsSingleProcess() { return CommandLine::ForCurrentProcess()->HasSwitch(switches::kSingleProcess); } void EnableSpdy(bool enable) { RenderThread::current()->EnableSpdy(enable); } void UserMetricsRecordAction(const std::string& action) { RenderThread::current()->Send( new ViewHostMsg_UserMetricsRecordAction(action)); } #if !defined(DISABLE_NACL) bool LaunchSelLdr(const char* alleged_url, int socket_count, void* imc_handles, void* nacl_process_handle, int* nacl_process_id) { std::vector<nacl::FileDescriptor> sockets; base::ProcessHandle nacl_process; if (!RenderThread::current()->Send( new ViewHostMsg_LaunchNaCl( ASCIIToWide(alleged_url), socket_count, &sockets, &nacl_process, reinterpret_cast<base::ProcessId*>(nacl_process_id)))) { return false; } CHECK(static_cast<int>(sockets.size()) == socket_count); for (int i = 0; i < socket_count; i++) { static_cast<nacl::Handle*>(imc_handles)[i] = nacl::ToNativeHandle(sockets[i]); } *static_cast<nacl::Handle*>(nacl_process_handle) = nacl_process; return true; } #endif #if defined(OS_LINUX) int MatchFontWithFallback(const std::string& face, bool bold, bool italic, int charset) { return renderer_sandbox_support::MatchFontWithFallback( face, bold, italic, charset); } bool GetFontTable(int fd, uint32_t table, uint8_t* output, size_t* output_length) { return renderer_sandbox_support::GetFontTable( fd, table, output, output_length); } #endif } // namespace webkit_glue <|endoftext|>
<commit_before>#ifndef INCLUDED_U5E_UTF8_ITERATOR #define INCLUDED_U5E_UTF8_ITERATOR #include <cmath> #include <iterator> #include <u5e/utf8_utils.hpp> #include <u5e/codepoint.hpp> #include <u5e/iterator_assertion.hpp> namespace u5e { /** * u5e::utf8_iterator * * Iterates over codepoints on utf8 data. * * Since this iterator manipulates data in octets and offers * codepoints, it can't offer a mutable interface. For write access, * you need to use an utf8_output_iterator. */ template <typename WRAPPEDITERATOR> class utf8_iterator_base { protected: iterator_assertion<WRAPPEDITERATOR, char> _assertions; WRAPPEDITERATOR raw_iterator_; public: typedef codepoint value_type; typedef const codepoint& reference; typedef int difference_type; typedef std::bidirectional_iterator_tag iterator_category; inline utf8_iterator_base(const WRAPPEDITERATOR raw_iterator) : raw_iterator_(raw_iterator) { }; inline void forward_one_codepoint() { difference_type size = utf8_utils::codepoint_size(*raw_iterator_); raw_iterator_ += size; } inline bool rewind_to_start_of_codepoint(const char current_octet) { // when we do '*it = codepoint', we will leave the iterator // halfway into the next character if (__builtin_clz(~((current_octet)<<24)) == 1) { while ((*(raw_iterator_) & 0b11000000) == 0b10000000) { raw_iterator_--; } return true; } else { return false; } } inline void rewind_one_codepoint() { rewind_to_start_of_codepoint(*raw_iterator_); raw_iterator_--; while ((*(raw_iterator_) & 0b11000000) == 0b10000000) { raw_iterator_--; } } const codepoint current_codepoint() { char first_octet = *raw_iterator_; if ((first_octet & 0b10000000) == 0) { return first_octet; } else { if (rewind_to_start_of_codepoint(first_octet)) { first_octet = *raw_iterator_; } WRAPPEDITERATOR copy_ = raw_iterator_; difference_type size = utf8_utils::codepoint_size(first_octet); unsigned char mask_first_octet = ~(0xFF<<(7-size)); int value = (first_octet & mask_first_octet); while (--size) { value = value<<6 | (*(++copy_) & 0b00111111); } return value; } } }; template <typename WRAPPEDITERATOR> class utf8_const_iterator : public utf8_iterator_base<WRAPPEDITERATOR> { public: typedef utf8_const_iterator pointer; inline utf8_const_iterator(const WRAPPEDITERATOR raw_iterator) : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) { }; inline utf8_const_iterator(const utf8_const_iterator& tocopy) : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) { }; inline utf8_const_iterator& operator++() { this->forward_one_codepoint(); return *this; } inline utf8_const_iterator operator++(int junk) { utf8_const_iterator copy(this->raw_iterator_); ++(*this); return copy; } inline utf8_const_iterator& operator--() { this->rewind_one_codepoint(); return *this; } inline utf8_const_iterator operator--(int junk) { utf8_const_iterator copy(this->raw_iterator_); --(*this); return copy; } inline bool operator==(const utf8_const_iterator& rhs) const { return this->raw_iterator_ == rhs.raw_iterator_; } inline bool operator!=(const utf8_const_iterator& rhs) const { return this->raw_iterator_ != rhs.raw_iterator_; } inline const codepoint operator*() { return this->current_codepoint(); } }; template <typename WRAPPEDITERATOR> class utf8_iterator : public utf8_iterator_base<WRAPPEDITERATOR> { public: typedef utf8_iterator pointer; inline utf8_iterator(const WRAPPEDITERATOR raw_iterator) : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) {}; inline utf8_iterator(const utf8_iterator& tocopy) : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) {}; inline utf8_iterator& operator++() { this->forward_one_codepoint(); return *this; } inline utf8_iterator operator++(int junk) { utf8_iterator copy(this->raw_iterator_); ++(*this); return copy; } inline utf8_iterator& operator--() { this->rewind_one_codepoint(); return *this; } inline utf8_iterator operator--(int junk) { utf8_iterator copy(this->raw_iterator_); --(*this); return copy; } inline bool operator==(const utf8_iterator& rhs) const { return this->raw_iterator_ == rhs.raw_iterator_; } inline bool operator!=(const utf8_iterator& rhs) const { return this->raw_iterator_ != rhs.raw_iterator_; } class proxyobject : public codepoint { private: utf8_iterator<WRAPPEDITERATOR>& ref; public: proxyobject(utf8_iterator<WRAPPEDITERATOR>& refin) :ref(refin) { utf8_iterator<WRAPPEDITERATOR> copy = refin; value = copy.current_codepoint().value; }; proxyobject& operator=(const codepoint c) { int value = c.value; // operate on codepoint as integer int size = std::ceil((float)(32 - __builtin_clz(value)) / (float)6); if (size <= 1) { *(ref.raw_iterator_) = (value & 0xFF); } else { utf8_iterator<WRAPPEDITERATOR> copy = ref; unsigned char first_octet = (0xFF<<(8-size)); first_octet |= ((value>>((size-1)*6)) & 0xFF); *(copy.raw_iterator_) = first_octet; copy.raw_iterator_++; while (--size) { unsigned char octet = 0b10000000; octet |= ((value>>((size-1)*6)) & 0b00111111); *(copy.raw_iterator_) = octet; copy.raw_iterator_++; } } return *this; } }; // non const version returns a proxy object inline proxyobject operator*() { return proxyobject(*this); } }; }; #endif <commit_msg>- replaced += with std::advance: allows for bidi iterator rather than random access iterator as underlying type for utf8_iterator<commit_after>#ifndef INCLUDED_U5E_UTF8_ITERATOR #define INCLUDED_U5E_UTF8_ITERATOR #include <cmath> #include <iterator> #include <u5e/utf8_utils.hpp> #include <u5e/codepoint.hpp> #include <u5e/iterator_assertion.hpp> namespace u5e { /** * u5e::utf8_iterator * * Iterates over codepoints on utf8 data. * * Since this iterator manipulates data in octets and offers * codepoints, it can't offer a mutable interface. For write access, * you need to use an utf8_output_iterator. */ template <typename WRAPPEDITERATOR> class utf8_iterator_base { protected: iterator_assertion<WRAPPEDITERATOR, char> _assertions; WRAPPEDITERATOR raw_iterator_; public: typedef codepoint value_type; typedef const codepoint& reference; typedef int difference_type; typedef std::bidirectional_iterator_tag iterator_category; inline utf8_iterator_base(const WRAPPEDITERATOR raw_iterator) : raw_iterator_(raw_iterator) { }; inline void forward_one_codepoint() { difference_type size = utf8_utils::codepoint_size(*raw_iterator_); std::advance(raw_iterator_, size); } inline bool rewind_to_start_of_codepoint(const char current_octet) { // when we do '*it = codepoint', we will leave the iterator // halfway into the next character if (__builtin_clz(~((current_octet)<<24)) == 1) { while ((*(raw_iterator_) & 0b11000000) == 0b10000000) { raw_iterator_--; } return true; } else { return false; } } inline void rewind_one_codepoint() { rewind_to_start_of_codepoint(*raw_iterator_); raw_iterator_--; while ((*(raw_iterator_) & 0b11000000) == 0b10000000) { raw_iterator_--; } } const codepoint current_codepoint() { char first_octet = *raw_iterator_; if ((first_octet & 0b10000000) == 0) { return first_octet; } else { if (rewind_to_start_of_codepoint(first_octet)) { first_octet = *raw_iterator_; } WRAPPEDITERATOR copy_ = raw_iterator_; difference_type size = utf8_utils::codepoint_size(first_octet); unsigned char mask_first_octet = ~(0xFF<<(7-size)); int value = (first_octet & mask_first_octet); while (--size) { value = value<<6 | (*(++copy_) & 0b00111111); } return value; } } }; template <typename WRAPPEDITERATOR> class utf8_const_iterator : public utf8_iterator_base<WRAPPEDITERATOR> { public: typedef utf8_const_iterator pointer; inline utf8_const_iterator(const WRAPPEDITERATOR raw_iterator) : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) { }; inline utf8_const_iterator(const utf8_const_iterator& tocopy) : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) { }; inline utf8_const_iterator& operator++() { this->forward_one_codepoint(); return *this; } inline utf8_const_iterator operator++(int junk) { utf8_const_iterator copy(this->raw_iterator_); ++(*this); return copy; } inline utf8_const_iterator& operator--() { this->rewind_one_codepoint(); return *this; } inline utf8_const_iterator operator--(int junk) { utf8_const_iterator copy(this->raw_iterator_); --(*this); return copy; } inline bool operator==(const utf8_const_iterator& rhs) const { return this->raw_iterator_ == rhs.raw_iterator_; } inline bool operator!=(const utf8_const_iterator& rhs) const { return this->raw_iterator_ != rhs.raw_iterator_; } inline const codepoint operator*() { return this->current_codepoint(); } }; template <typename WRAPPEDITERATOR> class utf8_iterator : public utf8_iterator_base<WRAPPEDITERATOR> { public: typedef utf8_iterator pointer; inline utf8_iterator(const WRAPPEDITERATOR raw_iterator) : utf8_iterator_base<WRAPPEDITERATOR>(raw_iterator) {}; inline utf8_iterator(const utf8_iterator& tocopy) : utf8_iterator_base<WRAPPEDITERATOR>(tocopy.raw_iterator_) {}; inline utf8_iterator& operator++() { this->forward_one_codepoint(); return *this; } inline utf8_iterator operator++(int junk) { utf8_iterator copy(this->raw_iterator_); ++(*this); return copy; } inline utf8_iterator& operator--() { this->rewind_one_codepoint(); return *this; } inline utf8_iterator operator--(int junk) { utf8_iterator copy(this->raw_iterator_); --(*this); return copy; } inline bool operator==(const utf8_iterator& rhs) const { return this->raw_iterator_ == rhs.raw_iterator_; } inline bool operator!=(const utf8_iterator& rhs) const { return this->raw_iterator_ != rhs.raw_iterator_; } class proxyobject : public codepoint { private: utf8_iterator<WRAPPEDITERATOR>& ref; public: proxyobject(utf8_iterator<WRAPPEDITERATOR>& refin) :ref(refin) { utf8_iterator<WRAPPEDITERATOR> copy = refin; value = copy.current_codepoint().value; }; proxyobject& operator=(const codepoint c) { int value = c.value; // operate on codepoint as integer int size = std::ceil((float)(32 - __builtin_clz(value)) / (float)6); if (size <= 1) { *(ref.raw_iterator_) = (value & 0xFF); } else { utf8_iterator<WRAPPEDITERATOR> copy = ref; unsigned char first_octet = (0xFF<<(8-size)); first_octet |= ((value>>((size-1)*6)) & 0xFF); *(copy.raw_iterator_) = first_octet; copy.raw_iterator_++; while (--size) { unsigned char octet = 0b10000000; octet |= ((value>>((size-1)*6)) & 0b00111111); *(copy.raw_iterator_) = octet; copy.raw_iterator_++; } } return *this; } }; // non const version returns a proxy object inline proxyobject operator*() { return proxyobject(*this); } }; }; #endif <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- /// \file variant_tree.hpp //---------------------------------------------------------------------------- /// \brief This file contains a tree class that can hold variant values. //---------------------------------------------------------------------------- // Author: Serge Aleynikov // Created: 2010-07-10 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file may be included in various open-source projects. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTIL_VARIANT_TREE_HPP_ #define _UTIL_VARIANT_TREE_HPP_ #include <util/variant.hpp> #include <util/typeinfo.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/lexical_cast.hpp> #include <boost/utility/enable_if.hpp> #include <boost/throw_exception.hpp> namespace boost { namespace property_tree { // Custom translator that works with util::variant instead of std::string. // This translator is used to read/write values from files. template <> struct translator_between<util::variant, std::string> { typedef translator_between<util::variant, std::string> type; typedef std::string external_type; typedef util::variant internal_type; boost::optional<external_type> get_value(const internal_type& value) const { return boost::optional<external_type>( value.type() == internal_type::TYPE_NULL ? "" : value.to_string()); } boost::optional<internal_type> put_value(const external_type& value) const { try { long n = lexical_cast<long>(value); for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it) if (*it < '0' || *it > '9') throw false; return boost::optional<internal_type>(n); } catch (...) {} try { double n = lexical_cast<double>(value); return boost::optional<internal_type>(n); } catch (...) {} if (value == "true" || value == "false") return boost::optional<internal_type>(value[0] == 't'); return boost::optional<internal_type>(value); } }; } // namespace property_tree } // namespace boost namespace util { namespace detail { // Custom translator that works with variant instead of std::string // This translator is used to get/put values through explicit get/put calls. template <class Ext> struct variant_translator { typedef Ext external_type; typedef variant internal_type; /* typedef boost::mpl::joint_view<variant::int_types, boost::mpl::vector<bool,double> > valid_non_string_types; */ typedef variant::valid_types valid_types; external_type get_value(const internal_type& value) const { return value.get<external_type>(); } template<typename T> typename boost::disable_if< boost::is_same< boost::mpl::end<valid_types>::type, boost::mpl::find<variant::valid_types, T> >, internal_type>::type put_value(T value) const { return variant(value); } }; typedef boost::property_tree::basic_ptree< std::string, // Key type variant, // Data type std::less<std::string> // Key comparison > basic_variant_tree; } // namespace detail class variant_tree : public detail::basic_variant_tree { typedef detail::basic_variant_tree base; typedef variant_tree self_type; public: typedef boost::property_tree::ptree_bad_path bad_path; variant_tree() {} template <typename Source> static void read_info(Source& src, variant_tree& tree) { boost::property_tree::info_parser::read_info(src, tree); } template <typename Target> static void write_info(Target& tar, variant_tree& tree) { boost::property_tree::info_parser::write_info(tar, tree); } template <typename Target, typename Settings> static void write_info(Target& tar, variant_tree& tree, const Settings& tt) { boost::property_tree::info_parser::write_info(tar, tree, tt); } template <class T> T get_value() const { using boost::throw_exception; if(boost::optional<T> o = base::get_value_optional<T>(detail::variant_translator<T>())) { return *o; } BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data( std::string("conversion of data to type \"") + typeid(T).name() + "\" failed", base::data())); } template <class T> T get_value(const T& default_value) const { return base::get_value(default_value, detail::variant_translator<T>()); } std::string get_value(const char* default_value) const { return base::get_value(std::string(default_value), detail::variant_translator<std::string>()); } template <class T> boost::optional<T> get_value_optional() const { return base::get_value(detail::variant_translator<T>()); } template <class T> void put_value(const T& value) { base::put_value(value, detail::variant_translator<T>()); } template <class T> T get(const path_type& path) const { try { return base::get_child(path).BOOST_NESTED_TEMPLATE get_value<T>(detail::variant_translator<T>()); } catch (boost::bad_get& e) { std::stringstream s; s << "Cannot convert value to type '" << type_to_string<T>() << "'"; throw bad_path(s.str(), path); } } template <class T> T get(const path_type& path, const T& default_value) const { try { return base::get(path, default_value, detail::variant_translator<T>()); } catch (boost::bad_get& e) { throw bad_path("Wrong or missing value type", path); } } std::string get(const path_type& path, const char* default_value) const { return base::get(path, std::string(default_value), detail::variant_translator<std::string>()); } template <class T> boost::optional<T> get_optional(const path_type& path) const { return base::get_optional(path, detail::variant_translator<T>()); } template <class T> void put(const path_type& path, const T& value) { base::put(path, value, detail::variant_translator<T>()); } template <class T> self_type& add(const path_type& path, const T& value) { return static_cast<self_type&>( base::add(path, value, detail::variant_translator<T>())); } void swap(variant_tree& rhs) { base::swap(rhs); } void swap(boost::property_tree::basic_ptree< std::string, variant, std::less<std::string> >& rhs) { base::swap(rhs); } self_type &get_child(const path_type &path) { return static_cast<self_type&>(base::get_child(path)); } /** Get the child at the given path, or throw @c ptree_bad_path. */ const self_type &get_child(const path_type &path) const { return static_cast<const self_type&>(base::get_child(path)); } /** Get the child at the given path, or return @p default_value. */ self_type &get_child(const path_type &path, self_type &default_value) { return static_cast<self_type&>(base::get_child(path, default_value)); } /** Get the child at the given path, or return @p default_value. */ const self_type &get_child(const path_type &path, const self_type &default_value) const { return static_cast<const self_type&>(base::get_child(path, default_value)); } /** Get the child at the given path, or return boost::null. */ boost::optional<self_type &> get_child_optional(const path_type &path) { boost::optional<base&> o = base::get_child_optional(path); if (!o) return boost::optional<self_type&>(); return boost::optional<self_type&>(static_cast<self_type&>(*o)); } /** Get the child at the given path, or return boost::null. */ boost::optional<const self_type &> get_child_optional(const path_type &path) const { boost::optional<const base&> o = base::get_child_optional(path); if (!o) return boost::optional<const self_type&>(); return boost::optional<const self_type&>(static_cast<const self_type&>(*o)); } self_type &put_child(const path_type &path, const self_type &value) { return static_cast<self_type&>(base::put_child(path, value)); } }; } // namespace util #endif // _UTIL_VARIANT_TREE_HPP_ <commit_msg>Fixed casting problem<commit_after>//---------------------------------------------------------------------------- /// \file variant_tree.hpp //---------------------------------------------------------------------------- /// \brief This file contains a tree class that can hold variant values. //---------------------------------------------------------------------------- // Author: Serge Aleynikov // Created: 2010-07-10 //---------------------------------------------------------------------------- /* ***** BEGIN LICENSE BLOCK ***** This file may be included in various open-source projects. Copyright (C) 2010 Serge Aleynikov <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU 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 ***** END LICENSE BLOCK ***** */ #ifndef _UTIL_VARIANT_TREE_HPP_ #define _UTIL_VARIANT_TREE_HPP_ #include <util/variant.hpp> #include <util/typeinfo.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/info_parser.hpp> #include <boost/lexical_cast.hpp> #include <boost/utility/enable_if.hpp> #include <boost/throw_exception.hpp> namespace boost { namespace property_tree { // Custom translator that works with util::variant instead of std::string. // This translator is used to read/write values from files. template <> struct translator_between<util::variant, std::string> { typedef translator_between<util::variant, std::string> type; typedef std::string external_type; typedef util::variant internal_type; boost::optional<external_type> get_value(const internal_type& value) const { return boost::optional<external_type>( value.type() == internal_type::TYPE_NULL ? "" : value.to_string()); } boost::optional<internal_type> put_value(const external_type& value) const { try { long n = lexical_cast<long>(value); for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it) if (*it < '0' || *it > '9') throw false; return boost::optional<internal_type>(n); } catch (...) {} try { double n = lexical_cast<double>(value); return boost::optional<internal_type>(n); } catch (...) {} if (value == "true" || value == "false") return boost::optional<internal_type>(value[0] == 't'); return boost::optional<internal_type>(value); } }; } // namespace property_tree } // namespace boost namespace util { namespace detail { // Custom translator that works with variant instead of std::string // This translator is used to get/put values through explicit get/put calls. template <class Ext> struct variant_translator { typedef Ext external_type; typedef variant internal_type; /* typedef boost::mpl::joint_view<variant::int_types, boost::mpl::vector<bool,double> > valid_non_string_types; */ typedef variant::valid_types valid_types; external_type get_value(const internal_type& value) const { return value.get<external_type>(); } template<typename T> typename boost::disable_if< boost::is_same< boost::mpl::end<valid_types>::type, boost::mpl::find<variant::valid_types, T> >, internal_type>::type put_value(T value) const { return variant(value); } }; typedef boost::property_tree::basic_ptree< std::string, // Key type variant, // Data type std::less<std::string> // Key comparison > basic_variant_tree; } // namespace detail class variant_tree : public detail::basic_variant_tree { typedef detail::basic_variant_tree base; typedef variant_tree self_type; public: typedef boost::property_tree::ptree_bad_path bad_path; typedef std::pair<std::string, variant_tree> value_type; variant_tree() {} variant_tree(const detail::basic_variant_tree& a_rhs) : detail::basic_variant_tree(a_rhs) {} template <typename Source> static void read_info(Source& src, variant_tree& tree) { boost::property_tree::info_parser::read_info(src, tree); } template <typename Target> static void write_info(Target& tar, variant_tree& tree) { boost::property_tree::info_parser::write_info(tar, tree); } template <typename Target, typename Settings> static void write_info(Target& tar, variant_tree& tree, const Settings& tt) { boost::property_tree::info_parser::write_info(tar, tree, tt); } template <class T> T get_value() const { using boost::throw_exception; if(boost::optional<T> o = base::get_value_optional<T>(detail::variant_translator<T>())) { return *o; } BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data( std::string("conversion of data to type \"") + typeid(T).name() + "\" failed", base::data())); } template <class T> T get_value(const T& default_value) const { return base::get_value(default_value, detail::variant_translator<T>()); } std::string get_value(const char* default_value) const { return base::get_value(std::string(default_value), detail::variant_translator<std::string>()); } template <class T> boost::optional<T> get_value_optional() const { return base::get_value(detail::variant_translator<T>()); } template <class T> void put_value(const T& value) { base::put_value(value, detail::variant_translator<T>()); } template <class T> T get(const path_type& path) const { try { return base::get_child(path).BOOST_NESTED_TEMPLATE get_value<T>(detail::variant_translator<T>()); } catch (boost::bad_get& e) { std::stringstream s; s << "Cannot convert value to type '" << type_to_string<T>() << "'"; throw bad_path(s.str(), path); } } template <class T> T get(const path_type& path, const T& default_value) const { try { return base::get(path, default_value, detail::variant_translator<T>()); } catch (boost::bad_get& e) { throw bad_path("Wrong or missing value type", path); } } std::string get(const path_type& path, const char* default_value) const { return base::get(path, std::string(default_value), detail::variant_translator<std::string>()); } template <class T> boost::optional<T> get_optional(const path_type& path) const { return base::get_optional(path, detail::variant_translator<T>()); } template <class T> void put(const path_type& path, const T& value) { base::put(path, value, detail::variant_translator<T>()); } template <class T> self_type& add(const path_type& path, const T& value) { return static_cast<self_type&>( base::add(path, value, detail::variant_translator<T>())); } void swap(variant_tree& rhs) { base::swap(rhs); } void swap(boost::property_tree::basic_ptree< std::string, variant, std::less<std::string> >& rhs) { base::swap(rhs); } self_type &get_child(const path_type &path) { return static_cast<self_type&>(base::get_child(path)); } /** Get the child at the given path, or throw @c ptree_bad_path. */ const self_type &get_child(const path_type &path) const { return static_cast<const self_type&>(base::get_child(path)); } /** Get the child at the given path, or return @p default_value. */ self_type &get_child(const path_type &path, self_type &default_value) { return static_cast<self_type&>(base::get_child(path, default_value)); } /** Get the child at the given path, or return @p default_value. */ const self_type &get_child(const path_type &path, const self_type &default_value) const { return static_cast<const self_type&>(base::get_child(path, default_value)); } /** Get the child at the given path, or return boost::null. */ boost::optional<self_type &> get_child_optional(const path_type &path) { boost::optional<base&> o = base::get_child_optional(path); if (!o) return boost::optional<self_type&>(); return boost::optional<self_type&>(static_cast<self_type&>(*o)); } /** Get the child at the given path, or return boost::null. */ boost::optional<const self_type &> get_child_optional(const path_type &path) const { boost::optional<const base&> o = base::get_child_optional(path); if (!o) return boost::optional<const self_type&>(); return boost::optional<const self_type&>(static_cast<const self_type&>(*o)); } self_type &put_child(const path_type &path, const self_type &value) { return static_cast<self_type&>(base::put_child(path, value)); } }; } // namespace util #endif // _UTIL_VARIANT_TREE_HPP_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_vas_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF; constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000; constexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000; constexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000; constexpr uint64_t literal_0x1 = 0x1; fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer)); } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer )); l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer )); l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer )); l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer )); l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer )); l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer)); } } { FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer )); constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1; l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0; l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF ); } FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer )); l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <commit_msg>Logic flushed to 0s, xFC provides better performance and is intended value<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include "p9_vas_scom.H" #include <stdint.h> #include <stddef.h> #include <fapi2.H> using namespace fapi2; constexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF; constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000; constexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000; constexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000; constexpr uint64_t literal_0x1 = 0x1; constexpr uint64_t literal_0xFC = 0xFC; fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0, const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1) { { fapi2::ATTR_EC_Type l_chip_ec; fapi2::ATTR_NAME_Type l_chip_id; FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id)); FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec)); fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE; FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE)); fapi2::buffer<uint64_t> l_scom_buffer; { FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer )); l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer)); } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer )); l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer )); l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer )); l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer )); l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer)); } } { if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) ) { FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer )); l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer)); } } { FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer )); constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0; l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF ); if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP)) { constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1; l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON ); } else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE)) { constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0; l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF ); } l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC ); l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC ); FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer)); } { FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer )); l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 ); FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer)); } }; fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- /// /// @file p9_pcie_scominit.H /// @brief Perform PCIE Phase1 init sequence (FAPI2) /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 1 // *HWP Consumed by: HB #ifndef _P9_PCIE_SCOMINIT_H_ #define _P9_PCIE_SCOMINIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> //----------------------------------------------------------------------------------- // Helper Macros //----------------------------------------------------------------------------------- #define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ l_buf = 0; \ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- const uint8_t NUM_PCS_CONFIG = 4; const uint8_t NUM_PCIE_LANES = 16; const uint8_t NUM_M_CONFIG = 4; const uint8_t PEC0_IOP_CONFIG_START_BIT = 13; const uint8_t PEC1_IOP_CONFIG_START_BIT = 14; const uint8_t PEC2_IOP_CONFIG_START_BIT = 10; const uint8_t PEC0_IOP_BIT_COUNT = 1; const uint8_t PEC1_IOP_BIT_COUNT = 2; const uint8_t PEC2_IOP_BIT_COUNT = 3; const uint8_t PEC0_IOP_SWAP_START_BIT = 11; const uint8_t PEC1_IOP_SWAP_START_BIT = 12; const uint8_t PEC2_IOP_SWAP_START_BIT = 7; const uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32; const uint8_t PEC_IOP_PMA_RESET_START_BIT = 29; const uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28; const uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58; const uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F; const uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F; const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F; const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F; const uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] = { 0x8000008D0D010C3F, 0x800000CD0D010C3F, 0x8000018D0D010C3F, 0x800001CD0D010C3F, 0x8000028D0D010C3F, 0x800002CD0D010C3F, 0x8000038D0D010C3F, 0x800003CD0D010C3F, 0x8000088D0D010C3F, 0x800008CD0D010C3F, 0x8000098D0D010C3F, 0x800009CD0D010C3F, 0x80000A8D0D010C3F, 0x80000ACD0D010C3F, 0x80000B8D0D010C3F, 0x80000BCD0D010C3F, }; const uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] = { 0x800000A60D010C3F, 0x800000E60D010C3F, 0x800001A60D010C3F, 0x800001E60D010C3F, 0x800002A60D010C3F, 0x800002E60D010C3F, 0x800003A60D010C3F, 0x800003E60D010C3F, 0x800008A60D010C3F, 0x800008E60D010C3F, 0x800009A60D010C3F, 0x800009E60D010C3F, 0x80000AA60D010C3F, 0x80000AE60D010C3F, 0x80000BA60D010C3F, 0x80000BE60D010C3F, }; const uint32_t PCS_CONFIG_MODE0 = 0xA006; const uint32_t PCS_CONFIG_MODE1 = 0xA805; const uint32_t PCS_CONFIG_MODE2 = 0xB071; const uint32_t PCS_CONFIG_MODE3 = 0xB870; const uint32_t MAX_NUM_POLLS = 100; //Maximum number of iterations (So, 400ns * 100 = 40us before timeout) const uint64_t PMA_RESET_NANO_SEC_DELAY = 400; //400ns to wait for PMA RESET to go through const uint64_t PMA_RESET_CYC_DELAY = 400; //400ns to wait for PMA RESET to go through extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Perform PCIE Phase1 init sequence /// @param[in] i_target => P9 chip target /// @return FAPI_RC_SUCCESS if the setup completes successfully, // fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } //extern"C" #endif //_P9_PCIE_SCOMINIT_H_ <commit_msg>p9_pcie_scominit PEC0 swap bit position fixed<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //----------------------------------------------------------------------------------- /// /// @file p9_pcie_scominit.H /// @brief Perform PCIE Phase1 init sequence (FAPI2) /// // *HWP HWP Owner: Christina Graves [email protected] // *HWP FW Owner: Thi Tran [email protected] // *HWP Team: Nest // *HWP Level: 1 // *HWP Consumed by: HB #ifndef _P9_PCIE_SCOMINIT_H_ #define _P9_PCIE_SCOMINIT_H_ //----------------------------------------------------------------------------------- // Includes //----------------------------------------------------------------------------------- #include <fapi2.H> //----------------------------------------------------------------------------------- // Helper Macros //----------------------------------------------------------------------------------- #define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\ l_buf = 0; \ FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \ FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \ FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); #define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\ FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \ FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \ FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf)); //----------------------------------------------------------------------------------- // Structure definitions //----------------------------------------------------------------------------------- //function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&); //----------------------------------------------------------------------------------- // Constant definitions //----------------------------------------------------------------------------------- const uint8_t NUM_PCS_CONFIG = 4; const uint8_t NUM_PCIE_LANES = 16; const uint8_t NUM_M_CONFIG = 4; const uint8_t PEC0_IOP_CONFIG_START_BIT = 13; const uint8_t PEC1_IOP_CONFIG_START_BIT = 14; const uint8_t PEC2_IOP_CONFIG_START_BIT = 10; const uint8_t PEC0_IOP_BIT_COUNT = 1; const uint8_t PEC1_IOP_BIT_COUNT = 2; const uint8_t PEC2_IOP_BIT_COUNT = 3; const uint8_t PEC0_IOP_SWAP_START_BIT = 12; const uint8_t PEC1_IOP_SWAP_START_BIT = 12; const uint8_t PEC2_IOP_SWAP_START_BIT = 7; const uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4; const uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32; const uint8_t PEC_IOP_PMA_RESET_START_BIT = 29; const uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28; const uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58; const uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F; const uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F; const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F; const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F; const uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] = { 0x8000008D0D010C3F, 0x800000CD0D010C3F, 0x8000018D0D010C3F, 0x800001CD0D010C3F, 0x8000028D0D010C3F, 0x800002CD0D010C3F, 0x8000038D0D010C3F, 0x800003CD0D010C3F, 0x8000088D0D010C3F, 0x800008CD0D010C3F, 0x8000098D0D010C3F, 0x800009CD0D010C3F, 0x80000A8D0D010C3F, 0x80000ACD0D010C3F, 0x80000B8D0D010C3F, 0x80000BCD0D010C3F, }; const uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] = { 0x800000A60D010C3F, 0x800000E60D010C3F, 0x800001A60D010C3F, 0x800001E60D010C3F, 0x800002A60D010C3F, 0x800002E60D010C3F, 0x800003A60D010C3F, 0x800003E60D010C3F, 0x800008A60D010C3F, 0x800008E60D010C3F, 0x800009A60D010C3F, 0x800009E60D010C3F, 0x80000AA60D010C3F, 0x80000AE60D010C3F, 0x80000BA60D010C3F, 0x80000BE60D010C3F, }; const uint32_t PCS_CONFIG_MODE0 = 0xA006; const uint32_t PCS_CONFIG_MODE1 = 0xA805; const uint32_t PCS_CONFIG_MODE2 = 0xB071; const uint32_t PCS_CONFIG_MODE3 = 0xB870; const uint32_t MAX_NUM_POLLS = 100; //Maximum number of iterations (So, 400ns * 100 = 40us before timeout) const uint64_t PMA_RESET_NANO_SEC_DELAY = 400; //400ns to wait for PMA RESET to go through const uint64_t PMA_RESET_CYC_DELAY = 400; //400ns to wait for PMA RESET to go through extern "C" { //----------------------------------------------------------------------------------- // Function prototype //----------------------------------------------------------------------------------- /// @brief Perform PCIE Phase1 init sequence /// @param[in] i_target => P9 chip target /// @return FAPI_RC_SUCCESS if the setup completes successfully, // fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); } //extern"C" #endif //_P9_PCIE_SCOMINIT_H_ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_pfet_control.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_pfet_control.C /// @brief Enable PFET devices to power on/off all enabled Core and Cache /// chiplets in target passed. /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sumit Kumar <[email protected]> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : OCC:CME:FSP //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // PFET Control // Power-on via Hardare FSM: // ------------------------ // VDD first, VCS second // Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000. // Write PFETCNTLSTAT_REG with values defined below // -vdd_pfet_force_state = 11 (Force Von) // -vdd_pfet_val_override = 0 (Override disabled) // -vdd_pfet_sel_override = 0 (Override disabled) // -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM) // Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL]being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // Write PFETCNTLSTAT_REG_OR with values defined below // -vcs_pfet_force_state = 11 (Force Von) // Write to PFETCNTLSTAT_REG_CLR // -vcs_pfet_val_override = 0 (Override disabled) // -vcs_pfet_sel_override = 0 (Override disabled) // Note there is no vcs_pfet_enable_regulation_finger // Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL] being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // // Power-off via Hardare FSM: // ------------------------- // VCS first, VDD second // Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000. // Write PFETCNTLSTAT_REG with values defined below // -vcs_pfet_force_state = 01 (Force Voff) // -vcs_pfet_val_override = 0 (Override disabled) // -vcs_pfet_sel_override = 0 (Override disabled) // Note there is no vcs_pfet_enable_regulation_finger // Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL]being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // Write PFETCNTLSTAT_REG_OR with values defined below // -vdd_pfet_force_state = 01 (Force Voff) // Write to PFETCNTLSTAT_REG_CLR // -vdd_pfet_val_override = 0 (Override disabled) // -vdd_pfet_sel_override = 0 (Override disabled) // -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM) // Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL] being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // // NOTE: // For EQ supports: VDD,VCS,BOTH // For EC & EX supports: VDD only. VCS returns an error. BOTH reports a warning that only VDD was controlled. // EX target only powers OFF the two cores associated with that 'half' of the quad. // // Procedure Prereq: // - System clocks are running // // @endverbatim //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_common_poweronoff.H> #include <p9_common_poweronoff.C> #include <p9_pm_pfet_control.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Global variables //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /// /// @brief Enable power on/off for core and cache chiplets /// /// @param [in] i_target Target type Core/EQ/Ex chiplet /// @param [in] i_rail Valid rail options:BOTH/VDD/VCS /// @param [in] i_op Valid options:OFF/ON /// /// @return FAPI2_RC_SUCCESS on success, error otherwise. /// template <fapi2::TargetType K > static fapi2::ReturnCode pfet_ctrl( const fapi2::Target< K >& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op); // Procedure pfet control-EQ entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_eq( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; uint32_t l_unit_pos = 0; bool core_target_found = false; FAPI_INF("p9_pm_pfet_control_eq: Entering..."); // Get chiplet position l_unit_pos = i_target.getChipletNumber(); FAPI_INF("pfet control for EQ chiplet %d", l_unit_pos); // When i_op == OFF all functional cores first followed by EQ // When i_op == ON EQ first followed by all functional cores if(i_op == PM_PFET_TYPE_C::ON) { FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target, i_rail, i_op), "Error: pfet_ctrl for eq!!"); } // Check for all core chiplets in EQ and power on/off targets accordingly for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL)) { l_unit_pos = l_core_target.getChipletNumber(); FAPI_INF("Core chiplet %d in EQ", l_unit_pos); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); core_target_found = true; } // Power on/off EQ target if( (i_op == PM_PFET_TYPE_C::OFF) && (core_target_found) ) { FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target, i_rail, i_op), "Error: pfet_ctrl for eq!!"); } else if( ((i_op == PM_PFET_TYPE_C::ON) && !(core_target_found)) || ((i_op == PM_PFET_TYPE_C::OFF) && !(core_target_found)) ) { FAPI_INF("EQ chiplet no. %d; No core target found in functional state in this EQ\n", l_unit_pos); } FAPI_INF("p9_pm_pfet_control_eq: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_eq // Procedure pfet control-EX entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_ex( const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; uint32_t l_unit_pos = 0; bool core_target_found = false; FAPI_INF("p9_pm_pfet_control_ex: Entering..."); // Get chiplet position l_unit_pos = i_target.getChipletNumber(); FAPI_INF("pfet control for EX chiplet %d", l_unit_pos); // Check for all core chiplets in EX and power on/off targets accordingly for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL)) { l_unit_pos = l_core_target.getChipletNumber(); FAPI_INF("Core chiplet %d in EX", l_unit_pos); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); core_target_found = true; } // When no functional chiplet target found if(!core_target_found) { FAPI_INF("EX chiplet no. %d; No core target found in functional state in this EX\n", l_unit_pos); } FAPI_INF("p9_pm_pfet_control_ex: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_ex // Procedure pfet control-Core entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_ec( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; FAPI_INF("p9_pm_pfet_control_core: Entering..."); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(i_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); FAPI_INF("p9_pm_pfet_control_core: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_ec //------------------------------------------------------------------------------ // pfet_ctrl: // Function to power on/off core and cache chiplets //------------------------------------------------------------------------------ template <fapi2::TargetType K > fapi2::ReturnCode pfet_ctrl( const fapi2::Target< K >& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; uint32_t l_unit_pos = 0; FAPI_INF("pfet_ctrl: Entering..."); // Get chiplet position l_unit_pos = i_target.getChipletNumber(); // Check for target passed if(i_target.getType() & fapi2::TARGET_TYPE_CORE) { FAPI_INF("pfet control for Core chiplet %d", l_unit_pos); } else if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_INF("pfet control for EQ chiplet %d", l_unit_pos); } else { // Invalid chiplet selected FAPI_ASSERT(false, fapi2::PFET_CTRL_INVALID_CHIPLET_ERROR() .set_TARGET(i_target), "ERROR: Invalid chiplet selected"); } switch(i_op) { case PM_PFET_TYPE_C::OFF: switch(i_rail) { case PM_PFET_TYPE_C::BOTH: if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF)); } else { FAPI_IMP("WARNING:Only VDD (not BOTH/VCS) is controlled for target Core & EX"); FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD)); } break; case PM_PFET_TYPE_C::VDD: FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD)); break; case PM_PFET_TYPE_C::VCS: FAPI_IMP("WARNING:Only VDD or both VDD/VCS controlled for target Core/EX & Cache respectively"); break; } break; case PM_PFET_TYPE_C::ON: switch(i_rail) { case PM_PFET_TYPE_C::BOTH: if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON)); } else { FAPI_IMP("WARNING:Only VDD (not BOTH/VCS) is controlled for target Core & EX"); FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD)); } break; case PM_PFET_TYPE_C::VDD: FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD)); break; case PM_PFET_TYPE_C::VCS: FAPI_IMP("WARNING:Only VDD or both VDD/VCS controlled for target Core/EX & Cache respectively"); break; } break; } fapi_try_exit: return fapi2::current_err; } <commit_msg>Solve compilation issues when FAPI_INF is disabled<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_pfet_control.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2017 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_pfet_control.C /// @brief Enable PFET devices to power on/off all enabled Core and Cache /// chiplets in target passed. /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sumit Kumar <[email protected]> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : OCC:CME:FSP //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // PFET Control // Power-on via Hardare FSM: // ------------------------ // VDD first, VCS second // Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000. // Write PFETCNTLSTAT_REG with values defined below // -vdd_pfet_force_state = 11 (Force Von) // -vdd_pfet_val_override = 0 (Override disabled) // -vdd_pfet_sel_override = 0 (Override disabled) // -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM) // Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL]being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // Write PFETCNTLSTAT_REG_OR with values defined below // -vcs_pfet_force_state = 11 (Force Von) // Write to PFETCNTLSTAT_REG_CLR // -vcs_pfet_val_override = 0 (Override disabled) // -vcs_pfet_sel_override = 0 (Override disabled) // Note there is no vcs_pfet_enable_regulation_finger // Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL] being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // // Power-off via Hardare FSM: // ------------------------- // VCS first, VDD second // Read PFETCNTLSTAT_REG and check for bits 0:3 being 0b0000. // Write PFETCNTLSTAT_REG with values defined below // -vcs_pfet_force_state = 01 (Force Voff) // -vcs_pfet_val_override = 0 (Override disabled) // -vcs_pfet_sel_override = 0 (Override disabled) // Note there is no vcs_pfet_enable_regulation_finger // Poll for PFETCNTLSTAT_REG[VCS_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VCS_PG_SEL]being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vcs_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // Write PFETCNTLSTAT_REG_OR with values defined below // -vdd_pfet_force_state = 01 (Force Voff) // Write to PFETCNTLSTAT_REG_CLR // -vdd_pfet_val_override = 0 (Override disabled) // -vdd_pfet_sel_override = 0 (Override disabled) // -vdd_pfet_enable_regulation_finger = 0 (Regulation finger controlled by FSM) // Poll for PFETCNTLSTAT_REG[VDD_PG_STATE] for 0b1000 (FSM idle)-Timeout value = 1ms // (Optional) Check PFETCNTLSTAT_REG[VDD_PG_SEL] being 0x8 (Off encode point) // Write PFETCNTLSTAT_REG_WCLEAR // -vdd_pfet_force_state = 00 (No Operation);all fields set to 1 for WAND // // NOTE: // For EQ supports: VDD,VCS,BOTH // For EC & EX supports: VDD only. VCS returns an error. BOTH reports a warning that only VDD was controlled. // EX target only powers OFF the two cores associated with that 'half' of the quad. // // Procedure Prereq: // - System clocks are running // // @endverbatim //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_common_poweronoff.H> #include <p9_common_poweronoff.C> #include <p9_pm_pfet_control.H> //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Global variables //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ /// /// @brief Enable power on/off for core and cache chiplets /// /// @param [in] i_target Target type Core/EQ/Ex chiplet /// @param [in] i_rail Valid rail options:BOTH/VDD/VCS /// @param [in] i_op Valid options:OFF/ON /// /// @return FAPI2_RC_SUCCESS on success, error otherwise. /// template <fapi2::TargetType K > static fapi2::ReturnCode pfet_ctrl( const fapi2::Target< K >& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op); // Procedure pfet control-EQ entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_eq( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; bool core_target_found = false; FAPI_INF("p9_pm_pfet_control_eq: Entering..."); // Print chiplet position FAPI_INF("pfet control for EQ chiplet %d", i_target.getChipletNumber()); // When i_op == OFF all functional cores first followed by EQ // When i_op == ON EQ first followed by all functional cores if(i_op == PM_PFET_TYPE_C::ON) { FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target, i_rail, i_op), "Error: pfet_ctrl for eq!!"); } // Check for all core chiplets in EQ and power on/off targets accordingly for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_INF("Core chiplet %d in EQ", l_core_target.getChipletNumber()); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); core_target_found = true; } // Power on/off EQ target if( (i_op == PM_PFET_TYPE_C::OFF) && (core_target_found) ) { FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_EQ>(i_target, i_rail, i_op), "Error: pfet_ctrl for eq!!"); } else if( ((i_op == PM_PFET_TYPE_C::ON) && !(core_target_found)) || ((i_op == PM_PFET_TYPE_C::OFF) && !(core_target_found)) ) { FAPI_INF("EQ chiplet no. %d; No core target found in functional state in this EQ\n", i_target.getChipletNumber()); } FAPI_INF("p9_pm_pfet_control_eq: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_eq // Procedure pfet control-EX entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_ex( const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; bool core_target_found = false; FAPI_INF("p9_pm_pfet_control_ex: Entering..."); // Get chiplet position FAPI_INF("pfet control for EX chiplet %d", i_target.getChipletNumber()); // Check for all core chiplets in EX and power on/off targets accordingly for (auto& l_core_target : i_target.getChildren<fapi2::TARGET_TYPE_CORE> (fapi2::TARGET_STATE_FUNCTIONAL)) { FAPI_INF("Core chiplet %d in EX", l_core_target.getChipletNumber()); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(l_core_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); core_target_found = true; } // When no functional chiplet target found if(!core_target_found) { FAPI_INF("EX chiplet no. %d; No core target found in functional state" " in this EX", i_target.getChipletNumber()); } FAPI_INF("p9_pm_pfet_control_ex: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_ex // Procedure pfet control-Core entry point, comments in header fapi2::ReturnCode p9_pm_pfet_control_ec( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; FAPI_INF("p9_pm_pfet_control_core: Entering..."); FAPI_TRY(pfet_ctrl<fapi2::TargetType::TARGET_TYPE_CORE>(i_target, i_rail, i_op), "Error: pfet_ctrl for core!!"); FAPI_INF("p9_pm_pfet_control_core: ...Exiting"); fapi_try_exit: return fapi2::current_err; } //p9_pm_pfet_control_ec //------------------------------------------------------------------------------ // pfet_ctrl: // Function to power on/off core and cache chiplets //------------------------------------------------------------------------------ template <fapi2::TargetType K > fapi2::ReturnCode pfet_ctrl( const fapi2::Target< K >& i_target, const PM_PFET_TYPE_C::pfet_rail_t i_rail, const PM_PFET_TYPE_C::pfet_force_t i_op) { fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; FAPI_INF("pfet_ctrl: Entering..."); // Check for target passed if(i_target.getType() & fapi2::TARGET_TYPE_CORE) { FAPI_INF("pfet control for Core chiplet %d", i_target.getChipletNumber()); } else if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_INF("pfet control for EQ chiplet %d", i_target.getChipletNumber()); } else { // Invalid chiplet selected FAPI_ASSERT(false, fapi2::PFET_CTRL_INVALID_CHIPLET_ERROR() .set_TARGET(i_target), "ERROR: Invalid chiplet selected"); } switch(i_op) { case PM_PFET_TYPE_C::OFF: switch(i_rail) { case PM_PFET_TYPE_C::BOTH: if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF)); } else { FAPI_IMP("WARNING:Only VDD (not BOTH/VCS) is controlled for target Core & EX"); FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD)); } break; case PM_PFET_TYPE_C::VDD: FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_OFF_VDD)); break; case PM_PFET_TYPE_C::VCS: FAPI_IMP("WARNING:Only VDD or both VDD/VCS controlled for target Core/EX & Cache respectively"); break; } break; case PM_PFET_TYPE_C::ON: switch(i_rail) { case PM_PFET_TYPE_C::BOTH: if(i_target.getType() & fapi2::TARGET_TYPE_EQ) { FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON)); } else { FAPI_IMP("WARNING:Only VDD (not BOTH/VCS) is controlled for target Core & EX"); FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD)); } break; case PM_PFET_TYPE_C::VDD: FAPI_TRY(p9_common_poweronoff(i_target, p9power::POWER_ON_VDD)); break; case PM_PFET_TYPE_C::VCS: FAPI_IMP("WARNING:Only VDD or both VDD/VCS controlled for target Core/EX & Cache respectively"); break; } break; } fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>/* This file is part of Akregator. Copyright (C) 2008 Frank Osterfeld <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "createfeedcommand.h" #include "addfeeddialog.h" #include "feed.h" #include "feedpropertiesdialog.h" #include "folder.h" #include "subscriptionlistview.h" #include <KInputDialog> #include <KLocalizedString> #include <KUrl> #include <QPointer> #include <QTimer> #include <cassert> using namespace Akregator; class CreateFeedCommand::Private { CreateFeedCommand* const q; public: explicit Private( CreateFeedCommand* qq ); void doCreate(); QPointer<Folder> m_rootFolder; QPointer<SubscriptionListView> m_subscriptionListView; QString m_url; QPointer<Folder> m_parentFolder; QPointer<TreeNode> m_after; bool m_autoexec; }; CreateFeedCommand::Private::Private( CreateFeedCommand* qq ) : q( qq ), m_rootFolder( 0 ), m_subscriptionListView( 0 ), m_parentFolder( 0 ), m_after( 0 ), m_autoexec( false ) { } void CreateFeedCommand::Private::doCreate() { assert( m_rootFolder ); assert( m_subscriptionListView ); QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" ); afd->setUrl( KUrl::fromPercentEncoding( m_url.toLatin1() ) ); QPointer<QObject> thisPointer( q ); if ( m_autoexec ) afd->accept(); else afd->exec(); if ( !thisPointer ) // "this" might have been deleted while exec()! return; Feed* const feed = afd->feed(); delete afd; if ( !feed ) { q->done(); return; } QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" ); dlg->setFeed( feed ); dlg->selectFeedName(); if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) ) { delete feed; } else { m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder; m_parentFolder->insertChild( feed, m_after ); m_subscriptionListView->ensureNodeVisible( feed ); } delete dlg; q->done(); } CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) ) { } CreateFeedCommand::~CreateFeedCommand() { delete d; } void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view ) { d->m_subscriptionListView = view; } void CreateFeedCommand::setRootFolder( Folder* rootFolder ) { d->m_rootFolder = rootFolder; } void CreateFeedCommand::setUrl( const QString& url ) { d->m_url = url; } void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after ) { d->m_parentFolder = parent; d->m_after = after; } void CreateFeedCommand::setAutoExecute( bool autoexec ) { d->m_autoexec = autoexec; } void CreateFeedCommand::doStart() { QTimer::singleShot( 0, this, SLOT( doCreate() ) ); } void CreateFeedCommand::doAbort() { } #include "createfeedcommand.moc" <commit_msg>Paste clipboard contents in add feed dlg if it is a valid URL Patch by Jordi De Groof, jordi.degroof at gmail.com BUG:111214<commit_after>/* This file is part of Akregator. Copyright (C) 2008 Frank Osterfeld <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "createfeedcommand.h" #include "addfeeddialog.h" #include "feed.h" #include "feedpropertiesdialog.h" #include "folder.h" #include "subscriptionlistview.h" #include <KInputDialog> #include <KLocalizedString> #include <KUrl> #include <QPointer> #include <QTimer> #include <QClipboard> #include <cassert> using namespace Akregator; class CreateFeedCommand::Private { CreateFeedCommand* const q; public: explicit Private( CreateFeedCommand* qq ); void doCreate(); QPointer<Folder> m_rootFolder; QPointer<SubscriptionListView> m_subscriptionListView; QString m_url; QPointer<Folder> m_parentFolder; QPointer<TreeNode> m_after; bool m_autoexec; }; CreateFeedCommand::Private::Private( CreateFeedCommand* qq ) : q( qq ), m_rootFolder( 0 ), m_subscriptionListView( 0 ), m_parentFolder( 0 ), m_after( 0 ), m_autoexec( false ) { } void CreateFeedCommand::Private::doCreate() { assert( m_rootFolder ); assert( m_subscriptionListView ); QPointer<AddFeedDialog> afd = new AddFeedDialog( q->parentWidget(), "add_feed" ); QString url = m_url; if( url.isEmpty() ) { const QClipboard* const clipboard = QApplication::clipboard(); assert( clipboard ); const QString clipboardText = clipboard->text(); // Check for the hostname, since the isValid method is not strict enough if( !KUrl( clipboardText ).isEmpty() ) url = clipboardText; } afd->setUrl( KUrl::fromPercentEncoding( url.toLatin1() ) ); QPointer<QObject> thisPointer( q ); if ( m_autoexec ) afd->accept(); else afd->exec(); if ( !thisPointer ) // "this" might have been deleted while exec()! return; Feed* const feed = afd->feed(); delete afd; if ( !feed ) { q->done(); return; } QPointer<FeedPropertiesDialog> dlg = new FeedPropertiesDialog( q->parentWidget(), "edit_feed" ); dlg->setFeed( feed ); dlg->selectFeedName(); if ( !m_autoexec && ( dlg->exec() != QDialog::Accepted || !thisPointer ) ) { delete feed; } else { m_parentFolder = m_parentFolder ? m_parentFolder : m_rootFolder; m_parentFolder->insertChild( feed, m_after ); m_subscriptionListView->ensureNodeVisible( feed ); } delete dlg; q->done(); } CreateFeedCommand::CreateFeedCommand( QObject* parent ) : Command( parent ), d( new Private( this ) ) { } CreateFeedCommand::~CreateFeedCommand() { delete d; } void CreateFeedCommand::setSubscriptionListView( SubscriptionListView* view ) { d->m_subscriptionListView = view; } void CreateFeedCommand::setRootFolder( Folder* rootFolder ) { d->m_rootFolder = rootFolder; } void CreateFeedCommand::setUrl( const QString& url ) { d->m_url = url; } void CreateFeedCommand::setPosition( Folder* parent, TreeNode* after ) { d->m_parentFolder = parent; d->m_after = after; } void CreateFeedCommand::setAutoExecute( bool autoexec ) { d->m_autoexec = autoexec; } void CreateFeedCommand::doStart() { QTimer::singleShot( 0, this, SLOT( doCreate() ) ); } void CreateFeedCommand::doAbort() { } #include "createfeedcommand.moc" <|endoftext|>
<commit_before>#include "akregatorconfig.h" #include "settings_advanced.h" #include "storagefactory.h" #include "storagefactoryregistry.h" #include <QPushButton> #include <QStringList> #include <QWidget> #include <kcombobox.h> namespace Akregator { SettingsAdvanced::SettingsAdvanced(QWidget* parent, const char* name) : QWidget(parent) { setObjectName(name); setupUi(this); QStringList backends = Backend::StorageFactoryRegistry::self()->list(); QString tname; int i = 0; QStringList::Iterator end( backends.end() ); for (QStringList::Iterator it = backends.begin(); it != end; ++it) { m_factories[i] = Backend::StorageFactoryRegistry::self()->getFactory(*it); m_keyPos[m_factories[i]->key()] = i; cbBackend->addItem(m_factories[i]->name()); i++; } connect(pbBackendConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureStorage())); connect(cbBackend, SIGNAL(activated(int)), this, SLOT(slotFactorySelected(int))); } QString SettingsAdvanced::selectedFactory() const { return m_factories[cbBackend->currentIndex()]->key(); } void SettingsAdvanced::selectFactory(const QString& key) { cbBackend->setCurrentIndex(m_keyPos[key]); pbBackendConfigure->setEnabled((m_factories[m_keyPos[key]]->isConfigurable())); } void SettingsAdvanced::slotConfigureStorage() { m_factories[cbBackend->currentIndex()]->configure(); } void SettingsAdvanced::slotFactorySelected(int pos) { pbBackendConfigure->setEnabled(m_factories[pos]->isConfigurable()); } } //namespace Akregator #include "settings_advanced.moc" <commit_msg>Fix crash when backend doesn't exist<commit_after>#include "akregatorconfig.h" #include "settings_advanced.h" #include "storagefactory.h" #include "storagefactoryregistry.h" #include <QPushButton> #include <QStringList> #include <QWidget> #include <kcombobox.h> namespace Akregator { SettingsAdvanced::SettingsAdvanced(QWidget* parent, const char* name) : QWidget(parent) { setObjectName(name); setupUi(this); QStringList backends = Backend::StorageFactoryRegistry::self()->list(); QString tname; int i = 0; QStringList::Iterator end( backends.end() ); for (QStringList::Iterator it = backends.begin(); it != end; ++it) { m_factories[i] = Backend::StorageFactoryRegistry::self()->getFactory(*it); if(m_factories[i]) { m_keyPos[m_factories[i]->key()] = i; cbBackend->addItem(m_factories[i]->name()); } i++; } connect(pbBackendConfigure, SIGNAL(clicked()), this, SLOT(slotConfigureStorage())); connect(cbBackend, SIGNAL(activated(int)), this, SLOT(slotFactorySelected(int))); } QString SettingsAdvanced::selectedFactory() const { return m_factories[cbBackend->currentIndex()]->key(); } void SettingsAdvanced::selectFactory(const QString& key) { cbBackend->setCurrentIndex(m_keyPos[key]); pbBackendConfigure->setEnabled((m_factories[m_keyPos[key]]->isConfigurable())); } void SettingsAdvanced::slotConfigureStorage() { m_factories[cbBackend->currentIndex()]->configure(); } void SettingsAdvanced::slotFactorySelected(int pos) { pbBackendConfigure->setEnabled(m_factories[pos]->isConfigurable()); } } //namespace Akregator #include "settings_advanced.moc" <|endoftext|>
<commit_before>#ifndef ENUMERABLE__H__ #define ENUMERABLE__H__ #include "iterbase.hpp" #include <utility> #include <iterator> #include <functional> #include <initializer_list> // enumerate functionality for python-style for-each enumerate loops // for (auto e : enumerate(vec)) { // std::cout << e.index // << ": " // << e.element // << '\n'; // } namespace iter { //Forward declarations of Enumerable and enumerate template <typename Container> class Enumerable; template <typename T> Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); template <typename Container> Enumerable<Container> enumerate(Container &&); template <typename Container> class Enumerable { private: Container & container; // The only thing allowed to directly instantiate an Enumerable is // the enumerate function friend Enumerable enumerate<Container>(Container &&); template <typename T> friend Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); using IterDef = IterBase<Container>; Enumerable(Container && container) : container(container) { } public: // Value constructor for use only in the enumerate function Enumerable () = delete; Enumerable & operator=(const Enumerable &) = delete; Enumerable(const Enumerable &) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield { public: std::size_t index; typename IterDef::contained_iter_ret element; IterYield(std::size_t i, typename IterDef::contained_iter_ret elem): index(i), element(elem) { } }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator { private: typename IterDef::contained_iter_type sub_iter; std::size_t index; public: Iterator (typename IterDef::contained_iter_type si) : sub_iter(si), index(0) { } IterYield operator*() const { return IterYield(this->index, *this->sub_iter); } Iterator & operator++() { ++this->sub_iter; ++this->index; return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator(std::begin(this->container)); } Iterator end() const { return Iterator(std::end(this->container)); } }; // Helper function to instantiate an Enumerable template <typename Container> Enumerable<Container> enumerate(Container && container) { return Enumerable<Container>(std::forward<Container>(container)); } template <typename T> Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il) { return Enumerable<std::initializer_list<T>>(std::move(il)); } } #endif //ifndef ENUMERABLE__H__ <commit_msg>flattens with explicit using<commit_after>#ifndef ENUMERABLE__H__ #define ENUMERABLE__H__ #include "iterbase.hpp" #include <utility> #include <iterator> #include <functional> #include <initializer_list> // enumerate functionality for python-style for-each enumerate loops // for (auto e : enumerate(vec)) { // std::cout << e.index // << ": " // << e.element // << '\n'; // } namespace iter { //Forward declarations of Enumerable and enumerate template <typename Container> class Enumerable; template <typename T> Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); template <typename Container> Enumerable<Container> enumerate(Container &&); template <typename Container> class Enumerable { private: Container & container; // The only thing allowed to directly instantiate an Enumerable is // the enumerate function friend Enumerable enumerate<Container>(Container &&); template <typename T> friend Enumerable<std::initializer_list<T>> enumerate( std::initializer_list<T> &&); using contained_iter_ret = typename IterBase<Container>::contained_iter_ret; using contained_iter_type = typename IterBase<Container>::contained_iter_type; Enumerable(Container && container) : container(container) { } public: // Value constructor for use only in the enumerate function Enumerable () = delete; Enumerable & operator=(const Enumerable &) = delete; Enumerable(const Enumerable &) = default; // "yielded" by the Enumerable::Iterator. Has a .index, and a // .element referencing the value yielded by the subiterator class IterYield { public: std::size_t index; contained_iter_ret element; IterYield(std::size_t i, contained_iter_ret elem): index(i), element(elem) { } }; // Holds an iterator of the contained type and a size_t for the // index. Each call to ++ increments both of these data members. // Each dereference returns an IterYield. class Iterator { private: contained_iter_type sub_iter; std::size_t index; public: Iterator (contained_iter_type si) : sub_iter(si), index(0) { } IterYield operator*() const { return IterYield(this->index, *this->sub_iter); } Iterator & operator++() { ++this->sub_iter; ++this->index; return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter; } }; Iterator begin() const { return Iterator(std::begin(this->container)); } Iterator end() const { return Iterator(std::end(this->container)); } }; // Helper function to instantiate an Enumerable template <typename Container> Enumerable<Container> enumerate(Container && container) { return Enumerable<Container>(std::forward<Container>(container)); } template <typename T> Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il) { return Enumerable<std::initializer_list<T>>(std::move(il)); } } #endif //ifndef ENUMERABLE__H__ <|endoftext|>
<commit_before>#include <iostream> void distinct_permute( int main() { } <commit_msg>combinatorics: Removed all distinct permutation generator - missing implementation.<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/debug.hpp> #include <mapnik/image_reader.hpp> #include <mapnik/noncopyable.hpp> extern "C" { #include <png.h> } #include <boost/scoped_array.hpp> namespace mapnik { class png_reader : public image_reader, mapnik::noncopyable { private: std::string fileName_; unsigned width_; unsigned height_; int bit_depth_; int color_type_; public: explicit png_reader(std::string const& fileName); ~png_reader(); unsigned width() const; unsigned height() const; bool premultiplied_alpha() const { return false; } //http://www.libpng.org/pub/png/spec/1.1/PNG-Rationale.html void read(unsigned x,unsigned y,image_data_32& image); private: void init(); }; namespace { image_reader* create_png_reader(std::string const& file) { return new png_reader(file); } const bool registered = register_image_reader("png",create_png_reader); } png_reader::png_reader(std::string const& fileName) : fileName_(fileName), width_(0), height_(0), bit_depth_(0), color_type_(0) { init(); } png_reader::~png_reader() {} void user_error_fn(png_structp png_ptr, png_const_charp error_msg) { throw image_reader_exception("failed to read invalid png"); } void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg) { MAPNIK_LOG_DEBUG(png_reader) << "libpng warning: '" << warning_msg << "'"; } static void png_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { png_size_t check; check = (png_size_t)fread(data, (png_size_t)1, length, (FILE *)png_get_io_ptr(png_ptr)); if (check != length) { png_error(png_ptr, "Read Error"); } } void png_reader::init() { FILE *fp=fopen(fileName_.c_str(),"rb"); if (!fp) throw image_reader_exception("cannot open image file "+fileName_); png_byte header[8]; memset(header,0,8); if ( fread(header,1,8,fp) != 8) { fclose(fp); throw image_reader_exception("Could not read " + fileName_); } int is_png=!png_sig_cmp(header,0,8); if (!is_png) { fclose(fp); throw image_reader_exception(fileName_ + " is not a png file"); } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { fclose(fp); throw image_reader_exception("failed to allocate png_ptr"); } // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); png_infop info_ptr; try { info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw image_reader_exception("failed to create info_ptr"); } } catch (std::exception const& ex) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw; } png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data); png_set_sig_bytes(png_ptr,8); png_read_info(png_ptr, info_ptr); png_uint_32 width, height; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0); width_=width; height_=height; MAPNIK_LOG_DEBUG(png_reader) << "png_reader: bit_depth=" << bit_depth_ << ",color_type=" << color_type_; png_destroy_read_struct(&png_ptr,&info_ptr,0); fclose(fp); } unsigned png_reader::width() const { return width_; } unsigned png_reader::height() const { return height_; } void png_reader::read(unsigned x0, unsigned y0,image_data_32& image) { FILE *fp=fopen(fileName_.c_str(),"rb"); if (!fp) throw image_reader_exception("cannot open image file "+fileName_); png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { fclose(fp); throw image_reader_exception("failed to allocate png_ptr"); } // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); png_infop info_ptr; try { info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw image_reader_exception("failed to create info_ptr"); } } catch (std::exception const& ex) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw; } png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data); png_read_info(png_ptr, info_ptr); if (color_type_ == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); if (bit_depth_ == 16) png_set_strip_16(png_ptr); if (color_type_ == PNG_COLOR_TYPE_GRAY || color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); // quick hack -- only work in >=libpng 1.2.7 png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); //rgba double gamma; if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, 2.2, gamma); if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_) { if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7) { png_set_interlace_handling(png_ptr); // FIXME: libpng bug? // according to docs png_read_image // "..automatically handles interlacing, // so you don't need to call png_set_interlace_handling()" } png_read_update_info(png_ptr, info_ptr); // we can read whole image at once // alloc row pointers boost::scoped_array<png_byte*> rows(new png_bytep[height_]); for (unsigned i=0; i<height_; ++i) rows[i] = (png_bytep)image.getRow(i); png_read_image(png_ptr, rows.get()); } else { png_read_update_info(png_ptr, info_ptr); unsigned w=std::min(unsigned(image.width()),width_); unsigned h=std::min(unsigned(image.height()),height_); unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr); boost::scoped_array<png_byte> row(new png_byte[rowbytes]); //START read image rows for (unsigned i=0;i<height_;++i) { png_read_row(png_ptr,row.get(),0); if (i>=y0 && i<h) { image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0]),w); } } //END } png_read_end(png_ptr,0); png_destroy_read_struct(&png_ptr, &info_ptr,0); fclose(fp); } } <commit_msg>+ fix region reading, so png's can be used in raster.input<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <mapnik/debug.hpp> #include <mapnik/image_reader.hpp> #include <mapnik/noncopyable.hpp> extern "C" { #include <png.h> } #include <boost/scoped_array.hpp> namespace mapnik { class png_reader : public image_reader, mapnik::noncopyable { private: std::string fileName_; unsigned width_; unsigned height_; int bit_depth_; int color_type_; public: explicit png_reader(std::string const& fileName); ~png_reader(); unsigned width() const; unsigned height() const; bool premultiplied_alpha() const { return false; } //http://www.libpng.org/pub/png/spec/1.1/PNG-Rationale.html void read(unsigned x,unsigned y,image_data_32& image); private: void init(); }; namespace { image_reader* create_png_reader(std::string const& file) { return new png_reader(file); } const bool registered = register_image_reader("png",create_png_reader); } png_reader::png_reader(std::string const& fileName) : fileName_(fileName), width_(0), height_(0), bit_depth_(0), color_type_(0) { init(); } png_reader::~png_reader() {} void user_error_fn(png_structp png_ptr, png_const_charp error_msg) { throw image_reader_exception("failed to read invalid png"); } void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg) { MAPNIK_LOG_DEBUG(png_reader) << "libpng warning: '" << warning_msg << "'"; } static void png_read_data(png_structp png_ptr, png_bytep data, png_size_t length) { png_size_t check; check = (png_size_t)fread(data, (png_size_t)1, length, (FILE *)png_get_io_ptr(png_ptr)); if (check != length) { png_error(png_ptr, "Read Error"); } } void png_reader::init() { FILE *fp=fopen(fileName_.c_str(),"rb"); if (!fp) throw image_reader_exception("cannot open image file "+fileName_); png_byte header[8]; memset(header,0,8); if ( fread(header,1,8,fp) != 8) { fclose(fp); throw image_reader_exception("Could not read " + fileName_); } int is_png=!png_sig_cmp(header,0,8); if (!is_png) { fclose(fp); throw image_reader_exception(fileName_ + " is not a png file"); } png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { fclose(fp); throw image_reader_exception("failed to allocate png_ptr"); } // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); png_infop info_ptr; try { info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw image_reader_exception("failed to create info_ptr"); } } catch (std::exception const& ex) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw; } png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data); png_set_sig_bytes(png_ptr,8); png_read_info(png_ptr, info_ptr); png_uint_32 width, height; png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth_, &color_type_,0,0,0); width_=width; height_=height; MAPNIK_LOG_DEBUG(png_reader) << "png_reader: bit_depth=" << bit_depth_ << ",color_type=" << color_type_; png_destroy_read_struct(&png_ptr,&info_ptr,0); fclose(fp); } unsigned png_reader::width() const { return width_; } unsigned png_reader::height() const { return height_; } void png_reader::read(unsigned x0, unsigned y0,image_data_32& image) { FILE *fp=fopen(fileName_.c_str(),"rb"); if (!fp) throw image_reader_exception("cannot open image file "+fileName_); png_structp png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING,0,0,0); if (!png_ptr) { fclose(fp); throw image_reader_exception("failed to allocate png_ptr"); } // catch errors in a custom way to avoid the need for setjmp png_set_error_fn(png_ptr, png_get_error_ptr(png_ptr), user_error_fn, user_warning_fn); png_infop info_ptr; try { info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw image_reader_exception("failed to create info_ptr"); } } catch (std::exception const& ex) { png_destroy_read_struct(&png_ptr,0,0); fclose(fp); throw; } png_set_read_fn(png_ptr, (png_voidp)fp, png_read_data); png_read_info(png_ptr, info_ptr); if (color_type_ == PNG_COLOR_TYPE_PALETTE) png_set_expand(png_ptr); if (color_type_ == PNG_COLOR_TYPE_GRAY && bit_depth_ < 8) png_set_expand(png_ptr); if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_expand(png_ptr); if (bit_depth_ == 16) png_set_strip_16(png_ptr); if (color_type_ == PNG_COLOR_TYPE_GRAY || color_type_ == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png_ptr); // quick hack -- only work in >=libpng 1.2.7 png_set_add_alpha(png_ptr,0xff,PNG_FILLER_AFTER); //rgba double gamma; if (png_get_gAMA(png_ptr, info_ptr, &gamma)) png_set_gamma(png_ptr, 2.2, gamma); if (x0 == 0 && y0 == 0 && image.width() >= width_ && image.height() >= height_) { if (png_get_interlace_type(png_ptr,info_ptr) == PNG_INTERLACE_ADAM7) { png_set_interlace_handling(png_ptr); // FIXME: libpng bug? // according to docs png_read_image // "..automatically handles interlacing, // so you don't need to call png_set_interlace_handling()" } png_read_update_info(png_ptr, info_ptr); // we can read whole image at once // alloc row pointers boost::scoped_array<png_byte*> rows(new png_bytep[height_]); for (unsigned i=0; i<height_; ++i) rows[i] = (png_bytep)image.getRow(i); png_read_image(png_ptr, rows.get()); } else { png_read_update_info(png_ptr, info_ptr); unsigned w=std::min(unsigned(image.width()),width_ - x0); unsigned h=std::min(unsigned(image.height()),height_ - y0); unsigned rowbytes=png_get_rowbytes(png_ptr, info_ptr); boost::scoped_array<png_byte> row(new png_byte[rowbytes]); //START read image rows for (unsigned i = 0;i < height_; ++i) { png_read_row(png_ptr,row.get(),0); if (i >= y0 && i < (y0 + h)) { image.setRow(i-y0,reinterpret_cast<unsigned*>(&row[x0 * 4]),w); } } //END } png_read_end(png_ptr,0); png_destroy_read_struct(&png_ptr, &info_ptr,0); fclose(fp); } } <|endoftext|>
<commit_before>/************************************************************************* * * 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: newppdlg.cxx,v $ * $Revision: 1.15 $ * * 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. * ************************************************************************/ #include <stdio.h> #include <unistd.h> #include <psprint/ppdparser.hxx> #include <psprint/helper.hxx> #include <vcl/svapp.hxx> #include <vcl/mnemonic.hxx> #include <tools/urlobj.hxx> #ifndef __SGI_STL_LIST #include <list> #endif #include <osl/file.hxx> #include <helper.hxx> #ifndef _PAD_PADIALOG_HRC_ #include <padialog.hrc> #endif #include <newppdlg.hxx> #include <padialog.hxx> #include <progress.hxx> #define PPDIMPORT_GROUP "PPDImport" using namespace padmin; using namespace psp; using namespace osl; using namespace rtl; PPDImportDialog::PPDImportDialog( Window* pParent ) : ModalDialog( pParent, PaResId( RID_PPDIMPORT_DLG ) ), m_aOKBtn( this, PaResId( RID_PPDIMP_BTN_OK ) ), m_aCancelBtn( this, PaResId( RID_PPDIMP_BTN_CANCEL ) ), m_aPathTxt( this, PaResId( RID_PPDIMP_TXT_PATH ) ), m_aPathBox( this, PaResId( RID_PPDIMP_LB_PATH ) ), m_aSearchBtn( this, PaResId( RID_PPDIMP_BTN_SEARCH ) ), m_aDriverTxt( this, PaResId( RID_PPDIMP_TXT_DRIVER ) ), m_aDriverLB( this, PaResId( RID_PPDIMP_LB_DRIVER ) ), m_aPathGroup( this, PaResId( RID_PPDIMP_GROUP_PATH ) ), m_aDriverGroup( this, PaResId( RID_PPDIMP_GROUP_DRIVER ) ), m_aLoadingPPD( PaResId( RID_PPDIMP_STR_LOADINGPPD ) ) { FreeResource(); String aText( m_aDriverTxt.GetText() ); aText.SearchAndReplaceAscii( "%s", Button::GetStandardText( BUTTON_OK ) ); m_aDriverTxt.SetText( MnemonicGenerator::EraseAllMnemonicChars( aText ) ); Config& rConfig = getPadminRC(); rConfig.SetGroup( PPDIMPORT_GROUP ); m_aPathBox.SetText( String( rConfig.ReadKey( "LastDir" ), RTL_TEXTENCODING_UTF8 ) ); for( int i = 0; i < 11; i++ ) { ByteString aEntry( rConfig.ReadKey( ByteString::CreateFromInt32( i ) ) ); if( aEntry.Len() ) m_aPathBox.InsertEntry( String( aEntry, RTL_TEXTENCODING_UTF8 ) ); } m_aOKBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aCancelBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aSearchBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aPathBox.SetSelectHdl( LINK( this, PPDImportDialog, SelectHdl ) ); m_aPathBox.SetModifyHdl( LINK( this, PPDImportDialog, ModifyHdl ) ); if( m_aPathBox.GetText().Len() ) Import(); } PPDImportDialog::~PPDImportDialog() { while( m_aDriverLB.GetEntryCount() ) { delete (String*)m_aDriverLB.GetEntryData( 0 ); m_aDriverLB.RemoveEntry( 0 ); } } void PPDImportDialog::Import() { String aImportPath( m_aPathBox.GetText() ); Config& rConfig = getPadminRC(); rConfig.SetGroup( PPDIMPORT_GROUP ); rConfig.WriteKey( "LastDir", ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) ); int nEntries = m_aPathBox.GetEntryCount(); while( nEntries-- ) if( aImportPath == m_aPathBox.GetEntry( nEntries ) ) break; if( nEntries < 0 ) { int nNextEntry = rConfig.ReadKey( "NextEntry" ).ToInt32(); rConfig.WriteKey( ByteString::CreateFromInt32( nNextEntry ), ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) ); nNextEntry = nNextEntry < 10 ? nNextEntry+1 : 0; rConfig.WriteKey( "NextEntry", ByteString::CreateFromInt32( nNextEntry ) ); m_aPathBox.InsertEntry( aImportPath ); } while( m_aDriverLB.GetEntryCount() ) { delete (String*)m_aDriverLB.GetEntryData( 0 ); m_aDriverLB.RemoveEntry( 0 ); } ProgressDialog aProgress( Application::GetFocusWindow() ); aProgress.startOperation( m_aLoadingPPD ); ::std::list< String > aFiles; FindFiles( aImportPath, aFiles, String::CreateFromAscii( "PS;PPD" ) ); int i = 0; aProgress.setRange( 0, aFiles.size() ); while( aFiles.size() ) { aProgress.setValue( ++i ); aProgress.setFilename( aFiles.front() ); INetURLObject aPath( aImportPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL ); aPath.Append( aFiles.front() ); String aPrinterName = PPDParser::getPPDPrinterName( aPath.PathToFileName() ); aFiles.pop_front(); if( ! aPrinterName.Len() ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "Warning: File %s has empty printer name.\n", rtl::OUStringToOString( aPath.PathToFileName(), osl_getThreadTextEncoding() ).getStr() ); #endif continue; } USHORT nPos = m_aDriverLB.InsertEntry( aPrinterName ); m_aDriverLB.SetEntryData( nPos, new String( aPath.PathToFileName() ) ); } } IMPL_LINK( PPDImportDialog, ClickBtnHdl, PushButton*, pButton ) { if( pButton == &m_aCancelBtn ) { EndDialog( 0 ); } else if( pButton == &m_aOKBtn ) { // copy the files ::std::list< rtl::OUString > aToDirs; psp::getPrinterPathList( aToDirs, PSPRINT_PPDDIR ); ::std::list< rtl::OUString >::iterator writeDir = aToDirs.begin(); for( int i = 0; i < m_aDriverLB.GetSelectEntryCount(); i++ ) { INetURLObject aFile( *(String*)m_aDriverLB.GetEntryData( m_aDriverLB.GetSelectEntryPos( i ) ), INET_PROT_FILE, INetURLObject::ENCODE_ALL ); OUString aFromUni( aFile.GetMainURL(INetURLObject::DECODE_TO_IURI) ); do { INetURLObject aToFile( *writeDir, INET_PROT_FILE, INetURLObject::ENCODE_ALL ); aToFile.Append( aFile.GetName() ); aToFile.setExtension( String::CreateFromAscii( "PPD" ) ); OUString aToUni( aToFile.GetMainURL(INetURLObject::DECODE_TO_IURI) ); if( ! File::copy( aFromUni, aToUni ) ) break; ++writeDir; } while( writeDir != aToDirs.end() ); } EndDialog( 1 ); } else if( pButton == &m_aSearchBtn ) { String aPath( m_aPathBox.GetText() ); if( chooseDirectory( aPath ) ) { m_aPathBox.SetText( aPath ); Import(); } } return 0; } IMPL_LINK( PPDImportDialog, SelectHdl, ComboBox*, pListBox ) { if( pListBox == &m_aPathBox ) { Import(); } return 0; } IMPL_LINK( PPDImportDialog, ModifyHdl, ComboBox*, pListBox ) { if( pListBox == &m_aPathBox ) { ByteString aDir( m_aPathBox.GetText(), osl_getThreadTextEncoding() ); if( ! access( aDir.GetBuffer(), F_OK ) ) Import(); } return 0; } <commit_msg>INTEGRATION: CWS vcl89 (1.15.4); FILE MERGED 2008/05/07 19:44:47 pl 1.15.4.2: #i72327# support for system ppd dir 2008/05/07 17:40:12 pl 1.15.4.1: #i72327# support for gzipped PPD files<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: newppdlg.cxx,v $ * $Revision: 1.16 $ * * 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. * ************************************************************************/ #include <stdio.h> #include <unistd.h> #include <psprint/ppdparser.hxx> #include <psprint/helper.hxx> #include <vcl/svapp.hxx> #include <vcl/mnemonic.hxx> #include <tools/urlobj.hxx> #ifndef __SGI_STL_LIST #include <list> #endif #include <osl/file.hxx> #include <helper.hxx> #ifndef _PAD_PADIALOG_HRC_ #include <padialog.hrc> #endif #include <newppdlg.hxx> #include <padialog.hxx> #include <progress.hxx> #define PPDIMPORT_GROUP "PPDImport" using namespace padmin; using namespace psp; using namespace osl; using namespace rtl; PPDImportDialog::PPDImportDialog( Window* pParent ) : ModalDialog( pParent, PaResId( RID_PPDIMPORT_DLG ) ), m_aOKBtn( this, PaResId( RID_PPDIMP_BTN_OK ) ), m_aCancelBtn( this, PaResId( RID_PPDIMP_BTN_CANCEL ) ), m_aPathTxt( this, PaResId( RID_PPDIMP_TXT_PATH ) ), m_aPathBox( this, PaResId( RID_PPDIMP_LB_PATH ) ), m_aSearchBtn( this, PaResId( RID_PPDIMP_BTN_SEARCH ) ), m_aDriverTxt( this, PaResId( RID_PPDIMP_TXT_DRIVER ) ), m_aDriverLB( this, PaResId( RID_PPDIMP_LB_DRIVER ) ), m_aPathGroup( this, PaResId( RID_PPDIMP_GROUP_PATH ) ), m_aDriverGroup( this, PaResId( RID_PPDIMP_GROUP_DRIVER ) ), m_aLoadingPPD( PaResId( RID_PPDIMP_STR_LOADINGPPD ) ) { FreeResource(); String aText( m_aDriverTxt.GetText() ); aText.SearchAndReplaceAscii( "%s", Button::GetStandardText( BUTTON_OK ) ); m_aDriverTxt.SetText( MnemonicGenerator::EraseAllMnemonicChars( aText ) ); Config& rConfig = getPadminRC(); rConfig.SetGroup( PPDIMPORT_GROUP ); m_aPathBox.SetText( String( rConfig.ReadKey( "LastDir" ), RTL_TEXTENCODING_UTF8 ) ); for( int i = 0; i < 11; i++ ) { ByteString aEntry( rConfig.ReadKey( ByteString::CreateFromInt32( i ) ) ); if( aEntry.Len() ) m_aPathBox.InsertEntry( String( aEntry, RTL_TEXTENCODING_UTF8 ) ); } m_aOKBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aCancelBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aSearchBtn.SetClickHdl( LINK( this, PPDImportDialog, ClickBtnHdl ) ); m_aPathBox.SetSelectHdl( LINK( this, PPDImportDialog, SelectHdl ) ); m_aPathBox.SetModifyHdl( LINK( this, PPDImportDialog, ModifyHdl ) ); if( m_aPathBox.GetText().Len() ) Import(); } PPDImportDialog::~PPDImportDialog() { while( m_aDriverLB.GetEntryCount() ) { delete (String*)m_aDriverLB.GetEntryData( 0 ); m_aDriverLB.RemoveEntry( 0 ); } } void PPDImportDialog::Import() { String aImportPath( m_aPathBox.GetText() ); Config& rConfig = getPadminRC(); rConfig.SetGroup( PPDIMPORT_GROUP ); rConfig.WriteKey( "LastDir", ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) ); int nEntries = m_aPathBox.GetEntryCount(); while( nEntries-- ) if( aImportPath == m_aPathBox.GetEntry( nEntries ) ) break; if( nEntries < 0 ) { int nNextEntry = rConfig.ReadKey( "NextEntry" ).ToInt32(); rConfig.WriteKey( ByteString::CreateFromInt32( nNextEntry ), ByteString( aImportPath, RTL_TEXTENCODING_UTF8 ) ); nNextEntry = nNextEntry < 10 ? nNextEntry+1 : 0; rConfig.WriteKey( "NextEntry", ByteString::CreateFromInt32( nNextEntry ) ); m_aPathBox.InsertEntry( aImportPath ); } while( m_aDriverLB.GetEntryCount() ) { delete (String*)m_aDriverLB.GetEntryData( 0 ); m_aDriverLB.RemoveEntry( 0 ); } ProgressDialog aProgress( Application::GetFocusWindow() ); aProgress.startOperation( m_aLoadingPPD ); ::std::list< String > aFiles; FindFiles( aImportPath, aFiles, String( RTL_CONSTASCII_USTRINGPARAM( "PS;PPD;PS.GZ;PPD.GZ" ) ), true ); int i = 0; aProgress.setRange( 0, aFiles.size() ); while( aFiles.size() ) { aProgress.setValue( ++i ); aProgress.setFilename( aFiles.front() ); INetURLObject aPath( aImportPath, INET_PROT_FILE, INetURLObject::ENCODE_ALL ); aPath.Append( aFiles.front() ); String aPrinterName = PPDParser::getPPDPrinterName( aPath.PathToFileName() ); aFiles.pop_front(); if( ! aPrinterName.Len() ) { #if OSL_DEBUG_LEVEL > 1 fprintf( stderr, "Warning: File %s has empty printer name.\n", rtl::OUStringToOString( aPath.PathToFileName(), osl_getThreadTextEncoding() ).getStr() ); #endif continue; } USHORT nPos = m_aDriverLB.InsertEntry( aPrinterName ); m_aDriverLB.SetEntryData( nPos, new String( aPath.PathToFileName() ) ); } } IMPL_LINK( PPDImportDialog, ClickBtnHdl, PushButton*, pButton ) { if( pButton == &m_aCancelBtn ) { EndDialog( 0 ); } else if( pButton == &m_aOKBtn ) { // copy the files ::std::list< rtl::OUString > aToDirs; psp::getPrinterPathList( aToDirs, PRINTER_PPDDIR ); ::std::list< rtl::OUString >::iterator writeDir = aToDirs.begin(); for( int i = 0; i < m_aDriverLB.GetSelectEntryCount(); i++ ) { INetURLObject aFile( *(String*)m_aDriverLB.GetEntryData( m_aDriverLB.GetSelectEntryPos( i ) ), INET_PROT_FILE, INetURLObject::ENCODE_ALL ); OUString aFromUni( aFile.GetMainURL(INetURLObject::DECODE_TO_IURI) ); do { INetURLObject aToFile( *writeDir, INET_PROT_FILE, INetURLObject::ENCODE_ALL ); aToFile.Append( aFile.GetName() ); OUString aToUni( aToFile.GetMainURL(INetURLObject::DECODE_TO_IURI) ); if( ! File::copy( aFromUni, aToUni ) ) break; ++writeDir; } while( writeDir != aToDirs.end() ); } EndDialog( 1 ); } else if( pButton == &m_aSearchBtn ) { String aPath( m_aPathBox.GetText() ); if( chooseDirectory( aPath ) ) { m_aPathBox.SetText( aPath ); Import(); } } return 0; } IMPL_LINK( PPDImportDialog, SelectHdl, ComboBox*, pListBox ) { if( pListBox == &m_aPathBox ) { Import(); } return 0; } IMPL_LINK( PPDImportDialog, ModifyHdl, ComboBox*, pListBox ) { if( pListBox == &m_aPathBox ) { ByteString aDir( m_aPathBox.GetText(), osl_getThreadTextEncoding() ); if( ! access( aDir.GetBuffer(), F_OK ) ) Import(); } return 0; } <|endoftext|>
<commit_before>#include "../../../shared/generated/cpp/MediaplayerBase.h" #include "net/INetRequest.h" #include "RhoFile.h" namespace rho { using namespace apiGenerator; std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } class CMediaplayerImpl: public CMediaplayerBase { public: CMediaplayerImpl(const rho::String& strID): CMediaplayerBase() { } }; class CMediaplayerSingleton: public CMediaplayerSingletonBase { static HANDLE m_hPlayThread; /// Handle to player thread static HANDLE m_hPlayProcess; /// Handle to player process static StringW lFilename; ~CMediaplayerSingleton(){} virtual rho::String getInitialDefaultID(); virtual void enumerate(CMethodResult& oResult); /** * Function to kill the player thread so that VideoCapture can unlock * any in-use media files */ void KillPlayer() { if (m_hPlayProcess) { TerminateProcess(m_hPlayProcess, -1); WaitForSingleObject(m_hPlayProcess, 500); CloseHandle(m_hPlayProcess); m_hPlayProcess = NULL; } if (m_hPlayThread) { TerminateThread(m_hPlayThread, -1); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; } } bool playLocalAudio() { LOG(INFO) + __FUNCTION__ + ": playLocalAudio called"; m_hPlayThread = CreateThread(NULL, 0, (&rho::CMediaplayerSingleton::playThreadProc), this, 0, NULL); return (m_hPlayThread != NULL); } static DWORD WINAPI playThreadProc(LPVOID lpParam) { DWORD dwRet = S_OK; CMediaplayerSingleton *pMediaplayer = (CMediaplayerSingleton *)lpParam; if (pMediaplayer) { LOG(INFO) + __FUNCTION__ + "pMediaplayer object exists: using lFilename: " + lFilename.c_str(); if (!PlaySound(lFilename.c_str(), NULL, SND_FILENAME|SND_SYNC|SND_NODEFAULT)) { LOG(INFO) + __FUNCTION__ + " PlaySound function failed "; dwRet = false; } CloseHandle(pMediaplayer->m_hPlayThread); pMediaplayer->m_hPlayThread = NULL; } return dwRet; } // Play an audio file. virtual void start( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult) { // Check that the filename is not empty or NULL. if (!filename.empty() && (!m_hPlayThread)) { // Download the audio file and store name in lFilename if(String_startsWith(filename, "http://") || String_startsWith(filename, "https://")) { rho::common::CRhoFile::deleteFile("download.wav"); // Networked code LOG(INFO) + __FUNCTION__ + "Attempting to download the file. " + filename; NetRequest oNetRequest; Hashtable<String,String> mapHeaders; bool overwriteFile = true; bool createFolders = false; bool fileExists = false; String& newfilename = String("download.wav"); // Call the download function with the url and new filename the temp filename to be used. net::CNetRequestHolder *requestHolder = new net::CNetRequestHolder(); requestHolder->setSslVerifyPeer(false); NetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists); delete requestHolder; if (!resp.isOK()) { LOG(INFO) + __FUNCTION__ + "Could not download the file"; return; // Don't attempt to play the file. } else { LOG(INFO) + __FUNCTION__ + "Could download the file"; lFilename = s2ws(newfilename); } } else { // Store the local filename away. lFilename = s2ws(filename); } // Launch the audio player. playLocalAudio(); } } // Stop playing an audio file. virtual void stop(rho::apiGenerator::CMethodResult& oResult) { // If the player is currently playing an audio file, stop it. PlaySound(NULL, NULL, 0); LOG(INFO) + __FUNCTION__ + " Stopping audio playback"; if (WaitForSingleObject(m_hPlayThread, 500) == WAIT_TIMEOUT) { TerminateThread(m_hPlayThread, -1); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; } } // Start playing a video file. virtual void startvideo( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult) { // Attempt to kill the player. If we don't do this, WMP holds a lock on the file and we cannot delete it. KillPlayer(); rho::common::CRhoFile::deleteFile("download.wmv"); // Check that the filename is not empty or NULL. if (!filename.empty() && (!m_hPlayProcess)) { PROCESS_INFORMATION pi; StringW m_lpzFilename; if (String_startsWith(filename, "http://") || String_startsWith(filename, "https://")) { // Networked code LOG(INFO) + __FUNCTION__ + "Attempting to download the file. " + filename; NetRequest oNetRequest; Hashtable<String,String> mapHeaders; bool overwriteFile = true; bool createFolders = false; bool fileExists = false; String& newfilename = String("download.wmv"); // Call the download function with the url and new filename the temp filename to be used. net::CNetRequestHolder *requestHolder = new net::CNetRequestHolder(); requestHolder->setSslVerifyPeer(false); NetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists); delete requestHolder; if (!resp.isOK()) { LOG(INFO) + __FUNCTION__ + "Could not download the file"; return; // Don't attempt to play the file. } else { LOG(INFO) + __FUNCTION__ + "Could download the file"; m_lpzFilename = s2ws(newfilename); } } else { // Local file, just change the name to a format the WM/CE understands. m_lpzFilename = s2ws(filename); } // Launch the video player. if (!CreateProcess(L"\\windows\\WMPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { // for WinCE CEPlayer we need to set a registry key to make sure it launches full screen HKEY hKey = 0; LPCWSTR subkey = L"SOFTWARE\\Microsoft\\CEPlayer"; if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,0,&hKey) == ERROR_SUCCESS) { DWORD dwType = REG_DWORD; DWORD dwData = 1; // Set AlwaysFullSize to 1 RegSetValueEx(hKey, L"AlwaysFullSize", 0, dwType, (BYTE*)&dwData, sizeof(dwData)); RegCloseKey(hKey); } if (!CreateProcess(L"\\windows\\CEPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { // if CEPlayer doesn't exist either, try VPlayer if (!CreateProcess(L"\\windows\\VPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { LOG(INFO) + __FUNCTION__ + "Error launching MediaPlayer"; return; } } m_hPlayProcess = pi.hProcess; m_hPlayThread = pi.hThread; } m_hPlayProcess = pi.hProcess; m_hPlayThread = pi.hThread; } } // Stop playing a video file. virtual void stopvideo(rho::apiGenerator::CMethodResult& oResult) { // If the player is currently playing a video file, stop it. TerminateProcess(m_hPlayProcess, -1); WaitForSingleObject(m_hPlayProcess, 500); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; CloseHandle(m_hPlayProcess); m_hPlayProcess = NULL; LOG(INFO) + __FUNCTION__ + " stopping video player."; } virtual void getAllRingtones(rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } virtual void playRingTone( const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } virtual void stopRingTone(rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } }; StringW CMediaplayerSingleton::lFilename; HANDLE CMediaplayerSingleton::m_hPlayThread = NULL; HANDLE CMediaplayerSingleton::m_hPlayProcess = NULL; class CMediaplayerFactory: public CMediaplayerFactoryBase { ~CMediaplayerFactory(){} virtual IMediaplayerSingleton* createModuleSingleton(); virtual IMediaplayer* createModuleByID(const rho::String& strID); }; extern "C" void Init_Mediaplayer_extension() { CMediaplayerFactory::setInstance( new CMediaplayerFactory() ); Init_Mediaplayer_API(); } IMediaplayer* CMediaplayerFactory::createModuleByID(const rho::String& strID) { return new CMediaplayerImpl(strID); } IMediaplayerSingleton* CMediaplayerFactory::createModuleSingleton() { return new CMediaplayerSingleton(); } void CMediaplayerSingleton::enumerate(CMethodResult& oResult) { rho::Vector<rho::String> arIDs; arIDs.addElement("SC1"); arIDs.addElement("SC2"); oResult.set(arIDs); } rho::String CMediaplayerSingleton::getInitialDefaultID() { CMethodResult oRes; enumerate(oRes); rho::Vector<rho::String>& arIDs = oRes.getStringArray(); return arIDs[0]; } }<commit_msg>/****************************************/ /* SR ID - EMBPD00128123 Issue Description - Video Files are not getting played in MediaPlayer with Native Application on WM Fix Provided - Issue was reproducing because of CreateProcess Microsoft API which donot understand the path which consists of space. Hence we need to put an extra double inverted at the front & at the end of the string. Developer Name - Abhineet Agarwal File Name - Mediaplayer_impl.cpp Function Name - startvideo Date - 09/06/2014 */ /****************************************/<commit_after>#include "../../../shared/generated/cpp/MediaplayerBase.h" #include "net/INetRequest.h" #include "RhoFile.h" namespace rho { using namespace apiGenerator; std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } class CMediaplayerImpl: public CMediaplayerBase { public: CMediaplayerImpl(const rho::String& strID): CMediaplayerBase() { } }; class CMediaplayerSingleton: public CMediaplayerSingletonBase { static HANDLE m_hPlayThread; /// Handle to player thread static HANDLE m_hPlayProcess; /// Handle to player process static StringW lFilename; ~CMediaplayerSingleton(){} virtual rho::String getInitialDefaultID(); virtual void enumerate(CMethodResult& oResult); /** * Function to kill the player thread so that VideoCapture can unlock * any in-use media files */ void KillPlayer() { if (m_hPlayProcess) { TerminateProcess(m_hPlayProcess, -1); WaitForSingleObject(m_hPlayProcess, 500); CloseHandle(m_hPlayProcess); m_hPlayProcess = NULL; } if (m_hPlayThread) { TerminateThread(m_hPlayThread, -1); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; } } bool playLocalAudio() { LOG(INFO) + __FUNCTION__ + ": playLocalAudio called"; m_hPlayThread = CreateThread(NULL, 0, (&rho::CMediaplayerSingleton::playThreadProc), this, 0, NULL); return (m_hPlayThread != NULL); } static DWORD WINAPI playThreadProc(LPVOID lpParam) { DWORD dwRet = S_OK; CMediaplayerSingleton *pMediaplayer = (CMediaplayerSingleton *)lpParam; if (pMediaplayer) { LOG(INFO) + __FUNCTION__ + "pMediaplayer object exists: using lFilename: " + lFilename.c_str(); if (!PlaySound(lFilename.c_str(), NULL, SND_FILENAME|SND_SYNC|SND_NODEFAULT)) { LOG(INFO) + __FUNCTION__ + " PlaySound function failed "; dwRet = false; } CloseHandle(pMediaplayer->m_hPlayThread); pMediaplayer->m_hPlayThread = NULL; } return dwRet; } // Play an audio file. virtual void start( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult) { // Check that the filename is not empty or NULL. if (!filename.empty() && (!m_hPlayThread)) { // Download the audio file and store name in lFilename if(String_startsWith(filename, "http://") || String_startsWith(filename, "https://")) { rho::common::CRhoFile::deleteFile("download.wav"); // Networked code LOG(INFO) + __FUNCTION__ + "Attempting to download the file. " + filename; NetRequest oNetRequest; Hashtable<String,String> mapHeaders; bool overwriteFile = true; bool createFolders = false; bool fileExists = false; String& newfilename = String("download.wav"); // Call the download function with the url and new filename the temp filename to be used. net::CNetRequestHolder *requestHolder = new net::CNetRequestHolder(); requestHolder->setSslVerifyPeer(false); NetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists); delete requestHolder; if (!resp.isOK()) { LOG(INFO) + __FUNCTION__ + "Could not download the file"; return; // Don't attempt to play the file. } else { LOG(INFO) + __FUNCTION__ + "Could download the file"; lFilename = s2ws(newfilename); } } else { // Store the local filename away. lFilename = s2ws(filename); } // Launch the audio player. playLocalAudio(); } } // Stop playing an audio file. virtual void stop(rho::apiGenerator::CMethodResult& oResult) { // If the player is currently playing an audio file, stop it. PlaySound(NULL, NULL, 0); LOG(INFO) + __FUNCTION__ + " Stopping audio playback"; if (WaitForSingleObject(m_hPlayThread, 500) == WAIT_TIMEOUT) { TerminateThread(m_hPlayThread, -1); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; } } // Start playing a video file. virtual void startvideo( const rho::String& filename, rho::apiGenerator::CMethodResult& oResult) { // Attempt to kill the player. If we don't do this, WMP holds a lock on the file and we cannot delete it. KillPlayer(); rho::common::CRhoFile::deleteFile("download.wmv"); // Check that the filename is not empty or NULL. if (!filename.empty() && (!m_hPlayProcess)) { PROCESS_INFORMATION pi; StringW m_lpzFilename; if (String_startsWith(filename, "http://") || String_startsWith(filename, "https://")) { // Networked code LOG(INFO) + __FUNCTION__ + "Attempting to download the file. " + filename; NetRequest oNetRequest; Hashtable<String,String> mapHeaders; bool overwriteFile = true; bool createFolders = false; bool fileExists = false; String& newfilename = String("download.wmv"); // Call the download function with the url and new filename the temp filename to be used. net::CNetRequestHolder *requestHolder = new net::CNetRequestHolder(); requestHolder->setSslVerifyPeer(false); NetResponse resp = getNetRequest(requestHolder).pullFile( filename, newfilename, null, &mapHeaders,overwriteFile,createFolders,&fileExists); delete requestHolder; if (!resp.isOK()) { LOG(INFO) + __FUNCTION__ + "Could not download the file"; return; // Don't attempt to play the file. } else { LOG(INFO) + __FUNCTION__ + "Could download the file"; m_lpzFilename = s2ws(newfilename); } } else { // Local file, just change the name to a format the WM/CE understands. m_lpzFilename = s2ws(filename); } /****************************************/ /* SR ID - EMBPD00128123 Issue Description - Video Files are not getting played in MediaPlayer with Native Application on WM Fix Provided - Issue was reproducing because of CreateProcess Microsoft API which donot understand the path which consists of space. Hence we need to put an extra double inverted at the front & at the end of the string. Developer Name - Abhineet Agarwal File Name - Mediaplayer_impl.cpp Function Name - startvideo Date - 09/06/2014 */ /****************************************/ m_lpzFilename = L"\"" + m_lpzFilename + L"\""; // Launch the video player. if (!CreateProcess(L"\\windows\\WMPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { // for WinCE CEPlayer we need to set a registry key to make sure it launches full screen HKEY hKey = 0; LPCWSTR subkey = L"SOFTWARE\\Microsoft\\CEPlayer"; if( RegOpenKeyEx(HKEY_LOCAL_MACHINE,subkey,0,0,&hKey) == ERROR_SUCCESS) { DWORD dwType = REG_DWORD; DWORD dwData = 1; // Set AlwaysFullSize to 1 RegSetValueEx(hKey, L"AlwaysFullSize", 0, dwType, (BYTE*)&dwData, sizeof(dwData)); RegCloseKey(hKey); } if (!CreateProcess(L"\\windows\\CEPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { // if CEPlayer doesn't exist either, try VPlayer if (!CreateProcess(L"\\windows\\VPlayer.exe", m_lpzFilename.c_str(), NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)) { LOG(INFO) + __FUNCTION__ + "Error launching MediaPlayer"; return; } } m_hPlayProcess = pi.hProcess; m_hPlayThread = pi.hThread; } m_hPlayProcess = pi.hProcess; m_hPlayThread = pi.hThread; } } // Stop playing a video file. virtual void stopvideo(rho::apiGenerator::CMethodResult& oResult) { // If the player is currently playing a video file, stop it. TerminateProcess(m_hPlayProcess, -1); WaitForSingleObject(m_hPlayProcess, 500); CloseHandle(m_hPlayThread); m_hPlayThread = NULL; CloseHandle(m_hPlayProcess); m_hPlayProcess = NULL; LOG(INFO) + __FUNCTION__ + " stopping video player."; } virtual void getAllRingtones(rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } virtual void playRingTone( const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } virtual void stopRingTone(rho::apiGenerator::CMethodResult& oResult) { // Not implemented in CE } }; StringW CMediaplayerSingleton::lFilename; HANDLE CMediaplayerSingleton::m_hPlayThread = NULL; HANDLE CMediaplayerSingleton::m_hPlayProcess = NULL; class CMediaplayerFactory: public CMediaplayerFactoryBase { ~CMediaplayerFactory(){} virtual IMediaplayerSingleton* createModuleSingleton(); virtual IMediaplayer* createModuleByID(const rho::String& strID); }; extern "C" void Init_Mediaplayer_extension() { CMediaplayerFactory::setInstance( new CMediaplayerFactory() ); Init_Mediaplayer_API(); } IMediaplayer* CMediaplayerFactory::createModuleByID(const rho::String& strID) { return new CMediaplayerImpl(strID); } IMediaplayerSingleton* CMediaplayerFactory::createModuleSingleton() { return new CMediaplayerSingleton(); } void CMediaplayerSingleton::enumerate(CMethodResult& oResult) { rho::Vector<rho::String> arIDs; arIDs.addElement("SC1"); arIDs.addElement("SC2"); oResult.set(arIDs); } rho::String CMediaplayerSingleton::getInitialDefaultID() { CMethodResult oRes; enumerate(oRes); rho::Vector<rho::String>& arIDs = oRes.getStringArray(); return arIDs[0]; } }<|endoftext|>
<commit_before>/* * Copyright 2013 Jeremie Roy. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "common.h" #include "bgfx_utils.h" #include <bx/timer.h> #include <bx/string.h> #include <bx/math.h> #include "font/font_manager.h" #include "font/text_buffer_manager.h" #include "entry/input.h" #include <iconfontheaders/icons_font_awesome.h> #include <iconfontheaders/icons_kenney.h> #include <wchar.h> #include "imgui/imgui.h" namespace { TrueTypeHandle loadTtf(FontManager* _fm, const char* _filePath) { uint32_t size; void* data = load(_filePath, &size); if (NULL != data) { TrueTypeHandle handle = _fm->createTtf( (uint8_t*)data, size); BX_FREE(entry::getAllocator(), data); return handle; } TrueTypeHandle invalid = BGFX_INVALID_HANDLE; return invalid; } static const char* s_fontFilePath[] = { "font/droidsans.ttf", "font/chp-fire.ttf", "font/bleeding_cowboys.ttf", "font/mias_scribblings.ttf", "font/ruritania.ttf", "font/signika-regular.ttf", "font/five_minutes.otf", }; class ExampleFont : public entry::AppI { public: ExampleFont(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Init the text rendering system. m_fontManager = new FontManager(512); m_textBufferManager = new TextBufferManager(m_fontManager); // Load some TTF files. for (uint32_t ii = 0; ii < numFonts; ++ii) { // Instantiate a usable font. m_fontFiles[ii] = loadTtf(m_fontManager, s_fontFilePath[ii]); m_fonts[ii] = m_fontManager->createFontByPixelSize(m_fontFiles[ii], 0, 32); // Preload glyphs and blit them to atlas. m_fontManager->preloadGlyph(m_fonts[ii], L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. \n"); // You can unload the truetype files at this stage, but in that // case, the set of glyph's will be limited to the set of preloaded // glyph. m_fontManager->destroyTtf(m_fontFiles[ii]); } m_fontAwesomeTtf = loadTtf(m_fontManager, "font/fontawesome-webfont.ttf"); m_fontKenneyTtf = loadTtf(m_fontManager, "font/kenney-icon-font.ttf"); // This font doesn't have any preloaded glyph's but the truetype file // is loaded so glyph will be generated as needed. m_fontAwesome72 = m_fontManager->createFontByPixelSize(m_fontAwesomeTtf, 0, 72); m_fontKenney64 = m_fontManager->createFontByPixelSize(m_fontKenneyTtf, 0, 64); m_visitorTtf = loadTtf(m_fontManager, "font/visitor1.ttf"); // This font doesn't have any preloaded glyph's but the truetype file // is loaded so glyph will be generated as needed. m_visitor10 = m_fontManager->createFontByPixelSize(m_visitorTtf, 0, 10); //create a static text buffer compatible with alpha font //a static text buffer content cannot be modified after its first submit. m_staticText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Static); // The pen position represent the top left of the box of the first line // of text. m_textBufferManager->setPenPosition(m_staticText, 24.0f, 100.0f); for (uint32_t ii = 0; ii < numFonts; ++ii) { // Add some text to the buffer. // The position of the pen is adjusted when there is an endline. m_textBufferManager->appendText(m_staticText, m_fonts[ii], L"The quick brown fox jumps over the lazy dog\n"); } // Now write some styled text. // Setup style colors. m_textBufferManager->setBackgroundColor(m_staticText, 0x551111ff); m_textBufferManager->setUnderlineColor(m_staticText, 0xff2222ff); m_textBufferManager->setOverlineColor(m_staticText, 0x2222ffff); m_textBufferManager->setStrikeThroughColor(m_staticText, 0x22ff22ff); // Background. m_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"The quick "); // Strike-through. m_textBufferManager->setStyle(m_staticText, STYLE_STRIKE_THROUGH); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"brown fox "); // Overline. m_textBufferManager->setStyle(m_staticText, STYLE_OVERLINE); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"jumps over "); // Underline. m_textBufferManager->setStyle(m_staticText, STYLE_UNDERLINE); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"the lazy "); // Background + strike-through. m_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND | STYLE_STRIKE_THROUGH); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"dog\n"); m_textBufferManager->setStyle(m_staticText, STYLE_NORMAL); m_textBufferManager->appendText(m_staticText, m_fontAwesome72, " " ICON_FA_POWER_OFF " " ICON_FA_TWITTER_SQUARE " " ICON_FA_CERTIFICATE " " ICON_FA_FLOPPY_O " " ICON_FA_GITHUB " " ICON_FA_GITHUB_ALT "\n" ); m_textBufferManager->appendText(m_staticText, m_fontKenney64, " " ICON_KI_COMPUTER " " ICON_KI_JOYSTICK " " ICON_KI_EXLAMATION " " ICON_KI_STAR " " ICON_KI_BUTTON_START " " ICON_KI_DOWNLOAD "\n" ); // Create a transient buffer for real-time data. m_transientText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Transient); imguiCreate(); } virtual int shutdown() override { imguiDestroy(); m_fontManager->destroyTtf(m_fontKenneyTtf); m_fontManager->destroyTtf(m_fontAwesomeTtf); m_fontManager->destroyTtf(m_visitorTtf); // Destroy the fonts. m_fontManager->destroyFont(m_fontKenney64); m_fontManager->destroyFont(m_fontAwesome72); m_fontManager->destroyFont(m_visitor10); for (uint32_t ii = 0; ii < numFonts; ++ii) { m_fontManager->destroyFont(m_fonts[ii]); } m_textBufferManager->destroyTextBuffer(m_staticText); m_textBufferManager->destroyTextBuffer(m_transientText); delete m_textBufferManager; delete m_fontManager; // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); imguiEndFrame(); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0 / freq; // Use transient text to display debug information. wchar_t fpsText[64]; bx::swnprintf(fpsText, BX_COUNTOF(fpsText), L"Frame: % 7.3f[ms]", double(frameTime) * toMs); m_textBufferManager->clearTextBuffer(m_transientText); m_textBufferManager->setPenPosition(m_transientText, m_width - 150.0f, 10.0f); m_textBufferManager->appendText(m_transientText, m_visitor10, L"Transient\n"); m_textBufferManager->appendText(m_transientText, m_visitor10, L"text buffer\n"); m_textBufferManager->appendText(m_transientText, m_visitor10, fpsText); float at[3] = { 0, 0, 0.0f }; float eye[3] = { 0, 0, -1.0f }; float view[16]; bx::mtxLookAt(view, eye, at); const float centering = 0.5f; // Setup a top-left ortho matrix for screen space drawing. const bgfx::HMD* hmd = bgfx::getHMD(); const bgfx::Caps* caps = bgfx::getCaps(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float proj[16]; bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f, caps->homogeneousDepth); static float time = 0.0f; time += 0.05f; const float dist = 10.0f; const float offset0 = -proj[8] + (hmd->eye[0].viewOffset[0] / dist * proj[0]); const float offset1 = -proj[8] + (hmd->eye[1].viewOffset[0] / dist * proj[0]); float ortho[2][16]; const float offsetx = m_width/2.0f; bx::mtxOrtho( ortho[0] , centering , offsetx + centering , m_height + centering , centering , -1.0f , 1.0f , offset0 , caps->homogeneousDepth ); bx::mtxOrtho( ortho[1] , centering , offsetx + centering , m_height + centering , centering , -1.0f , 1.0f , offset1 , caps->homogeneousDepth ); bgfx::setViewTransform(0, view, ortho[0], BGFX_VIEW_STEREO, ortho[1]); bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float ortho[16]; bx::mtxOrtho( ortho , centering , m_width + centering , m_height + centering , centering , 0.0f , 100.0f , 0.0f , caps->homogeneousDepth ); bgfx::setViewTransform(0, view, ortho); bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); } // Submit the debug text. m_textBufferManager->submitTextBuffer(m_transientText, 0); // Submit the static text. m_textBufferManager->submitTextBuffer(m_staticText, 0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } entry::MouseState m_mouseState; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; FontManager* m_fontManager; TextBufferManager* m_textBufferManager; FontHandle m_visitor10; TrueTypeHandle m_fontAwesomeTtf; TrueTypeHandle m_fontKenneyTtf; FontHandle m_fontAwesome72; FontHandle m_fontKenney64; TrueTypeHandle m_visitorTtf; TextBufferHandle m_transientText; TextBufferHandle m_staticText; static const uint32_t numFonts = BX_COUNTOF(s_fontFilePath); TrueTypeHandle m_fontFiles[numFonts]; FontHandle m_fonts[numFonts]; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleFont, "10-font", "Use the font system to display text and styled text."); <commit_msg>Removed use of wchar_t.<commit_after>/* * Copyright 2013 Jeremie Roy. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #include "common.h" #include "bgfx_utils.h" #include <bx/timer.h> #include <bx/string.h> #include <bx/math.h> #include "font/font_manager.h" #include "font/text_buffer_manager.h" #include "entry/input.h" #include <iconfontheaders/icons_font_awesome.h> #include <iconfontheaders/icons_kenney.h> #include <wchar.h> #include "imgui/imgui.h" namespace { TrueTypeHandle loadTtf(FontManager* _fm, const char* _filePath) { uint32_t size; void* data = load(_filePath, &size); if (NULL != data) { TrueTypeHandle handle = _fm->createTtf( (uint8_t*)data, size); BX_FREE(entry::getAllocator(), data); return handle; } TrueTypeHandle invalid = BGFX_INVALID_HANDLE; return invalid; } static const char* s_fontFilePath[] = { "font/droidsans.ttf", "font/chp-fire.ttf", "font/bleeding_cowboys.ttf", "font/mias_scribblings.ttf", "font/ruritania.ttf", "font/signika-regular.ttf", "font/five_minutes.otf", }; class ExampleFont : public entry::AppI { public: ExampleFont(const char* _name, const char* _description) : entry::AppI(_name, _description) { } void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override { Args args(_argc, _argv); m_width = _width; m_height = _height; m_debug = BGFX_DEBUG_NONE; m_reset = BGFX_RESET_VSYNC; bgfx::init(args.m_type, args.m_pciId); bgfx::reset(m_width, m_height, m_reset); // Enable debug text. bgfx::setDebug(m_debug); // Set view 0 clear state. bgfx::setViewClear(0 , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH , 0x303030ff , 1.0f , 0 ); // Init the text rendering system. m_fontManager = new FontManager(512); m_textBufferManager = new TextBufferManager(m_fontManager); // Load some TTF files. for (uint32_t ii = 0; ii < numFonts; ++ii) { // Instantiate a usable font. m_fontFiles[ii] = loadTtf(m_fontManager, s_fontFilePath[ii]); m_fonts[ii] = m_fontManager->createFontByPixelSize(m_fontFiles[ii], 0, 32); // Preload glyphs and blit them to atlas. m_fontManager->preloadGlyph(m_fonts[ii], L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. \n"); // You can unload the truetype files at this stage, but in that // case, the set of glyph's will be limited to the set of preloaded // glyph. m_fontManager->destroyTtf(m_fontFiles[ii]); } m_fontAwesomeTtf = loadTtf(m_fontManager, "font/fontawesome-webfont.ttf"); m_fontKenneyTtf = loadTtf(m_fontManager, "font/kenney-icon-font.ttf"); // This font doesn't have any preloaded glyph's but the truetype file // is loaded so glyph will be generated as needed. m_fontAwesome72 = m_fontManager->createFontByPixelSize(m_fontAwesomeTtf, 0, 72); m_fontKenney64 = m_fontManager->createFontByPixelSize(m_fontKenneyTtf, 0, 64); m_visitorTtf = loadTtf(m_fontManager, "font/visitor1.ttf"); // This font doesn't have any preloaded glyph's but the truetype file // is loaded so glyph will be generated as needed. m_visitor10 = m_fontManager->createFontByPixelSize(m_visitorTtf, 0, 10); //create a static text buffer compatible with alpha font //a static text buffer content cannot be modified after its first submit. m_staticText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Static); // The pen position represent the top left of the box of the first line // of text. m_textBufferManager->setPenPosition(m_staticText, 24.0f, 100.0f); for (uint32_t ii = 0; ii < numFonts; ++ii) { // Add some text to the buffer. // The position of the pen is adjusted when there is an endline. m_textBufferManager->appendText(m_staticText, m_fonts[ii], L"The quick brown fox jumps over the lazy dog\n"); } // Now write some styled text. // Setup style colors. m_textBufferManager->setBackgroundColor(m_staticText, 0x551111ff); m_textBufferManager->setUnderlineColor(m_staticText, 0xff2222ff); m_textBufferManager->setOverlineColor(m_staticText, 0x2222ffff); m_textBufferManager->setStrikeThroughColor(m_staticText, 0x22ff22ff); // Background. m_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"The quick "); // Strike-through. m_textBufferManager->setStyle(m_staticText, STYLE_STRIKE_THROUGH); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"brown fox "); // Overline. m_textBufferManager->setStyle(m_staticText, STYLE_OVERLINE); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"jumps over "); // Underline. m_textBufferManager->setStyle(m_staticText, STYLE_UNDERLINE); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"the lazy "); // Background + strike-through. m_textBufferManager->setStyle(m_staticText, STYLE_BACKGROUND | STYLE_STRIKE_THROUGH); m_textBufferManager->appendText(m_staticText, m_fonts[0], L"dog\n"); m_textBufferManager->setStyle(m_staticText, STYLE_NORMAL); m_textBufferManager->appendText(m_staticText, m_fontAwesome72, " " ICON_FA_POWER_OFF " " ICON_FA_TWITTER_SQUARE " " ICON_FA_CERTIFICATE " " ICON_FA_FLOPPY_O " " ICON_FA_GITHUB " " ICON_FA_GITHUB_ALT "\n" ); m_textBufferManager->appendText(m_staticText, m_fontKenney64, " " ICON_KI_COMPUTER " " ICON_KI_JOYSTICK " " ICON_KI_EXLAMATION " " ICON_KI_STAR " " ICON_KI_BUTTON_START " " ICON_KI_DOWNLOAD "\n" ); // Create a transient buffer for real-time data. m_transientText = m_textBufferManager->createTextBuffer(FONT_TYPE_ALPHA, BufferType::Transient); imguiCreate(); } virtual int shutdown() override { imguiDestroy(); m_fontManager->destroyTtf(m_fontKenneyTtf); m_fontManager->destroyTtf(m_fontAwesomeTtf); m_fontManager->destroyTtf(m_visitorTtf); // Destroy the fonts. m_fontManager->destroyFont(m_fontKenney64); m_fontManager->destroyFont(m_fontAwesome72); m_fontManager->destroyFont(m_visitor10); for (uint32_t ii = 0; ii < numFonts; ++ii) { m_fontManager->destroyFont(m_fonts[ii]); } m_textBufferManager->destroyTextBuffer(m_staticText); m_textBufferManager->destroyTextBuffer(m_transientText); delete m_textBufferManager; delete m_fontManager; // Shutdown bgfx. bgfx::shutdown(); return 0; } bool update() override { if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) ) { imguiBeginFrame(m_mouseState.m_mx , m_mouseState.m_my , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0) | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0) , m_mouseState.m_mz , uint16_t(m_width) , uint16_t(m_height) ); showExampleDialog(this); imguiEndFrame(); // This dummy draw call is here to make sure that view 0 is cleared // if no other draw calls are submitted to view 0. bgfx::touch(0); int64_t now = bx::getHPCounter(); static int64_t last = now; const int64_t frameTime = now - last; last = now; const double freq = double(bx::getHPFrequency() ); const double toMs = 1000.0 / freq; // Use transient text to display debug information. char fpsText[64]; bx::snprintf(fpsText, BX_COUNTOF(fpsText), "Frame: % 7.3f[ms]", double(frameTime) * toMs); m_textBufferManager->clearTextBuffer(m_transientText); m_textBufferManager->setPenPosition(m_transientText, m_width - 150.0f, 10.0f); m_textBufferManager->appendText(m_transientText, m_visitor10, "Transient\n"); m_textBufferManager->appendText(m_transientText, m_visitor10, "text buffer\n"); m_textBufferManager->appendText(m_transientText, m_visitor10, fpsText); float at[3] = { 0, 0, 0.0f }; float eye[3] = { 0, 0, -1.0f }; float view[16]; bx::mtxLookAt(view, eye, at); const float centering = 0.5f; // Setup a top-left ortho matrix for screen space drawing. const bgfx::HMD* hmd = bgfx::getHMD(); const bgfx::Caps* caps = bgfx::getCaps(); if (NULL != hmd && 0 != (hmd->flags & BGFX_HMD_RENDERING) ) { float proj[16]; bx::mtxProj(proj, hmd->eye[0].fov, 0.1f, 100.0f, caps->homogeneousDepth); static float time = 0.0f; time += 0.05f; const float dist = 10.0f; const float offset0 = -proj[8] + (hmd->eye[0].viewOffset[0] / dist * proj[0]); const float offset1 = -proj[8] + (hmd->eye[1].viewOffset[0] / dist * proj[0]); float ortho[2][16]; const float offsetx = m_width/2.0f; bx::mtxOrtho( ortho[0] , centering , offsetx + centering , m_height + centering , centering , -1.0f , 1.0f , offset0 , caps->homogeneousDepth ); bx::mtxOrtho( ortho[1] , centering , offsetx + centering , m_height + centering , centering , -1.0f , 1.0f , offset1 , caps->homogeneousDepth ); bgfx::setViewTransform(0, view, ortho[0], BGFX_VIEW_STEREO, ortho[1]); bgfx::setViewRect(0, 0, 0, hmd->width, hmd->height); } else { float ortho[16]; bx::mtxOrtho( ortho , centering , m_width + centering , m_height + centering , centering , 0.0f , 100.0f , 0.0f , caps->homogeneousDepth ); bgfx::setViewTransform(0, view, ortho); bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) ); } // Submit the debug text. m_textBufferManager->submitTextBuffer(m_transientText, 0); // Submit the static text. m_textBufferManager->submitTextBuffer(m_staticText, 0); // Advance to next frame. Rendering thread will be kicked to // process submitted rendering primitives. bgfx::frame(); return true; } return false; } entry::MouseState m_mouseState; uint32_t m_width; uint32_t m_height; uint32_t m_debug; uint32_t m_reset; FontManager* m_fontManager; TextBufferManager* m_textBufferManager; FontHandle m_visitor10; TrueTypeHandle m_fontAwesomeTtf; TrueTypeHandle m_fontKenneyTtf; FontHandle m_fontAwesome72; FontHandle m_fontKenney64; TrueTypeHandle m_visitorTtf; TextBufferHandle m_transientText; TextBufferHandle m_staticText; static const uint32_t numFonts = BX_COUNTOF(s_fontFilePath); TrueTypeHandle m_fontFiles[numFonts]; FontHandle m_fonts[numFonts]; }; } // namespace ENTRY_IMPLEMENT_MAIN(ExampleFont, "10-font", "Use the font system to display text and styled text."); <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> #include "configure.h" using namespace tiramisu; expr mixf(expr x, expr y, expr a) { return x * (1 - a) + y * a; } int main() { init("resize_conv_block"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- var o_x("o_x", 0, IMG_WIDTH), o_y("o_y", 0, IMG_HEIGHT), fin("fin", 0, FIn), n("n", 0, BATCH_SIZE); var x("x", 0, N), y("y", 0, N); var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2); var k_x("k_x", 0, K_X), k_y("k_y", 0, K_Y), fout("fout", 0, FOut); var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING); input c_input("c_input", {n, o_y, o_x, fin}, p_float32); input conv_filter("conv_filter", {fout_b, k_y, k_x, fin, ffout}, p_float32); input conv_bias("conv_bias", {fout_b, ffout}, p_float32); // Resize computation computation init_resized_input("init_resized_input", {n, y_pad, x_pad, fin}, 0.f); expr o_r((cast(p_float32, y) + 0.5f) * (cast(p_float32, IMG_HEIGHT) / cast(p_float32, N)) - 0.5f); expr o_c((cast(p_float32, x) + 0.5f) * (cast(p_float32, IMG_WIDTH) / cast(p_float32, N)) - 0.5f); expr r_coeff(expr(o_r) - expr(o_floor, o_r)); expr c_coeff(expr(o_c) - expr(o_floor, o_c)); expr A00_r(cast(p_int32, expr(o_floor, o_r))); expr A00_c(cast(p_int32, expr(o_floor, o_c))); computation resize( "resize", {n, y, x, fin}, mixf( mixf( c_input(n, A00_r, A00_c, fin), c_input(n, A00_r + 1, A00_c, fin), r_coeff ), mixf( c_input(n, A00_r, A00_c + 1, fin), c_input(n, A00_r + 1, A00_c + 1, fin), r_coeff ), c_coeff ) ); view input_resized("input_resized", {n, y_pad, x_pad, fin}, p_float32); // Convolution computation computation init_output("init_output", {n, fout_b, y, x, ffout}, conv_bias(fout_b, ffout)); computation conv( "conv", {n, fout_b, y, x, k_y, k_x, fin, ffout}, init_output(n, fout_b, y, x, ffout) + input_resized(n, y + k_y, x + k_x, fin)*conv_filter(fout_b, k_y, k_x, fin, ffout) ); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- init_resized_input.then(resize, n) .then(init_output, n) .then(conv, x); resize.tag_unroll_level(fin); resize.vectorize(x, 8); conv.tag_unroll_level(fin); conv.vectorize(ffout, FOUT_BLOCKING); conv.tag_parallel_level(n); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer input_resized_buf("input_resized_buf", {BATCH_SIZE, N + 2, N + 2, FIn}, p_float32, a_temporary); buffer output_buf("output_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output); init_resized_input.store_in(&input_resized_buf); resize.store_in(&input_resized_buf, {n, y + 1, x + 1, fin}); input_resized.store_in(&input_resized_buf); init_output.store_in(&output_buf); conv.store_in(&output_buf, {n, fout_b, y, x, ffout}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- codegen({ c_input.get_buffer(), conv_filter.get_buffer(), conv_bias.get_buffer(), &output_buf }, "resize_conv_tiramisu.o"); return 0; } <commit_msg>Resize-Conv : small edit to Tiramisu version<commit_after>#include <tiramisu/tiramisu.h> #include "configure.h" using namespace tiramisu; expr mixf(expr x, expr y, expr a) { return x + (y - x) * a; } int main() { init("resize_conv_block"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- var o_x("o_x", 0, IMG_WIDTH), o_y("o_y", 0, IMG_HEIGHT), fin("fin", 0, FIn), n("n", 0, BATCH_SIZE); var x("x", 0, N), y("y", 0, N); var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2); var k_x("k_x", 0, K_X), k_y("k_y", 0, K_Y), fout("fout", 0, FOut); var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING); input c_input("c_input", {n, o_y, o_x, fin}, p_float32); input conv_filter("conv_filter", {fout_b, k_y, k_x, fin, ffout}, p_float32); input conv_bias("conv_bias", {fout_b, ffout}, p_float32); // Resize computation computation init_resized_input("init_resized_input", {n, y_pad, x_pad, fin}, 0.f); expr o_r((cast(p_float32, y) + 0.5f) * (cast(p_float32, IMG_HEIGHT) / cast(p_float32, N)) - 0.5f); expr o_c((cast(p_float32, x) + 0.5f) * (cast(p_float32, IMG_WIDTH) / cast(p_float32, N)) - 0.5f); expr r_coeff(expr(o_r) - expr(o_floor, o_r)); expr c_coeff(expr(o_c) - expr(o_floor, o_c)); expr A00_r(cast(p_int32, expr(o_floor, o_r))); expr A00_c(cast(p_int32, expr(o_floor, o_c))); computation resize( "resize", {n, y, x, fin}, mixf( mixf( c_input(n, A00_r, A00_c, fin), c_input(n, A00_r + 1, A00_c, fin), r_coeff ), mixf( c_input(n, A00_r, A00_c + 1, fin), c_input(n, A00_r + 1, A00_c + 1, fin), r_coeff ), c_coeff ) ); view input_resized("input_resized", {n, y_pad, x_pad, fin}, p_float32); // Convolution computation computation init_output("init_output", {n, fout_b, y, x, ffout}, conv_bias(fout_b, ffout)); computation conv( "conv", {n, fout_b, y, x, k_y, k_x, fin, ffout}, init_output(n, fout_b, y, x, ffout) + input_resized(n, y + k_y, x + k_x, fin)*conv_filter(fout_b, k_y, k_x, fin, ffout) ); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- init_resized_input.then(resize, n) .then(init_output, n) .then(conv, x); resize.tag_unroll_level(fin); resize.vectorize(x, 8); conv.tag_unroll_level(fin); conv.vectorize(ffout, FOUT_BLOCKING); conv.tag_parallel_level(n); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer input_resized_buf("input_resized_buf", {BATCH_SIZE, N + 2, N + 2, FIn}, p_float32, a_temporary); buffer output_buf("output_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output); init_resized_input.store_in(&input_resized_buf); resize.store_in(&input_resized_buf, {n, y + 1, x + 1, fin}); input_resized.store_in(&input_resized_buf); init_output.store_in(&output_buf); conv.store_in(&output_buf, {n, fout_b, y, x, ffout}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- codegen({ c_input.get_buffer(), conv_filter.get_buffer(), conv_bias.get_buffer(), &output_buf }, "resize_conv_tiramisu.o"); return 0; } <|endoftext|>
<commit_before>/// /// @file primecount.cpp /// @brief Function definitions of primecount.hpp /// /// Copyright (C) 2019 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <calculator.hpp> #include <int128_t.hpp> #include <imath.hpp> #include <algorithm> #include <chrono> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primecount { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = 0; #endif // Below 10^7 LMO is faster than Deleglise-Rivat const int lmo_threshold_ = 10000000; int status_precision_ = -1; // Tuning factor used in the Lagarias-Miller-Odlyzko // and Deleglise-Rivat algorithms. double alpha_ = -1; // Tuning factor used in Xavier Gourdon's algorithm double alpha_y_ = -1; // Tuning factor used in Xavier Gourdon's algorithm double alpha_z_ = -1; } namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { if (x <= lmo_threshold_) return pi_lmo5(x); else return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); else return pi_deleglise_rivat(x, threads); } #endif string pi(const string& x) { return pi(x, get_num_threads()); } string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } int64_t pi_legendre(int64_t x) { return pi_legendre(x, get_num_threads()); } int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, get_num_threads()); } int64_t pi_lmo(int64_t x) { return pi_lmo(x, get_num_threads()); } int64_t pi_lmo(int64_t x, int threads) { return pi_lmo_parallel(x, threads); } int64_t pi_meissel(int64_t x) { return pi_meissel(x, get_num_threads()); } int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, get_num_threads()); } int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_parallel1(x, threads); } #ifdef HAVE_INT128_T int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, get_num_threads()); } int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat_parallel1((int64_t) x, threads); else return pi_deleglise_rivat_parallel2(x, threads); } #endif int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } /// Returns the largest integer supported by pi(x). The /// return type is a string as get_max_x() can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primecount is limited by: // z <= 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha <= 2^62 // x <= (2^62 * alpha)^(3/2) // double max_x = pow(pow(2.0, 62.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the time in seconds double get_time() { auto now = chrono::steady_clock::now(); auto time = now.time_since_epoch(); auto micro = chrono::duration_cast<chrono::microseconds>(time); return (double) micro.count() / 1e6; } int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } void set_alpha_y(double alpha_y) { alpha_y_ = alpha_y; } void set_alpha_z(double alpha_z) { alpha_z_ = alpha_z; } /// Tuning factor used in the Lagarias-Miller-Odlyzko /// and Deleglise-Rivat algorithms. /// double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Tuning factor used in Xavier Gourdon's algorithm. double get_alpha_y(maxint_t x, int64_t y) { // y = x13 * alpha_y, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Tuning factor used in Xavier Gourdon's algorithm. double get_alpha_z(int64_t y, int64_t z) { // z = y * alpha_z, thus alpha_z = z / y return (double) z / y; } /// Get the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c have been determined empirically. /// @see doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = alpha_; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Get the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d have been determined empirically. /// @see doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = alpha_; double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00033826; double b = 0.0018113; double c = -0.110407; double d = 1.3724; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha, iroot<6>(x)); } /// y = x^(1/3) * alpha_y, with alpha_y >= 1. /// alpha_y is a tuning factor which should be determined /// experimentally by running benchmarks. /// /// Note that in Xavier Gourdon's paper alpha_y is named c /// but we name it alpha_y since y = x^(1/3) * alpha_y /// and the tuning factor in Tomás Oliveira e Silva's paper /// is also named alpha. /// double get_alpha_y_gourdon(maxint_t x) { double alpha_y = alpha_y_; double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha_y < 1) { double a = 0.000451957; double b = -0.0128774; double c = 0.0999006; double d = 0.860792; double logx = log(x2); alpha_y = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha_y, iroot<6>(x)); } /// z = y * alpha_z, with alpha_z >= 1. /// In Xavier Gourdon's paper the alpha_z tuning factor /// is named d. alpha_z should be determined experimentally /// by running benchmarks. /// double get_alpha_z_gourdon(maxint_t x) { double alpha_y = get_alpha_y_gourdon(x); double alpha_z = alpha_z_; if (alpha_z < 1) { // Xavier Gourdon's fastpix11.exe binary uses d = 2.4 but // according to my benchmarks alpha_z should grow very slowly // and be much smaller than alpha_y. double log_alpha_y = log(max(1.0, alpha_y)); double loglog_alpha_y = log(max(1.0, log_alpha_y)); alpha_z = 1 + loglog_alpha_y; } double x16 = (double) iroot<6>(x); double max_alpha = min(alpha_y * alpha_z, x16); return in_between(1, alpha_z, max_alpha); } /// x_star = max(x^(1/4), x / y^2) /// /// After my implementation of Xavier Gourdon's algorithm worked for /// the first time there were still many miscalculations mainly for /// small numbers < 10^6. By debugging I found that most errors were /// related to the Sigma formulas (Σ0 - Σ6) and the x_star variable /// was responsible for most errors. For some unknown reason the /// bounds from Xavier's paper (max(x^(1/4), x / y^2)) don't seem to /// be enough. By trial and error I figured out a few more bounds that /// fix all miscalculations in my implementation. /// int64_t get_x_star_gourdon(maxint_t x, int64_t y) { // For some unknown reason it is necessary // to round up (x / y^2). Without rounding up // there are many miscalculations below 2000 // in my implementation. y = max(y, (int64_t) 1); maxint_t yy = (maxint_t) y * y; maxint_t x_div_yy = ceil_div(x, yy); int64_t x_star = (int64_t) max(iroot<4>(x), x_div_yy); int64_t sqrt_xy = (int64_t) isqrt(x / y); // x_star <= y // x_star <= (x / y)^(1/2) // The bounds above are missing in Xavier Gourdon's // paper. Without these bounds many of the 7 Sigma // formulas (Σ0 - Σ6) return incorrect results for // numbers below 10^6. x_star = min(x_star, y); x_star = min(x_star, sqrt_xy); x_star = max(x_star, (int64_t) 1); return x_star; } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #endif primesieve::set_num_threads(threads); } int get_num_threads() { #ifdef _OPENMP if (threads_) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return max(status_precision_, 0); } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } string primecount_version() { return PRIMECOUNT_VERSION; } } // namespace <commit_msg>Tune alpha_y factor<commit_after>/// /// @file primecount.cpp /// @brief Function definitions of primecount.hpp /// /// Copyright (C) 2019 Kim Walisch, <[email protected]> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount.hpp> #include <primecount-internal.hpp> #include <primesieve.hpp> #include <calculator.hpp> #include <int128_t.hpp> #include <imath.hpp> #include <algorithm> #include <chrono> #include <cmath> #include <limits> #include <sstream> #include <string> #include <stdint.h> #ifdef _OPENMP #include <omp.h> #endif #ifdef HAVE_MPI #include <mpi.h> namespace primecount { int mpi_num_procs() { int procs; MPI_Comm_size(MPI_COMM_WORLD, &procs); return procs; } int mpi_proc_id() { int proc_id; MPI_Comm_rank(MPI_COMM_WORLD, &proc_id); return proc_id; } int mpi_master_proc_id() { return 0; } bool is_mpi_master_proc() { return mpi_proc_id() == mpi_master_proc_id(); } } // namespace #endif using namespace std; namespace { #ifdef _OPENMP int threads_ = 0; #endif // Below 10^7 LMO is faster than Deleglise-Rivat const int lmo_threshold_ = 10000000; int status_precision_ = -1; // Tuning factor used in the Lagarias-Miller-Odlyzko // and Deleglise-Rivat algorithms. double alpha_ = -1; // Tuning factor used in Xavier Gourdon's algorithm double alpha_y_ = -1; // Tuning factor used in Xavier Gourdon's algorithm double alpha_z_ = -1; } namespace primecount { int64_t pi(int64_t x) { return pi(x, get_num_threads()); } int64_t pi(int64_t x, int threads) { if (x <= lmo_threshold_) return pi_lmo5(x); else return pi_deleglise_rivat(x, threads); } #ifdef HAVE_INT128_T int128_t pi(int128_t x) { return pi(x, get_num_threads()); } int128_t pi(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi((int64_t) x, threads); else return pi_deleglise_rivat(x, threads); } #endif string pi(const string& x) { return pi(x, get_num_threads()); } string pi(const string& x, int threads) { maxint_t pi_x = pi(to_maxint(x), threads); ostringstream oss; oss << pi_x; return oss.str(); } int64_t pi_legendre(int64_t x) { return pi_legendre(x, get_num_threads()); } int64_t pi_lehmer(int64_t x) { return pi_lehmer(x, get_num_threads()); } int64_t pi_lmo(int64_t x) { return pi_lmo(x, get_num_threads()); } int64_t pi_lmo(int64_t x, int threads) { return pi_lmo_parallel(x, threads); } int64_t pi_meissel(int64_t x) { return pi_meissel(x, get_num_threads()); } int64_t pi_deleglise_rivat(int64_t x) { return pi_deleglise_rivat(x, get_num_threads()); } int64_t pi_deleglise_rivat(int64_t x, int threads) { return pi_deleglise_rivat_parallel1(x, threads); } #ifdef HAVE_INT128_T int128_t pi_deleglise_rivat(int128_t x) { return pi_deleglise_rivat(x, get_num_threads()); } int128_t pi_deleglise_rivat(int128_t x, int threads) { // use 64-bit if possible if (x <= numeric_limits<int64_t>::max()) return pi_deleglise_rivat_parallel1((int64_t) x, threads); else return pi_deleglise_rivat_parallel2(x, threads); } #endif int64_t nth_prime(int64_t n) { return nth_prime(n, get_num_threads()); } int64_t phi(int64_t x, int64_t a) { return phi(x, a, get_num_threads()); } /// Returns the largest integer supported by pi(x). The /// return type is a string as get_max_x() can be a 128-bit /// integer which is not supported by all compilers. /// string get_max_x(double alpha) { ostringstream oss; #ifdef HAVE_INT128_T // primecount is limited by: // z <= 2^62, with z = x^(2/3) / alpha // x^(2/3) / alpha <= 2^62 // x <= (2^62 * alpha)^(3/2) // double max_x = pow(pow(2.0, 62.0) * alpha, 3.0 / 2.0); oss << (int128_t) max_x; #else unused_param(alpha); oss << numeric_limits<int64_t>::max(); #endif return oss.str(); } /// Get the time in seconds double get_time() { auto now = chrono::steady_clock::now(); auto time = now.time_since_epoch(); auto micro = chrono::duration_cast<chrono::microseconds>(time); return (double) micro.count() / 1e6; } int ideal_num_threads(int threads, int64_t sieve_limit, int64_t thread_threshold) { thread_threshold = max((int64_t) 1, thread_threshold); threads = (int) min((int64_t) threads, sieve_limit / thread_threshold); threads = max(1, threads); return threads; } void set_alpha(double alpha) { alpha_ = alpha; } void set_alpha_y(double alpha_y) { alpha_y_ = alpha_y; } void set_alpha_z(double alpha_z) { alpha_z_ = alpha_z; } /// Tuning factor used in the Lagarias-Miller-Odlyzko /// and Deleglise-Rivat algorithms. /// double get_alpha(maxint_t x, int64_t y) { // y = x13 * alpha, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Tuning factor used in Xavier Gourdon's algorithm. double get_alpha_y(maxint_t x, int64_t y) { // y = x13 * alpha_y, thus alpha = y / x13 double x13 = (double) iroot<3>(x); return (double) y / x13; } /// Tuning factor used in Xavier Gourdon's algorithm. double get_alpha_z(int64_t y, int64_t z) { // z = y * alpha_z, thus alpha_z = z / y return (double) z / y; } /// Get the Lagarias-Miller-Odlyzko alpha tuning factor. /// alpha = a log(x)^2 + b log(x) + c /// a, b and c have been determined empirically. /// @see doc/alpha-factor-tuning.pdf /// double get_alpha_lmo(maxint_t x) { double alpha = alpha_; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00156512; double b = -0.0261411; double c = 0.990948; double logx = log((double) x); alpha = a * pow(logx, 2) + b * logx + c; } return in_between(1, alpha, iroot<6>(x)); } /// Get the Deleglise-Rivat alpha tuning factor. /// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d /// a, b, c and d have been determined empirically. /// @see doc/alpha-tuning-factor.pdf /// double get_alpha_deleglise_rivat(maxint_t x) { double alpha = alpha_; double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha < 1) { double a = 0.00033826; double b = 0.0018113; double c = -0.110407; double d = 1.3724; double logx = log(x2); alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha, iroot<6>(x)); } /// y = x^(1/3) * alpha_y, with alpha_y >= 1. /// alpha_y is a tuning factor which should be determined /// experimentally by running benchmarks. /// /// Note that in Xavier Gourdon's paper alpha_y is named c /// but we name it alpha_y since y = x^(1/3) * alpha_y /// and the tuning factor in Tomás Oliveira e Silva's paper /// is also named alpha. /// double get_alpha_y_gourdon(maxint_t x) { double alpha_y = alpha_y_; double x2 = (double) x; // use default alpha if no command-line alpha provided if (alpha_y < 1) { double a = 0.000446563; double b = -0.0125132; double c = 0.094232; double d = 0.875222; double logx = log(x2); alpha_y = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d; } return in_between(1, alpha_y, iroot<6>(x)); } /// z = y * alpha_z, with alpha_z >= 1. /// In Xavier Gourdon's paper the alpha_z tuning factor /// is named d. alpha_z should be determined experimentally /// by running benchmarks. /// double get_alpha_z_gourdon(maxint_t x) { double alpha_y = get_alpha_y_gourdon(x); double alpha_z = alpha_z_; if (alpha_z < 1) { // Xavier Gourdon's fastpix11.exe binary uses d = 2.4 but // according to my benchmarks alpha_z should grow very slowly // and be much smaller than alpha_y. double log_alpha_y = log(max(1.0, alpha_y)); double loglog_alpha_y = log(max(1.0, log_alpha_y)); alpha_z = 1 + loglog_alpha_y; } double x16 = (double) iroot<6>(x); double max_alpha = min(alpha_y * alpha_z, x16); return in_between(1, alpha_z, max_alpha); } /// x_star = max(x^(1/4), x / y^2) /// /// After my implementation of Xavier Gourdon's algorithm worked for /// the first time there were still many miscalculations mainly for /// small numbers < 10^6. By debugging I found that most errors were /// related to the Sigma formulas (Σ0 - Σ6) and the x_star variable /// was responsible for most errors. For some unknown reason the /// bounds from Xavier's paper (max(x^(1/4), x / y^2)) don't seem to /// be enough. By trial and error I figured out a few more bounds that /// fix all miscalculations in my implementation. /// int64_t get_x_star_gourdon(maxint_t x, int64_t y) { // For some unknown reason it is necessary // to round up (x / y^2). Without rounding up // there are many miscalculations below 2000 // in my implementation. y = max(y, (int64_t) 1); maxint_t yy = (maxint_t) y * y; maxint_t x_div_yy = ceil_div(x, yy); int64_t x_star = (int64_t) max(iroot<4>(x), x_div_yy); int64_t sqrt_xy = (int64_t) isqrt(x / y); // x_star <= y // x_star <= (x / y)^(1/2) // The bounds above are missing in Xavier Gourdon's // paper. Without these bounds many of the 7 Sigma // formulas (Σ0 - Σ6) return incorrect results for // numbers below 10^6. x_star = min(x_star, y); x_star = min(x_star, sqrt_xy); x_star = max(x_star, (int64_t) 1); return x_star; } void set_num_threads(int threads) { #ifdef _OPENMP threads_ = in_between(1, threads, omp_get_max_threads()); #endif primesieve::set_num_threads(threads); } int get_num_threads() { #ifdef _OPENMP if (threads_) return threads_; else return max(1, omp_get_max_threads()); #else return 1; #endif } void set_status_precision(int precision) { status_precision_ = in_between(0, precision, 5); } int get_status_precision(maxint_t x) { // use default precision when no command-line precision provided if (status_precision_ < 0) { if ((double) x >= 1e23) return 2; if ((double) x >= 1e21) return 1; } return max(status_precision_, 0); } maxint_t to_maxint(const string& expr) { maxint_t n = calculator::eval<maxint_t>(expr); return n; } string primecount_version() { return PRIMECOUNT_VERSION; } } // namespace <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: browserview.hxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2006-12-13 11:56:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ #define _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #include <com/sun/star/lang/XMultiServiceFactory.hpp> #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif // #95343# -------------------- #ifndef _COM_SUN_STAR_AWT_SIZE_HPP_ #include <com/sun/star/awt/Size.hpp> #endif //............................................................................ namespace pcr { //............................................................................ class OPropertyEditor; //======================================================================== //= //======================================================================== class OPropertyBrowserView : public Window { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; OPropertyEditor* m_pPropBox; sal_uInt16 m_nActivePage; Link m_aPageActivationHandler; protected: virtual void Resize(); virtual void GetFocus(); public: OPropertyBrowserView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB, Window* pParent, WinBits nBits = 0); virtual ~OPropertyBrowserView(); OPropertyEditor& getPropertyBox() { return *m_pPropBox; } // page handling sal_uInt16 getActivaPage() const { return m_nActivePage; } void activatePage(sal_uInt16 _nPage); void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; } Link getPageActivationHandler() const { return m_aPageActivationHandler; } // #95343# ------------------ ::com::sun::star::awt::Size getMinimumSize(); protected: DECL_LINK(OnPageActivation, void*); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ <commit_msg>INTEGRATION: CWS dba22b (1.9.176); FILE MERGED 2006/12/18 11:07:27 fs 1.9.176.2: RESYNC: (1.9-1.10); FILE MERGED 2006/12/06 09:46:29 fs 1.9.176.1: #i63285# don't let DEL/BACKSPACE keys leave the property browser<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: browserview.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: vg $ $Date: 2007-01-15 14:40:35 $ * * 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 _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ #define _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #include <com/sun/star/lang/XMultiServiceFactory.hpp> #ifndef _SV_WINDOW_HXX #include <vcl/window.hxx> #endif #ifndef _TOOLS_RESID_HXX #include <tools/resid.hxx> #endif // #95343# -------------------- #ifndef _COM_SUN_STAR_AWT_SIZE_HPP_ #include <com/sun/star/awt/Size.hpp> #endif //............................................................................ namespace pcr { //............................................................................ class OPropertyEditor; //======================================================================== //= //======================================================================== class OPropertyBrowserView : public Window { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > m_xORB; OPropertyEditor* m_pPropBox; sal_uInt16 m_nActivePage; Link m_aPageActivationHandler; protected: virtual void Resize(); virtual void GetFocus(); virtual long Notify( NotifyEvent& _rNEvt ); public: OPropertyBrowserView(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB, Window* pParent, WinBits nBits = 0); virtual ~OPropertyBrowserView(); OPropertyEditor& getPropertyBox() { return *m_pPropBox; } // page handling sal_uInt16 getActivaPage() const { return m_nActivePage; } void activatePage(sal_uInt16 _nPage); void setPageActivationHandler(const Link& _rHdl) { m_aPageActivationHandler = _rHdl; } Link getPageActivationHandler() const { return m_aPageActivationHandler; } // #95343# ------------------ ::com::sun::star::awt::Size getMinimumSize(); protected: DECL_LINK(OnPageActivation, void*); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_BROWSERVIEW_HXX_ <|endoftext|>
<commit_before>// // Created by haohanwang on 2/2/16. // #include <limits> #include <stdexcept> #ifdef BAZEL #include "Models/MultiPopLasso.hpp" #else #include "MultiPopLasso.hpp" #endif using namespace std; using namespace Eigen; void MultiPopLasso::setXY(MatrixXd m, MatrixXd n) { X = m; y = n; } void MultiPopLasso::initBeta() { cout << "Multipop lasso does not suppor init beta explicitly here, beta will be initialized when formating data" << endl; } void MultiPopLasso::setLambda(double l) { lambda = l; } void MultiPopLasso::setPopulation(VectorXd pop) { // population indicator must start from 0 population = pop; popNum = (long)population.maxCoeff() + 1; } double MultiPopLasso::cost() { initTraining(); return 0.5 * (y - X * beta).squaredNorm() + lambda * groupPenalization(); } double MultiPopLasso::groupPenalization() { double r = 0; MatrixXd tmp = getBetaInside(); for (long i = 0; i < tmp.rows(); i++) { r += tmp.row(i).squaredNorm(); } return r; } void MultiPopLasso::assertReadyToRun() { // X and Y must be compatible if (!((X.rows() > 0) && (X.rows() == y.rows()) && (X.cols() > 0) && (y.cols() > 0))) { throw runtime_error("X and Y matrices of size (" + to_string(X.rows()) + "," + to_string(X.cols()) + "), and (" + to_string(y.rows()) + "," + to_string(y.cols()) + ") are not compatible."); } // Population Labels must have n rows (one for each sample) if (population.rows() != X.rows()) { throw runtime_error("Population labels of length " + to_string(population.rows()) + " are the wrong size for X with " + to_string(X.rows()) + " samples."); } cerr << "assertReadyToRun passed" << endl; } void MultiPopLasso::setAttributeMatrix(const string& str, MatrixXd* Z) { if (str == "population") { cerr << "setting population" << endl; // todo: stop copying data setPopulation(VectorXd(Map<VectorXd>(Z->data(), Z->rows()))); } else if (str == "X") { setX(*Z); } else if (str == "Y") { setY(*Z); } else { throw runtime_error("MultiPopLasso models have no attribute with name" + str); } } void MultiPopLasso::initTraining() { if (!initTrainingFlag){ initTrainingFlag = true; reArrangeData(); formatData(); initC(); } } void MultiPopLasso::reArrangeData() { // arrange data according to its population long r = X.rows(); long c = X.cols(); MatrixXd tmpX = MatrixXd::Zero(r, c); MatrixXd tmpY = MatrixXd::Zero(r, 1); VectorXd tmpPop = VectorXd::Zero(r); vector<long> idx; long count = 0; for (long i=0; i<popNum; i++){ idx = getPopulationIndex(i); for (unsigned long j=0; j<idx.size(); j++){ tmpX.row(count) = X.row(idx.at(j)); tmpY.row(count) = y.row(idx.at(j)); tmpPop(count++) = i; } } X = tmpX; y = tmpY; population = tmpPop; } void MultiPopLasso::removeColumns() { long c = X.cols(); removeCols = VectorXi::Zero(c); for (long i = 0; i < c; i++) { double var = Math::getInstance().variance(X.col(i)); if (var < 1e-3) { removeCols(i) = 1; } } long r = X.rows(); long b = r / popNum; MatrixXd tmp; double cor; double std; for (long i = 0; i < r; i += b) { tmp = X.block(i, 0, b, c); for (long j = 0; j < c; j++) { if (removeCols(j) == 0) { for (long k = j + 1; k < c; k++) { if (removeCols(k) == 0) { cor = Math::getInstance().correlation(tmp.col(j), tmp.col(k)); if (cor > 0.98) { removeCols(k) = 1; } } } std = Math::getInstance().std(tmp.col(j)); if (std < 1e-9) { removeCols(j) = 1; } } } } } MatrixXd MultiPopLasso::normalizeData_col(MatrixXd a) { long c = a.cols(); VectorXd mean = a.colwise().mean(); VectorXd std_inv = VectorXd::Zero(c); for (long i = 0; i < c; i++) { std_inv(i) = 1.0 / Math::getInstance().std(a.col(i)); } return ((a.colwise() - mean).array().colwise() * std_inv.array()).matrix(); } void MultiPopLasso::formatData() { // format data, put data into X matrix and init beta // todo: here we don't remove columns, may add it later // for (long i = removeCols.size() - 1; i >= 0; i--) { // if (removeCols(i) == 1) { // Math::getInstance().removeCol(&X, i); // } // } long c = X.cols(); long r = X.rows(); MatrixXd tmpX = MatrixXd::Zero(r, c * popNum); double pIdx = 0; for (long i=0;i<r;i++){ pIdx = population(i); for (long j=0;j<c;j++){ tmpX(i, j*popNum+pIdx) = X(i, j); } } X = tmpX; beta = MatrixXd::Random(c * popNum, 1); L = ((X.transpose()*X).eigenvalues()).real().maxCoeff(); } void MultiPopLasso::initC() { long c = X.cols(); C = MatrixXd::Zero(c * popNum, c); for (long i = 0; i < c; i++) { for (long j = 0; j < popNum; j++) { C(i*j+j, i) = gamma; } } } MatrixXd MultiPopLasso::proximal_derivative() { long r = beta.rows(); long c = beta.cols(); MatrixXd A = MatrixXd::Zero(r*popNum, c); MatrixXd tmp = C*beta; for (long i=0;i<r*popNum;i++){ A.row(i) = Math::getInstance().L2Thresholding(tmp.row(i)/mu); } return X.transpose()*(X*beta-y) + C.transpose()*A; } MatrixXd MultiPopLasso::proximal_operator(MatrixXd in, float lr) { MatrixXd sign = ((in.array()>0).matrix()).cast<double>(); sign += -1.0*((in.array()<0).matrix()).cast<double>(); in = ((in.array().abs()-lr*lambda).max(0)).matrix(); return (in.array()*sign.array()).matrix(); } //MatrixXd MultiPopLasso::deriveMatrixA(double lr, long loops, double tol) { // long r = beta.rows(); // long c = C.rows(); // MatrixXd A = MatrixXd::Zero(r, c); // MatrixXd bct = beta*C.transpose(); // double prev_residue = numeric_limits<double>::max(); // double curr_residue; // for (long i=0;i<loops;i++){ // A = A - lr*(bct - A); // A = project(A); // curr_residue = (bct*A).trace() - 0.5*A.norm(); // if (prev_residue - curr_residue<= tol){ // break; // } // else{ // prev_residue = curr_residue; // } // } // return A; //} // //MatrixXd MultiPopLasso::project(MatrixXd A) { // if (A.norm() <= 1){ // return A; // } // else{ // return A; // } //} // double MultiPopLasso::getL(){ double c = C.norm()/mu; return c + L; } vector<long> MultiPopLasso::getPopulationIndex(long pi) { vector<long> idx; for (long i=0;i<y.rows();i++){ if (population(i) == pi){ idx.push_back(i); } } return idx; } MatrixXd MultiPopLasso::getBetaInside() { long c = X.cols()/popNum; MatrixXd r = MatrixXd::Zero(popNum, c); for (long i=0;i<popNum;i++){ for (long j=0;j<c;j++){ r(i, j) = beta(j*popNum+i,i/popNum); } } return r; } MatrixXd MultiPopLasso::getBeta() { long c = X.cols()/popNum; MatrixXd r = MatrixXd::Zero(popNum*betaAll.cols(), c); for (long k=0;k<betaAll.cols();k++){ for (long i=0;i<popNum;i++){ for (long j=0;j<c;j++){ r(i+k*popNum, j) = betaAll(j*popNum+i,k); } } } return r.transpose()*100; } void MultiPopLasso::setMu(double m) { mu = m; } void MultiPopLasso::setGamma(double g) { gamma = g; } MatrixXd MultiPopLasso::getFormattedBeta() { return beta; } MatrixXd MultiPopLasso::predict() { cout << "does not allow prediction with original X, please use predict(X, population) method instead"<<endl; return MatrixXd::Random(1,1); } MatrixXd MultiPopLasso::predict(MatrixXd x) { cout << "does not allow prediction without population information"<<endl; return MatrixXd::Random(1,1); } MatrixXd MultiPopLasso::predict(MatrixXd x, VectorXd pop){ long r= x.rows(); MatrixXd y(r, 1); MatrixXd b = getBeta(); for (long i=0;i<r;i++){ y.row(i) = x.row(i)*(b.row(long(pop(i))).transpose()); } return y; } MultiPopLasso::MultiPopLasso() { initTrainingFlag = false; lambda = default_lambda; mu = default_mu; gamma = default_gamma; betaAll = MatrixXd::Ones(1,1); } MultiPopLasso::MultiPopLasso(const unordered_map<string, string> &options) { initTrainingFlag = false; try { lambda = stod(options.at("lambda")); } catch (std::out_of_range& oor) { lambda = default_lambda; } try { mu = stod(options.at("mu")); } catch (std::out_of_range& oor) { mu = default_mu; } try { gamma = stod(options.at("gamma")); } catch (std::out_of_range& oor) { gamma = default_gamma; } betaAll = MatrixXd::Ones(1,1); } void MultiPopLasso::updateBetaAll() { if (betaAll.rows() == 1){ betaAll = beta; } else{ betaAll.conservativeResize(betaAll.rows(),betaAll.cols()+1); betaAll.col(betaAll.cols()-1) = beta; } } MatrixXd MultiPopLasso::getBetaAll() { return betaAll; } void MultiPopLasso::reSetFlag() { initTrainingFlag = false; } <commit_msg>fix prediction for tests<commit_after>// // Created by haohanwang on 2/2/16. // #include <limits> #include <stdexcept> #ifdef BAZEL #include "Models/MultiPopLasso.hpp" #else #include "MultiPopLasso.hpp" #endif using namespace std; using namespace Eigen; void MultiPopLasso::setXY(MatrixXd m, MatrixXd n) { X = m; y = n; } void MultiPopLasso::initBeta() { cout << "Multipop lasso does not suppor init beta explicitly here, beta will be initialized when formating data" << endl; } void MultiPopLasso::setLambda(double l) { lambda = l; } void MultiPopLasso::setPopulation(VectorXd pop) { // population indicator must start from 0 population = pop; popNum = (long)population.maxCoeff() + 1; } double MultiPopLasso::cost() { initTraining(); return 0.5 * (y - X * beta).squaredNorm() + lambda * groupPenalization(); } double MultiPopLasso::groupPenalization() { double r = 0; MatrixXd tmp = getBetaInside(); for (long i = 0; i < tmp.rows(); i++) { r += tmp.row(i).squaredNorm(); } return r; } void MultiPopLasso::assertReadyToRun() { // X and Y must be compatible if (!((X.rows() > 0) && (X.rows() == y.rows()) && (X.cols() > 0) && (y.cols() > 0))) { throw runtime_error("X and Y matrices of size (" + to_string(X.rows()) + "," + to_string(X.cols()) + "), and (" + to_string(y.rows()) + "," + to_string(y.cols()) + ") are not compatible."); } // Population Labels must have n rows (one for each sample) if (population.rows() != X.rows()) { throw runtime_error("Population labels of length " + to_string(population.rows()) + " are the wrong size for X with " + to_string(X.rows()) + " samples."); } cerr << "assertReadyToRun passed" << endl; } void MultiPopLasso::setAttributeMatrix(const string& str, MatrixXd* Z) { if (str == "population") { cerr << "setting population" << endl; // todo: stop copying data setPopulation(VectorXd(Map<VectorXd>(Z->data(), Z->rows()))); } else if (str == "X") { setX(*Z); } else if (str == "Y") { setY(*Z); } else { throw runtime_error("MultiPopLasso models have no attribute with name" + str); } } void MultiPopLasso::initTraining() { if (!initTrainingFlag){ initTrainingFlag = true; reArrangeData(); formatData(); initC(); } } void MultiPopLasso::reArrangeData() { // arrange data according to its population long r = X.rows(); long c = X.cols(); MatrixXd tmpX = MatrixXd::Zero(r, c); MatrixXd tmpY = MatrixXd::Zero(r, 1); VectorXd tmpPop = VectorXd::Zero(r); vector<long> idx; long count = 0; for (long i=0; i<popNum; i++){ idx = getPopulationIndex(i); for (unsigned long j=0; j<idx.size(); j++){ tmpX.row(count) = X.row(idx.at(j)); tmpY.row(count) = y.row(idx.at(j)); tmpPop(count++) = i; } } X = tmpX; y = tmpY; population = tmpPop; } void MultiPopLasso::removeColumns() { long c = X.cols(); removeCols = VectorXi::Zero(c); for (long i = 0; i < c; i++) { double var = Math::getInstance().variance(X.col(i)); if (var < 1e-3) { removeCols(i) = 1; } } long r = X.rows(); long b = r / popNum; MatrixXd tmp; double cor; double std; for (long i = 0; i < r; i += b) { tmp = X.block(i, 0, b, c); for (long j = 0; j < c; j++) { if (removeCols(j) == 0) { for (long k = j + 1; k < c; k++) { if (removeCols(k) == 0) { cor = Math::getInstance().correlation(tmp.col(j), tmp.col(k)); if (cor > 0.98) { removeCols(k) = 1; } } } std = Math::getInstance().std(tmp.col(j)); if (std < 1e-9) { removeCols(j) = 1; } } } } } MatrixXd MultiPopLasso::normalizeData_col(MatrixXd a) { long c = a.cols(); VectorXd mean = a.colwise().mean(); VectorXd std_inv = VectorXd::Zero(c); for (long i = 0; i < c; i++) { std_inv(i) = 1.0 / Math::getInstance().std(a.col(i)); } return ((a.colwise() - mean).array().colwise() * std_inv.array()).matrix(); } void MultiPopLasso::formatData() { // format data, put data into X matrix and init beta // todo: here we don't remove columns, may add it later // for (long i = removeCols.size() - 1; i >= 0; i--) { // if (removeCols(i) == 1) { // Math::getInstance().removeCol(&X, i); // } // } long c = X.cols(); long r = X.rows(); MatrixXd tmpX = MatrixXd::Zero(r, c * popNum); double pIdx = 0; for (long i=0;i<r;i++){ pIdx = population(i); for (long j=0;j<c;j++){ tmpX(i, j*popNum+pIdx) = X(i, j); } } X = tmpX; beta = MatrixXd::Random(c * popNum, 1); L = ((X.transpose()*X).eigenvalues()).real().maxCoeff(); } void MultiPopLasso::initC() { long c = X.cols(); C = MatrixXd::Zero(c * popNum, c); for (long i = 0; i < c; i++) { for (long j = 0; j < popNum; j++) { C(i*j+j, i) = gamma; } } } MatrixXd MultiPopLasso::proximal_derivative() { long r = beta.rows(); long c = beta.cols(); MatrixXd A = MatrixXd::Zero(r*popNum, c); MatrixXd tmp = C*beta; for (long i=0;i<r*popNum;i++){ A.row(i) = Math::getInstance().L2Thresholding(tmp.row(i)/mu); } return X.transpose()*(X*beta-y) + C.transpose()*A; } MatrixXd MultiPopLasso::proximal_operator(MatrixXd in, float lr) { MatrixXd sign = ((in.array()>0).matrix()).cast<double>(); sign += -1.0*((in.array()<0).matrix()).cast<double>(); in = ((in.array().abs()-lr*lambda).max(0)).matrix(); return (in.array()*sign.array()).matrix(); } //MatrixXd MultiPopLasso::deriveMatrixA(double lr, long loops, double tol) { // long r = beta.rows(); // long c = C.rows(); // MatrixXd A = MatrixXd::Zero(r, c); // MatrixXd bct = beta*C.transpose(); // double prev_residue = numeric_limits<double>::max(); // double curr_residue; // for (long i=0;i<loops;i++){ // A = A - lr*(bct - A); // A = project(A); // curr_residue = (bct*A).trace() - 0.5*A.norm(); // if (prev_residue - curr_residue<= tol){ // break; // } // else{ // prev_residue = curr_residue; // } // } // return A; //} // //MatrixXd MultiPopLasso::project(MatrixXd A) { // if (A.norm() <= 1){ // return A; // } // else{ // return A; // } //} // double MultiPopLasso::getL(){ double c = C.norm()/mu; return c + L; } vector<long> MultiPopLasso::getPopulationIndex(long pi) { vector<long> idx; for (long i=0;i<y.rows();i++){ if (population(i) == pi){ idx.push_back(i); } } return idx; } MatrixXd MultiPopLasso::getBetaInside() { long c = X.cols()/popNum; MatrixXd r = MatrixXd::Zero(popNum, c); for (long i=0;i<popNum;i++){ for (long j=0;j<c;j++){ r(i, j) = beta(j*popNum+i,i/popNum); } } return r; } MatrixXd MultiPopLasso::getBeta() { long c = X.cols()/popNum; MatrixXd r = MatrixXd::Zero(popNum*betaAll.cols(), c); for (long k=0;k<betaAll.cols();k++){ for (long i=0;i<popNum;i++){ for (long j=0;j<c;j++){ r(i+k*popNum, j) = betaAll(j*popNum+i,k); } } } return r.transpose()*100; } void MultiPopLasso::setMu(double m) { mu = m; } void MultiPopLasso::setGamma(double g) { gamma = g; } MatrixXd MultiPopLasso::getFormattedBeta() { return beta; } MatrixXd MultiPopLasso::predict() { cout << "does not allow prediction with original X, please use predict(X, population) method instead"<<endl; return MatrixXd::Random(1,1); } MatrixXd MultiPopLasso::predict(MatrixXd x) { cout << "does not allow prediction without population information"<<endl; return MatrixXd::Random(1,1); } MatrixXd MultiPopLasso::predict(MatrixXd x, VectorXd pop){ long r= x.rows(); MatrixXd y(r, 1); MatrixXd b = getBetaInside(); for (long i=0;i<r;i++){ y.row(i) = x.row(i)*(b.row(long(pop(i))).transpose()); } return y; } MultiPopLasso::MultiPopLasso() { initTrainingFlag = false; lambda = default_lambda; mu = default_mu; gamma = default_gamma; betaAll = MatrixXd::Ones(1,1); } MultiPopLasso::MultiPopLasso(const unordered_map<string, string> &options) { initTrainingFlag = false; try { lambda = stod(options.at("lambda")); } catch (std::out_of_range& oor) { lambda = default_lambda; } try { mu = stod(options.at("mu")); } catch (std::out_of_range& oor) { mu = default_mu; } try { gamma = stod(options.at("gamma")); } catch (std::out_of_range& oor) { gamma = default_gamma; } betaAll = MatrixXd::Ones(1,1); } void MultiPopLasso::updateBetaAll() { if (betaAll.rows() == 1){ betaAll = beta; } else{ betaAll.conservativeResize(betaAll.rows(),betaAll.cols()+1); betaAll.col(betaAll.cols()-1) = beta; } } MatrixXd MultiPopLasso::getBetaAll() { return betaAll; } void MultiPopLasso::reSetFlag() { initTrainingFlag = false; } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/EngineLog.hpp> # include <Siv3D/Keyboard.hpp> # include <Siv3D/Window/IWindow.hpp> # include <Siv3D/Common/Siv3DEngine.hpp> # include "CTextInput.hpp" extern "C" { using namespace s3d; CTextInput* pTextInput = nullptr; XIMCallback preeditStart; XIMCallback preeditDraw; XIMCallback preeditDone; XIMCallback preeditCaret; void preeditStartCallback(XIC, XPointer, XPointer) { // do nothing } void preeditDoneCallback(XIC, XPointer, XPointer) { // do nothing } void preeditDrawCallback(XIC ic, XPointer client_data, XIMPreeditDrawCallbackStruct *call_data) { pTextInput->preeditDrawCallback(ic, client_data, call_data); } void preeditCaretCallback(XIC, XPointer, XIMPreeditCaretCallbackStruct *) { // do nothing } XVaNestedList s3d_PreeditAttributes(XPointer client_data) { preeditStart.client_data = client_data; preeditStart.callback = (XIMProc)preeditStartCallback; preeditDone.client_data = client_data; preeditDone.callback = (XIMProc)preeditDoneCallback; preeditDraw.client_data = client_data; preeditDraw.callback = (XIMProc)preeditDrawCallback; preeditCaret.client_data = client_data; preeditCaret.callback = (XIMProc)preeditCaretCallback; return XVaCreateNestedList(0, XNPreeditStartCallback, &preeditStart.client_data, XNPreeditDoneCallback, &preeditDone.client_data, XNPreeditDrawCallback, &preeditDraw.client_data, XNPreeditCaretCallback, &preeditCaret.client_data, NULL); } void s3d_InputText(char *text) { pTextInput->sendInputText(Unicode::FromUTF8(text)); } void s3d_SetICFocus(XIC) { pTextInput->updateWindowFocus(true); } void s3d_UnsetICFocus(XIC) { pTextInput->updateWindowFocus(false); } XIC s3d_GetXICFromGLFWWindow(GLFWwindow *window); } namespace s3d { CTextInput::CTextInput() { pTextInput = this; } CTextInput::~CTextInput() { LOG_SCOPED_TRACE(U"CTextInput::~CTextInput()"); pTextInput = nullptr; } void CTextInput::init() { LOG_SCOPED_TRACE(U"CTextInput::init()"); if (GLFWwindow* glfwWindow = static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle())) { ::glfwSetCharCallback(glfwWindow, OnCharacterInput); } } void CTextInput::update() { { std::lock_guard lock{ m_mutex }; m_chars = m_internalChars; m_internalChars.clear(); } { std::lock_guard lock{ m_mutexPreeditStatus }; m_preeditText = m_internalPreeditText; m_preeditTextStyle = m_internalPreeditTextStyle; m_preeditCaret = m_internalPreeditCaret; } } void CTextInput::pushChar(const uint32 ch) { std::lock_guard lock{ m_mutex }; m_internalChars.push_back(static_cast<char32>(ch)); } const String& CTextInput::getChars() const { return m_chars; } const String& CTextInput::getEditingText() const { return m_preeditText; } void CTextInput::enableIME(bool enabled) { m_imeEnabled = enabled; updateICFocus(); } std::pair<int32, int32> CTextInput::getCursorIndex() const { return{ m_preeditCaret, 0}; } const Array<String>& CTextInput::getCandidates() const { static const Array<String> dummy; return dummy; } const Array<EditingTextCharStyle>& CTextInput::getEditingTextStyle() const { return m_preeditTextStyle; } void CTextInput::preeditDrawCallback(XIC, XPointer, XIMPreeditDrawCallbackStruct* call_data) { std::lock_guard lock{ m_mutexPreeditStatus }; m_internalPreeditCaret = call_data->caret; if (call_data->text) { String text; if (call_data->text->encoding_is_wchar) { text = Unicode::FromWstring(call_data->text->string.wide_char); } else { text = Unicode::FromUTF8(call_data->text->string.multi_byte); } m_internalPreeditText.erase(call_data->chg_first, call_data->chg_length); m_internalPreeditText.insert(call_data->chg_first, text); m_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length)); m_internalPreeditTextStyle.insert(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), text.length(), EditingTextCharStyle::NoStyle); auto itr = std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first); EditingTextCharStyle style = EditingTextCharStyle::NoStyle; for(size_t idx = 0; idx < text.length(); idx++) { auto feedback = call_data->text->feedback[idx]; if(feedback == 0) { *itr = style; } else { if (feedback & XIMReverse) { *itr |= EditingTextCharStyle::Highlight; } if (feedback & XIMHighlight) { *itr |= EditingTextCharStyle::DashedUnderline; } if (feedback & XIMUnderline) { *itr = (*itr & ~EditingTextCharStyle::UnderlineMask) | EditingTextCharStyle::Underline; } } itr++; } } else { m_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length)); m_internalPreeditText.erase(call_data->chg_first, call_data->chg_length); } } void CTextInput::updateWindowFocus(bool focus) { m_windowHasFocus = focus; updateICFocus(); } void CTextInput::sendInputText(const String& text) { std::lock_guard lock { m_mutexChars }; m_internalChars.append(text); } void CTextInput::updateICFocus() { XIC ic = s3d_GetXICFromGLFWWindow(static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle())); if (ic) { if (m_imeEnabled && m_windowHasFocus) { XSetICFocus(ic); } else { XUnsetICFocus(ic); } } } void CTextInput::OnCharacterInput(GLFWwindow*, const uint32 codePoint) { SIV3D_ENGINE(TextInput)->pushChar(codePoint); } } <commit_msg>[Linux] 変数名の変更し忘れを修正<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/EngineLog.hpp> # include <Siv3D/Keyboard.hpp> # include <Siv3D/Window/IWindow.hpp> # include <Siv3D/Common/Siv3DEngine.hpp> # include "CTextInput.hpp" extern "C" { using namespace s3d; CTextInput* pTextInput = nullptr; XIMCallback preeditStart; XIMCallback preeditDraw; XIMCallback preeditDone; XIMCallback preeditCaret; void preeditStartCallback(XIC, XPointer, XPointer) { // do nothing } void preeditDoneCallback(XIC, XPointer, XPointer) { // do nothing } void preeditDrawCallback(XIC ic, XPointer client_data, XIMPreeditDrawCallbackStruct *call_data) { pTextInput->preeditDrawCallback(ic, client_data, call_data); } void preeditCaretCallback(XIC, XPointer, XIMPreeditCaretCallbackStruct *) { // do nothing } XVaNestedList s3d_PreeditAttributes(XPointer client_data) { preeditStart.client_data = client_data; preeditStart.callback = (XIMProc)preeditStartCallback; preeditDone.client_data = client_data; preeditDone.callback = (XIMProc)preeditDoneCallback; preeditDraw.client_data = client_data; preeditDraw.callback = (XIMProc)preeditDrawCallback; preeditCaret.client_data = client_data; preeditCaret.callback = (XIMProc)preeditCaretCallback; return XVaCreateNestedList(0, XNPreeditStartCallback, &preeditStart.client_data, XNPreeditDoneCallback, &preeditDone.client_data, XNPreeditDrawCallback, &preeditDraw.client_data, XNPreeditCaretCallback, &preeditCaret.client_data, NULL); } void s3d_InputText(char *text) { pTextInput->sendInputText(Unicode::FromUTF8(text)); } void s3d_SetICFocus(XIC) { pTextInput->updateWindowFocus(true); } void s3d_UnsetICFocus(XIC) { pTextInput->updateWindowFocus(false); } XIC s3d_GetXICFromGLFWWindow(GLFWwindow *window); } namespace s3d { CTextInput::CTextInput() { pTextInput = this; } CTextInput::~CTextInput() { LOG_SCOPED_TRACE(U"CTextInput::~CTextInput()"); pTextInput = nullptr; } void CTextInput::init() { LOG_SCOPED_TRACE(U"CTextInput::init()"); if (GLFWwindow* glfwWindow = static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle())) { ::glfwSetCharCallback(glfwWindow, OnCharacterInput); } } void CTextInput::update() { { std::lock_guard lock{ m_mutexChars }; m_chars = m_internalChars; m_internalChars.clear(); } { std::lock_guard lock{ m_mutexPreeditStatus }; m_preeditText = m_internalPreeditText; m_preeditTextStyle = m_internalPreeditTextStyle; m_preeditCaret = m_internalPreeditCaret; } } void CTextInput::pushChar(const uint32 ch) { std::lock_guard lock{ m_mutexChars }; m_internalChars.push_back(static_cast<char32>(ch)); } const String& CTextInput::getChars() const { return m_chars; } const String& CTextInput::getEditingText() const { return m_preeditText; } void CTextInput::enableIME(bool enabled) { m_imeEnabled = enabled; updateICFocus(); } std::pair<int32, int32> CTextInput::getCursorIndex() const { return{ m_preeditCaret, 0}; } const Array<String>& CTextInput::getCandidates() const { static const Array<String> dummy; return dummy; } const Array<EditingTextCharStyle>& CTextInput::getEditingTextStyle() const { return m_preeditTextStyle; } void CTextInput::preeditDrawCallback(XIC, XPointer, XIMPreeditDrawCallbackStruct* call_data) { std::lock_guard lock{ m_mutexPreeditStatus }; m_internalPreeditCaret = call_data->caret; if (call_data->text) { String text; if (call_data->text->encoding_is_wchar) { text = Unicode::FromWstring(call_data->text->string.wide_char); } else { text = Unicode::FromUTF8(call_data->text->string.multi_byte); } m_internalPreeditText.erase(call_data->chg_first, call_data->chg_length); m_internalPreeditText.insert(call_data->chg_first, text); m_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length)); m_internalPreeditTextStyle.insert(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), text.length(), EditingTextCharStyle::NoStyle); auto itr = std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first); EditingTextCharStyle style = EditingTextCharStyle::NoStyle; for(size_t idx = 0; idx < text.length(); idx++) { auto feedback = call_data->text->feedback[idx]; if(feedback == 0) { *itr = style; } else { if (feedback & XIMReverse) { *itr |= EditingTextCharStyle::Highlight; } if (feedback & XIMHighlight) { *itr |= EditingTextCharStyle::DashedUnderline; } if (feedback & XIMUnderline) { *itr = (*itr & ~EditingTextCharStyle::UnderlineMask) | EditingTextCharStyle::Underline; } } itr++; } } else { m_internalPreeditTextStyle.erase(std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first), std::next(m_internalPreeditTextStyle.begin(), call_data->chg_first + call_data->chg_length)); m_internalPreeditText.erase(call_data->chg_first, call_data->chg_length); } } void CTextInput::updateWindowFocus(bool focus) { m_windowHasFocus = focus; updateICFocus(); } void CTextInput::sendInputText(const String& text) { std::lock_guard lock { m_mutexChars }; m_internalChars.append(text); } void CTextInput::updateICFocus() { XIC ic = s3d_GetXICFromGLFWWindow(static_cast<GLFWwindow*>(SIV3D_ENGINE(Window)->getHandle())); if (ic) { if (m_imeEnabled && m_windowHasFocus) { XSetICFocus(ic); } else { XUnsetICFocus(ic); } } } void CTextInput::OnCharacterInput(GLFWwindow*, const uint32 codePoint) { SIV3D_ENGINE(TextInput)->pushChar(codePoint); } } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2012-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. /// \file /// Render Tests for the OsgBoxRepresentation class. #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Graphics/OsgAxesRepresentation.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgCapsuleRepresentation.h" #include "SurgSim/Graphics/OsgCylinderRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgSphereRepresentation.h" #include "SurgSim/Graphics/OsgSceneryRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/Vector.h" #include <gtest/gtest.h> #include <random> #include <osgUtil/SmoothingVisitor> using SurgSim::Framework::Runtime; using SurgSim::Framework::Scene; using SurgSim::Framework::SceneElement; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; using SurgSim::Math::Vector2d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; namespace SurgSim { namespace Graphics { struct OsgRepresentationRenderTests : public RenderTest { }; /// This test will put all shape one by one along the X-axis /// To make sure all shapes are aligned. /// X-axis points horizontally to the right /// Y-axis points vertically up /// Z-axis is perpendicular to the screen and points out TEST_F(OsgRepresentationRenderTests, RepresentationTest) { /// Box position Vector3d boxPosition(0.05, 0.0, -0.2); /// Capsule position Vector3d capsulePosition(-0.05, 0.0, -0.2); /// Cylinder position Vector3d cylinderPosition(-0.025, 0.0, -0.2); /// Sphere position Vector3d spherePosition(0.025, 0.0, -0.2); /// Size of the box Vector3d boxSize(0.01, 0.015, 0.01); /// Size of the capsule (radius, height) Vector2d capsuleSize(0.005, 0.015); /// Size of the cylinder Vector2d cylinderSize(0.005, 0.015); /// Radius of the sphere double sphereRadius = 0.005; /// Add representations to the view element so we don't need to make another concrete scene element std::shared_ptr<BoxRepresentation> boxRepresentation = std::make_shared<OsgBoxRepresentation>("box representation"); viewElement->addComponent(boxRepresentation); std::shared_ptr<CapsuleRepresentation> capsuleRepresentation = std::make_shared<OsgCapsuleRepresentation>("capsule representation"); viewElement->addComponent(capsuleRepresentation); std::shared_ptr<CylinderRepresentation> cylinderRepresentation = std::make_shared<OsgCylinderRepresentation>("cylinder representation"); viewElement->addComponent(cylinderRepresentation); std::shared_ptr<SphereRepresentation> sphereRepresentation = std::make_shared<OsgSphereRepresentation>("sphere representation"); viewElement->addComponent(sphereRepresentation); std::shared_ptr<AxesRepresentation> axesRepresentation = std::make_shared<OsgAxesRepresentation>("axes"); viewElement->addComponent(axesRepresentation); /// Run the thread runtime->start(); boxRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), boxPosition)); capsuleRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), capsulePosition)); cylinderRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), cylinderPosition)); sphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), spherePosition)); axesRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); /// Set the size of box boxRepresentation->setSizeXYZ(boxSize.x(), boxSize.y(), boxSize.z()); /// Set the size of capsule /// Capsule should use Y-axis as its axis capsuleRepresentation->setSize(capsuleSize.x(), capsuleSize.y()); /// Set the size of cylinder /// Cylinder should use Y-axis as its axis cylinderRepresentation->setSize(cylinderSize.x(), cylinderSize.y()); /// Set the size of sphere sphereRepresentation->setRadius(sphereRadius); axesRepresentation->setSize(0.01); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); boxRepresentation->setDrawAsWireFrame(true); capsuleRepresentation->setDrawAsWireFrame(true); cylinderRepresentation->setDrawAsWireFrame(true); sphereRepresentation->setDrawAsWireFrame(true); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } class LineGeometryVisitor : public osg::NodeVisitor { public : LineGeometryVisitor() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN), m_normalsScale(0.1) { } virtual ~LineGeometryVisitor() {} void apply(osg::Node& node) // NOLINT { traverse(node); } void apply(osg::Geode& geode) // NOLINT { // Only deal with 1 geometry for now ... if (geode.getNumDrawables() > 0) { osg::Geometry* curGeom = geode.getDrawable(0)->asGeometry(); if (curGeom) { osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(curGeom->getVertexArray()); auto normals = curGeom->getNormalArray(); geode.addDrawable(buildGeometry(vertices, normals, osg::Vec4(0.0, 0.0, 1.0, 1.0))); auto tangents = curGeom->getVertexAttribArray(7); auto cast = dynamic_cast<osg::Vec4Array*>(tangents); ASSERT_NE(nullptr, cast); ASSERT_EQ(vertices->size(), cast->size()); geode.addDrawable(buildGeometry(vertices, tangents, osg::Vec4(1.0, 0.0, 0.0, 1.0))); auto bitangents = curGeom->getVertexAttribArray(8); cast = dynamic_cast<osg::Vec4Array*>(bitangents); ASSERT_NE(nullptr, cast); ASSERT_EQ(vertices->size(), cast->size()); geode.addDrawable(buildGeometry(vertices, bitangents, osg::Vec4(0.0, 1.0, 0.0, 1.0))); } } } osg::Geometry* buildGeometry(osg::Vec3Array* geomVertices, osg::Array* directions, osg::Vec4 color) { // create Geometry object to store all the vertices and lines primitive. osg::Geometry* linesGeom = new osg::Geometry(); osg::Vec3Array* vertices = new osg::Vec3Array(geomVertices->size() * 2); osg::Vec3 direction; for (size_t i = 0; i < geomVertices->size(); ++i) { (*vertices)[i * 2] = (*geomVertices)[i]; switch (directions->getType()) { case osg::Array::Vec3ArrayType: direction = static_cast<const osg::Vec3Array&>(*directions)[i]; break; case osg::Array::Vec4ArrayType: for (int j = 0; j < 3; ++j) { direction[j] = static_cast<const osg::Vec4Array&>(*directions)[i].ptr()[j]; } break; default: SURGSIM_FAILURE() << "Unhandled Array type."; } (*vertices)[i * 2 + 1] = (*geomVertices)[i] + direction * m_normalsScale; } // pass the created vertex array to the points geometry object. linesGeom->setVertexArray(vertices); // set the colors as before, plus using the above osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(color); linesGeom->setColorArray(colors, osg::Array::BIND_OVERALL); // set the normal in the same way color. osg::Vec3Array* normals = new osg::Vec3Array; normals->push_back(osg::Vec3(0.0f, -1.0f, 0.0f)); linesGeom->setNormalArray(normals, osg::Array::BIND_OVERALL); linesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size())); osg::StateSet* state = linesGeom->getOrCreateStateSet(); state->setMode(GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF); return linesGeom; } private: float m_normalsScale; }; TEST_F(OsgRepresentationRenderTests, TangentTest) { auto element = std::make_shared<Framework::BasicSceneElement>("sphere"); auto graphics = std::make_shared<OsgSceneryRepresentation>("sphere"); graphics->loadModel("OsgRepresentationRenderTests/sphere0_5.obj"); //graphics->setDrawAsWireFrame(true); viewElement->enableManipulator(true); camera->setLocalPose(Math::makeRigidTransform( Vector3d(0.0, 0.0, -4.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0))); osg::ref_ptr<osg::Node> node = graphics->getOsgNode(); // Generate normals osgUtil::SmoothingVisitor sv; node->accept(sv); graphics->setGenerateTangents(true); LineGeometryVisitor visitor; node->accept(visitor); element->addComponent(graphics); scene->addSceneElement(element); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; // namespace Graphics }; // namespace SurgSim <commit_msg>Fix TangentRenderTest<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2012-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. /// \file /// Render Tests for the OsgBoxRepresentation class. #include "SurgSim/Framework/Runtime.h" #include "SurgSim/Framework/Scene.h" #include "SurgSim/Framework/SceneElement.h" #include "SurgSim/Graphics/OsgAxesRepresentation.h" #include "SurgSim/Graphics/OsgBoxRepresentation.h" #include "SurgSim/Graphics/OsgCapsuleRepresentation.h" #include "SurgSim/Graphics/OsgCylinderRepresentation.h" #include "SurgSim/Graphics/OsgManager.h" #include "SurgSim/Graphics/OsgSphereRepresentation.h" #include "SurgSim/Graphics/OsgSceneryRepresentation.h" #include "SurgSim/Graphics/OsgViewElement.h" #include "SurgSim/Graphics/RenderTests/RenderTest.h" #include "SurgSim/Math/Quaternion.h" #include "SurgSim/Math/Vector.h" #include <gtest/gtest.h> #include <random> #include <osgUtil/SmoothingVisitor> using SurgSim::Framework::Runtime; using SurgSim::Framework::Scene; using SurgSim::Framework::SceneElement; using SurgSim::Math::Quaterniond; using SurgSim::Math::RigidTransform3d; using SurgSim::Math::Vector3d; using SurgSim::Math::Vector2d; using SurgSim::Math::makeRigidTransform; using SurgSim::Math::makeRotationQuaternion; namespace SurgSim { namespace Graphics { struct OsgRepresentationRenderTests : public RenderTest { }; /// This test will put all shape one by one along the X-axis /// To make sure all shapes are aligned. /// X-axis points horizontally to the right /// Y-axis points vertically up /// Z-axis is perpendicular to the screen and points out TEST_F(OsgRepresentationRenderTests, RepresentationTest) { /// Box position Vector3d boxPosition(0.05, 0.0, -0.2); /// Capsule position Vector3d capsulePosition(-0.05, 0.0, -0.2); /// Cylinder position Vector3d cylinderPosition(-0.025, 0.0, -0.2); /// Sphere position Vector3d spherePosition(0.025, 0.0, -0.2); /// Size of the box Vector3d boxSize(0.01, 0.015, 0.01); /// Size of the capsule (radius, height) Vector2d capsuleSize(0.005, 0.015); /// Size of the cylinder Vector2d cylinderSize(0.005, 0.015); /// Radius of the sphere double sphereRadius = 0.005; /// Add representations to the view element so we don't need to make another concrete scene element std::shared_ptr<BoxRepresentation> boxRepresentation = std::make_shared<OsgBoxRepresentation>("box representation"); viewElement->addComponent(boxRepresentation); std::shared_ptr<CapsuleRepresentation> capsuleRepresentation = std::make_shared<OsgCapsuleRepresentation>("capsule representation"); viewElement->addComponent(capsuleRepresentation); std::shared_ptr<CylinderRepresentation> cylinderRepresentation = std::make_shared<OsgCylinderRepresentation>("cylinder representation"); viewElement->addComponent(cylinderRepresentation); std::shared_ptr<SphereRepresentation> sphereRepresentation = std::make_shared<OsgSphereRepresentation>("sphere representation"); viewElement->addComponent(sphereRepresentation); std::shared_ptr<AxesRepresentation> axesRepresentation = std::make_shared<OsgAxesRepresentation>("axes"); viewElement->addComponent(axesRepresentation); /// Run the thread runtime->start(); boxRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), boxPosition)); capsuleRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), capsulePosition)); cylinderRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), cylinderPosition)); sphereRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), spherePosition)); axesRepresentation->setLocalPose(makeRigidTransform(Quaterniond::Identity(), Vector3d(0.0, 0.0, -0.2))); /// Set the size of box boxRepresentation->setSizeXYZ(boxSize.x(), boxSize.y(), boxSize.z()); /// Set the size of capsule /// Capsule should use Y-axis as its axis capsuleRepresentation->setSize(capsuleSize.x(), capsuleSize.y()); /// Set the size of cylinder /// Cylinder should use Y-axis as its axis cylinderRepresentation->setSize(cylinderSize.x(), cylinderSize.y()); /// Set the size of sphere sphereRepresentation->setRadius(sphereRadius); axesRepresentation->setSize(0.01); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); boxRepresentation->setDrawAsWireFrame(true); capsuleRepresentation->setDrawAsWireFrame(true); cylinderRepresentation->setDrawAsWireFrame(true); sphereRepresentation->setDrawAsWireFrame(true); boost::this_thread::sleep(boost::posix_time::milliseconds(1500)); } class LineGeometryVisitor : public osg::NodeVisitor { public : LineGeometryVisitor() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN), m_normalsScale(0.1) { } virtual ~LineGeometryVisitor() {} void apply(osg::Node& node) // NOLINT { traverse(node); } void apply(osg::Geode& geode) // NOLINT { // Only deal with 1 geometry for now ... if (geode.getNumDrawables() > 0) { osg::Geometry* curGeom = geode.getDrawable(0)->asGeometry(); if (curGeom) { osg::Vec3Array* vertices = dynamic_cast<osg::Vec3Array*>(curGeom->getVertexArray()); auto normals = curGeom->getNormalArray(); geode.addDrawable(buildGeometry(vertices, normals, osg::Vec4(0.0, 0.0, 1.0, 1.0))); auto tangents = curGeom->getVertexAttribArray(TANGENT_VERTEX_ATTRIBUTE_ID); auto cast = dynamic_cast<osg::Vec4Array*>(tangents); ASSERT_NE(nullptr, cast); ASSERT_EQ(vertices->size(), cast->size()); geode.addDrawable(buildGeometry(vertices, tangents, osg::Vec4(1.0, 0.0, 0.0, 1.0))); auto bitangents = curGeom->getVertexAttribArray(BITANGENT_VERTEX_ATTRIBUTE_ID); cast = dynamic_cast<osg::Vec4Array*>(bitangents); ASSERT_NE(nullptr, cast); ASSERT_EQ(vertices->size(), cast->size()); geode.addDrawable(buildGeometry(vertices, bitangents, osg::Vec4(0.0, 1.0, 0.0, 1.0))); } } } osg::Geometry* buildGeometry(osg::Vec3Array* geomVertices, osg::Array* directions, osg::Vec4 color) { // create Geometry object to store all the vertices and lines primitive. osg::Geometry* linesGeom = new osg::Geometry(); osg::Vec3Array* vertices = new osg::Vec3Array(geomVertices->size() * 2); osg::Vec3 direction; for (size_t i = 0; i < geomVertices->size(); ++i) { (*vertices)[i * 2] = (*geomVertices)[i]; switch (directions->getType()) { case osg::Array::Vec3ArrayType: direction = static_cast<const osg::Vec3Array&>(*directions)[i]; break; case osg::Array::Vec4ArrayType: for (int j = 0; j < 3; ++j) { direction[j] = static_cast<const osg::Vec4Array&>(*directions)[i].ptr()[j]; } break; default: SURGSIM_FAILURE() << "Unhandled Array type."; } (*vertices)[i * 2 + 1] = (*geomVertices)[i] + direction * m_normalsScale; } // pass the created vertex array to the points geometry object. linesGeom->setVertexArray(vertices); // set the colors as before, plus using the above osg::Vec4Array* colors = new osg::Vec4Array; colors->push_back(color); linesGeom->setColorArray(colors, osg::Array::BIND_OVERALL); // set the normal in the same way color. osg::Vec3Array* normals = new osg::Vec3Array; normals->push_back(osg::Vec3(0.0f, -1.0f, 0.0f)); linesGeom->setNormalArray(normals, osg::Array::BIND_OVERALL); linesGeom->addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::LINES, 0, vertices->size())); osg::StateSet* state = linesGeom->getOrCreateStateSet(); state->setMode(GL_LIGHTING, osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF); return linesGeom; } private: float m_normalsScale; }; TEST_F(OsgRepresentationRenderTests, TangentTest) { auto element = std::make_shared<Framework::BasicSceneElement>("sphere"); auto graphics = std::make_shared<OsgSceneryRepresentation>("sphere"); graphics->loadModel("OsgRepresentationRenderTests/sphere0_5.obj"); //graphics->setDrawAsWireFrame(true); viewElement->enableManipulator(true); camera->setLocalPose(Math::makeRigidTransform( Vector3d(0.0, 0.0, -4.0), Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0))); osg::ref_ptr<osg::Node> node = graphics->getOsgNode(); // Generate normals osgUtil::SmoothingVisitor sv; node->accept(sv); graphics->setGenerateTangents(true); LineGeometryVisitor visitor; node->accept(visitor); element->addComponent(graphics); scene->addSceneElement(element); runtime->start(); boost::this_thread::sleep(boost::posix_time::milliseconds(500)); runtime->stop(); } }; // namespace Graphics }; // namespace SurgSim <|endoftext|>
<commit_before> #define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" #include <algorithm> #include <string> #include <vector> #include "geometry/sign.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/dimensionless.hpp" #include "testing_utilities/numerics.hpp" #include "testing_utilities/statistics.hpp" using principia::testing_utilities::AbsoluteError; using testing::AllOf; using testing::Gt; using testing::Lt; using principia::testing_utilities::BidimensionalDatasetMathematicaInput; using principia::testing_utilities::Slope; using principia::testing_utilities::PearsonProductMomentCorrelationCoefficient; namespace principia { namespace integrators { namespace { using quantities::Dimensionless; inline void compute_harmonic_oscillator_force(double const t, std::vector<double> const& q, std::vector<double>* result) { (*result)[0] = -q[0]; } inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p, std::vector<double>* result) { (*result)[0] = p[0]; } } // namespace class SPRKTest : public testing::Test { public: static void SetUpTestCase() { google::LogToStderr(); } protected: void SetUp() override {} SPRKIntegrator integrator_; SPRKIntegrator::Parameters parameters_; SPRKIntegrator::Solution solution_; }; TEST_F(SPRKTest, HarmonicOscillator) { parameters_.q0 = {1.0}; parameters_.p0 = {0.0}; parameters_.t0 = 0.0; #ifdef _DEBUG parameters_.tmax = 100.0; #else parameters_.tmax = 1000.0; #endif parameters_.Δt = 1.0E-4; parameters_.coefficients = integrator_.Order5Optimal(); parameters_.sampling_period = 1; integrator_.Solve(&compute_harmonic_oscillator_force, &compute_harmonic_oscillator_velocity, parameters_, &solution_); double q_error = 0; double p_error = 0; for (size_t i = 0; i < solution_.time.quantities.size(); ++i) { q_error = std::max(q_error, std::abs(solution_.position[0].quantities[i] - std::cos(solution_.time.quantities[i]))); p_error = std::max(p_error, std::abs(solution_.momentum[0].quantities[i] + std::sin(solution_.time.quantities[i]))); } LOG(INFO) << "q_error = " << q_error; LOG(INFO) << "p_error = " << p_error; EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax)); EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax)); } TEST_F(SPRKTest, Convergence) { parameters_.q0 = {1.0}; parameters_.p0 = {0.0}; parameters_.t0 = 0.0; parameters_.tmax = 100; parameters_.coefficients = integrator_.Order5Optimal(); parameters_.sampling_period = 0; // For 0.2 * 1.1⁻²¹ < |Δt| < 0.2 , the correlation between step size and error // is very strong. It the step is small enough to converge and large enough to // stay clear of floating point inaccuracy. parameters_.Δt = 0.2; int const step_sizes = 22; double const step_reduction = 1.1; std::vector<Dimensionless> log_step_sizes(step_sizes); std::vector<Dimensionless> log_q_errors(step_sizes); std::vector<Dimensionless> log_p_errors(step_sizes); for (int i = 0; i < step_sizes; ++i, parameters_.Δt /= step_reduction) { solution_ = SPRKIntegrator::Solution(); integrator_.Solve(&compute_harmonic_oscillator_force, &compute_harmonic_oscillator_velocity, parameters_, &solution_); log_step_sizes[i] = std::log10(parameters_.Δt); log_q_errors[i] = std::log10( std::abs(solution_.position[0].quantities[0] - std::cos(solution_.time.quantities[0]))); log_p_errors[i] = std::log10( std::abs(solution_.momentum[0].quantities[0] + std::sin(solution_.time.quantities[0]))); } google::LogToStderr(); Dimensionless const q_convergence_order = Slope(log_step_sizes, log_q_errors); Dimensionless const q_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_q_errors); LOG(INFO) << "Convergence order in q : " << q_convergence_order; LOG(INFO) << "Correlation : " << q_correlation; LOG(INFO) << "Convergence data for q :\n" << BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors); EXPECT_THAT(q_convergence_order, AllOf(Gt(4.9), Lt(5.1))); EXPECT_THAT(q_correlation, AllOf(Gt(0.999), Lt(1.01))); Dimensionless const p_convergence_order = Slope(log_step_sizes, log_p_errors); Dimensionless const p_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_p_errors); LOG(INFO) << "Convergence order in p : " << p_convergence_order; LOG(INFO) << "Correlation : " << p_correlation; LOG(INFO) << "Convergence data for p :\n" << BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors); EXPECT_THAT(p_convergence_order, AllOf(Gt(5.9), Lt(6.1))); EXPECT_THAT(p_correlation, AllOf(Gt(0.999), Lt(1.01))); } } // namespace integrators } // namespace principia <commit_msg>Why is that here?<commit_after> #define TRACE_SYMPLECTIC_PARTITIONED_RUNGE_KUTTA_INTEGRATOR #include "integrators/symplectic_partitioned_runge_kutta_integrator.hpp" #include <algorithm> #include <string> #include <vector> #include "geometry/sign.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "quantities/dimensionless.hpp" #include "testing_utilities/numerics.hpp" #include "testing_utilities/statistics.hpp" using principia::testing_utilities::AbsoluteError; using testing::AllOf; using testing::Gt; using testing::Lt; using principia::testing_utilities::BidimensionalDatasetMathematicaInput; using principia::testing_utilities::Slope; using principia::testing_utilities::PearsonProductMomentCorrelationCoefficient; namespace principia { namespace integrators { namespace { using quantities::Dimensionless; inline void compute_harmonic_oscillator_force(double const t, std::vector<double> const& q, std::vector<double>* result) { (*result)[0] = -q[0]; } inline void compute_harmonic_oscillator_velocity(std::vector<double> const& p, std::vector<double>* result) { (*result)[0] = p[0]; } } // namespace class SPRKTest : public testing::Test { public: static void SetUpTestCase() { google::LogToStderr(); } protected: void SetUp() override {} SPRKIntegrator integrator_; SPRKIntegrator::Parameters parameters_; SPRKIntegrator::Solution solution_; }; TEST_F(SPRKTest, HarmonicOscillator) { parameters_.q0 = {1.0}; parameters_.p0 = {0.0}; parameters_.t0 = 0.0; #ifdef _DEBUG parameters_.tmax = 100.0; #else parameters_.tmax = 1000.0; #endif parameters_.Δt = 1.0E-4; parameters_.coefficients = integrator_.Order5Optimal(); parameters_.sampling_period = 1; integrator_.Solve(&compute_harmonic_oscillator_force, &compute_harmonic_oscillator_velocity, parameters_, &solution_); double q_error = 0; double p_error = 0; for (size_t i = 0; i < solution_.time.quantities.size(); ++i) { q_error = std::max(q_error, std::abs(solution_.position[0].quantities[i] - std::cos(solution_.time.quantities[i]))); p_error = std::max(p_error, std::abs(solution_.momentum[0].quantities[i] + std::sin(solution_.time.quantities[i]))); } LOG(INFO) << "q_error = " << q_error; LOG(INFO) << "p_error = " << p_error; EXPECT_THAT(q_error, Lt(2E-16 * parameters_.tmax)); EXPECT_THAT(p_error, Lt(2E-16 * parameters_.tmax)); } TEST_F(SPRKTest, Convergence) { parameters_.q0 = {1.0}; parameters_.p0 = {0.0}; parameters_.t0 = 0.0; parameters_.tmax = 100; parameters_.coefficients = integrator_.Order5Optimal(); parameters_.sampling_period = 0; // For 0.2 * 1.1⁻²¹ < |Δt| < 0.2 , the correlation between step size and error // is very strong. It the step is small enough to converge and large enough to // stay clear of floating point inaccuracy. parameters_.Δt = 0.2; int const step_sizes = 22; double const step_reduction = 1.1; std::vector<Dimensionless> log_step_sizes(step_sizes); std::vector<Dimensionless> log_q_errors(step_sizes); std::vector<Dimensionless> log_p_errors(step_sizes); for (int i = 0; i < step_sizes; ++i, parameters_.Δt /= step_reduction) { solution_ = SPRKIntegrator::Solution(); integrator_.Solve(&compute_harmonic_oscillator_force, &compute_harmonic_oscillator_velocity, parameters_, &solution_); log_step_sizes[i] = std::log10(parameters_.Δt); log_q_errors[i] = std::log10( std::abs(solution_.position[0].quantities[0] - std::cos(solution_.time.quantities[0]))); log_p_errors[i] = std::log10( std::abs(solution_.momentum[0].quantities[0] + std::sin(solution_.time.quantities[0]))); } Dimensionless const q_convergence_order = Slope(log_step_sizes, log_q_errors); Dimensionless const q_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_q_errors); LOG(INFO) << "Convergence order in q : " << q_convergence_order; LOG(INFO) << "Correlation : " << q_correlation; LOG(INFO) << "Convergence data for q :\n" << BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors); EXPECT_THAT(q_convergence_order, AllOf(Gt(4.9), Lt(5.1))); EXPECT_THAT(q_correlation, AllOf(Gt(0.999), Lt(1.01))); Dimensionless const p_convergence_order = Slope(log_step_sizes, log_p_errors); Dimensionless const p_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_p_errors); LOG(INFO) << "Convergence order in p : " << p_convergence_order; LOG(INFO) << "Correlation : " << p_correlation; LOG(INFO) << "Convergence data for p :\n" << BidimensionalDatasetMathematicaInput(log_step_sizes, log_q_errors); EXPECT_THAT(p_convergence_order, AllOf(Gt(5.9), Lt(6.1))); EXPECT_THAT(p_correlation, AllOf(Gt(0.999), Lt(1.01))); } } // namespace integrators } // namespace principia <|endoftext|>
<commit_before>#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "pearson.h" const int T_MAX = 10000; Formura_Navigator navi; float frand() { return rand() / float(RAND_MAX); } void init() { for(int y = navi.lower_y; y < navi.upper_y; ++y) { for(int x = navi.lower_x; x < navi.upper_x; ++x) { U[y][x] = 1; V[y][x] = 0; } } for (int y = 118; y < 138; ++y) { for (int x = 118; x < 138; ++x) { U[y][x] = 0.5+0.01*frand(); V[y][x] = 0.25+0.01*frand(); } } } int main (int argc, char **argv) { system("mkdir -p frames"); srand(time(NULL)); MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); init(); while(navi.time_step < T_MAX) { if(navi.time_step % 20 == 0) { printf("t = %d\n", navi.time_step); char fn[256]; sprintf(fn, "frames/%06d.txt", navi.time_step); FILE *fp = fopen(fn,"w"); for(int y = navi.lower_y; y < navi.upper_y; ++y) { for(int x = navi.lower_x; x < navi.upper_x; ++x) { fprintf(fp, "%d %d %f\n", x, y, U[y][x]); } fprintf(fp, "\n"); } fclose(fp); } Formura_Forward(&navi); } MPI_Finalize(); } <commit_msg>Fix the x-y confusion in pearson-main.cpp<commit_after>#include <mpi.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "pearson.h" const int T_MAX = 10000; Formura_Navigator navi; float frand() { return rand() / float(RAND_MAX); } void init() { for(int x = navi.lower_x; x < navi.upper_x; ++x) { for(int y = navi.lower_y; y < navi.upper_y; ++y) { U[x][y] = 1; V[x][y] = 0; } } for (int x = 58; x < 78; ++x) { for (int y = 58; y < 78; ++y) { U[x][y] = 0.5+0.01*frand(); V[x][y] = 0.25+0.01*frand(); } } } int main (int argc, char **argv) { system("mkdir -p frames"); srand(time(NULL)); MPI_Init(&argc, &argv); Formura_Init(&navi, MPI_COMM_WORLD); init(); while(navi.time_step < T_MAX) { if(navi.time_step % 20 == 0) { printf("t = %d\n", navi.time_step); char fn[256]; sprintf(fn, "frames/%06d.txt", navi.time_step); FILE *fp = fopen(fn,"w"); for(int x = navi.lower_x; x < navi.upper_x; ++x) { for(int y = navi.lower_y; y < navi.upper_y; ++y) { fprintf(fp, "%d %d %f\n", x, y, U[x][y]); } fprintf(fp, "\n"); } fclose(fp); } Formura_Forward(&navi); } MPI_Finalize(); } <|endoftext|>
<commit_before>/* * File: RetroboxSystem.cpp * Author: matthieu * * Created on 29 novembre 2014, 03:15 */ #include "RecalboxSystem.h" #include <stdlib.h> #include <sys/statvfs.h> #include <sstream> #include "Settings.h" #include <iostream> #include <fstream> #include "Log.h" #include "HttpReq.h" #include "AudioManager.h" #include "VolumeControl.h" #include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> RecalboxSystem::RecalboxSystem() { } RecalboxSystem *RecalboxSystem::instance = NULL; RecalboxSystem *RecalboxSystem::getInstance() { if (RecalboxSystem::instance == NULL) { RecalboxSystem::instance = new RecalboxSystem(); } return RecalboxSystem::instance; } unsigned long RecalboxSystem::getFreeSpaceGB(std::string mountpoint) { struct statvfs fiData; const char *fnPath = mountpoint.c_str(); int free = 0; if ((statvfs(fnPath, &fiData)) >= 0) { free = (fiData.f_bfree * fiData.f_bsize) / (1024 * 1024 * 1024); } return free; } std::string RecalboxSystem::getFreeSpaceInfo() { struct statvfs fiData; std::string sharePart = Settings::getInstance()->getString("SharePartition"); if (sharePart.size() > 0) { const char *fnPath = sharePart.c_str(); if ((statvfs(fnPath, &fiData)) < 0) { return ""; } else { unsigned long total = (fiData.f_blocks * (fiData.f_bsize / 1024)) / (1024L * 1024L); unsigned long free = (fiData.f_bfree * (fiData.f_bsize / 1024)) / (1024L * 1024L); unsigned long used = total - free; unsigned long percent = used * 100 / total; std::ostringstream oss; oss << used << "GB/" << total << "GB (" << percent << "%)"; return oss.str(); } } else { return "ERROR"; } } bool RecalboxSystem::isFreeSpaceLimit() { std::string sharePart = Settings::getInstance()->getString("SharePartition"); if (sharePart.size() > 0) { return getFreeSpaceGB(sharePart) < 2; } else { return "ERROR"; } } std::string RecalboxSystem::getVersion() { std::string version = Settings::getInstance()->getString("VersionFile"); if (version.size() > 0) { std::ifstream ifs(version); if (ifs.good()) { std::string contents; std::getline(ifs, contents); return contents; } } return ""; } bool RecalboxSystem::needToShowVersionMessage() { std::string versionFile = Settings::getInstance()->getString("LastVersionFile"); if (versionFile.size() > 0) { std::ifstream lvifs(versionFile); if (lvifs.good()) { std::string lastVersion; std::getline(lvifs, lastVersion); std::string currentVersion = getVersion(); if (lastVersion == currentVersion) { return false; } } } return true; } bool RecalboxSystem::versionMessageDisplayed() { std::string versionFile = Settings::getInstance()->getString("LastVersionFile"); std::string currentVersion = getVersion(); std::ostringstream oss; oss << "echo " << currentVersion << " > " << versionFile; if (system(oss.str().c_str())) { LOG(LogWarning) << "Error executing " << oss.str().c_str(); return false; } else { LOG(LogInfo) << "Version message displayed ok"; return true; } return false; } std::string RecalboxSystem::getVersionMessage() { std::string versionMessageFile = Settings::getInstance()->getString("VersionMessage"); if (versionMessageFile.size() > 0) { std::ifstream ifs(versionMessageFile); if (ifs.good()) { std::string contents((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); return contents; } } return ""; } bool RecalboxSystem::setAudioOutputDevice(std::string device) { int commandValue = -1; int returnValue = false; if (device == "auto") { commandValue = 0; } else if (device == "jack") { commandValue = 1; } else if (device == "hdmi") { commandValue = 2; } else { LOG(LogWarning) << "Unable to find audio output device to use !"; } if (commandValue != -1) { std::ostringstream oss; oss << "amixer cset numid=3 " << commandValue; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; returnValue = false; } else { LOG(LogInfo) << "Audio output device set to : " << device; returnValue = true; } } return returnValue; } bool RecalboxSystem::setOverscan(bool enable) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "overscan"; if (enable) { oss << " " << "enable"; } else { oss << " " << "disable"; } std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; return false; } else { LOG(LogInfo) << "Overscan set to : " << enable; return true; } } bool RecalboxSystem::setOverclock(std::string mode) { if (mode != "") { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "overclock" << " " << mode; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; return false; } else { LOG(LogInfo) << "Overclocking set to " << mode; return true; } } return false; } bool RecalboxSystem::updateSystem() { std::string updatecommand = Settings::getInstance()->getString("UpdateCommand"); if (updatecommand.size() > 0) { int exitcode = system(updatecommand.c_str()); return exitcode == 0; } return false; } bool RecalboxSystem::ping() { std::string updateserver = Settings::getInstance()->getString("UpdateServer"); std::string s("ping -c 1 " + updateserver); int exitcode = system(s.c_str()); return exitcode == 0; } bool RecalboxSystem::canUpdate() { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "canupdate"; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Can update "; return true; } else { LOG(LogInfo) << "Cannot update "; return false; } } bool RecalboxSystem::launchKodi(Window *window) { LOG(LogInfo) << "Attempting to launch kodi..."; AudioManager::getInstance()->deinit(); VolumeControl::getInstance()->deinit(); window->deinit(); std::string command = "/recalbox/scripts/kodilauncher.sh"; int exitCode = system(command.c_str()); window->init(); VolumeControl::getInstance()->init(); AudioManager::getInstance()->resumeMusic(); window->normalizeNextUpdate(); return exitCode == 0; } bool RecalboxSystem::enableWifi(std::string ssid, std::string key) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "wifi" << " " << "enable" << " \"" << ssid << "\" \"" << key << "\""; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Wifi enabled "; return true; } else { LOG(LogInfo) << "Cannot enable wifi "; return false; } } bool RecalboxSystem::disableWifi() { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "wifi" << " " << "disable"; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Wifi disabled "; return true; } else { LOG(LogInfo) << "Cannot disable wifi "; return false; } } std::string RecalboxSystem::getRecalboxConfig(std::string key) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxConfigScript") << " " << " -command load " << " -key " << key; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; FILE *pipe = popen(command.c_str(), "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } bool RecalboxSystem::setRecalboxConfig(std::string key, std::string value) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxConfigScript") << " " << " -command save" << " -key " << key << " -value " << value; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << key << " saved in recalbox.conf"; return true; } else { LOG(LogInfo) << "Cannot save " << key << " in recalbox.conf"; return false; } } bool RecalboxSystem::reboot() { bool success = system("touch /tmp/reboot.please") == 0; SDL_Event *quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return success; } bool RecalboxSystem::shutdown() { bool success = system("touch /tmp/shutdown.please") == 0; SDL_Event *quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return success; } std::string RecalboxSystem::getIpAdress() { struct ifaddrs *ifAddrStruct = NULL; struct ifaddrs *ifa = NULL; void *tmpAddrPtr = NULL; std::string result = "NOT CONNECTED"; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); if (std::string(ifa->ifa_name).find("eth") != std::string::npos || std::string(ifa->ifa_name).find("wlan") != std::string::npos) { result = std::string(addressBuffer); } } } // Seeking for ipv6 if no IPV4 if (result.compare("NOT CONNECTED") == 0) { for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6 // is a valid IP6 Address tmpAddrPtr = &((struct sockaddr_in6 *) ifa->ifa_addr)->sin6_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); if (std::string(ifa->ifa_name).find("eth") != std::string::npos || std::string(ifa->ifa_name).find("wlan") != std::string::npos) { return std::string(addressBuffer); } } } } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); return result; } std::vector<std::string> *RecalboxSystem::scanBluetooth() { std::vector<std::string> *res = new std::vector<std::string>(); std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "hcitoolscan"; FILE *pipe = popen(oss.str().c_str(), "r"); char line[1024]; if (pipe == NULL) { return NULL; } while (fgets(line, 1024, pipe)) { strtok(line, "\n"); res->push_back(std::string(line)); } pclose(pipe); return res; } bool RecalboxSystem::pairBluetooth(std::string &controller) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "hiddpair" << " " << controller; int exitcode = system(oss.str().c_str()); return exitcode == 0; } <commit_msg>added new kodi launch<commit_after>/* * File: RetroboxSystem.cpp * Author: matthieu * * Created on 29 novembre 2014, 03:15 */ #include "RecalboxSystem.h" #include <stdlib.h> #include <sys/statvfs.h> #include <sstream> #include "Settings.h" #include <iostream> #include <fstream> #include "Log.h" #include "HttpReq.h" #include "AudioManager.h" #include "VolumeControl.h" #include "InputManager.h" #include <stdio.h> #include <sys/types.h> #include <ifaddrs.h> #include <netinet/in.h> #include <string.h> #include <arpa/inet.h> RecalboxSystem::RecalboxSystem() { } RecalboxSystem *RecalboxSystem::instance = NULL; RecalboxSystem *RecalboxSystem::getInstance() { if (RecalboxSystem::instance == NULL) { RecalboxSystem::instance = new RecalboxSystem(); } return RecalboxSystem::instance; } unsigned long RecalboxSystem::getFreeSpaceGB(std::string mountpoint) { struct statvfs fiData; const char *fnPath = mountpoint.c_str(); int free = 0; if ((statvfs(fnPath, &fiData)) >= 0) { free = (fiData.f_bfree * fiData.f_bsize) / (1024 * 1024 * 1024); } return free; } std::string RecalboxSystem::getFreeSpaceInfo() { struct statvfs fiData; std::string sharePart = Settings::getInstance()->getString("SharePartition"); if (sharePart.size() > 0) { const char *fnPath = sharePart.c_str(); if ((statvfs(fnPath, &fiData)) < 0) { return ""; } else { unsigned long total = (fiData.f_blocks * (fiData.f_bsize / 1024)) / (1024L * 1024L); unsigned long free = (fiData.f_bfree * (fiData.f_bsize / 1024)) / (1024L * 1024L); unsigned long used = total - free; unsigned long percent = used * 100 / total; std::ostringstream oss; oss << used << "GB/" << total << "GB (" << percent << "%)"; return oss.str(); } } else { return "ERROR"; } } bool RecalboxSystem::isFreeSpaceLimit() { std::string sharePart = Settings::getInstance()->getString("SharePartition"); if (sharePart.size() > 0) { return getFreeSpaceGB(sharePart) < 2; } else { return "ERROR"; } } std::string RecalboxSystem::getVersion() { std::string version = Settings::getInstance()->getString("VersionFile"); if (version.size() > 0) { std::ifstream ifs(version); if (ifs.good()) { std::string contents; std::getline(ifs, contents); return contents; } } return ""; } bool RecalboxSystem::needToShowVersionMessage() { std::string versionFile = Settings::getInstance()->getString("LastVersionFile"); if (versionFile.size() > 0) { std::ifstream lvifs(versionFile); if (lvifs.good()) { std::string lastVersion; std::getline(lvifs, lastVersion); std::string currentVersion = getVersion(); if (lastVersion == currentVersion) { return false; } } } return true; } bool RecalboxSystem::versionMessageDisplayed() { std::string versionFile = Settings::getInstance()->getString("LastVersionFile"); std::string currentVersion = getVersion(); std::ostringstream oss; oss << "echo " << currentVersion << " > " << versionFile; if (system(oss.str().c_str())) { LOG(LogWarning) << "Error executing " << oss.str().c_str(); return false; } else { LOG(LogInfo) << "Version message displayed ok"; return true; } return false; } std::string RecalboxSystem::getVersionMessage() { std::string versionMessageFile = Settings::getInstance()->getString("VersionMessage"); if (versionMessageFile.size() > 0) { std::ifstream ifs(versionMessageFile); if (ifs.good()) { std::string contents((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); return contents; } } return ""; } bool RecalboxSystem::setAudioOutputDevice(std::string device) { int commandValue = -1; int returnValue = false; if (device == "auto") { commandValue = 0; } else if (device == "jack") { commandValue = 1; } else if (device == "hdmi") { commandValue = 2; } else { LOG(LogWarning) << "Unable to find audio output device to use !"; } if (commandValue != -1) { std::ostringstream oss; oss << "amixer cset numid=3 " << commandValue; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; returnValue = false; } else { LOG(LogInfo) << "Audio output device set to : " << device; returnValue = true; } } return returnValue; } bool RecalboxSystem::setOverscan(bool enable) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "overscan"; if (enable) { oss << " " << "enable"; } else { oss << " " << "disable"; } std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; return false; } else { LOG(LogInfo) << "Overscan set to : " << enable; return true; } } bool RecalboxSystem::setOverclock(std::string mode) { if (mode != "") { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "overclock" << " " << mode; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str())) { LOG(LogWarning) << "Error executing " << command; return false; } else { LOG(LogInfo) << "Overclocking set to " << mode; return true; } } return false; } bool RecalboxSystem::updateSystem() { std::string updatecommand = Settings::getInstance()->getString("UpdateCommand"); if (updatecommand.size() > 0) { int exitcode = system(updatecommand.c_str()); return exitcode == 0; } return false; } bool RecalboxSystem::ping() { std::string updateserver = Settings::getInstance()->getString("UpdateServer"); std::string s("ping -c 1 " + updateserver); int exitcode = system(s.c_str()); return exitcode == 0; } bool RecalboxSystem::canUpdate() { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "canupdate"; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Can update "; return true; } else { LOG(LogInfo) << "Cannot update "; return false; } } bool RecalboxSystem::launchKodi(Window *window) { LOG(LogInfo) << "Attempting to launch kodi..."; AudioManager::getInstance()->deinit(); VolumeControl::getInstance()->deinit(); window->deinit(); std::string commandline = InputManager::getInstance()->configureEmulators(); std::string command = "configgen -system kodi -rom '' "+commandline; int exitCode = system(command.c_str()); window->init(); VolumeControl::getInstance()->init(); AudioManager::getInstance()->resumeMusic(); window->normalizeNextUpdate(); return exitCode == 0; } bool RecalboxSystem::enableWifi(std::string ssid, std::string key) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "wifi" << " " << "enable" << " \"" << ssid << "\" \"" << key << "\""; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Wifi enabled "; return true; } else { LOG(LogInfo) << "Cannot enable wifi "; return false; } } bool RecalboxSystem::disableWifi() { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "wifi" << " " << "disable"; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << "Wifi disabled "; return true; } else { LOG(LogInfo) << "Cannot disable wifi "; return false; } } std::string RecalboxSystem::getRecalboxConfig(std::string key) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxConfigScript") << " " << " -command load " << " -key " << key; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; FILE *pipe = popen(command.c_str(), "r"); if (!pipe) return "ERROR"; char buffer[128]; std::string result = ""; while (!feof(pipe)) { if (fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } bool RecalboxSystem::setRecalboxConfig(std::string key, std::string value) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxConfigScript") << " " << " -command save" << " -key " << key << " -value " << value; std::string command = oss.str(); LOG(LogInfo) << "Launching " << command; if (system(command.c_str()) == 0) { LOG(LogInfo) << key << " saved in recalbox.conf"; return true; } else { LOG(LogInfo) << "Cannot save " << key << " in recalbox.conf"; return false; } } bool RecalboxSystem::reboot() { bool success = system("touch /tmp/reboot.please") == 0; SDL_Event *quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return success; } bool RecalboxSystem::shutdown() { bool success = system("touch /tmp/shutdown.please") == 0; SDL_Event *quit = new SDL_Event(); quit->type = SDL_QUIT; SDL_PushEvent(quit); return success; } std::string RecalboxSystem::getIpAdress() { struct ifaddrs *ifAddrStruct = NULL; struct ifaddrs *ifa = NULL; void *tmpAddrPtr = NULL; std::string result = "NOT CONNECTED"; getifaddrs(&ifAddrStruct); for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET) { // check it is IP4 // is a valid IP4 Address tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr; char addressBuffer[INET_ADDRSTRLEN]; inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); if (std::string(ifa->ifa_name).find("eth") != std::string::npos || std::string(ifa->ifa_name).find("wlan") != std::string::npos) { result = std::string(addressBuffer); } } } // Seeking for ipv6 if no IPV4 if (result.compare("NOT CONNECTED") == 0) { for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) { if (!ifa->ifa_addr) { continue; } if (ifa->ifa_addr->sa_family == AF_INET6) { // check it is IP6 // is a valid IP6 Address tmpAddrPtr = &((struct sockaddr_in6 *) ifa->ifa_addr)->sin6_addr; char addressBuffer[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN); printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); if (std::string(ifa->ifa_name).find("eth") != std::string::npos || std::string(ifa->ifa_name).find("wlan") != std::string::npos) { return std::string(addressBuffer); } } } } if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct); return result; } std::vector<std::string> *RecalboxSystem::scanBluetooth() { std::vector<std::string> *res = new std::vector<std::string>(); std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "hcitoolscan"; FILE *pipe = popen(oss.str().c_str(), "r"); char line[1024]; if (pipe == NULL) { return NULL; } while (fgets(line, 1024, pipe)) { strtok(line, "\n"); res->push_back(std::string(line)); } pclose(pipe); return res; } bool RecalboxSystem::pairBluetooth(std::string &controller) { std::ostringstream oss; oss << Settings::getInstance()->getString("RecalboxSettingScript") << " " << "hiddpair" << " " << controller; int exitcode = system(oss.str().c_str()); return exitcode == 0; } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ // $Id$ #include <QString> #include <QtTest> #include <QDir> #include <QtXml> #include <QFileInfo> #include "HopsanEssentials.h" #include "HopsanCoreMacros.h" #define DEFAULTLIBPATH "../componentLibraries/defaultLibrary" #ifndef BUILTINDEFAULTCOMPONENTLIB #ifdef _WIN32 #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH "/defaultComponentLibrary" TO_STR(DEBUG_EXT) ".dll" #else #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH "/libdefaultComponentLibrary" TO_STR(DEBUG_EXT) ".so" #endif #endif using namespace hopsan; class DefaultLibraryXMLTest : public QObject { Q_OBJECT public: DefaultLibraryXMLTest(); private Q_SLOTS: void initTestCase(); void testIconPaths(); void testPortNames(); void testSourceCodeLink(); private: void recurseCollectXMLFiles(const QDir &rDir); QFileInfoList mAllXMLFiles; HopsanEssentials mHopsanCore; }; typedef QMap<QString, QString> IconNameMapT; QDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc) { QFile file(rXMLFileInfo.absoluteFilePath()); if (!file.open(QIODevice::ReadOnly)) { return QDomElement(); } rDoc.setContent(&file); file.close(); QDomElement root = rDoc.documentElement(); if (root.tagName() == "hopsanobjectappearance") { return root; } else { return QDomElement(); } } IconNameMapT extractIconPathsFromMO(const QDomElement dom) { IconNameMapT map; QDomElement icon = dom.firstChildElement("icons").firstChildElement("icon"); while (!icon.isNull()) { map.insert(icon.attribute("type"), icon.attribute("path")); icon = icon.nextSiblingElement("icon"); } return map; } QStringList extractPortNamesFromMO(const QDomElement dom) { QStringList names; QDomElement port = dom.firstChildElement("ports").firstChildElement("port"); while (!port.isNull()) { names.append(port.attribute("name")); port = port.nextSiblingElement("port"); } return names; } QString extractTypeNameFromMO(const QDomElement dom) { return dom.attribute("typename"); } QString extractSourceCodeLinkFromMO(const QDomElement dom) { return dom.attribute("sourcecode"); } DefaultLibraryXMLTest::DefaultLibraryXMLTest() { } void DefaultLibraryXMLTest::initTestCase() { mAllXMLFiles.clear(); // Loop through all subdirs, to find all XML files, and store them in a list QDir libRoot(DEFAULTLIBPATH); QVERIFY2(libRoot.exists(), QString("Libroot: %1 could not be found!").arg(DEFAULTLIBPATH).toStdString().c_str()); recurseCollectXMLFiles(libRoot); #ifndef BUILTINDEFAULTCOMPONENTLIB bool loadOK = mHopsanCore.loadExternalComponentLib(DEFAULTCOMPONENTLIB); QVERIFY2(loadOK, "could not load the component library"); #endif } void DefaultLibraryXMLTest::testIconPaths() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { IconNameMapT map = extractIconPathsFromMO(mo); IconNameMapT::iterator it; for (it=map.begin(); it!=map.end(); ++it) { QString relPath = it.value(); QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+"/"+relPath); if (!iconFile.exists()) { QWARN(QString("The icon file %1 could not be found, linked from xml file: %2").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str()); isOK = false; } } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one icon not found!"); } void DefaultLibraryXMLTest::testPortNames() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { QString typeName = extractTypeNameFromMO(mo); QStringList portNames = extractPortNamesFromMO(mo); Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str()); if (pComponent) { for (int p=0; p<portNames.size(); ++p ) { Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str()); if (pPort == 0) { isOK = false; QWARN(QString("Component: %1 Port: %2 exist in XML but not in CODE!").arg(typeName).arg(portNames[p]).toStdString().c_str()); } } mHopsanCore.removeComponent(pComponent); } else { QWARN(QString("Component: %1 exist in XML but not in core!").arg(typeName).toStdString().c_str()); } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one port name mismatch in your XML and CODE"); } void DefaultLibraryXMLTest::testSourceCodeLink() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { QString typeName = extractTypeNameFromMO(mo); QString sourceCode = extractSourceCodeLinkFromMO(mo); if (sourceCode.isEmpty()) { QWARN(QString("SourceCode attribute not set for component %1!").arg(typeName).toStdString().c_str()); //isOK = false; // =================================== // Add the code automatically // QString codefile = typeName+".hpp"; // mo.setAttribute("sourcecode", codefile); // QFile f(mAllXMLFiles[i].absoluteFilePath()); // if (f.open(QIODevice::WriteOnly | QIODevice::Text)) // { // QTextStream out(&f); // QDomDocument doc = mo.ownerDocument(); // doc.save(out,4); // } // f.close(); // =================================== } else { QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+"/"+sourceCode); if(!sourceFile.exists()) { QWARN(QString("SourceCode file: %1 for component %2 is missing!").arg(sourceFile.absoluteFilePath()).arg(typeName).toStdString().c_str()); isOK = false; } } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one sourcecode link not working!"); } void DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir) { QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast); for (int i=0;i<contents.size();++i) { if (contents[i].isFile() && contents[i].suffix().toLower() == "xml") { mAllXMLFiles.append(contents[i]); } else if (contents[i].isDir()) { recurseCollectXMLFiles(contents[i].absoluteFilePath()); } } } QTEST_APPLESS_MAIN(DefaultLibraryXMLTest) #include "tst_defaultlibraryxmltest.moc" <commit_msg>Prevent reporting error for :graphics/ icons (that are built in) actually it should check that they exist, now it just ignores them<commit_after>/*----------------------------------------------------------------------------- This source file is a part of Hopsan Copyright (c) 2009 to present year, Hopsan Group This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. For license details and information about the Hopsan Group see the files GPLv3 and HOPSANGROUP in the Hopsan source code root directory For author and contributor information see the AUTHORS file -----------------------------------------------------------------------------*/ // $Id$ #include <QString> #include <QtTest> #include <QDir> #include <QtXml> #include <QFileInfo> #include "HopsanEssentials.h" #include "HopsanCoreMacros.h" #define DEFAULTLIBPATH "../componentLibraries/defaultLibrary" #ifndef BUILTINDEFAULTCOMPONENTLIB #ifdef _WIN32 #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH "/defaultComponentLibrary" TO_STR(DEBUG_EXT) ".dll" #else #define DEFAULTCOMPONENTLIB DEFAULTLIBPATH "/libdefaultComponentLibrary" TO_STR(DEBUG_EXT) ".so" #endif #endif using namespace hopsan; class DefaultLibraryXMLTest : public QObject { Q_OBJECT public: DefaultLibraryXMLTest(); private Q_SLOTS: void initTestCase(); void testIconPaths(); void testPortNames(); void testSourceCodeLink(); private: void recurseCollectXMLFiles(const QDir &rDir); QFileInfoList mAllXMLFiles; HopsanEssentials mHopsanCore; }; typedef QMap<QString, QString> IconNameMapT; QDomElement loadXMLFileToDOM(const QFileInfo &rXMLFileInfo, QDomDocument &rDoc) { QFile file(rXMLFileInfo.absoluteFilePath()); if (!file.open(QIODevice::ReadOnly)) { return QDomElement(); } rDoc.setContent(&file); file.close(); QDomElement root = rDoc.documentElement(); if (root.tagName() == "hopsanobjectappearance") { return root; } else { return QDomElement(); } } IconNameMapT extractIconPathsFromMO(const QDomElement dom) { IconNameMapT map; QDomElement icon = dom.firstChildElement("icons").firstChildElement("icon"); while (!icon.isNull()) { map.insert(icon.attribute("type"), icon.attribute("path")); icon = icon.nextSiblingElement("icon"); } return map; } QStringList extractPortNamesFromMO(const QDomElement dom) { QStringList names; QDomElement port = dom.firstChildElement("ports").firstChildElement("port"); while (!port.isNull()) { names.append(port.attribute("name")); port = port.nextSiblingElement("port"); } return names; } QString extractTypeNameFromMO(const QDomElement dom) { return dom.attribute("typename"); } QString extractSourceCodeLinkFromMO(const QDomElement dom) { return dom.attribute("sourcecode"); } DefaultLibraryXMLTest::DefaultLibraryXMLTest() { } void DefaultLibraryXMLTest::initTestCase() { mAllXMLFiles.clear(); // Loop through all subdirs, to find all XML files, and store them in a list QDir libRoot(DEFAULTLIBPATH); QVERIFY2(libRoot.exists(), QString("Libroot: %1 could not be found!").arg(DEFAULTLIBPATH).toStdString().c_str()); recurseCollectXMLFiles(libRoot); #ifndef BUILTINDEFAULTCOMPONENTLIB bool loadOK = mHopsanCore.loadExternalComponentLib(DEFAULTCOMPONENTLIB); QVERIFY2(loadOK, "could not load the component library"); #endif } void DefaultLibraryXMLTest::testIconPaths() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { IconNameMapT map = extractIconPathsFromMO(mo); IconNameMapT::iterator it; for (it=map.begin(); it!=map.end(); ++it) { QString relPath = it.value(); QFileInfo iconFile(mAllXMLFiles[i].absolutePath()+"/"+relPath); if (!iconFile.exists() && !relPath.startsWith(":graphics/")) { QWARN(QString("The icon file %1 could not be found, linked from xml file: %2").arg(iconFile.absoluteFilePath()).arg(mAllXMLFiles[i].absoluteFilePath()).toStdString().c_str()); isOK = false; } } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one icon not found!"); } void DefaultLibraryXMLTest::testPortNames() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { QString typeName = extractTypeNameFromMO(mo); QStringList portNames = extractPortNamesFromMO(mo); Component* pComponent = mHopsanCore.createComponent(typeName.toStdString().c_str()); if (pComponent) { for (int p=0; p<portNames.size(); ++p ) { Port *pPort = pComponent->getPort(portNames[p].toStdString().c_str()); if (pPort == 0) { isOK = false; QWARN(QString("Component: %1 Port: %2 exist in XML but not in CODE!").arg(typeName).arg(portNames[p]).toStdString().c_str()); } } mHopsanCore.removeComponent(pComponent); } else { QWARN(QString("Component: %1 exist in XML but not in core!").arg(typeName).toStdString().c_str()); } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one port name mismatch in your XML and CODE"); } void DefaultLibraryXMLTest::testSourceCodeLink() { bool isOK = true; for (int i=0; i<mAllXMLFiles.size(); ++i) { QDomDocument doc; QDomElement mo = loadXMLFileToDOM(mAllXMLFiles[i].absoluteFilePath(),doc).firstChildElement("modelobject"); while(!mo.isNull()) { QString typeName = extractTypeNameFromMO(mo); QString sourceCode = extractSourceCodeLinkFromMO(mo); if (sourceCode.isEmpty()) { QWARN(QString("SourceCode attribute not set for component %1!").arg(typeName).toStdString().c_str()); //isOK = false; // =================================== // Add the code automatically // QString codefile = typeName+".hpp"; // mo.setAttribute("sourcecode", codefile); // QFile f(mAllXMLFiles[i].absoluteFilePath()); // if (f.open(QIODevice::WriteOnly | QIODevice::Text)) // { // QTextStream out(&f); // QDomDocument doc = mo.ownerDocument(); // doc.save(out,4); // } // f.close(); // =================================== } else { QFileInfo sourceFile(mAllXMLFiles[i].absolutePath()+"/"+sourceCode); if(!sourceFile.exists()) { QWARN(QString("SourceCode file: %1 for component %2 is missing!").arg(sourceFile.absoluteFilePath()).arg(typeName).toStdString().c_str()); isOK = false; } } mo = mo.nextSiblingElement("modelobject"); } } QVERIFY2(isOK, "There were at least one sourcecode link not working!"); } void DefaultLibraryXMLTest::recurseCollectXMLFiles(const QDir &rDir) { QFileInfoList contents = rDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot, QDir::DirsLast); for (int i=0;i<contents.size();++i) { if (contents[i].isFile() && contents[i].suffix().toLower() == "xml") { mAllXMLFiles.append(contents[i]); } else if (contents[i].isDir()) { recurseCollectXMLFiles(contents[i].absoluteFilePath()); } } } QTEST_APPLESS_MAIN(DefaultLibraryXMLTest) #include "tst_defaultlibraryxmltest.moc" <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/projection.hpp> #include <mapnik/utils.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/well_known_srs.hpp> // stl #include <stdexcept> #ifdef MAPNIK_USE_PROJ4 // proj4 #include <proj_api.h> #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 #include <boost/thread/mutex.hpp> #ifdef _MSC_VER #pragma NOTE(mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8) #else #warning mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8 #endif static boost::mutex mutex_; #endif #endif namespace mapnik { projection::projection(std::string const& params, bool defer_proj_init) : params_(params), defer_proj_init_(defer_proj_init), proj_(NULL), proj_ctx_(NULL) { boost::optional<bool> is_known = is_known_geographic(params_); if (is_known){ is_geographic_ = *is_known; } else { #ifdef MAPNIK_USE_PROJ4 init_proj4(); #else throw std::runtime_error(std::string("Cannot initialize projection '") + params_ + " ' without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } if (!defer_proj_init_) init_proj4(); } projection::projection(projection const& rhs) : params_(rhs.params_), defer_proj_init_(rhs.defer_proj_init_), is_geographic_(rhs.is_geographic_), proj_(NULL), proj_ctx_(NULL) { if (!defer_proj_init_) init_proj4(); } projection& projection::operator=(projection const& rhs) { projection tmp(rhs); swap(tmp); proj_ctx_ = 0; proj_ = 0; if (!defer_proj_init_) init_proj4(); return *this; } bool projection::operator==(const projection& other) const { return (params_ == other.params_); } bool projection::operator!=(const projection& other) const { return !(*this == other); } void projection::init_proj4() const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { #if PJ_VERSION >= 480 proj_ctx_ = pj_ctx_alloc(); proj_ = pj_init_plus_ctx(proj_ctx_, params_.c_str()); if (!proj_) { if (proj_ctx_) pj_ctx_free(proj_ctx_); throw proj_init_error(params_); } #else #if defined(MAPNIK_THREADSAFE) mutex::scoped_lock lock(mutex_); #endif proj_ = pj_init_plus(params_.c_str()); if (!proj_) throw proj_init_error(params_); #endif is_geographic_ = pj_is_latlong(proj_) ? true : false; } #endif } bool projection::is_initialized() const { return proj_ ? true : false; } bool projection::is_geographic() const { return is_geographic_; } boost::optional<well_known_srs_e> projection::well_known() const { return is_well_known_srs(params_); } std::string const& projection::params() const { return params_; } void projection::forward(double & x, double &y ) const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { throw std::runtime_error("projection::forward not supported unless proj4 is initialized"); } #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif projUV p; p.u = x * DEG_TO_RAD; p.v = y * DEG_TO_RAD; p = pj_fwd(p,proj_); x = p.u; y = p.v; if (is_geographic_) { x *=RAD_TO_DEG; y *=RAD_TO_DEG; } #else throw std::runtime_error("projection::forward not supported without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } void projection::inverse(double & x,double & y) const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { throw std::runtime_error("projection::inverse not supported unless proj4 is initialized"); } #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif if (is_geographic_) { x *=DEG_TO_RAD; y *=DEG_TO_RAD; } projUV p; p.u = x; p.v = y; p = pj_inv(p,proj_); x = RAD_TO_DEG * p.u; y = RAD_TO_DEG * p.v; #else throw std::runtime_error("projection::inverse not supported without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } projection::~projection() { #ifdef MAPNIK_USE_PROJ4 #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif if (proj_) pj_free(proj_); #if PJ_VERSION >= 480 if (proj_ctx_) pj_ctx_free(proj_ctx_); #endif #endif } std::string projection::expanded() const { #ifdef MAPNIK_USE_PROJ4 if (proj_) return mapnik::util::trim_copy(pj_get_def( proj_, 0 )); #endif return params_; } void projection::swap(projection& rhs) { std::swap(params_,rhs.params_); std::swap(defer_proj_init_,rhs.defer_proj_init_); std::swap(is_geographic_,rhs.is_geographic_); } } <commit_msg>prevent double-free in mapnik::projection<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/projection.hpp> #include <mapnik/utils.hpp> #include <mapnik/util/trim.hpp> #include <mapnik/well_known_srs.hpp> // stl #include <stdexcept> #ifdef MAPNIK_USE_PROJ4 // proj4 #include <proj_api.h> #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 #include <boost/thread/mutex.hpp> #ifdef _MSC_VER #pragma NOTE(mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8) #else #warning mapnik is building against < proj 4.8, reprojection will be faster if you use >= 4.8 #endif static boost::mutex mutex_; #endif #endif namespace mapnik { projection::projection(std::string const& params, bool defer_proj_init) : params_(params), defer_proj_init_(defer_proj_init), proj_(NULL), proj_ctx_(NULL) { boost::optional<bool> is_known = is_known_geographic(params_); if (is_known){ is_geographic_ = *is_known; } else { #ifdef MAPNIK_USE_PROJ4 init_proj4(); #else throw std::runtime_error(std::string("Cannot initialize projection '") + params_ + " ' without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } if (!defer_proj_init_) init_proj4(); } projection::projection(projection const& rhs) : params_(rhs.params_), defer_proj_init_(rhs.defer_proj_init_), is_geographic_(rhs.is_geographic_), proj_(NULL), proj_ctx_(NULL) { if (!defer_proj_init_) init_proj4(); } projection& projection::operator=(projection const& rhs) { projection tmp(rhs); swap(tmp); proj_ctx_ = 0; proj_ = 0; if (!defer_proj_init_) init_proj4(); return *this; } bool projection::operator==(const projection& other) const { return (params_ == other.params_); } bool projection::operator!=(const projection& other) const { return !(*this == other); } void projection::init_proj4() const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { #if PJ_VERSION >= 480 proj_ctx_ = pj_ctx_alloc(); proj_ = pj_init_plus_ctx(proj_ctx_, params_.c_str()); if (!proj_) { if (proj_ctx_) { pj_ctx_free(proj_ctx_); proj_ctx_ = 0; } throw proj_init_error(params_); } #else #if defined(MAPNIK_THREADSAFE) mutex::scoped_lock lock(mutex_); #endif proj_ = pj_init_plus(params_.c_str()); if (!proj_) throw proj_init_error(params_); #endif is_geographic_ = pj_is_latlong(proj_) ? true : false; } #endif } bool projection::is_initialized() const { return proj_ ? true : false; } bool projection::is_geographic() const { return is_geographic_; } boost::optional<well_known_srs_e> projection::well_known() const { return is_well_known_srs(params_); } std::string const& projection::params() const { return params_; } void projection::forward(double & x, double &y ) const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { throw std::runtime_error("projection::forward not supported unless proj4 is initialized"); } #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif projUV p; p.u = x * DEG_TO_RAD; p.v = y * DEG_TO_RAD; p = pj_fwd(p,proj_); x = p.u; y = p.v; if (is_geographic_) { x *=RAD_TO_DEG; y *=RAD_TO_DEG; } #else throw std::runtime_error("projection::forward not supported without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } void projection::inverse(double & x,double & y) const { #ifdef MAPNIK_USE_PROJ4 if (!proj_) { throw std::runtime_error("projection::inverse not supported unless proj4 is initialized"); } #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif if (is_geographic_) { x *=DEG_TO_RAD; y *=DEG_TO_RAD; } projUV p; p.u = x; p.v = y; p = pj_inv(p,proj_); x = RAD_TO_DEG * p.u; y = RAD_TO_DEG * p.v; #else throw std::runtime_error("projection::inverse not supported without proj4 support (-DMAPNIK_USE_PROJ4)"); #endif } projection::~projection() { #ifdef MAPNIK_USE_PROJ4 #if defined(MAPNIK_THREADSAFE) && PJ_VERSION < 480 mutex::scoped_lock lock(mutex_); #endif if (proj_) pj_free(proj_); #if PJ_VERSION >= 480 if (proj_ctx_) pj_ctx_free(proj_ctx_); #endif #endif } std::string projection::expanded() const { #ifdef MAPNIK_USE_PROJ4 if (proj_) return mapnik::util::trim_copy(pj_get_def( proj_, 0 )); #endif return params_; } void projection::swap(projection& rhs) { std::swap(params_,rhs.params_); std::swap(defer_proj_init_,rhs.defer_proj_init_); std::swap(is_geographic_,rhs.is_geographic_); } } <|endoftext|>
<commit_before>/*{{{ Copyright (C) 2013 Matthias Kretz <[email protected]> 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 the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. }}}*/ #include <array> #include <memory> #include <Vc/Vc> #include "../tsc.h" using Vc::float_v; /* * This example shows how an arbitrary problem scales depending on working-set size and FLOPs per * load/store. Understanding this can help to create better implementations. */ /* * The Runner is a method to generate the different scenarios with all parameters to the Work * available as constant expressions. * The idea is to have the compiler able to optimize as much as possible so that the actual workload * alone is benchmarked. * * The Runner recursively calls operator() on the Work template class with varying arguments for N * and FLOPs. */ template<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N = 256, std::size_t M = 4, int FLOPs = 2> struct Runner { static void run() { Work<N, M, (N > 4096 ? 1 : 4096 / N), FLOPs>()(); Runner<Work, N, M, int(FLOPs * 1.5)>::run(); } }; template<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N, std::size_t M> struct Runner<Work, N, M, 211> { static void run() { Runner<Work, N * 2, M>::run(); } }; template<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t M, int FLOPs> struct Runner<Work, 256 * 1024 * 1024, M, FLOPs> { static void run() { } }; /* * The Flops helper struct generates code that executes FLOPs many floating-point SIMD instructions * (add, sub, and mul) */ template<int FLOPs> struct Flops { inline float_v operator()(float_v a, float_v b, float_v c) { typedef Flops<(FLOPs - 5) / 2> F1; typedef Flops<(FLOPs - 4) / 2> F2; return F1()(a + b, a * b, c) + F2()(a * c, b + c, a); } }; template<> inline float_v Flops<2>::operator()(float_v a, float_v b, float_v c) { return a * b + c; } template<> inline float_v Flops<3>::operator()(float_v a, float_v b, float_v c) { return a * b + (c - a); } template<> inline float_v Flops<4>::operator()(float_v a, float_v b, float_v c) { return (a * b + c) + a * c; } template<> inline float_v Flops<5>::operator()(float_v a, float_v b, float_v c) { return a * b + (a + c) + a * c; } template<> inline float_v Flops<6>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c)) + (a * c - b); } template<> inline float_v Flops<7>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c)) + (a * c - (b + c)); } template<> inline float_v Flops<8>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c) + b) + (a * c - (b + c)); } /* * This is the benchmark code. It is called from Runner and uses Flops to do the work. */ template<std::size_t _N, std::size_t M, int Repetitions, int FLOPs> struct ScaleWorkingSetSize { void operator()() { constexpr std::size_t N = _N / sizeof(float_v) + 3 * 16 / float_v::Size; typedef std::array<std::array<float_v, N>, M> Cont; auto data = Vc::make_unique<Cont, Vc::AlignOnPage>(); for (auto &arr : *data) { for (auto &value : arr) { value = float_v::Random(); } } TimeStampCounter tsc; double throughput = 0.; for (std::size_t i = 0; i < 2 + 512 / N; ++i) { tsc.start(); // ------------- start of the benchmarked code --------------- for (int repetitions = 0; repetitions < Repetitions; ++repetitions) { for (std::size_t m = 0; m < M; ++m) { for (std::size_t n = 0; n < N; ++n) { (*data)[m][n] = Flops<FLOPs>()((*data)[(m + 1) % M][n], (*data)[(m + 2) % M][n], (*data)[(m + 3) % M][n]); } } } // -------------- end of the benchmarked code ---------------- tsc.stop(); throughput = std::max(throughput, (Repetitions * M * N * float_v::Size * FLOPs) / static_cast<double>(tsc.cycles())); } const long bytes = N * M * sizeof(float_v); printf("%10lu Byte | %4.2f FLOP/Byte | %4.1f FLOP/cycle\n", bytes, static_cast<double>(float_v::Size * FLOPs) / (4 * sizeof(float_v)), throughput ); } }; int Vc_CDECL main() { ScaleWorkingSetSize<256, 4, 10, 2>()(); printf("%10s | %4s | %4s\n", "Working-Set Size", "FLOPs per Byte", "Throughput (FLOPs/Cycle)"); Runner<ScaleWorkingSetSize>::run(); return 0; } <commit_msg>Examples: End recursion earlier to limit GCC memory consumption<commit_after>/*{{{ Copyright (C) 2013 Matthias Kretz <[email protected]> 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 the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaim all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. }}}*/ #include <array> #include <memory> #include <Vc/Vc> #include "../tsc.h" using Vc::float_v; /* * This example shows how an arbitrary problem scales depending on working-set size and FLOPs per * load/store. Understanding this can help to create better implementations. */ /* * The Runner is a method to generate the different scenarios with all parameters to the Work * available as constant expressions. * The idea is to have the compiler able to optimize as much as possible so that the actual workload * alone is benchmarked. * * The Runner recursively calls operator() on the Work template class with varying arguments for N * and FLOPs. */ template<template<std::size_t N, std::size_t M, int, int> class Work, std::size_t N = 256, std::size_t M = 4> struct Runner { static void run() { Work<N, M, (N > 4096 ? 1 : 4096 / N), 2>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 3>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 4>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 6>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 9>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 13>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 19>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 28>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 42>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 63>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 94>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 141>()(); Work<N, M, (N > 4096 ? 1 : 4096 / N), 211>()(); Runner<Work, N * 2, M>::run(); } }; template <template <std::size_t N, std::size_t M, int, int> class Work, std::size_t M> struct Runner<Work, 256 * 1024 * 32, // don't make this number larger, otherwise GCC6 // blows up with Vc::Scalar to 10GB of memory usage M> { static void run() { } }; /* * The Flops helper struct generates code that executes FLOPs many floating-point SIMD instructions * (add, sub, and mul) */ template<int FLOPs> struct Flops { inline float_v operator()(float_v a, float_v b, float_v c) { typedef Flops<(FLOPs - 5) / 2> F1; typedef Flops<(FLOPs - 4) / 2> F2; return F1()(a + b, a * b, c) + F2()(a * c, b + c, a); } }; template<> inline float_v Flops<2>::operator()(float_v a, float_v b, float_v c) { return a * b + c; } template<> inline float_v Flops<3>::operator()(float_v a, float_v b, float_v c) { return a * b + (c - a); } template<> inline float_v Flops<4>::operator()(float_v a, float_v b, float_v c) { return (a * b + c) + a * c; } template<> inline float_v Flops<5>::operator()(float_v a, float_v b, float_v c) { return a * b + (a + c) + a * c; } template<> inline float_v Flops<6>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c)) + (a * c - b); } template<> inline float_v Flops<7>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c)) + (a * c - (b + c)); } template<> inline float_v Flops<8>::operator()(float_v a, float_v b, float_v c) { return (a * b + (a + c) + b) + (a * c - (b + c)); } /* * This is the benchmark code. It is called from Runner and uses Flops to do the work. */ template<std::size_t _N, std::size_t M, int Repetitions, int FLOPs> struct ScaleWorkingSetSize { void operator()() { constexpr std::size_t N = _N / sizeof(float_v) + 3 * 16 / float_v::Size; typedef std::array<std::array<float_v, N>, M> Cont; auto data = Vc::make_unique<Cont, Vc::AlignOnPage>(); for (auto &arr : *data) { for (auto &value : arr) { value = float_v::Random(); } } TimeStampCounter tsc; double throughput = 0.; for (std::size_t i = 0; i < 2 + 512 / N; ++i) { tsc.start(); // ------------- start of the benchmarked code --------------- for (int repetitions = 0; repetitions < Repetitions; ++repetitions) { for (std::size_t m = 0; m < M; ++m) { for (std::size_t n = 0; n < N; ++n) { (*data)[m][n] = Flops<FLOPs>()((*data)[(m + 1) % M][n], (*data)[(m + 2) % M][n], (*data)[(m + 3) % M][n]); } } } // -------------- end of the benchmarked code ---------------- tsc.stop(); throughput = std::max(throughput, (Repetitions * M * N * float_v::Size * FLOPs) / static_cast<double>(tsc.cycles())); } const long bytes = N * M * sizeof(float_v); printf("%10lu Byte | %4.2f FLOP/Byte | %4.1f FLOP/cycle\n", bytes, static_cast<double>(float_v::Size * FLOPs) / (4 * sizeof(float_v)), throughput ); } }; int Vc_CDECL main() { ScaleWorkingSetSize<256, 4, 10, 2>()(); printf("%10s | %4s | %4s\n", "Working-Set Size", "FLOPs per Byte", "Throughput (FLOPs/Cycle)"); Runner<ScaleWorkingSetSize>::run(); return 0; } <|endoftext|>
<commit_before>/* * W.J. van der Laan 2011-2012 * The SLIMCoin Developers 2013 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { //the addition of the newline is there to bump the text up so it fully fits in the coin's picture splashref->showMessage(QString::fromStdString(message + "\n"), Qt::AlignBottom | Qt::AlignHCenter, QColor(55,55,55)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Slimcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for(int i = 1; i < argc; i++) { if(strlen(argv[i]) >= 8 && strncasecmp(argv[i], "slimcoin:", 9) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Command-line options take precedence: ParseParameters(argc, argv); // Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef MAC_OSX QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif /* FIXME: refactor to Qt5.6+ #if QT_VERSION >= 0x050500 // Because of the POODLE attack it is recommended to disable SSLv3 (https://disablessl3.com/), // so set SSL protocols to TLS1.0+. QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration(); sslconf.setProtocol(QSsl::TlsV1_0OrLater); QSslConfiguration::setDefaultConfiguration(sslconf); #endif */ // TODO: Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory // ... then bitcoin.conf: if(!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Slimcoin"); app.setOrganizationDomain("slimcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Slimcoin-Qt-testnet"); else app.setApplicationName("Slimcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale ("en_US") from command line or system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // "en" QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang); if(!qtTranslatorBase.isEmpty()) app.installTranslator(&qtTranslatorBase); qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory); if(!qtTranslator.isEmpty()) app.installTranslator(&qtTranslator); translatorBase.load(":/translations/"+lang); if(!translatorBase.isEmpty()) app.installTranslator(&translatorBase); translator.load(":/translations/"+lang_territory); if(!translator.isEmpty()) app.installTranslator(&translator); QPixmap testnet_splash_pixmap = QPixmap(":/images/splash_testnet"); QSplashScreen splash(QPixmap(":/images/splash"), 0); if(GetBoolArg("-splash", true) && !GetBoolArg("-min")) { if(GetBoolArg("-testnet", false)) splash.setPixmap(testnet_splash_pixmap); splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { BitcoinGUI window; guiref = &window; if(AppInit2(argc, argv)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if(splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for(int i = 1; i < argc; i++) { if(strlen(argv[i]) > 8 && strncasecmp(argv[i], "slimcoin:", 9) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <commit_msg>show version info on splashscreen<commit_after>/* * W.J. van der Laan 2011-2012 * The SLIMCoin Developers 2013 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "util.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { //the addition of the newline is there to bump the text up so it fully fits in the coin's picture // splashref->showMessage(QString::fromStdString(message + "\n"), Qt::AlignBottom | Qt::AlignHCenter, QColor(55,55,55)); splashref->showMessage(QString::fromStdString(message+"\n\n") + QString::fromStdString(FormatFullVersion().c_str()), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Slimcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for(int i = 1; i < argc; i++) { if(strlen(argv[i]) >= 8 && strncasecmp(argv[i], "slimcoin:", 9) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Command-line options take precedence: ParseParameters(argc, argv); // Basic Qt initialization (not dependent on parameters or configuration) #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif #if QT_VERSION > 0x050100 // Generate high-dpi pixmaps QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); #endif #if QT_VERSION >= 0x050600 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif #ifdef MAC_OSX QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif /* FIXME: refactor to Qt5.6+ #if QT_VERSION >= 0x050500 // Because of the POODLE attack it is recommended to disable SSLv3 (https://disablessl3.com/), // so set SSL protocols to TLS1.0+. QSslConfiguration sslconf = QSslConfiguration::defaultConfiguration(); sslconf.setProtocol(QSsl::TlsV1_0OrLater); QSslConfiguration::setDefaultConfiguration(sslconf); #endif */ // TODO: Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory // ... then bitcoin.conf: if(!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Slimcoin"); app.setOrganizationDomain("slimcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Slimcoin-Qt-testnet"); else app.setApplicationName("Slimcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale ("en_US") from command line or system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator QString lang = lang_territory; lang.truncate(lang_territory.lastIndexOf('_')); // "en" QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; qtTranslatorBase.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang); if(!qtTranslatorBase.isEmpty()) app.installTranslator(&qtTranslatorBase); qtTranslator.load(QLibraryInfo::location(QLibraryInfo::TranslationsPath) + "/qt_" + lang_territory); if(!qtTranslator.isEmpty()) app.installTranslator(&qtTranslator); translatorBase.load(":/translations/"+lang); if(!translatorBase.isEmpty()) app.installTranslator(&translatorBase); translator.load(":/translations/"+lang_territory); if(!translator.isEmpty()) app.installTranslator(&translator); QPixmap testnet_splash_pixmap = QPixmap(":/images/splash_testnet"); QSplashScreen splash(QPixmap(":/images/splash"), 0); if(GetBoolArg("-splash", true) && !GetBoolArg("-min")) { if(GetBoolArg("-testnet", false)) splash.setPixmap(testnet_splash_pixmap); splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { BitcoinGUI window; guiref = &window; if(AppInit2(argc, argv)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if(splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for(int i = 1; i < argc; i++) { if(strlen(argv[i]) > 8 && strncasecmp(argv[i], "slimcoin:", 9) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } // Shutdown the core and it's threads, but don't exit Bitcoin-Qt here Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST <|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) //======================================================================= #include "dll/neural/dense_layer.hpp" #include "dll/test.hpp" #include "dll/network.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<float, 28 * 28>>(); // Build the network using network_t = dll::dyn_network_desc< dll::network_layers< dll::dense_desc<28 * 28, 32, dll::relu>::layer_t, dll::dense_desc<32, 28 * 28, dll::sigmoid>::layer_t > , dll::batch_size<256> // The mini-batch size , dll::shuffle // Shuffle the dataset before each epoch , dll::binary_cross_entropy // Use a Binary Cross Entropy Loss , dll::scale_pre<255> // Scale the images (divide by 255) , dll::autoencoder // Indicate auto-encoder , dll::adadelta // Adadelta updates for gradient descent >::network_t; auto net = std::make_unique<network_t>(); // Display the network net->display(); // Train the network as auto-encoder net->fine_tune_ae(dataset.training_images, 50); // Test the network on test set net->evaluate_ae(dataset.test_images); return 0; } <commit_msg>Use the new utilities<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) //======================================================================= #include "dll/neural/dense_layer.hpp" #include "dll/test.hpp" #include "dll/network.hpp" #include "dll/datasets.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" int main(int /*argc*/, char* /*argv*/ []) { // Load the dataset auto dataset = dll::make_mnist_ae_dataset(0, dll::batch_size<256>{}, dll::scale_pre<255>{}); // Build the network using network_t = dll::dyn_network_desc< dll::network_layers< dll::dense_desc<28 * 28, 32, dll::relu>::layer_t, dll::dense_desc<32, 28 * 28, dll::sigmoid>::layer_t > , dll::batch_size<256> // The mini-batch size , dll::shuffle // Shuffle the dataset before each epoch , dll::binary_cross_entropy // Use a Binary Cross Entropy Loss , dll::adadelta // Adadelta updates for gradient descent >::network_t; auto net = std::make_unique<network_t>(); // Display the network net->display(); // Train the network as auto-encoder net->fine_tune_ae(dataset.train(), 50); // Test the network on test set net->evaluate_ae(dataset.test()); return 0; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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 NEKTAR_USE_EXPRESSION_TEMPLATES #define NEKTAR_USE_EXPRESSION_TEMPLATES #endif //NEKTAR_USE_EXPRESSION_TEMPLATES #include <boost/test/auto_unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/test/unit_test.hpp> #include <LibUtilities/LinearAlgebra/NekTypeDefs.hpp> #include <UnitTests/LibUtilities/ExpressionTemplates/CountedObjectExpression.h> #include <LibUtilities/LinearAlgebra/NekMatrix.hpp> #include <ExpressionTemplates/Node.hpp> #include <ExpressionTemplates/RemoveAllUnecessaryTemporaries.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits.hpp> #include <LibUtilities/LinearAlgebra/MatrixSize.hpp> // Tests the error in CoupledLinearNS.cpp:963 // DNekScalBlkMatSharedPtr m_Cinv; // NekVector< NekDouble > F_int // DNekScalBlkMatSharedPtr m_D_int; // NekVector< NekDouble > F_p // DNekScalBlkMatSharedPtr m_Btilde; // NekVector< NekDouble > F_bnd // F_int = (*m_Cinv)*(F_int + Transpose(*m_D_int)*F_p - Transpose(*m_Btilde)*F_bnd); namespace Nektar { namespace UnitTests { // Start my testing individual portions to help isolate the problem. BOOST_AUTO_TEST_CASE(TestScalBlkMatTimeVector) { // 2x2 block matrix, with submatrices also 2x2 double data_buf[] = {1, 2, 3, 4}; DNekMatSharedPtr m0(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m1(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m2(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m3(new DNekMat(2,2, data_buf)); DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0)); DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1)); DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2)); DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3)); DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2)); m->SetBlock(0, 0, s0); m->SetBlock(0, 1, s1); m->SetBlock(1, 0, s2); m->SetBlock(1, 1, s3); double v_buf[] = {1, 2, 3, 4, 5, 6, 7, 8}; NekVector<NekDouble> v(8, v_buf); NekVector<NekDouble> result = (*m)*v; } // The multiplication compiles, so I assume the problem is in a tree transformation. BOOST_AUTO_TEST_CASE(TestScaleBlkMatTermWithTransformation) { double data_buf[] = {1, 2, 3, 4}; DNekMatSharedPtr m0(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m1(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m2(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m3(new DNekMat(2,2, data_buf)); DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0)); DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1)); DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2)); DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3)); DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2)); m->SetBlock(0, 0, s0); m->SetBlock(0, 1, s1); m->SetBlock(1, 0, s2); m->SetBlock(1, 1, s3); double rhs_buf[] = {1, 2, 3, 4, 5, 6, 7, 8}; NekVector<NekDouble> rhs(8, rhs_buf); double lhs_buf[] = {1, 2, 3, 4, 5, 6, 7, 8}; NekVector<NekDouble> lhs(8, lhs_buf); NekVector<NekDouble> result = lhs + (*m)*rhs; DNekMat result2 = (*m)*((*m)*(*m)); // This fails. It appears that it is a failure of the commutative property // for matrix/vector multiplication. NekVector<NekDouble> result3 = (*m)*(lhs+rhs); NekVector<NekDouble> result1 = (*m)*(lhs + (*m)*rhs - (*m)*rhs); } } } <commit_msg><commit_after>/////////////////////////////////////////////////////////////////////////////// // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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 NEKTAR_USE_EXPRESSION_TEMPLATES #define NEKTAR_USE_EXPRESSION_TEMPLATES #endif //NEKTAR_USE_EXPRESSION_TEMPLATES #include <boost/test/auto_unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <boost/test/floating_point_comparison.hpp> #include <boost/test/unit_test.hpp> #include <LibUtilities/LinearAlgebra/NekTypeDefs.hpp> #include <UnitTests/LibUtilities/ExpressionTemplates/CountedObjectExpression.h> #include <LibUtilities/LinearAlgebra/NekMatrix.hpp> #include <ExpressionTemplates/Node.hpp> #include <ExpressionTemplates/RemoveAllUnecessaryTemporaries.hpp> #include <boost/mpl/assert.hpp> #include <boost/type_traits.hpp> #include <LibUtilities/LinearAlgebra/MatrixSize.hpp> // Tests the error in CoupledLinearNS.cpp:963 // DNekScalBlkMatSharedPtr m_Cinv; // NekVector< NekDouble > F_int // DNekScalBlkMatSharedPtr m_D_int; // NekVector< NekDouble > F_p // DNekScalBlkMatSharedPtr m_Btilde; // NekVector< NekDouble > F_bnd // F_int = (*m_Cinv)*(F_int + Transpose(*m_D_int)*F_p - Transpose(*m_Btilde)*F_bnd); namespace Nektar { namespace UnitTests { // Start my testing individual portions to help isolate the problem. BOOST_AUTO_TEST_CASE(TestScalBlkMatTimeVector) { // 2x2 block matrix, with submatrices also 2x2 double data_buf[] = {1, 2, 3, 4}; DNekMatSharedPtr m0(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m1(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m2(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m3(new DNekMat(2,2, data_buf)); DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0)); DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1)); DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2)); DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3)); DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2)); m->SetBlock(0, 0, s0); m->SetBlock(0, 1, s1); m->SetBlock(1, 0, s2); m->SetBlock(1, 1, s3); double v_buf[] = {1, 2, 3, 4, 5, 6, 7, 8}; NekVector<NekDouble> v(8, v_buf); NekVector<NekDouble> result = (*m)*v; } // The multiplication compiles, so I assume the problem is in a tree transformation. BOOST_AUTO_TEST_CASE(TestScaleBlkMatTermWithTransformation) { double data_buf[] = {1, 2, 3, 4}; DNekMatSharedPtr m0(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m1(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m2(new DNekMat(2,2, data_buf)); DNekMatSharedPtr m3(new DNekMat(2,2, data_buf)); DNekScalMatSharedPtr s0(new DNekScalMat(2.0, m0)); DNekScalMatSharedPtr s1(new DNekScalMat(3.0, m1)); DNekScalMatSharedPtr s2(new DNekScalMat(4.0, m2)); DNekScalMatSharedPtr s3(new DNekScalMat(5.0, m3)); DNekScalBlkMatSharedPtr m(new DNekScalBlkMat(2,2, 2, 2)); m->SetBlock(0, 0, s0); m->SetBlock(0, 1, s1); m->SetBlock(1, 0, s2); m->SetBlock(1, 1, s3); double rhs_buf[] = {1, 2, 3, 4}; NekVector<NekDouble> rhs(4, rhs_buf); double lhs_buf[] = {1, 2, 3, 4}; NekVector<NekDouble> lhs(4, lhs_buf); NekVector<NekDouble> result = lhs + (*m)*rhs; DNekMat result2 = (*m)*((*m)*(*m)); // This fails. It appears that it is a failure of the commutative property // for matrix/vector multiplication. NekVector<NekDouble> result3 = (*m)*(lhs+rhs); NekVector<NekDouble> result1 = (*m)*(lhs + (*m)*rhs - (*m)*rhs); } } } <|endoftext|>
<commit_before>#include <sys/resource.h> #include <sys/time.h> #include <fstream> #include <iostream> #include <memory> #include <string> #include <boost/program_options.hpp> #include "HyperscanEngine.h" #include "PcapSource.h" #include "PCRE2Engine.h" #include "regexbench.h" #include "RE2Engine.h" #include "REmatchEngine.h" #include "Rule.h" namespace po = boost::program_options; enum EngineType : uint64_t { ENGINE_HYPERSCAN, ENGINE_PCRE2, ENGINE_PCRE2JIT, ENGINE_RE2, ENGINE_REMATCH }; struct Arguments { std::string rule_file; std::string pcap_file; EngineType engine; int32_t repeat; uint32_t pcre2_concat; }; static bool endsWith(const std::string &, const char *); static std::vector<regexbench::Rule> loadRules(const std::string &); static Arguments parse_options(int argc, const char *argv[]); int main(int argc, const char *argv[]) { try { auto args = parse_options(argc, argv); std::unique_ptr<regexbench::Engine> engine; switch (args.engine) { case ENGINE_HYPERSCAN: engine = std::make_unique<regexbench::HyperscanEngine>(); engine->compile(loadRules(args.rule_file)); break; case ENGINE_PCRE2: engine = std::make_unique<regexbench::PCRE2Engine>(); if (!args.pcre2_concat) engine->compile(loadRules(args.rule_file)); else { auto rules = loadRules(args.rule_file); concatRules(rules); engine->compile(rules); } break; case ENGINE_PCRE2JIT: engine = std::make_unique<regexbench::PCRE2JITEngine>(); engine->compile(loadRules(args.rule_file)); break; case ENGINE_RE2: engine = std::make_unique<regexbench::RE2Engine>(); engine->compile(loadRules(args.rule_file)); break; case ENGINE_REMATCH: if (endsWith(args.rule_file, ".nfa")) { engine = std::make_unique<regexbench::REmatchAutomataEngine>(); engine->load(args.rule_file); } else if (endsWith(args.rule_file, ".so")) { engine = std::make_unique<regexbench::REmatchSOEngine>(); engine->load(args.rule_file); } else { engine = std::make_unique<regexbench::REmatchAutomataEngine>(); engine->compile(loadRules(args.rule_file)); } break; } regexbench::PcapSource pcap(args.pcap_file); auto result = match(*engine, pcap, args.repeat); std::cout << result.nmatches << " packets matched." << std::endl; std::cout << result.udiff.tv_sec << '.'; std::cout.width(6); std::cout.fill('0'); std::cout << result.udiff.tv_usec << "s user " << std::endl; std::cout << result.sdiff.tv_sec << '.'; std::cout.width(6); std::cout.fill('0'); std::cout << result.sdiff.tv_usec << "s system" << std::endl; struct timeval total; timeradd(&result.udiff, &result.sdiff, &total); std::cout << static_cast<double>(pcap.getNumberOfBytes() * static_cast<unsigned long>(args.repeat)) / (total.tv_sec + total.tv_usec * 1e-6) / 1000000 * 8 << " Mbps" << std::endl; std::cout << static_cast<double>(pcap.getNumberOfPackets() * static_cast<unsigned long>(args.repeat)) / (total.tv_sec + total.tv_usec * 1e-6) / 1000000 << " Mpps" << std::endl; } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } struct rusage stat; getrusage(RUSAGE_SELF, &stat); std::cout << stat.ru_maxrss / 1000 << " kB\n"; return EXIT_SUCCESS; } bool endsWith(const std::string &obj, const char *end) { auto r = obj.rfind(end); if ((r != std::string::npos) && (r == obj.size() - std::strlen(end))) return true; return false; } static std::vector<regexbench::Rule> loadRules(const std::string &filename) { std::ifstream ruleifs(filename); if (!ruleifs) { std::cerr << "cannot open rule file: " << filename << std::endl; std::exit(EXIT_FAILURE); } return regexbench::loadRules(ruleifs); } Arguments parse_options(int argc, const char *argv[]) { Arguments args; std::string engine; po::options_description posargs; posargs.add_options()("rule_file", po::value<std::string>(&args.rule_file), "Rule (regular expression) file name"); posargs.add_options()("pcap_file", po::value<std::string>(&args.pcap_file), "pcap file name"); po::positional_options_description positions; positions.add("rule_file", 1).add("pcap_file", 1); po::options_description optargs("Options"); optargs.add_options()("help,h", "Print usage information."); optargs.add_options()( "engine,e", po::value<std::string>(&engine)->default_value("hyperscan"), "Matching engine to run."); optargs.add_options()( "repeat,r", po::value<int32_t>(&args.repeat)->default_value(1), "Repeat pcap multiple times."); optargs.add_options()( "concat,c", po::value<uint32_t>(&args.pcre2_concat)->default_value(0), "Concatenate PCRE2 rules."); po::options_description cliargs; cliargs.add(posargs).add(optargs); po::variables_map vm; po::store(po::command_line_parser(argc, argv) .options(cliargs) .positional(positions) .run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << "Usage: regexbench <rule_file> <pcap_file>" << std::endl; std::exit(EXIT_SUCCESS); } if (engine == "hyperscan") args.engine = ENGINE_HYPERSCAN; else if (engine == "pcre2") args.engine = ENGINE_PCRE2; else if (engine == "pcre2jit") args.engine = ENGINE_PCRE2JIT; else if (engine == "re2") args.engine = ENGINE_RE2; else if (engine == "rematch") args.engine = ENGINE_REMATCH; else { std::cerr << "unknown engine: " << engine << std::endl; std::exit(EXIT_FAILURE); } if (args.repeat <= 0) { std::cerr << "invalid repeat value: " << args.repeat << std::endl; std::exit(EXIT_FAILURE); } if (!vm.count("rule_file")) { std::cerr << "error: no rule file" << std::endl; std::exit(EXIT_FAILURE); } if (!vm.count("pcap_file")) { std::cerr << "error: no pcap file" << std::endl; std::exit(EXIT_FAILURE); } return args; } <commit_msg>Enable rule concatenation for pcre2JIT engine<commit_after>#include <sys/resource.h> #include <sys/time.h> #include <fstream> #include <iostream> #include <memory> #include <string> #include <boost/program_options.hpp> #include "HyperscanEngine.h" #include "PcapSource.h" #include "PCRE2Engine.h" #include "regexbench.h" #include "RE2Engine.h" #include "REmatchEngine.h" #include "Rule.h" namespace po = boost::program_options; enum EngineType : uint64_t { ENGINE_HYPERSCAN, ENGINE_PCRE2, ENGINE_PCRE2JIT, ENGINE_RE2, ENGINE_REMATCH }; struct Arguments { std::string rule_file; std::string pcap_file; EngineType engine; int32_t repeat; uint32_t pcre2_concat; }; static bool endsWith(const std::string &, const char *); static std::vector<regexbench::Rule> loadRules(const std::string &); static Arguments parse_options(int argc, const char *argv[]); static void compilePCRE2(const Arguments &, std::unique_ptr<regexbench::Engine> &); int main(int argc, const char *argv[]) { try { auto args = parse_options(argc, argv); std::unique_ptr<regexbench::Engine> engine; switch (args.engine) { case ENGINE_HYPERSCAN: engine = std::make_unique<regexbench::HyperscanEngine>(); engine->compile(loadRules(args.rule_file)); break; case ENGINE_PCRE2: engine = std::make_unique<regexbench::PCRE2Engine>(); compilePCRE2(args, engine); break; case ENGINE_PCRE2JIT: engine = std::make_unique<regexbench::PCRE2JITEngine>(); compilePCRE2(args, engine); break; case ENGINE_RE2: engine = std::make_unique<regexbench::RE2Engine>(); engine->compile(loadRules(args.rule_file)); break; case ENGINE_REMATCH: if (endsWith(args.rule_file, ".nfa")) { engine = std::make_unique<regexbench::REmatchAutomataEngine>(); engine->load(args.rule_file); } else if (endsWith(args.rule_file, ".so")) { engine = std::make_unique<regexbench::REmatchSOEngine>(); engine->load(args.rule_file); } else { engine = std::make_unique<regexbench::REmatchAutomataEngine>(); engine->compile(loadRules(args.rule_file)); } break; } regexbench::PcapSource pcap(args.pcap_file); auto result = match(*engine, pcap, args.repeat); std::cout << result.nmatches << " packets matched." << std::endl; std::cout << result.udiff.tv_sec << '.'; std::cout.width(6); std::cout.fill('0'); std::cout << result.udiff.tv_usec << "s user " << std::endl; std::cout << result.sdiff.tv_sec << '.'; std::cout.width(6); std::cout.fill('0'); std::cout << result.sdiff.tv_usec << "s system" << std::endl; struct timeval total; timeradd(&result.udiff, &result.sdiff, &total); std::cout << static_cast<double>(pcap.getNumberOfBytes() * static_cast<unsigned long>(args.repeat)) / (total.tv_sec + total.tv_usec * 1e-6) / 1000000 * 8 << " Mbps" << std::endl; std::cout << static_cast<double>(pcap.getNumberOfPackets() * static_cast<unsigned long>(args.repeat)) / (total.tv_sec + total.tv_usec * 1e-6) / 1000000 << " Mpps" << std::endl; } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } struct rusage stat; getrusage(RUSAGE_SELF, &stat); std::cout << stat.ru_maxrss / 1000 << " kB\n"; return EXIT_SUCCESS; } bool endsWith(const std::string &obj, const char *end) { auto r = obj.rfind(end); if ((r != std::string::npos) && (r == obj.size() - std::strlen(end))) return true; return false; } static std::vector<regexbench::Rule> loadRules(const std::string &filename) { std::ifstream ruleifs(filename); if (!ruleifs) { std::cerr << "cannot open rule file: " << filename << std::endl; std::exit(EXIT_FAILURE); } return regexbench::loadRules(ruleifs); } Arguments parse_options(int argc, const char *argv[]) { Arguments args; std::string engine; po::options_description posargs; posargs.add_options()("rule_file", po::value<std::string>(&args.rule_file), "Rule (regular expression) file name"); posargs.add_options()("pcap_file", po::value<std::string>(&args.pcap_file), "pcap file name"); po::positional_options_description positions; positions.add("rule_file", 1).add("pcap_file", 1); po::options_description optargs("Options"); optargs.add_options()("help,h", "Print usage information."); optargs.add_options()( "engine,e", po::value<std::string>(&engine)->default_value("hyperscan"), "Matching engine to run."); optargs.add_options()( "repeat,r", po::value<int32_t>(&args.repeat)->default_value(1), "Repeat pcap multiple times."); optargs.add_options()( "concat,c", po::value<uint32_t>(&args.pcre2_concat)->default_value(0), "Concatenate PCRE2 rules."); po::options_description cliargs; cliargs.add(posargs).add(optargs); po::variables_map vm; po::store(po::command_line_parser(argc, argv) .options(cliargs) .positional(positions) .run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << "Usage: regexbench <rule_file> <pcap_file>" << std::endl; std::exit(EXIT_SUCCESS); } if (engine == "hyperscan") args.engine = ENGINE_HYPERSCAN; else if (engine == "pcre2") args.engine = ENGINE_PCRE2; else if (engine == "pcre2jit") args.engine = ENGINE_PCRE2JIT; else if (engine == "re2") args.engine = ENGINE_RE2; else if (engine == "rematch") args.engine = ENGINE_REMATCH; else { std::cerr << "unknown engine: " << engine << std::endl; std::exit(EXIT_FAILURE); } if (args.repeat <= 0) { std::cerr << "invalid repeat value: " << args.repeat << std::endl; std::exit(EXIT_FAILURE); } if (!vm.count("rule_file")) { std::cerr << "error: no rule file" << std::endl; std::exit(EXIT_FAILURE); } if (!vm.count("pcap_file")) { std::cerr << "error: no pcap file" << std::endl; std::exit(EXIT_FAILURE); } return args; } static void compilePCRE2(const Arguments &args, std::unique_ptr<regexbench::Engine> &engine) { if (!args.pcre2_concat) engine->compile(loadRules(args.rule_file)); else { auto rules = loadRules(args.rule_file); concatRules(rules); engine->compile(rules); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "retirement.hpp" #include "assets.hpp" #include "accounts.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "budget_exception.hpp" #include "config.hpp" #include "console.hpp" #include "writer.hpp" using namespace budget; namespace { constexpr size_t running_limit = 12; money running_expenses(){ auto today = budget::local_day(); budget::date end = today - budget::days(today.day() - 1); budget::date start = end - budget::months(running_limit); budget::money total; for(auto& expense : all_expenses()){ if(expense.date >= start && expense.date < end){ total += expense.amount; } } return total; } double running_savings_rate(){ auto today = budget::local_day(); double savings_rate = 0.0; for(size_t i = 1; i <= running_limit; ++i){ auto d = today - budget::months(i); budget::money expenses; for (auto& expense : all_expenses()) { if (expense.date.year() == d.year() && expense.date.month() == d.month()) { expenses += expense.amount; } } budget::money earnings; for (auto& earning : all_earnings()) { if (earning.date.year() == d.year() && earning.date.month() == d.month()) { earnings += earning.amount; } } budget::money income; for (auto& account : all_accounts(d.year(), d.month())){ income += account.amount; } auto balance = income + earnings - expenses; auto local = balance / (income + earnings); if(local < 0){ local = 0; } savings_rate += local; } return savings_rate / running_limit; } void retirement_set() { double wrate = 4.0; double roi = 4.0; if(internal_config_contains("withdrawal_rate")){ wrate = to_number<double>(internal_config_value("withdrawal_rate")); } if(internal_config_contains("expected_roi")){ roi = to_number<double>(internal_config_value("expected_roi")); } edit_double(wrate, "Withdrawal Rate (%)"); edit_double(roi, "Expected Annual Return (%)"); // Save the configuration internal_config_value("withdrawal_rate") = to_string(wrate); internal_config_value("expected_roi") = to_string(roi); } } // end of anonymous namespace void budget::retirement_module::load() { load_accounts(); load_assets(); load_expenses(); load_earnings(); } void budget::retirement_module::handle(std::vector<std::string>& args) { console_writer w(std::cout); if (args.empty() || args.size() == 1) { retirement_status(w); } else { auto& subcommand = args[1]; if (subcommand == "status") { retirement_status(w); } else if (subcommand == "set") { retirement_set(); std::cout << std::endl; retirement_status(w); } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::retirement_status(budget::writer& w) { if (!w.is_web()) { if (!internal_config_contains("withdrawal_rate")) { w << "Not enough information, please configure first with retirement set" << end_of_line; return; } if (!internal_config_contains("expected_roi")) { w << "Not enough information, please configure first with retirement set" << end_of_line; return; } } auto currency = get_default_currency(); auto wrate = to_number<double>(internal_config_value("withdrawal_rate")); auto roi = to_number<double>(internal_config_value("expected_roi")); auto years = double(int(100.0 / wrate)); auto expenses = running_expenses(); auto savings_rate = running_savings_rate(); auto nw = get_net_worth(); auto missing = years * expenses - nw; auto income = 12 * get_base_income(); auto a_savings_rate = (income - expenses) / income; size_t base_months = 0; size_t a_base_months = 0; auto current_nw = nw; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (savings_rate * income) / 12; ++base_months; } current_nw = nw; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (a_savings_rate * income) / 12; ++a_base_months; } std::vector<std::string> columns = {}; std::vector<std::vector<std::string>> contents; using namespace std::string_literals; contents.push_back({"Withdrawal rate"s, to_string(wrate) + "%"}); contents.push_back({"Annual Return"s, to_string(roi) + "%"}); contents.push_back({"Years of expense"s, to_string(years)}); contents.push_back({"Running expenses"s, to_string(expenses) + " " + currency}); contents.push_back({"Monthly expenses"s, to_string(expenses / 12) + " " + currency}); contents.push_back({"Target Net Worth"s, to_string(years * expenses) + " " + currency}); contents.push_back({"Current Net Worth"s, to_string(nw) + " " + currency}); contents.push_back({"Missing Net Worth"s, to_string(missing) + " " + currency}); contents.push_back({"FI Ratio"s, to_string(100 * (nw / missing)) + "%"}); contents.push_back({"Months of FI"s, to_string(nw / (expenses / 12))}); contents.push_back({"Yearly income"s, to_string(income) + " " + currency}); contents.push_back({"Running Savings Rate"s, to_string(100 * savings_rate) + "%"}); contents.push_back({"Yearly savings"s, to_string(savings_rate * income) + " " + currency}); contents.push_back({"Time to FI (w/o returns)"s, to_string(missing / (savings_rate * income)) + " years"}); contents.push_back({"Time to FI (w/ returns)"s, to_string(base_months / 12.0) + " years"}); contents.push_back({"Adjusted Savings Rate"s, to_string(100 * a_savings_rate) + "%"}); contents.push_back({"Adjusted Yearly savings"s, to_string(a_savings_rate * income) + " " + currency}); contents.push_back({"Adjusted Time to FI (w/o returns)"s, to_string(missing / (a_savings_rate * income)) + " years"}); contents.push_back({"Adjusted Time to FI (w/ returns)"s, to_string(a_base_months / 12.0) + " years"}); w.display_table(columns, contents); std::array<int, 5> rate_decs{1, 2, 5, 10, 20}; // Note: this not totally correct since we ignore the // correlation between the savings rate and the expenses for (auto dec : rate_decs) { auto dec_savings_rate = savings_rate + 0.01 * dec; auto current_nw = nw; size_t months = 0; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (dec_savings_rate * income) / 12; ++months; } w << p_begin << "Increasing Savings Rate by " << dec << "% would save " << (base_months - months) / 12.0 << " years (in " << months / 12.0 << " years)" << p_end; } std::array<int, 5> exp_decs{10, 50, 100, 200, 500}; for (auto dec : exp_decs) { auto current_nw = nw; size_t months = 0; auto new_savings_rate = (income - (expenses - dec * 12)) / income;; while (current_nw < years * (expenses - (dec * 12))) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (new_savings_rate * income) / 12; ++months; } w << p_begin << "Decreasing monthly expenses by " << dec << " " << currency << " would save " << (base_months - months) / 12.0 << " years (in " << months / 12.0 << " (adjusted) years)" << p_end; } } <commit_msg>Improve FI metrics<commit_after>//======================================================================= // Copyright (c) 2013-2018 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "retirement.hpp" #include "assets.hpp" #include "accounts.hpp" #include "expenses.hpp" #include "earnings.hpp" #include "budget_exception.hpp" #include "config.hpp" #include "console.hpp" #include "writer.hpp" using namespace budget; namespace { constexpr size_t running_limit = 12; money running_expenses(){ auto today = budget::local_day(); budget::date end = today - budget::days(today.day() - 1); budget::date start = end - budget::months(running_limit); budget::money total; for(auto& expense : all_expenses()){ if(expense.date >= start && expense.date < end){ total += expense.amount; } } return total; } double running_savings_rate(){ auto today = budget::local_day(); double savings_rate = 0.0; for(size_t i = 1; i <= running_limit; ++i){ auto d = today - budget::months(i); budget::money expenses; for (auto& expense : all_expenses()) { if (expense.date.year() == d.year() && expense.date.month() == d.month()) { expenses += expense.amount; } } budget::money earnings; for (auto& earning : all_earnings()) { if (earning.date.year() == d.year() && earning.date.month() == d.month()) { earnings += earning.amount; } } budget::money income; for (auto& account : all_accounts(d.year(), d.month())){ income += account.amount; } auto balance = income + earnings - expenses; auto local = balance / (income + earnings); if(local < 0){ local = 0; } savings_rate += local; } return savings_rate / running_limit; } void retirement_set() { double wrate = 4.0; double roi = 4.0; if(internal_config_contains("withdrawal_rate")){ wrate = to_number<double>(internal_config_value("withdrawal_rate")); } if(internal_config_contains("expected_roi")){ roi = to_number<double>(internal_config_value("expected_roi")); } edit_double(wrate, "Withdrawal Rate (%)"); edit_double(roi, "Expected Annual Return (%)"); // Save the configuration internal_config_value("withdrawal_rate") = to_string(wrate); internal_config_value("expected_roi") = to_string(roi); } } // end of anonymous namespace void budget::retirement_module::load() { load_accounts(); load_assets(); load_expenses(); load_earnings(); } void budget::retirement_module::handle(std::vector<std::string>& args) { console_writer w(std::cout); if (args.empty() || args.size() == 1) { retirement_status(w); } else { auto& subcommand = args[1]; if (subcommand == "status") { retirement_status(w); } else if (subcommand == "set") { retirement_set(); std::cout << std::endl; retirement_status(w); } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::retirement_status(budget::writer& w) { if (!w.is_web()) { if (!internal_config_contains("withdrawal_rate")) { w << "Not enough information, please configure first with retirement set" << end_of_line; return; } if (!internal_config_contains("expected_roi")) { w << "Not enough information, please configure first with retirement set" << end_of_line; return; } } auto currency = get_default_currency(); auto wrate = to_number<double>(internal_config_value("withdrawal_rate")); auto roi = to_number<double>(internal_config_value("expected_roi")); auto years = double(int(100.0 / wrate)); auto expenses = running_expenses(); auto savings_rate = running_savings_rate(); auto nw = get_net_worth(); auto missing = years * expenses - nw; auto income = 12 * get_base_income(); auto a_savings_rate = (income - expenses) / income; size_t base_months = 0; size_t a_base_months = 0; auto current_nw = nw; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (savings_rate * income) / 12; ++base_months; } current_nw = nw; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (a_savings_rate * income) / 12; ++a_base_months; } std::vector<std::string> columns = {}; std::vector<std::vector<std::string>> contents; using namespace std::string_literals; // The configuration contents.push_back({"Withdrawal rate"s, to_string(wrate) + "%"}); contents.push_back({"Annual Return"s, to_string(roi) + "%"}); contents.push_back({"Years of expense"s, to_string(years)}); // The target contents.push_back({""s, ""s}); contents.push_back({"Running expenses"s, to_string(expenses) + " " + currency}); contents.push_back({"Monthly expenses"s, to_string(expenses / 12) + " " + currency}); contents.push_back({"Target Net Worth"s, to_string(years * expenses) + " " + currency}); contents.push_back({""s, ""s}); contents.push_back({"Current Net Worth"s, to_string(nw) + " " + currency}); contents.push_back({"Missing Net Worth"s, to_string(missing) + " " + currency}); contents.push_back({"Yearly income"s, to_string(income) + " " + currency}); contents.push_back({"Running Savings Rate"s, to_string(100 * savings_rate) + "%"}); contents.push_back({"Yearly savings"s, to_string(savings_rate * income) + " " + currency}); contents.push_back({"FI Ratio"s, to_string(100 * (nw / missing)) + "%"}); auto fi_date = budget::local_day() + budget::months(base_months); contents.push_back({""s, ""s}); contents.push_back({"Months to FI"s, to_string(base_months)}); contents.push_back({"Years to FI"s, to_string(base_months / 12.0)}); contents.push_back({"Date to FI"s, to_string(fi_date)}); contents.push_back({""s, ""s}); contents.push_back({"Current Withdrawal Rate"s, to_string(100.0 * (expenses / nw)) + "%"}); contents.push_back({"Months of FI"s, to_string(nw / (expenses / 12))}); contents.push_back({"Years of FI"s, to_string(nw / (expenses))}); contents.push_back({""s, ""s}); contents.push_back({"Current Yearly Allowance"s, to_string(nw * (wrate / 100.0))}); contents.push_back({"Current Monthly Allowance"s, to_string((nw * (wrate / 100.0)) / 12)}); auto a_fi_date = budget::local_day() + budget::months(a_base_months); contents.push_back({""s, ""s}); contents.push_back({"Adjusted Savings Rate"s, to_string(100 * a_savings_rate) + "%"}); contents.push_back({"Adjusted Yearly savings"s, to_string(a_savings_rate * income) + " " + currency}); contents.push_back({"Adjusted Months to FI"s, to_string(a_base_months)}); contents.push_back({"Adjusted Years to FI"s, to_string(a_base_months / 12.0)}); contents.push_back({"Adjusted Date to FI"s, to_string(a_fi_date)}); w.display_table(columns, contents); std::array<int, 5> rate_decs{1, 2, 5, 10, 20}; // Note: this not totally correct since we ignore the // correlation between the savings rate and the expenses for (auto dec : rate_decs) { auto dec_savings_rate = savings_rate + 0.01 * dec; auto current_nw = nw; size_t months = 0; while (current_nw < years * expenses) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (dec_savings_rate * income) / 12; ++months; } w << p_begin << "Increasing Savings Rate by " << dec << "% would save " << (base_months - months) / 12.0 << " years (in " << months / 12.0 << " years)" << p_end; } std::array<int, 5> exp_decs{10, 50, 100, 200, 500}; for (auto dec : exp_decs) { auto current_nw = nw; size_t months = 0; auto new_savings_rate = (income - (expenses - dec * 12)) / income;; while (current_nw < years * (expenses - (dec * 12))) { current_nw *= 1.0 + (roi / 100.0) / 12; current_nw += (new_savings_rate * income) / 12; ++months; } w << p_begin << "Decreasing monthly expenses by " << dec << " " << currency << " would save " << (base_months - months) / 12.0 << " years (in " << months / 12.0 << " (adjusted) years)" << p_end; } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_common_poweronoff.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_common_poweronoff.H /// @brief common procedure for power on/off /// /// *HWP HWP Owner : David Du <[email protected]> /// *HWP Backup HWP Owner : Greg Still <[email protected]> /// *HWP FW Owner : Sangeetha T S <[email protected]> /// *HWP Team : PM /// *HWP Consumed by : SBE:SGPE:CME /// *HWP Level : 2 /// #ifndef __P9_COMMON_POWERONOFF_H__ #define __P9_COMMON_POWERONOFF_H__ namespace p9power { enum powerOperation_t { POWER_ON = 0x0, POWER_OFF = 0xFF, POWER_ON_VDD = 0x1, POWER_OFF_VDD = 0xFE }; } // Define only address offset to be compatible with both core and cache domain #define PPM_PFCS 0x000f0118 #define PPM_PFCS_CLR 0x000f0119 #define PPM_PFCS_OR 0x000f011a #define PPM_PFDLY 0x000f011b #define PPM_PFSNS 0x000f011c #define PPM_PFOFF 0x000f011d /// @typedef p9_common_poweronoff_FP_t /// function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) ( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_CORE > &, const p9power::powerOperation_t i_operation); extern "C" { /// @brief common procedure for power on/off /// /// @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target /// @param [in] i_operation ENUM(ON,OFF) /// /// @attr /// @attritem ATTR_PFET_TIMING - EX target, uint32 /// /// @retval FAPI_RC_SUCCESS fapi2::ReturnCode p9_common_poweronoff( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_CORE > & i_target, const p9power::powerOperation_t i_operation); } // extern C #endif // __P9_COMMON_POWERONOFF_H__ <commit_msg>HWP-CORE/CACHE: Update Istep 4 procedures regressed on model 34<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/lib/p9_common_poweronoff.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_common_poweronoff.H /// @brief common procedure for power on/off /// // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : SBE:SGPE:CME // *HWP Level : 2 #ifndef __P9_COMMON_POWERONOFF_H__ #define __P9_COMMON_POWERONOFF_H__ #include <fapi2.H> namespace p9power { enum powerOperation_t { POWER_ON = 0x0, POWER_OFF = 0xFF, POWER_ON_VDD = 0x1, POWER_OFF_VDD = 0xFE }; } /// @typedef p9_common_poweronoff_FP_t /// function pointer typedef definition for HWP call support /// @todo: consider template solution here typedef fapi2::ReturnCode (*p9_common_poweronoff_FP_t) ( const fapi2::Target < fapi2::TARGET_TYPE_EQ | fapi2::TARGET_TYPE_CORE > &, const p9power::powerOperation_t i_operation); /// @brief common procedure for power on/off /// /// @param [in] i_target TARGET_TYPE_EQ|TARGET_TYPE_CORE target /// @param [in] i_operation ENUM(ON,OFF) /// /// @attr /// @attritem ATTR_PFET_TIMING - EX target, uint32 /// /// @retval FAPI_RC_SUCCESS template <fapi2::TargetType K> fapi2::ReturnCode p9_common_poweronoff( const fapi2::Target<K>& i_target, const p9power::powerOperation_t i_operation); #endif // __P9_COMMON_POWERONOFF_H__ <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.H /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_EFF_CONFIG__ #define __P9_MSS_EFF_CONFIG__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&); extern "C" { /// /// @brief Configure the attributes for each controller /// @param[in] i_target, the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target ); } #endif <commit_msg>Modify spd_decoder, eff_config, unit tests. Modify dependent files<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_eff_config.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_mss_eff_config.H /// @brief Command and Control for the memory subsystem - populate attributes /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Brian Silver <[email protected]> // *HWP Team: Memory // *HWP Level: 1 // *HWP Consumed by: FSP:HB #ifndef __P9_MSS_EFF_CONFIG__ #define __P9_MSS_EFF_CONFIG__ #include <fapi2.H> typedef fapi2::ReturnCode (*p9_mss_eff_config_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&); extern "C" { /// /// @brief Configure the attributes for each controller /// @param[in] i_target the controller (e.g., MCS) /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode p9_mss_eff_config( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target ); } #endif <|endoftext|>
<commit_before>#include "serializer.h" #include <cmath> #include <cstdint> #include <cstdlib> #include <limits> namespace rapscallion { void serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) { while (value >= 0x80) { s.addByte((uint8_t)(value & 0x7F) | 0x80); value >>= 7; } s.addByte((uint8_t)value); } void serializer<long>::write(Serializer& s, const long v) { std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0); serializer<std::uint_least64_t>::write(s, val); } void serializer<int>::write(Serializer& s, const int v) { serializer<long>::write(s, v); } void serializer<std::string>::write(Serializer& s, const std::string& value) { serializer<std::uint_least64_t>::write(s, value.size()); for (auto& c : value) s.addByte(c); } void serializer<bool>::write(Serializer& s, const bool b) { serializer<std::uint_least64_t>::write(s, b ? 1 : 0); } namespace { enum Type { Zero, Infinity, NaN, Normal }; struct float_repr { // Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats std::int_least32_t exponent; // Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits) std::uint_least64_t fraction; // One bit reserved for sign bit static constexpr unsigned fraction_bits = 63 - 1; bool is_negative; Type type; }; auto bitreverse(std::uint_least64_t b) -> decltype(b) { b = ((b & 0b1111111111111111111111111111111100000000000000000000000000000000ULL) >> 32) | ((b & 0b0000000000000000000000000000000011111111111111111111111111111111ULL) << 32); b = ((b & 0b1111111111111111000000000000000011111111111111110000000000000000ULL) >> 16) | ((b & 0b0000000000000000111111111111111100000000000000001111111111111111ULL) << 16); b = ((b & 0b1111111100000000111111110000000011111111000000001111111100000000ULL) >> 8) | ((b & 0b0000000011111111000000001111111100000000111111110000000011111111ULL) << 8); b = ((b & 0b1111000011110000111100001111000011110000111100001111000011110000ULL) >> 4) | ((b & 0b0000111100001111000011110000111100001111000011110000111100001111ULL) << 4); b = ((b & 0b1100110011001100110011001100110011001100110011001100110011001100ULL) >> 2) | ((b & 0b0011001100110011001100110011001100110011001100110011001100110011ULL) << 2); b = ((b & 0b1010101010101010101010101010101010101010101010101010101010101010ULL) >> 1) | ((b & 0b0101010101010101010101010101010101010101010101010101010101010101ULL) << 1); return b; } } template <> struct serializer<float_repr> { static void write(Serializer& s, float_repr const &b) { // Using multiplication to avoid bit shifting a signed integer switch(b.type) { default: { serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type); } break; case Normal: { const decltype(b.exponent) exponent = b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative); const decltype(b.fraction) reversed_fraction = bitreverse(b.fraction); serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3); serializer<decltype(+b.fraction)>::write(s, reversed_fraction); } break; }; } static float_repr read(Deserializer& s) { float_repr result; auto exponent = serializer<decltype(result.exponent)>::read(s); if (exponent < 3 && exponent >= -2) { result.is_negative = (exponent < 0); result.type = (Type)std::abs(exponent); } else { exponent = (exponent < 0) ? exponent + 2 : exponent - 3; result.is_negative = !!((exponent/ 1) % 2); result.type = Normal; result.exponent = exponent / 2; const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s); result.fraction = bitreverse(reversed_fraction); return result; } } }; void serializer<double>::write(Serializer& s, double const b) { switch (std::fpclassify(b)) { case FP_ZERO: serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero }); break; case FP_INFINITE: serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity }); break; case FP_NAN: // The bit reversal is to ensure the most efficient encoding can be used serializer<float_repr>::write(s, { 0, 0, false, NaN }); break; case FP_NORMAL: case FP_SUBNORMAL: float_repr repr; repr.type = Normal; repr.is_negative = !!std::signbit(b); // Make the fraction a positive integer repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits); serializer<decltype(repr)>::write(s, repr); break; } } double serializer<double>::read(Deserializer& s) { const auto repr = serializer<float_repr>::read(s); switch(repr.type) { case Zero: return (repr.is_negative ? -0.0 : 0.0); case Infinity: return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity(); case NaN: return std::numeric_limits<double>::quiet_NaN(); default: return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits); } } void serializer<float>::write(Serializer& s, float const b) { serializer<double>::write(s, b); } float serializer<float>::read(Deserializer& s) { return serializer<double>::read(s); } std::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) { std::uint_least64_t val = 0, offs = 0, b = s.getByte(); while (b & 0x80) { val |= (b & 0x7F) << offs; offs += 7; b = s.getByte(); } val |= b << offs; return val; } long serializer<long>::read(Deserializer& s) { const auto val = serializer<std::uint_least64_t>::read(s); auto value = static_cast<long>(val >> 1); if (val & 1) value = -value; return value; } int serializer<int>::read(Deserializer& s) { return serializer<long>::read(s); } std::string serializer<std::string>::read(Deserializer& s) { const auto length = serializer<std::uint_least64_t>::read(s); const uint8_t* ptr = s.ptr; const uint8_t* end = ptr + length; if (end > s.end) throw parse_exception("buffer underrun"); s.ptr = end; return std::string(reinterpret_cast<const char*>(ptr), length); } bool serializer<bool>::read(Deserializer& s) { return serializer<std::uint_least64_t>::read(s) > 0; } } <commit_msg>Fix warning<commit_after>#include "serializer.h" #include <cmath> #include <cstdint> #include <cstdlib> #include <limits> namespace rapscallion { void serializer<std::uint_least64_t>::write(Serializer& s, std::uint_least64_t value) { while (value >= 0x80) { s.addByte((uint8_t)(value & 0x7F) | 0x80); value >>= 7; } s.addByte((uint8_t)value); } void serializer<long>::write(Serializer& s, const long v) { std::uint_least64_t val = (std::abs(v) << 1) | (v < 0 ? 1 : 0); serializer<std::uint_least64_t>::write(s, val); } void serializer<int>::write(Serializer& s, const int v) { serializer<long>::write(s, v); } void serializer<std::string>::write(Serializer& s, const std::string& value) { serializer<std::uint_least64_t>::write(s, value.size()); for (auto& c : value) s.addByte(c); } void serializer<bool>::write(Serializer& s, const bool b) { serializer<std::uint_least64_t>::write(s, b ? 1 : 0); } namespace { enum Type { Zero, Infinity, NaN, Normal }; struct float_repr { // Can fit an exponent of 32-2=20 bits, can support octuple-precision IEEE754 floats std::int_least32_t exponent; // Can support double precision IEEE754 floats (quadruple requires 112 bits, octuple 236 bits) std::uint_least64_t fraction; // One bit reserved for sign bit static constexpr unsigned fraction_bits = 63 - 1; bool is_negative; Type type; }; auto bitreverse(std::uint_least64_t b) -> decltype(b) { b = ((b & 0b1111111111111111111111111111111100000000000000000000000000000000ULL) >> 32) | ((b & 0b0000000000000000000000000000000011111111111111111111111111111111ULL) << 32); b = ((b & 0b1111111111111111000000000000000011111111111111110000000000000000ULL) >> 16) | ((b & 0b0000000000000000111111111111111100000000000000001111111111111111ULL) << 16); b = ((b & 0b1111111100000000111111110000000011111111000000001111111100000000ULL) >> 8) | ((b & 0b0000000011111111000000001111111100000000111111110000000011111111ULL) << 8); b = ((b & 0b1111000011110000111100001111000011110000111100001111000011110000ULL) >> 4) | ((b & 0b0000111100001111000011110000111100001111000011110000111100001111ULL) << 4); b = ((b & 0b1100110011001100110011001100110011001100110011001100110011001100ULL) >> 2) | ((b & 0b0011001100110011001100110011001100110011001100110011001100110011ULL) << 2); b = ((b & 0b1010101010101010101010101010101010101010101010101010101010101010ULL) >> 1) | ((b & 0b0101010101010101010101010101010101010101010101010101010101010101ULL) << 1); return b; } } template <> struct serializer<float_repr> { static void write(Serializer& s, float_repr const &b) { // Using multiplication to avoid bit shifting a signed integer switch(b.type) { default: { serializer<decltype(+b.exponent)>::write(s, b.is_negative ? -b.type : b.type); } break; case Normal: { const decltype(b.exponent) exponent = b.exponent * 2 + (b.exponent < 0 ? -b.is_negative : b.is_negative); const decltype(b.fraction) reversed_fraction = bitreverse(b.fraction); serializer<decltype(+exponent)>::write(s, exponent < 0 ? exponent - 2 : exponent + 3); serializer<decltype(+b.fraction)>::write(s, reversed_fraction); } break; }; } static float_repr read(Deserializer& s) { float_repr result; auto exponent = serializer<decltype(result.exponent)>::read(s); if (exponent < 3 && exponent >= -2) { result.is_negative = (exponent < 0); result.type = (Type)std::abs(exponent); } else { exponent = (exponent < 0) ? exponent + 2 : exponent - 3; result.is_negative = !!((exponent/ 1) % 2); result.type = Normal; result.exponent = exponent / 2; const auto reversed_fraction = serializer<decltype(result.fraction)>::read(s); result.fraction = bitreverse(reversed_fraction); } return result; } }; void serializer<double>::write(Serializer& s, double const b) { switch (std::fpclassify(b)) { case FP_ZERO: serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Zero }); break; case FP_INFINITE: serializer<float_repr>::write(s, { 0, 0, !!std::signbit(b), Infinity }); break; case FP_NAN: // The bit reversal is to ensure the most efficient encoding can be used serializer<float_repr>::write(s, { 0, 0, false, NaN }); break; case FP_NORMAL: case FP_SUBNORMAL: float_repr repr; repr.type = Normal; repr.is_negative = !!std::signbit(b); // Make the fraction a positive integer repr.fraction = std::ldexp(std::abs(std::frexp(b, &repr.exponent)), repr.fraction_bits); serializer<decltype(repr)>::write(s, repr); break; } } double serializer<double>::read(Deserializer& s) { const auto repr = serializer<float_repr>::read(s); switch(repr.type) { case Zero: return (repr.is_negative ? -0.0 : 0.0); case Infinity: return repr.is_negative ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity(); case NaN: return std::numeric_limits<double>::quiet_NaN(); default: return (repr.is_negative ? -1.0 : 1.0) * std::ldexp(static_cast<double>(repr.fraction), repr.exponent - repr.fraction_bits); } } void serializer<float>::write(Serializer& s, float const b) { serializer<double>::write(s, b); } float serializer<float>::read(Deserializer& s) { return serializer<double>::read(s); } std::uint_least64_t serializer<std::uint_least64_t>::read(Deserializer& s) { std::uint_least64_t val = 0, offs = 0, b = s.getByte(); while (b & 0x80) { val |= (b & 0x7F) << offs; offs += 7; b = s.getByte(); } val |= b << offs; return val; } long serializer<long>::read(Deserializer& s) { const auto val = serializer<std::uint_least64_t>::read(s); auto value = static_cast<long>(val >> 1); if (val & 1) value = -value; return value; } int serializer<int>::read(Deserializer& s) { return serializer<long>::read(s); } std::string serializer<std::string>::read(Deserializer& s) { const auto length = serializer<std::uint_least64_t>::read(s); const uint8_t* ptr = s.ptr; const uint8_t* end = ptr + length; if (end > s.end) throw parse_exception("buffer underrun"); s.ptr = end; return std::string(reinterpret_cast<const char*>(ptr), length); } bool serializer<bool>::read(Deserializer& s) { return serializer<std::uint_least64_t>::read(s) > 0; } } <|endoftext|>
<commit_before>// // sio_packet.cpp // // Created by Melo Yao on 3/22/15. // #include "sio_packet.h" #include <rapidjson/document.h> #include <rapidjson/encodedstream.h> #include <rapidjson/writer.h> #include <cassert> namespace sio { using namespace rapidjson; using namespace std; void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers); void accept_int_message(int_message const& msg, Value& val) { val.SetInt64(msg.get_int()); } void accept_double_message(double_message const& msg, Value& val) { val.SetDouble(msg.get_double()); } void accept_string_message(string_message const& msg, Value& val) { val.SetString(msg.get_string().data(),(SizeType) msg.get_string().length()); } void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetObject(); Value boolVal; boolVal.SetBool(true); val.AddMember("_placeholder", boolVal, doc.GetAllocator()); Value numVal; numVal.SetInt((int)buffers.size()); val.AddMember("num", numVal, doc.GetAllocator()); //FIXME can not avoid binary copy here. shared_ptr<string> write_buffer = make_shared<string>(); write_buffer->reserve(msg.get_binary()->size()+1); char frame_char = packet::frame_message; write_buffer->append(&frame_char,1); write_buffer->append(*(msg.get_binary())); buffers.push_back(write_buffer); } void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetArray(); for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) { Value child; accept_message(*(*it), child, doc,buffers); val.PushBack(child, doc.GetAllocator()); } } void accept_object_message(object_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetObject(); for (map<string,message::ptr>::const_iterator it = msg.get_map().begin(); it!= msg.get_map().end(); ++it) { Value nameVal; nameVal.SetString(it->first.data(), (SizeType)it->first.length(), doc.GetAllocator()); Value valueVal; accept_message(*(it->second), valueVal, doc,buffers); val.AddMember(nameVal, valueVal, doc.GetAllocator()); } } void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers) { const message* msg_ptr = &msg; switch(msg.get_flag()) { case message::flag_integer: { accept_int_message(*(static_cast<const int_message*>(msg_ptr)), val); break; } case message::flag_double: { accept_double_message(*(static_cast<const double_message*>(msg_ptr)), val); break; } case message::flag_string: { accept_string_message(*(static_cast<const string_message*>(msg_ptr)), val); break; } case message::flag_binary: { accept_binary_message(*(static_cast<const binary_message*>(msg_ptr)), val,doc,buffers); break; } case message::flag_array: { accept_array_message(*(static_cast<const array_message*>(msg_ptr)), val,doc,buffers); break; } case message::flag_object: { accept_object_message(*(static_cast<const object_message*>(msg_ptr)), val,doc,buffers); break; } default: break; } } message::ptr from_json(Value const& value, vector<shared_ptr<const string> > const& buffers) { if(value.IsInt64()) { return int_message::create(value.GetInt64()); } else if(value.IsDouble()) { return double_message::create(value.GetDouble()); } else if(value.IsString()) { string str(value.GetString(),value.GetStringLength()); return string_message::create(str); } else if(value.IsArray()) { message::ptr ptr = array_message::create(); for (SizeType i = 0; i< value.Size(); ++i) { static_cast<array_message*>(ptr.get())->get_vector().push_back(from_json(value[i],buffers)); } return ptr; } else if(value.IsObject()) { //binary placeholder if (value.HasMember("_placeholder") && value["_placeholder"].GetBool()) { int num = value["num"].GetInt(); if(num > 0 && num < buffers.size()) { return binary_message::create(buffers[num]); } return message::ptr(); } //real object message. message::ptr ptr = object_message::create(); for (auto it = value.MemberBegin();it!=value.MemberEnd();++it) { if(it->name.IsString()) { string key(it->name.GetString(),it->name.GetStringLength()); static_cast<object_message*>(ptr.get())->get_map()[key] = from_json(it->value,buffers); } } return ptr; } return message::ptr(); } packet::packet(string const& nsp,message::ptr const& msg,int pack_id, bool isAck): _frame(frame_message), _type((isAck?type_ack : type_event) | type_undetermined), _nsp(nsp), _message(msg), _pack_id(pack_id), _pending_buffers(0) { assert((!isAck || (isAck&&pack_id>=0))); } packet::packet(type type,message::ptr const& msg): _frame(frame_message), _type(type), _message(msg), _pack_id(-1), _pending_buffers(0) { } packet::packet(packet::frame_type frame): _frame(frame), _type(type_undetermined), _pack_id(-1), _pending_buffers(0) { } packet::packet(): _type(type_undetermined), _pack_id(-1), _pending_buffers(0) { } bool packet::is_binary_message(string const& payload_ptr) { return payload_ptr.size()>0 && payload_ptr[0] == frame_message; } bool packet::is_text_message(string const& payload_ptr) { return payload_ptr.size()>0 && payload_ptr[0] == (frame_message + '0'); } bool packet::is_message(string const& payload_ptr) { return is_binary_message(payload_ptr) || is_text_message(payload_ptr); } bool packet::parse_buffer(const string &buf_payload) { if (_pending_buffers > 0) { assert(is_binary_message(buf_payload));//this is ensured by outside. _buffers.push_back(std::make_shared<string>(buf_payload.data()+1,buf_payload.size()-1)); _pending_buffers--; if (_pending_buffers == 0) { Document doc; doc.Parse<0>(_buffers.front()->data()); _buffers.erase(_buffers.begin()); _message = from_json(doc, _buffers); _buffers.clear(); return false; } return true; } return false; } bool packet::parse(const string& payload_ptr) { assert(!is_binary_message(payload_ptr)); //this is ensured by outside _frame = (packet::frame_type) (payload_ptr[0] - '0'); size_t pos = 1; if (_frame == frame_message) { _type = (packet::type)(payload_ptr[pos] - '0'); if(_type < type_min || _type > type_max) { return false; } pos++; if (_type == type_binary_event || _type == type_binary_ack) { size_t score_pos = payload_ptr.find('-'); _pending_buffers = stoi(payload_ptr.substr(pos,score_pos)); pos = score_pos+1; } } size_t comma_pos = payload_ptr.find_first_of("{[,"); if( comma_pos!= string::npos && payload_ptr[comma_pos] == ',') { _nsp = payload_ptr.substr(pos,comma_pos - pos); pos = comma_pos+1; } if (pos >= payload_ptr.length()) { //message only have type, maybe with namespace. return false; } size_t data_pos = payload_ptr.find_first_of("[{", pos, 2); if (data_pos == string::npos) { //we have pack id, no message. _pack_id = stoi(payload_ptr.substr(pos)); return false; } else if(data_pos>pos) { //we have pack id and messages. _pack_id = stoi(payload_ptr.substr(pos,data_pos - pos)); } if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) { //parse later when all buffers are arrived. _buffers.push_back(make_shared<const string>(payload_ptr.data() + data_pos, payload_ptr.length() - data_pos)); return true; } else { Document doc; doc.Parse<0>(payload_ptr.substr(data_pos).data()); _message = from_json(doc, vector<shared_ptr<const string> >()); return false; } } bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers) { char frame_char = _frame+'0'; payload_ptr.append(&frame_char,1); if (_frame!=frame_message) { return false; } bool hasMessage = false; Document doc; if (_message) { accept_message(*_message, doc, doc, buffers); hasMessage = true; } bool hasBinary = buffers.size()>0; _type = _type&(~type_undetermined); if(_type == type_event) { _type = hasBinary?type_binary_event:type_event; } else if(_type == type_ack) { _type = hasBinary? type_binary_ack : type_ack; } ostringstream ss; ss.precision(8); ss<<_type; if (hasBinary) { ss<<buffers.size()<<"-"; } if(_nsp.size()>0 && _nsp!="/") { ss<<_nsp; if (hasMessage || _pack_id>=0) { ss<<","; } } if(_pack_id>=0) { ss<<_pack_id; } payload_ptr.append(ss.str()); if (hasMessage) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); payload_ptr.append(buffer.GetString(),buffer.GetSize()); } return hasBinary; } packet::frame_type packet::get_frame() const { return _frame; } packet::type packet::get_type() const { assert((_type & type_undetermined) == 0); return (type)_type; } string const& packet::get_nsp() const { return _nsp; } message::ptr const& packet::get_message() const { return _message; } unsigned packet::get_pack_id() const { return _pack_id; } void packet_manager::set_decode_callback(function<void (packet const&)> const& decode_callback) { m_decode_callback = decode_callback; } void packet_manager::set_encode_callback(function<void (bool,shared_ptr<const string> const&)> const& encode_callback) { m_encode_callback = encode_callback; } void packet_manager::reset() { m_partial_packet.reset(); } void packet_manager::encode(packet& pack,encode_callback_function const& override_encode_callback) const { shared_ptr<string> ptr = make_shared<string>(); vector<shared_ptr<const string> > buffers; const encode_callback_function *cb_ptr = &m_encode_callback; if(override_encode_callback) { cb_ptr = &override_encode_callback; } if(pack.accept(*ptr,buffers)) { if((*cb_ptr)) { (*cb_ptr)(false,ptr); } for(auto it = buffers.begin();it!=buffers.end();++it) { if((*cb_ptr)) { (*cb_ptr)(true,*it); } } } else { if((*cb_ptr)) { (*cb_ptr)(false,ptr); } } } void packet_manager::put_payload(string const& payload) { unique_ptr<packet> p; do { if(packet::is_text_message(payload)) { p.reset(new packet()); if(p->parse(payload)) { m_partial_packet = std::move(p); } else { break; } } else if(packet::is_binary_message(payload)) { if(m_partial_packet) { if(!m_partial_packet->parse_buffer(payload)) { p = std::move(m_partial_packet); break; } } } else { p.reset(new packet()); p->parse(payload); break; } return; }while(0); if(m_decode_callback) { m_decode_callback(*p); } } }<commit_msg>optimize json member access<commit_after>// // sio_packet.cpp // // Created by Melo Yao on 3/22/15. // #include "sio_packet.h" #include <rapidjson/document.h> #include <rapidjson/encodedstream.h> #include <rapidjson/writer.h> #include <cassert> #define kBIN_PLACE_HOLDER "_placeholder" namespace sio { using namespace rapidjson; using namespace std; void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers); void accept_int_message(int_message const& msg, Value& val) { val.SetInt64(msg.get_int()); } void accept_double_message(double_message const& msg, Value& val) { val.SetDouble(msg.get_double()); } void accept_string_message(string_message const& msg, Value& val) { val.SetString(msg.get_string().data(),(SizeType) msg.get_string().length()); } void accept_binary_message(binary_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetObject(); Value boolVal; boolVal.SetBool(true); val.AddMember(kBIN_PLACE_HOLDER, boolVal, doc.GetAllocator()); Value numVal; numVal.SetInt((int)buffers.size()); val.AddMember("num", numVal, doc.GetAllocator()); //FIXME can not avoid binary copy here. shared_ptr<string> write_buffer = make_shared<string>(); write_buffer->reserve(msg.get_binary()->size()+1); char frame_char = packet::frame_message; write_buffer->append(&frame_char,1); write_buffer->append(*(msg.get_binary())); buffers.push_back(write_buffer); } void accept_array_message(array_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetArray(); for (vector<message::ptr>::const_iterator it = msg.get_vector().begin(); it!=msg.get_vector().end(); ++it) { Value child; accept_message(*(*it), child, doc,buffers); val.PushBack(child, doc.GetAllocator()); } } void accept_object_message(object_message const& msg,Value& val,Document& doc,vector<shared_ptr<const string> >& buffers) { val.SetObject(); for (map<string,message::ptr>::const_iterator it = msg.get_map().begin(); it!= msg.get_map().end(); ++it) { Value nameVal; nameVal.SetString(it->first.data(), (SizeType)it->first.length(), doc.GetAllocator()); Value valueVal; accept_message(*(it->second), valueVal, doc,buffers); val.AddMember(nameVal, valueVal, doc.GetAllocator()); } } void accept_message(message const& msg,Value& val, Document& doc,vector<shared_ptr<const string> >& buffers) { const message* msg_ptr = &msg; switch(msg.get_flag()) { case message::flag_integer: { accept_int_message(*(static_cast<const int_message*>(msg_ptr)), val); break; } case message::flag_double: { accept_double_message(*(static_cast<const double_message*>(msg_ptr)), val); break; } case message::flag_string: { accept_string_message(*(static_cast<const string_message*>(msg_ptr)), val); break; } case message::flag_binary: { accept_binary_message(*(static_cast<const binary_message*>(msg_ptr)), val,doc,buffers); break; } case message::flag_array: { accept_array_message(*(static_cast<const array_message*>(msg_ptr)), val,doc,buffers); break; } case message::flag_object: { accept_object_message(*(static_cast<const object_message*>(msg_ptr)), val,doc,buffers); break; } default: break; } } message::ptr from_json(Value const& value, vector<shared_ptr<const string> > const& buffers) { if(value.IsInt64()) { return int_message::create(value.GetInt64()); } else if(value.IsDouble()) { return double_message::create(value.GetDouble()); } else if(value.IsString()) { string str(value.GetString(),value.GetStringLength()); return string_message::create(str); } else if(value.IsArray()) { message::ptr ptr = array_message::create(); for (SizeType i = 0; i< value.Size(); ++i) { static_cast<array_message*>(ptr.get())->get_vector().push_back(from_json(value[i],buffers)); } return ptr; } else if(value.IsObject()) { //binary placeholder auto mem_it = value.FindMember(kBIN_PLACE_HOLDER); if (mem_it!=value.MemberEnd() && mem_it->value.GetBool()) { int num = value["num"].GetInt(); if(num > 0 && num < buffers.size()) { return binary_message::create(buffers[num]); } return message::ptr(); } //real object message. message::ptr ptr = object_message::create(); for (auto it = value.MemberBegin();it!=value.MemberEnd();++it) { if(it->name.IsString()) { string key(it->name.GetString(),it->name.GetStringLength()); static_cast<object_message*>(ptr.get())->get_map()[key] = from_json(it->value,buffers); } } return ptr; } return message::ptr(); } packet::packet(string const& nsp,message::ptr const& msg,int pack_id, bool isAck): _frame(frame_message), _type((isAck?type_ack : type_event) | type_undetermined), _nsp(nsp), _message(msg), _pack_id(pack_id), _pending_buffers(0) { assert((!isAck || (isAck&&pack_id>=0))); } packet::packet(type type,message::ptr const& msg): _frame(frame_message), _type(type), _message(msg), _pack_id(-1), _pending_buffers(0) { } packet::packet(packet::frame_type frame): _frame(frame), _type(type_undetermined), _pack_id(-1), _pending_buffers(0) { } packet::packet(): _type(type_undetermined), _pack_id(-1), _pending_buffers(0) { } bool packet::is_binary_message(string const& payload_ptr) { return payload_ptr.size()>0 && payload_ptr[0] == frame_message; } bool packet::is_text_message(string const& payload_ptr) { return payload_ptr.size()>0 && payload_ptr[0] == (frame_message + '0'); } bool packet::is_message(string const& payload_ptr) { return is_binary_message(payload_ptr) || is_text_message(payload_ptr); } bool packet::parse_buffer(const string &buf_payload) { if (_pending_buffers > 0) { assert(is_binary_message(buf_payload));//this is ensured by outside. _buffers.push_back(std::make_shared<string>(buf_payload.data()+1,buf_payload.size()-1)); _pending_buffers--; if (_pending_buffers == 0) { Document doc; doc.Parse<0>(_buffers.front()->data()); _buffers.erase(_buffers.begin()); _message = from_json(doc, _buffers); _buffers.clear(); return false; } return true; } return false; } bool packet::parse(const string& payload_ptr) { assert(!is_binary_message(payload_ptr)); //this is ensured by outside _frame = (packet::frame_type) (payload_ptr[0] - '0'); size_t pos = 1; if (_frame == frame_message) { _type = (packet::type)(payload_ptr[pos] - '0'); if(_type < type_min || _type > type_max) { return false; } pos++; if (_type == type_binary_event || _type == type_binary_ack) { size_t score_pos = payload_ptr.find('-'); _pending_buffers = stoi(payload_ptr.substr(pos,score_pos)); pos = score_pos+1; } } size_t comma_pos = payload_ptr.find_first_of("{[,"); if( comma_pos!= string::npos && payload_ptr[comma_pos] == ',') { _nsp = payload_ptr.substr(pos,comma_pos - pos); pos = comma_pos+1; } if (pos >= payload_ptr.length()) { //message only have type, maybe with namespace. return false; } size_t data_pos = payload_ptr.find_first_of("[{", pos, 2); if (data_pos == string::npos) { //we have pack id, no message. _pack_id = stoi(payload_ptr.substr(pos)); return false; } else if(data_pos>pos) { //we have pack id and messages. _pack_id = stoi(payload_ptr.substr(pos,data_pos - pos)); } if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) { //parse later when all buffers are arrived. _buffers.push_back(make_shared<const string>(payload_ptr.data() + data_pos, payload_ptr.length() - data_pos)); return true; } else { Document doc; doc.Parse<0>(payload_ptr.substr(data_pos).data()); _message = from_json(doc, vector<shared_ptr<const string> >()); return false; } } bool packet::accept(string& payload_ptr, vector<shared_ptr<const string> >&buffers) { char frame_char = _frame+'0'; payload_ptr.append(&frame_char,1); if (_frame!=frame_message) { return false; } bool hasMessage = false; Document doc; if (_message) { accept_message(*_message, doc, doc, buffers); hasMessage = true; } bool hasBinary = buffers.size()>0; _type = _type&(~type_undetermined); if(_type == type_event) { _type = hasBinary?type_binary_event:type_event; } else if(_type == type_ack) { _type = hasBinary? type_binary_ack : type_ack; } ostringstream ss; ss.precision(8); ss<<_type; if (hasBinary) { ss<<buffers.size()<<"-"; } if(_nsp.size()>0 && _nsp!="/") { ss<<_nsp; if (hasMessage || _pack_id>=0) { ss<<","; } } if(_pack_id>=0) { ss<<_pack_id; } payload_ptr.append(ss.str()); if (hasMessage) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); doc.Accept(writer); payload_ptr.append(buffer.GetString(),buffer.GetSize()); } return hasBinary; } packet::frame_type packet::get_frame() const { return _frame; } packet::type packet::get_type() const { assert((_type & type_undetermined) == 0); return (type)_type; } string const& packet::get_nsp() const { return _nsp; } message::ptr const& packet::get_message() const { return _message; } unsigned packet::get_pack_id() const { return _pack_id; } void packet_manager::set_decode_callback(function<void (packet const&)> const& decode_callback) { m_decode_callback = decode_callback; } void packet_manager::set_encode_callback(function<void (bool,shared_ptr<const string> const&)> const& encode_callback) { m_encode_callback = encode_callback; } void packet_manager::reset() { m_partial_packet.reset(); } void packet_manager::encode(packet& pack,encode_callback_function const& override_encode_callback) const { shared_ptr<string> ptr = make_shared<string>(); vector<shared_ptr<const string> > buffers; const encode_callback_function *cb_ptr = &m_encode_callback; if(override_encode_callback) { cb_ptr = &override_encode_callback; } if(pack.accept(*ptr,buffers)) { if((*cb_ptr)) { (*cb_ptr)(false,ptr); } for(auto it = buffers.begin();it!=buffers.end();++it) { if((*cb_ptr)) { (*cb_ptr)(true,*it); } } } else { if((*cb_ptr)) { (*cb_ptr)(false,ptr); } } } void packet_manager::put_payload(string const& payload) { unique_ptr<packet> p; do { if(packet::is_text_message(payload)) { p.reset(new packet()); if(p->parse(payload)) { m_partial_packet = std::move(p); } else { break; } } else if(packet::is_binary_message(payload)) { if(m_partial_packet) { if(!m_partial_packet->parse_buffer(payload)) { p = std::move(m_partial_packet); break; } } } else { p.reset(new packet()); p->parse(payload); break; } return; }while(0); if(m_decode_callback) { m_decode_callback(*p); } } }<|endoftext|>
<commit_before>/* Copyright 2016 Fixstars Corporation 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 <libsgm.h> #include "internal.h" namespace sgm { static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; } static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; } struct CudaStereoSGMResources { void* d_src_left; void* d_src_right; void* d_left; void* d_right; void* d_scost; void* d_matching_cost; void* d_left_disp; void* d_right_disp; void* d_tmp_left_disp; void* d_tmp_right_disp; cudaStream_t cuda_streams[8]; void* d_output_16bit_buffer; uint16_t* h_output_16bit_buffer; CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) { if (is_cuda_input(inout_type_)) { this->d_src_left = NULL; this->d_src_right = NULL; } else { CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_)); } CudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamCreate(&this->cuda_streams[i])); } // create temporary buffer when dst type is 8bit host pointer if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { this->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_); } else { this->h_output_16bit_buffer = NULL; } } ~CudaStereoSGMResources() { CudaSafeCall(cudaFree(this->d_src_left)); CudaSafeCall(cudaFree(this->d_src_right)); CudaSafeCall(cudaFree(this->d_left)); CudaSafeCall(cudaFree(this->d_right)); CudaSafeCall(cudaFree(this->d_matching_cost)); CudaSafeCall(cudaFree(this->d_scost)); CudaSafeCall(cudaFree(this->d_left_disp)); CudaSafeCall(cudaFree(this->d_right_disp)); CudaSafeCall(cudaFree(this->d_tmp_left_disp)); CudaSafeCall(cudaFree(this->d_tmp_right_disp)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamDestroy(this->cuda_streams[i])); } free(h_output_16bit_buffer); } }; StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) : width_(width), height_(height), disparity_size_(disparity_size), input_depth_bits_(input_depth_bits), output_depth_bits_(output_depth_bits), inout_type_(inout_type), cu_res_(NULL) { // check values if (width_ % 2 != 0 || height_ % 2 != 0) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("width and height must be even"); } if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("depth bits must be 8 or 16"); } if (disparity_size_ != 64 && disparity_size_ != 128) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("disparity size must be 64 or 128"); } cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_); } StereoSGM::~StereoSGM() { if (cu_res_) { delete cu_res_; } } void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) { const void *d_input_left, *d_input_right; if (is_cuda_input(inout_type_)) { d_input_left = left_pixels; d_input_right = right_pixels; } else { CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); d_input_left = cu_res_->d_src_left; d_input_right = cu_res_->d_src_right; } sgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]); sgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]); CudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4])); sgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_); sgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams); cudaStreamSynchronize(cu_res_->cuda_streams[2]); cudaStreamSynchronize(cu_res_->cuda_streams[3]); sgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_); sgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_); sgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_); sgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_); // output disparity image void* disparity_image = cu_res_->d_tmp_left_disp; if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) { CudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) { *dst = disparity_image; // optimize! no-copy! } else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { CudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); for (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; } } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) { sgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_); } else { std::cerr << "not impl" << std::endl; } } } <commit_msg>remove unused buffer<commit_after>/* Copyright 2016 Fixstars Corporation 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 <libsgm.h> #include "internal.h" namespace sgm { static bool is_cuda_input(EXECUTE_INOUT type) { return (int)type & 0x1; } static bool is_cuda_output(EXECUTE_INOUT type) { return (int)type & 0x2; } struct CudaStereoSGMResources { void* d_src_left; void* d_src_right; void* d_left; void* d_right; void* d_scost; void* d_matching_cost; void* d_left_disp; void* d_right_disp; void* d_tmp_left_disp; void* d_tmp_right_disp; cudaStream_t cuda_streams[8]; uint16_t* h_output_16bit_buffer; CudaStereoSGMResources(int width_, int height_, int disparity_size_, int input_depth_bits_, int output_depth_bits_, EXECUTE_INOUT inout_type_) { if (is_cuda_input(inout_type_)) { this->d_src_left = NULL; this->d_src_right = NULL; } else { CudaSafeCall(cudaMalloc(&this->d_src_left, input_depth_bits_ / 8 * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_src_right, input_depth_bits_ / 8 * width_ * height_)); } CudaSafeCall(cudaMalloc(&this->d_left, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right, sizeof(uint64_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_matching_cost, sizeof(uint8_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_scost, sizeof(uint16_t) * width_ * height_ * disparity_size_)); CudaSafeCall(cudaMalloc(&this->d_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_left_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMalloc(&this->d_tmp_right_disp, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_left_disp, 0, sizeof(uint16_t) * width_ * height_)); CudaSafeCall(cudaMemset(&this->d_tmp_right_disp, 0, sizeof(uint16_t) * width_ * height_)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamCreate(&this->cuda_streams[i])); } // create temporary buffer when dst type is 8bit host pointer if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { this->h_output_16bit_buffer = (uint16_t*)malloc(sizeof(uint16_t) * width_ * height_); } else { this->h_output_16bit_buffer = NULL; } } ~CudaStereoSGMResources() { CudaSafeCall(cudaFree(this->d_src_left)); CudaSafeCall(cudaFree(this->d_src_right)); CudaSafeCall(cudaFree(this->d_left)); CudaSafeCall(cudaFree(this->d_right)); CudaSafeCall(cudaFree(this->d_matching_cost)); CudaSafeCall(cudaFree(this->d_scost)); CudaSafeCall(cudaFree(this->d_left_disp)); CudaSafeCall(cudaFree(this->d_right_disp)); CudaSafeCall(cudaFree(this->d_tmp_left_disp)); CudaSafeCall(cudaFree(this->d_tmp_right_disp)); for (int i = 0; i < 8; i++) { CudaSafeCall(cudaStreamDestroy(this->cuda_streams[i])); } free(h_output_16bit_buffer); } }; StereoSGM::StereoSGM(int width, int height, int disparity_size, int input_depth_bits, int output_depth_bits, EXECUTE_INOUT inout_type) : width_(width), height_(height), disparity_size_(disparity_size), input_depth_bits_(input_depth_bits), output_depth_bits_(output_depth_bits), inout_type_(inout_type), cu_res_(NULL) { // check values if (width_ % 2 != 0 || height_ % 2 != 0) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("width and height must be even"); } if (input_depth_bits_ != 8 && input_depth_bits_ != 16 && output_depth_bits_ != 8 && output_depth_bits_ != 16) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("depth bits must be 8 or 16"); } if (disparity_size_ != 64 && disparity_size_ != 128) { width_ = height_ = input_depth_bits_ = output_depth_bits_ = disparity_size_ = 0; throw std::runtime_error("disparity size must be 64 or 128"); } cu_res_ = new CudaStereoSGMResources(width_, height_, disparity_size_, input_depth_bits_, output_depth_bits_, inout_type_); } StereoSGM::~StereoSGM() { if (cu_res_) { delete cu_res_; } } void StereoSGM::execute(const void* left_pixels, const void* right_pixels, void** dst) { const void *d_input_left, *d_input_right; if (is_cuda_input(inout_type_)) { d_input_left = left_pixels; d_input_right = right_pixels; } else { CudaSafeCall(cudaMemcpy(cu_res_->d_src_left, left_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); CudaSafeCall(cudaMemcpy(cu_res_->d_src_right, right_pixels, input_depth_bits_ / 8 * width_ * height_, cudaMemcpyHostToDevice)); d_input_left = cu_res_->d_src_left; d_input_right = cu_res_->d_src_right; } sgm::details::census(d_input_left, (uint64_t*)cu_res_->d_left, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[0]); sgm::details::census(d_input_right, (uint64_t*)cu_res_->d_right, 9, 7, width_, height_, input_depth_bits_, cu_res_->cuda_streams[1]); CudaSafeCall(cudaMemsetAsync(cu_res_->d_left_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[2])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_right_disp, 0, sizeof(uint16_t) * width_ * height_, cu_res_->cuda_streams[3])); CudaSafeCall(cudaMemsetAsync(cu_res_->d_scost, 0, sizeof(uint16_t) * width_ * height_ * disparity_size_, cu_res_->cuda_streams[4])); sgm::details::matching_cost((const uint64_t*)cu_res_->d_left, (const uint64_t*)cu_res_->d_right, (uint8_t*)cu_res_->d_matching_cost, width_, height_, disparity_size_); sgm::details::scan_scost((const uint8_t*)cu_res_->d_matching_cost, (uint16_t*)cu_res_->d_scost, width_, height_, disparity_size_, cu_res_->cuda_streams); cudaStreamSynchronize(cu_res_->cuda_streams[2]); cudaStreamSynchronize(cu_res_->cuda_streams[3]); sgm::details::winner_takes_all((const uint16_t*)cu_res_->d_scost, (uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_right_disp, width_, height_, disparity_size_); sgm::details::median_filter((uint16_t*)cu_res_->d_left_disp, (uint16_t*)cu_res_->d_tmp_left_disp, width_, height_); sgm::details::median_filter((uint16_t*)cu_res_->d_right_disp, (uint16_t*)cu_res_->d_tmp_right_disp, width_, height_); sgm::details::check_consistency((uint16_t*)cu_res_->d_tmp_left_disp, (uint16_t*)cu_res_->d_tmp_right_disp, d_input_left, width_, height_, input_depth_bits_); // output disparity image void* disparity_image = cu_res_->d_tmp_left_disp; if (!is_cuda_output(inout_type_) && output_depth_bits_ == 16) { CudaSafeCall(cudaMemcpy(*dst, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 16) { *dst = disparity_image; // optimize! no-copy! } else if (!is_cuda_output(inout_type_) && output_depth_bits_ == 8) { CudaSafeCall(cudaMemcpy(cu_res_->h_output_16bit_buffer, disparity_image, sizeof(uint16_t) * width_ * height_, cudaMemcpyDeviceToHost)); for (int i = 0; i < width_ * height_; i++) { ((uint8_t*)*dst)[i] = (uint8_t)cu_res_->h_output_16bit_buffer[i]; } } else if (is_cuda_output(inout_type_) && output_depth_bits_ == 8) { sgm::details::cast_16bit_8bit_array((const uint16_t*)disparity_image, (uint8_t*)*dst, width_ * height_); } else { std::cerr << "not impl" << std::endl; } } } <|endoftext|>
<commit_before>#include "string_util.h" #include <cmath> #include <cstdarg> #include <array> #include <memory> #include <sstream> #include "arraysize.h" namespace benchmark { namespace { // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. const char kBigSIUnits[] = "kMGTPEZY"; // Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. const char kBigIECUnits[] = "KMGTPEZY"; // milli, micro, nano, pico, femto, atto, zepto, yocto. const char kSmallSIUnits[] = "munpfazy"; // We require that all three arrays have the same size. static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), "SI and IEC unit arrays must be the same size"); static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), "Small SI and Big SI unit arrays must be the same size"); static const int64_t kUnitsSize = arraysize(kBigSIUnits); } // end anonymous namespace void ToExponentAndMantissa(double val, double thresh, int precision, double one_k, std::string* mantissa, int64_t* exponent) { std::stringstream mantissa_stream; if (val < 0) { mantissa_stream << "-"; val = -val; } // Adjust threshold so that it never excludes things which can't be rendered // in 'precision' digits. const double adjusted_threshold = std::max(thresh, 1.0 / std::pow(10.0, precision)); const double big_threshold = adjusted_threshold * one_k; const double small_threshold = adjusted_threshold; if (val > big_threshold) { // Positive powers double scaled = val; for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { scaled /= one_k; if (scaled <= big_threshold) { mantissa_stream << scaled; *exponent = i + 1; *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else if (val < small_threshold) { // Negative powers double scaled = val; for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { scaled *= one_k; if (scaled >= small_threshold) { mantissa_stream << scaled; *exponent = -i - 1; *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else { mantissa_stream << val; *exponent = 0; } *mantissa = mantissa_stream.str(); } std::string ExponentToPrefix(int64_t exponent, bool iec) { if (exponent == 0) return ""; const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); if (index >= kUnitsSize) return ""; const char* array = (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); if (iec) return array[index] + std::string("i"); else return std::string(1, array[index]); } std::string ToBinaryStringFullySpecified(double value, double threshold, int precision) { std::string mantissa; int64_t exponent; ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa, &exponent); return mantissa + ExponentToPrefix(exponent, false); } void AppendHumanReadable(int n, std::string* str) { std::stringstream ss; // Round down to the nearest SI prefix. ss << "/" << ToBinaryStringFullySpecified(n, 1.0, 0); *str += ss.str(); } std::string HumanReadableNumber(double n) { // 1.1 means that figures up to 1.1k should be shown with the next unit down; // this softens edge effects. // 1 means that we should show one decimal place of precision. return ToBinaryStringFullySpecified(n, 1.1, 1); } std::string StringPrintFImp(const char *msg, va_list args) { // we might need a second shot at this, so pre-emptivly make a copy va_list args_cp; va_copy(args_cp, args); // TODO(ericwf): use std::array for first attempt to avoid one memory // allocation guess what the size might be std::array<char, 256> local_buff; std::size_t size = local_buff.size(); auto ret = std::vsnprintf(local_buff.data(), size, msg, args_cp); va_end(args_cp); // handle empty expansion if (ret == 0) return std::string{}; if (static_cast<std::size_t>(ret) < size) return std::string(local_buff.data()); // we did not provide a long enough buffer on our first attempt. // add 1 to size to account for null-byte in size cast to prevent overflow size = static_cast<std::size_t>(ret) + 1; auto buff_ptr = std::unique_ptr<char[]>(new char[size]); ret = std::vsnprintf(buff_ptr.get(), size, msg, args); return std::string(buff_ptr.get()); } std::string StringPrintF(const char* format, ...) { va_list args; va_start(args, format); std::string tmp = StringPrintFImp(format, args); va_end(args); return tmp; } void ReplaceAll(std::string* str, const std::string& from, const std::string& to) { std::size_t start = 0; while((start = str->find(from, start)) != std::string::npos) { str->replace(start, from.length(), to); start += to.length(); } } } // end namespace benchmark <commit_msg>Fixed bug in "ToExponentAndMantissa" when negative exponents where created.<commit_after>#include "string_util.h" #include <cmath> #include <cstdarg> #include <array> #include <memory> #include <sstream> #include "arraysize.h" namespace benchmark { namespace { // kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta. const char kBigSIUnits[] = "kMGTPEZY"; // Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi. const char kBigIECUnits[] = "KMGTPEZY"; // milli, micro, nano, pico, femto, atto, zepto, yocto. const char kSmallSIUnits[] = "munpfazy"; // We require that all three arrays have the same size. static_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits), "SI and IEC unit arrays must be the same size"); static_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits), "Small SI and Big SI unit arrays must be the same size"); static const int64_t kUnitsSize = arraysize(kBigSIUnits); } // end anonymous namespace void ToExponentAndMantissa(double val, double thresh, int precision, double one_k, std::string* mantissa, int64_t* exponent) { std::stringstream mantissa_stream; if (val < 0) { mantissa_stream << "-"; val = -val; } // Adjust threshold so that it never excludes things which can't be rendered // in 'precision' digits. const double adjusted_threshold = std::max(thresh, 1.0 / std::pow(10.0, precision)); const double big_threshold = adjusted_threshold * one_k; const double small_threshold = adjusted_threshold; if (val > big_threshold) { // Positive powers double scaled = val; for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) { scaled /= one_k; if (scaled <= big_threshold) { mantissa_stream << scaled; *exponent = i + 1; *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else if (val < small_threshold) { // Negative powers double scaled = val; for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) { scaled *= one_k; if (scaled >= small_threshold) { mantissa_stream << scaled; *exponent = -static_cast<int64_t>(i + 1); *mantissa = mantissa_stream.str(); return; } } mantissa_stream << val; *exponent = 0; } else { mantissa_stream << val; *exponent = 0; } *mantissa = mantissa_stream.str(); } std::string ExponentToPrefix(int64_t exponent, bool iec) { if (exponent == 0) return ""; const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1); if (index >= kUnitsSize) return ""; const char* array = (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits); if (iec) return array[index] + std::string("i"); else return std::string(1, array[index]); } std::string ToBinaryStringFullySpecified(double value, double threshold, int precision) { std::string mantissa; int64_t exponent; ToExponentAndMantissa(value, threshold, precision, 1024.0, &mantissa, &exponent); return mantissa + ExponentToPrefix(exponent, false); } void AppendHumanReadable(int n, std::string* str) { std::stringstream ss; // Round down to the nearest SI prefix. ss << "/" << ToBinaryStringFullySpecified(n, 1.0, 0); *str += ss.str(); } std::string HumanReadableNumber(double n) { // 1.1 means that figures up to 1.1k should be shown with the next unit down; // this softens edge effects. // 1 means that we should show one decimal place of precision. return ToBinaryStringFullySpecified(n, 1.1, 1); } std::string StringPrintFImp(const char *msg, va_list args) { // we might need a second shot at this, so pre-emptivly make a copy va_list args_cp; va_copy(args_cp, args); // TODO(ericwf): use std::array for first attempt to avoid one memory // allocation guess what the size might be std::array<char, 256> local_buff; std::size_t size = local_buff.size(); auto ret = std::vsnprintf(local_buff.data(), size, msg, args_cp); va_end(args_cp); // handle empty expansion if (ret == 0) return std::string{}; if (static_cast<std::size_t>(ret) < size) return std::string(local_buff.data()); // we did not provide a long enough buffer on our first attempt. // add 1 to size to account for null-byte in size cast to prevent overflow size = static_cast<std::size_t>(ret) + 1; auto buff_ptr = std::unique_ptr<char[]>(new char[size]); ret = std::vsnprintf(buff_ptr.get(), size, msg, args); return std::string(buff_ptr.get()); } std::string StringPrintF(const char* format, ...) { va_list args; va_start(args, format); std::string tmp = StringPrintFImp(format, args); va_end(args); return tmp; } void ReplaceAll(std::string* str, const std::string& from, const std::string& to) { std::size_t start = 0; while((start = str->find(from, start)) != std::string::npos) { str->replace(start, from.length(), to); start += to.length(); } } } // end namespace benchmark <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ //mapnik #include <mapnik/symbolizer.hpp> #include <mapnik/map.hpp> namespace mapnik { void symbolizer_base::add_metawriter(std::string const& name, metawriter_properties const& properties) { writer_name_ = name; properties_ = properties; } void symbolizer_base::cache_metawriters(Map const &m) { if (writer_name_.empty()) { properties_complete_.clear(); writer_ptr_ = metawriter_ptr(); return; // No metawriter } writer_ptr_ = m.find_metawriter(writer_name_); if (writer_ptr_) { properties_complete_ = writer_ptr_->get_default_properties(); properties_complete_.insert(properties_.begin(), properties_.end()); } else { properties_complete_.clear(); std::cerr << "WARNING: Metawriter '" << writer_name_ << "' used but not defined.\n"; } } metawriter_with_properties symbolizer_base::get_metawriter() const { return metawriter_with_properties(writer_ptr_, properties_complete_); } symbolizer_with_image::symbolizer_with_image(path_expression_ptr file) : image_filename_( file ), opacity_(1.0f) { matrix_[0] = 1.0; matrix_[1] = 0.0; matrix_[2] = 0.0; matrix_[3] = 1.0; matrix_[4] = 0.0; matrix_[5] = 0.0; } symbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs) : image_filename_(rhs.image_filename_), opacity_(rhs.opacity_), matrix_(rhs.matrix_) {} path_expression_ptr symbolizer_with_image::get_filename() const { return image_filename_; } void symbolizer_with_image::set_filename(path_expression_ptr image_filename) { image_filename_ = image_filename; } void symbolizer_with_image::set_transform(transform_type const& matrix) { matrix_ = matrix; } transform_type const& symbolizer_with_image::get_transform() const { return matrix_; } std::string const& symbolizer_with_image::get_transform_string() const { std::stringstream ss; ss << "matrix(" << matrix_[0] << ", " << matrix_[1] << ", " << matrix_[2] << ", " << matrix_[3] << ", " << matrix_[4] << ", " << matrix_[5] << ")"; return ss.str(); } void symbolizer_with_image::set_opacity(float opacity) { opacity_ = opacity; } float symbolizer_with_image::get_opacity() const { return opacity_; } } // end of namespace mapnik <commit_msg>formatting<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ //mapnik #include <mapnik/symbolizer.hpp> #include <mapnik/map.hpp> namespace mapnik { void symbolizer_base::add_metawriter(std::string const& name, metawriter_properties const& properties) { writer_name_ = name; properties_ = properties; } void symbolizer_base::cache_metawriters(Map const &m) { if (writer_name_.empty()) { properties_complete_.clear(); writer_ptr_ = metawriter_ptr(); return; // No metawriter } writer_ptr_ = m.find_metawriter(writer_name_); if (writer_ptr_) { properties_complete_ = writer_ptr_->get_default_properties(); properties_complete_.insert(properties_.begin(), properties_.end()); } else { properties_complete_.clear(); std::cerr << "WARNING: Metawriter '" << writer_name_ << "' used but not defined.\n"; } } metawriter_with_properties symbolizer_base::get_metawriter() const { return metawriter_with_properties(writer_ptr_, properties_complete_); } symbolizer_with_image::symbolizer_with_image(path_expression_ptr file) : image_filename_( file ), opacity_(1.0f) { matrix_[0] = 1.0; matrix_[1] = 0.0; matrix_[2] = 0.0; matrix_[3] = 1.0; matrix_[4] = 0.0; matrix_[5] = 0.0; } symbolizer_with_image::symbolizer_with_image( symbolizer_with_image const& rhs) : image_filename_(rhs.image_filename_), opacity_(rhs.opacity_), matrix_(rhs.matrix_) {} path_expression_ptr symbolizer_with_image::get_filename() const { return image_filename_; } void symbolizer_with_image::set_filename(path_expression_ptr image_filename) { image_filename_ = image_filename; } void symbolizer_with_image::set_transform(transform_type const& matrix) { matrix_ = matrix; } transform_type const& symbolizer_with_image::get_transform() const { return matrix_; } std::string const& symbolizer_with_image::get_transform_string() const { std::stringstream ss; ss << "matrix(" << matrix_[0] << ", " << matrix_[1] << ", " << matrix_[2] << ", " << matrix_[3] << ", " << matrix_[4] << ", " << matrix_[5] << ")"; return ss.str(); } void symbolizer_with_image::set_opacity(float opacity) { opacity_ = opacity; } float symbolizer_with_image::get_opacity() const { return opacity_; } } // end of namespace mapnik <|endoftext|>
<commit_before>// //! @file tcp_socket.cpp //! @brief tcp session socket class // // copyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD. // mail: // // Distributed under the Boost Software License, Version 1.0.(See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt // #include <boost/thread/thread.hpp> #include "tcp_socket.h" #include "logger.h" namespace l7vs{ //! construcor tcp_socket::tcp_socket(boost::asio::io_service& io): my_socket(io), open_flag(false){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::tcp_socket", __FILE__, __LINE__ ); } //! destructor tcp_socket::~tcp_socket(){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::~tcp_socket", __FILE__, __LINE__ ); } //! get reference control socket //! @return reference control socket boost::asio::ip::tcp::socket& tcp_socket::get_socket(){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::get_socket", __FILE__, __LINE__ ); return my_socket; } //! connect socket //! @param[in] connect_endpoint is connection endpoint //! @param[out] ec is reference error code object //! @return true is connect //! @return false is connect failure bool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::connect", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); if(!open_flag){ my_socket.connect(connect_endpoint,ec); if(!ec){ open_flag = true; //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::connect ["; buf << connect_endpoint; buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } //----Debug log---------------------------------------------------------------------- }else{ open_flag = false; } } return open_flag; } //! accept socket void tcp_socket::accept(){ boost::mutex::scoped_lock scope_lock(socket_mutex); open_flag = true; //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ boost::system::error_code ec; std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::accept ["; buf << my_socket.remote_endpoint(ec); buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } //----Debug log---------------------------------------------------------------------- } //! close socket //! @param[out] ec is reference error code object //! @return true is socket close //! @return false is not open socket bool tcp_socket::close(boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::close", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ if(open_flag){ boost::system::error_code ec; std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::close ["; buf << my_socket.remote_endpoint(ec); buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } } //----Debug log---------------------------------------------------------------------- bool bres = false; if(open_flag){ open_flag = false; bres = true; } my_socket.close(ec); return bres; } //! set non blocking mode of the socket //! @return ec is reference error code object bool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::set_non_blocking_mode", __FILE__, __LINE__ ); boost::asio::socket_base::non_blocking_io cmd(true); my_socket.io_control(cmd,ec); return true; } //! write socket //! @param[in] buffers is wite data buffer //! @param[out] ec is reference error code object //! @return write data size std::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::write_some", __FILE__, __LINE__ ); std::size_t res_size = 0; res_size = my_socket.write_some(buffers,ec); if(ec){ if (!open_flag) { res_size = 0; ec.clear(); } } return res_size; } //! read socket //! @param[out] buffers is read data buffer //! @param[out] ec is reference error code object //! @return read data size std::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::read_some", __FILE__, __LINE__ ); std::size_t res_size = 0; res_size = my_socket.read_some(buffers,ec); if(ec){ if (!open_flag) { res_size = 0; ec.clear(); } } return res_size; } //! is open //! @return true is open //! @return false is close bool tcp_socket::is_open(){ return open_flag; } }// namespace l7vs <commit_msg>#325<commit_after>// //! @file tcp_socket.cpp //! @brief tcp session socket class // // copyright (c) 2008 TOKYO COMPUTER SERVICE CO.,LTD. // mail: // // Distributed under the Boost Software License, Version 1.0.(See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt // #include <boost/thread/thread.hpp> #include "tcp_socket.h" #include "logger.h" namespace l7vs{ //! construcor tcp_socket::tcp_socket(boost::asio::io_service& io): my_socket(io), open_flag(false){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::tcp_socket", __FILE__, __LINE__ ); } //! destructor tcp_socket::~tcp_socket(){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::~tcp_socket", __FILE__, __LINE__ ); } //! get reference control socket //! @return reference control socket boost::asio::ip::tcp::socket& tcp_socket::get_socket(){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::get_socket", __FILE__, __LINE__ ); return my_socket; } //! connect socket //! @param[in] connect_endpoint is connection endpoint //! @param[out] ec is reference error code object //! @return true is connect //! @return false is connect failure bool tcp_socket::connect(boost::asio::ip::tcp::endpoint connect_endpoint, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::connect", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); if(!open_flag){ my_socket.connect(connect_endpoint,ec); if(!ec){ open_flag = true; //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::connect ["; buf << connect_endpoint; buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } //----Debug log---------------------------------------------------------------------- }else{ open_flag = false; } } return open_flag; } //! accept socket void tcp_socket::accept(){ boost::mutex::scoped_lock scope_lock(socket_mutex); open_flag = true; //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ boost::system::error_code ec; std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::accept ["; buf << my_socket.remote_endpoint(ec); buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } //----Debug log---------------------------------------------------------------------- } //! close socket //! @param[out] ec is reference error code object //! @return true is socket close //! @return false is not open socket bool tcp_socket::close(boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::close", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); //----Debug log---------------------------------------------------------------------- if (LOG_LV_DEBUG == Logger::getLogLevel(LOG_CAT_L7VSD_SESSION)){ if(open_flag){ boost::system::error_code ec; std::stringstream buf; buf << "Thread ID["; buf << boost::this_thread::get_id(); buf << "] tcp_socket::close ["; buf << my_socket.remote_endpoint(ec); buf << "]"; Logger::putLogDebug( LOG_CAT_L7VSD_SESSION, 9999, buf.str(), __FILE__, __LINE__ ); } } //----Debug log---------------------------------------------------------------------- bool bres = false; if(open_flag){ open_flag = false; bres = true; } my_socket.close(ec); return bres; } //! set non blocking mode of the socket //! @return ec is reference error code object bool tcp_socket::set_non_blocking_mode(boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::set_non_blocking_mode", __FILE__, __LINE__ ); boost::asio::socket_base::non_blocking_io cmd(true); my_socket.io_control(cmd,ec); return true; } //! write socket //! @param[in] buffers is wite data buffer //! @param[out] ec is reference error code object //! @return write data size std::size_t tcp_socket::write_some(boost::asio::mutable_buffers_1 buffers, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::write_some", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); std::size_t res_size = 0; res_size = my_socket.write_some(buffers,ec); if(ec){ if (!open_flag) { res_size = 0; ec.clear(); } } return res_size; } //! read socket //! @param[out] buffers is read data buffer //! @param[out] ec is reference error code object //! @return read data size std::size_t tcp_socket::read_some(boost::asio::mutable_buffers_1 buffers, boost::system::error_code& ec){ Logger logger( LOG_CAT_L7VSD_SESSION, 9999, "tcp_socket::read_some", __FILE__, __LINE__ ); boost::mutex::scoped_lock scope_lock(socket_mutex); std::size_t res_size = 0; res_size = my_socket.read_some(buffers,ec); if(ec){ if (!open_flag) { res_size = 0; ec.clear(); } } return res_size; } //! is open //! @return true is open //! @return false is close bool tcp_socket::is_open(){ return open_flag; } }// namespace l7vs <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("Catch is working", "[catch]") { REQUIRE ( (2 * 2) == 4); REQUIRE ( (10 * 10) > 50); }<commit_msg>Some tests<commit_after>#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "../language_data.h" #include "../message.h" #include "../key.h" #include "../solver.h" TEST_CASE("Catch is working") { REQUIRE ( (2 * 2) == 4); REQUIRE ( (10 * 10) > 50); } TEST_CASE("Language data gets initialized") { LanguageData::Initialize(); REQUIRE(LanguageData::GetTri(0) == 10); REQUIRE(LanguageData::GetTri(17574) == 27); } TEST_CASE("Z408 gets solved") { std::ifstream t("z408.txt"); std::stringstream buffer; buffer << t.rdbuf(); std::string str = buffer.str(); str.erase(std::remove(str.begin(), str.end(), '\n'), str.end()); LanguageData::Initialize(); Message msg(str); Key key; key.Init(msg); Solver solver(msg, key); solver.SetScoreLimit(38000); solver.SetTimeLimit(12); int result = solver.Start(); REQUIRE(result > 35000); }<|endoftext|>
<commit_before>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2002. // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // See http://www.boost.org for updates, documentation, and revision history. // // File : $RCSfile$ // // Version : $Id$ // // Description : supplies offline implemtation for the Test Tools // *************************************************************************** // Boost.Test #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_result.hpp> // BOOST #include <boost/config.hpp> // STL #include <fstream> #include <iostream> #include <algorithm> #include <cstring> #include <string> # ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::strcmp; using ::strncmp; using ::strlen; } # endif namespace boost { namespace test_toolbox { namespace detail { // ************************************************************************** // // ************** TOOL BOX Implementation ************** // // ************************************************************************** // void checkpoint_impl( wrap_stringstream& message, c_string_literal file_name, int line_num ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites ) unit_test_framework::checkpoint( message.str() ) BOOST_UT_LOG_END } //____________________________________________________________________________// void message_impl( wrap_stringstream& message, c_string_literal file_name, int line_num ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages ) message.str() BOOST_UT_LOG_END } //____________________________________________________________________________// void warn_and_continue_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass ) { if( !predicate ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings ) (add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" ) BOOST_UT_LOG_END } else { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests ) "condition " << message.str() << " is satisfied" BOOST_UT_LOG_END } } //____________________________________________________________________________// void warn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass ) { warn_and_continue_impl( !!v, message << (add_fail_pass && !v ? " is not satisfied. " : "" ) << *(v.p_message), file_name, line_num, false ); } //____________________________________________________________________________// bool test_and_continue_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( !predicate ) { unit_test_framework::unit_test_result::instance().inc_failed_assertions(); BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel ) (add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "") BOOST_UT_LOG_END return true; } else { unit_test_framework::unit_test_result::instance().inc_passed_assertions(); BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests ) (add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "") BOOST_UT_LOG_END return false; } } //____________________________________________________________________________// bool test_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { return test_and_continue_impl( !!v, message << (add_fail_pass ? (!v ? " failed. " : " passed. ") : "") << *(v.p_message), file_name, line_num, false, loglevel ); } //____________________________________________________________________________// void test_and_throw_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) { throw test_tool_failed(); // error already reported by test_and_continue_impl } } //____________________________________________________________________________// void test_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, int line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) { throw test_tool_failed(); // error already reported by test_and_continue_impl } } //____________________________________________________________________________// bool equal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message, c_string_literal file_name, int line_num, unit_test_framework::log_level loglevel ) { bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right); left = left ? left : "null string"; right = right ? right : "null string"; if( !predicate ) { return test_and_continue_impl( false, wrap_stringstream().ref() << "test " << message.str() << " failed [" << left << " != " << right << "]", file_name, line_num, false, loglevel ); } return test_and_continue_impl( true, message, file_name, line_num, true, loglevel ); } //____________________________________________________________________________// bool is_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value ) { // return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0; return std::strcmp( symbol_name, symbol_value + 2 ) != 0; } //____________________________________________________________________________// } // namespace detail // ************************************************************************** // // ************** output_test_stream ************** // // ************************************************************************** // struct output_test_stream::Impl { std::fstream m_pattern_to_match_or_save; bool m_match_or_save; std::string m_synced_string; void check_and_fill( detail::extended_predicate_value& res ) { if( !res.p_predicate_value.get() ) *(res.p_message) << "Output content: \"" << m_synced_string << '\"'; } }; //____________________________________________________________________________// output_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save ) : m_pimpl( new Impl ) { if( !pattern_file_name.empty() ) m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out ); m_pimpl->m_match_or_save = match_or_save; } //____________________________________________________________________________// output_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save ) : m_pimpl( new Impl ) { if( pattern_file_name && pattern_file_name[0] != '\0' ) m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out ); m_pimpl->m_match_or_save = match_or_save; } //____________________________________________________________________________// output_test_stream::~output_test_stream() { } //____________________________________________________________________________// detail::extended_predicate_value output_test_stream::is_empty( bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string.empty() ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// detail::extended_predicate_value output_test_stream::check_length( std::size_t length_, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string.length() == length_ ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// detail::extended_predicate_value output_test_stream::is_equal( c_string_literal arg, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == arg ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// detail::extended_predicate_value output_test_stream::is_equal( std::string const& arg, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == arg ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// detail::extended_predicate_value output_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == std::string( arg, n ) ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// bool output_test_stream::match_pattern( bool flush_stream ) { sync(); bool result = true; if( !m_pimpl->m_pattern_to_match_or_save.is_open() ) result = false; else { if( m_pimpl->m_match_or_save ) { c_string_literal ptr = m_pimpl->m_synced_string.c_str(); for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) { char c; m_pimpl->m_pattern_to_match_or_save.get( c ); if( m_pimpl->m_pattern_to_match_or_save.fail() || m_pimpl->m_pattern_to_match_or_save.eof() ) { result = false; break; } if( *ptr != c ) { result = false; } } } else { m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) ); m_pimpl->m_pattern_to_match_or_save.flush(); } } if( flush_stream ) flush(); return result; } //____________________________________________________________________________// void output_test_stream::flush() { m_pimpl->m_synced_string.erase(); #ifndef BOOST_NO_STRINGSTREAM str( std::string() ); #else seekp( 0, std::ios::beg ); #endif } //____________________________________________________________________________// std::size_t output_test_stream::length() { sync(); return m_pimpl->m_synced_string.length(); } //____________________________________________________________________________// void output_test_stream::sync() { #ifdef BOOST_NO_STRINGSTREAM m_pimpl->m_synced_string.assign( str(), pcount() ); freeze( false ); #else m_pimpl->m_synced_string = str(); #endif } //____________________________________________________________________________// } // namespace test_toolbox } // namespace boost // *************************************************************************** // Revision History : // // $Log$ // Revision 1.15 2003/02/15 21:54:18 rogeeff // is_defined made portable // // Revision 1.14 2003/02/14 06:40:27 rogeeff // mingw fix // // Revision 1.13 2003/02/13 08:15:25 rogeeff // BOOST_BITWIZE_EQUAL introduced // BOOST_CHECK_NO_THROW introduced // C string literals eliminated // report_level -> log_level // other minor fixes // // Revision 1.12 2002/12/08 18:20:30 rogeeff // wrapstratream separated in standalone file and renamed // switched to use c_string_literal // // Revision 1.11 2002/11/02 20:23:24 rogeeff // wrapstream copy constructor isuue fix reworked // // Revision 1.10 2002/11/02 20:04:41 rogeeff // release 1.29.0 merged into the main trank // // *************************************************************************** // EOF <commit_msg>added support for extended users predicate returning also error message<commit_after>// (C) Copyright Ullrich Koethe 2001, Gennadiy Rozental 2001-2003. // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied warranty, // and with no claim as to its suitability for any purpose. // See http://www.boost.org for updates, documentation, and revision history. // // File : $RCSfile$ // // Version : $Revision$ // // Description : supplies offline implemtation for the Test Tools // *************************************************************************** // Boost.Test #include <boost/test/test_tools.hpp> #include <boost/test/unit_test_result.hpp> // BOOST #include <boost/config.hpp> // STL #include <fstream> #include <iostream> #include <algorithm> #include <cstring> #include <string> # ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::strcmp; using ::strncmp; using ::strlen; } # endif namespace boost { namespace test_toolbox { namespace detail { // ************************************************************************** // // ************** TOOL BOX Implementation ************** // // ************************************************************************** // void checkpoint_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_test_suites ) unit_test_framework::checkpoint( message.str() ) BOOST_UT_LOG_END } //____________________________________________________________________________// void message_impl( wrap_stringstream& message, c_string_literal file_name, std::size_t line_num ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_messages ) message.str() BOOST_UT_LOG_END } //____________________________________________________________________________// void warn_and_continue_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass ) { if( !predicate ) { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_warnings ) (add_fail_pass ? "condition " : "") << message.str() << (add_fail_pass ? " is not satisfied" : "" ) BOOST_UT_LOG_END } else { BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests ) "condition " << message.str() << " is satisfied" BOOST_UT_LOG_END } } //____________________________________________________________________________// void warn_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass ) { warn_and_continue_impl( !!v, message << (add_fail_pass && !v ? " is not satisfied. " : "" ) << *(v.p_message), file_name, line_num, false ); } //____________________________________________________________________________// bool test_and_continue_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( !predicate ) { unit_test_framework::unit_test_result::instance().inc_failed_assertions(); BOOST_UT_LOG_BEGIN( file_name, line_num, loglevel ) (add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " failed" : "") BOOST_UT_LOG_END return true; } else { unit_test_framework::unit_test_result::instance().inc_passed_assertions(); BOOST_UT_LOG_BEGIN( file_name, line_num, unit_test_framework::log_successful_tests ) (add_fail_pass ? "test " : "") << message.str() << (add_fail_pass ? " passed" : "") BOOST_UT_LOG_END return false; } } //____________________________________________________________________________// bool test_and_continue_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { return test_and_continue_impl( !!v, message << (add_fail_pass ? (!v ? " failed. " : " passed. ") : "") << *(v.p_message), file_name, line_num, false, loglevel ); } //____________________________________________________________________________// void test_and_throw_impl( bool predicate, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( test_and_continue_impl( predicate, message, file_name, line_num, add_fail_pass, loglevel ) ) { throw test_tool_failed(); // error already reported by test_and_continue_impl } } //____________________________________________________________________________// void test_and_throw_impl( extended_predicate_value const& v, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, bool add_fail_pass, unit_test_framework::log_level loglevel ) { if( test_and_continue_impl( v, message, file_name, line_num, add_fail_pass, loglevel ) ) { throw test_tool_failed(); // error already reported by test_and_continue_impl } } //____________________________________________________________________________// bool equal_and_continue_impl( c_string_literal left, c_string_literal right, wrap_stringstream& message, c_string_literal file_name, std::size_t line_num, unit_test_framework::log_level loglevel ) { bool predicate = (left && right) ? std::strcmp( left, right ) == 0 : (left == right); left = left ? left : "null string"; right = right ? right : "null string"; if( !predicate ) { return test_and_continue_impl( false, wrap_stringstream().ref() << "test " << message.str() << " failed [" << left << " != " << right << "]", file_name, line_num, false, loglevel ); } return test_and_continue_impl( true, message, file_name, line_num, true, loglevel ); } //____________________________________________________________________________// bool is_defined_impl( c_string_literal symbol_name, c_string_literal symbol_value ) { // return std::strncmp( symbol_name, symbol_value, std::strlen( symbol_name ) ) != 0; return std::strcmp( symbol_name, symbol_value + 2 ) != 0; } //____________________________________________________________________________// } // namespace detail // ************************************************************************** // // ************** output_test_stream ************** // // ************************************************************************** // struct output_test_stream::Impl { std::fstream m_pattern_to_match_or_save; bool m_match_or_save; std::string m_synced_string; void check_and_fill( extended_predicate_value& res ) { if( !res.p_predicate_value.get() ) *(res.p_message) << "Output content: \"" << m_synced_string << '\"'; } }; //____________________________________________________________________________// output_test_stream::output_test_stream( std::string const& pattern_file_name, bool match_or_save ) : m_pimpl( new Impl ) { if( !pattern_file_name.empty() ) m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name.c_str(), match_or_save ? std::ios::in : std::ios::out ); m_pimpl->m_match_or_save = match_or_save; } //____________________________________________________________________________// output_test_stream::output_test_stream( c_string_literal pattern_file_name, bool match_or_save ) : m_pimpl( new Impl ) { if( pattern_file_name && pattern_file_name[0] != '\0' ) m_pimpl->m_pattern_to_match_or_save.open( pattern_file_name, match_or_save ? std::ios::in : std::ios::out ); m_pimpl->m_match_or_save = match_or_save; } //____________________________________________________________________________// output_test_stream::~output_test_stream() { } //____________________________________________________________________________// extended_predicate_value output_test_stream::is_empty( bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string.empty() ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// extended_predicate_value output_test_stream::check_length( std::size_t length_, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string.length() == length_ ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// extended_predicate_value output_test_stream::is_equal( c_string_literal arg, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == arg ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// extended_predicate_value output_test_stream::is_equal( std::string const& arg, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == arg ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// extended_predicate_value output_test_stream::is_equal( c_string_literal arg, std::size_t n, bool flush_stream ) { sync(); result_type res( m_pimpl->m_synced_string == std::string( arg, n ) ); m_pimpl->check_and_fill( res ); if( flush_stream ) flush(); return res; } //____________________________________________________________________________// bool output_test_stream::match_pattern( bool flush_stream ) { sync(); bool result = true; if( !m_pimpl->m_pattern_to_match_or_save.is_open() ) result = false; else { if( m_pimpl->m_match_or_save ) { c_string_literal ptr = m_pimpl->m_synced_string.c_str(); for( std::size_t i = 0; i != m_pimpl->m_synced_string.length(); i++, ptr++ ) { char c; m_pimpl->m_pattern_to_match_or_save.get( c ); if( m_pimpl->m_pattern_to_match_or_save.fail() || m_pimpl->m_pattern_to_match_or_save.eof() ) { result = false; break; } if( *ptr != c ) { result = false; } } } else { m_pimpl->m_pattern_to_match_or_save.write( m_pimpl->m_synced_string.c_str(), static_cast<std::streamsize>( m_pimpl->m_synced_string.length() ) ); m_pimpl->m_pattern_to_match_or_save.flush(); } } if( flush_stream ) flush(); return result; } //____________________________________________________________________________// void output_test_stream::flush() { m_pimpl->m_synced_string.erase(); #ifndef BOOST_NO_STRINGSTREAM str( std::string() ); #else seekp( 0, std::ios::beg ); #endif } //____________________________________________________________________________// std::size_t output_test_stream::length() { sync(); return m_pimpl->m_synced_string.length(); } //____________________________________________________________________________// void output_test_stream::sync() { #ifdef BOOST_NO_STRINGSTREAM m_pimpl->m_synced_string.assign( str(), pcount() ); freeze( false ); #else m_pimpl->m_synced_string = str(); #endif } //____________________________________________________________________________// } // namespace test_toolbox } // namespace boost // *************************************************************************** // Revision History : // // $Log$ // Revision 1.16 2003/06/09 09:14:35 rogeeff // added support for extended users predicate returning also error message // // *************************************************************************** // EOF <|endoftext|>
<commit_before>#pragma once using namespace std; #include <vector> #include <regex> #include "ICommand.hpp" #include "Line.hpp" #include "Utility.hpp" namespace OCScript { // OCScript̃RANXłB class Core { private: vector<ICommandExecutable*> _Commands; vector<Line> _ScriptStorage; int _CurrentLineIndex; public: // R}hlj܂B // : ICommandExecutableR}h̃NX void AddCommand(ICommandExecutable *command) { _Commands.push_back(command); } // ɎssύX܂B // : s0n܂CfbNX void SetCurrentLineIndex(int lineIndex) { _CurrentLineIndex = lineIndex; } // XNvg ScriptStorage Ɉꊇǂݍ݂܂B // : s؂蕶̃xN^ // O”\̂郁\bhł void LoadScript(const vector<string> scriptLines) { vector<Line> lines; int lineIndex = 1; for (auto scriptLine : scriptLines) { smatch m1, m2; // sł͂Ȃ if (!regex_match(scriptLine, regex("^[ \t]*$"))) { m1 = smatch(); // \Ƀ}b` if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$"))) { string commandName = m1[1]; string paramsStr = m1[2]; vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ','); vector<string> paramsDestVec; int paramIndex = 1; for (auto paramToken : paramsSourceVec) { string content; m1 = smatch(); m2 = smatch(); // NH[gẗł if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$"))) { if (!m1.empty()) content = m1[1]; else if (!m2.empty()) content = m2[1]; else throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str()); } else { m1 = smatch(); if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$"))) throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str()); content = m1[1]; } paramsDestVec.push_back(content); paramIndex++; } lines.push_back(Line(commandName, paramsDestVec)); } else throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str()); } lineIndex++; } _ScriptStorage = vector<Line>(lines); } // XNvg ScriptStorage Ɉꊇǂݍ݂܂B // : XNvg̕ // O”\̂郁\bhł void LoadScript(const string scriptText) { vector<string> scriptLines = Utility::StrSplit(scriptText, '\n'); LoadScript(scriptLines); } // s̑ΏۂƂȂĂXNvgs܂B void ExecuteCurrentLine() { if (_ScriptStorage.empty()) throw("ScriptStorage̒głB"); } }; }<commit_msg>fix typo<commit_after>#pragma once using namespace std; #include <vector> #include <regex> #include "ICommand.hpp" #include "Line.hpp" #include "Utility.hpp" namespace OCScript { // OCScript̃RANXłB class Core { private: vector<ICommandExecutable*> _Commands; vector<Line> _ScriptStorage; int _CurrentLineIndex; public: // R}hlj܂B // : ICommandExecutableR}h̃NX void AddCommand(ICommandExecutable *command) { _Commands.push_back(command); } // ɎssύX܂B // : s0n܂CfbNX void SetCurrentLineIndex(int lineIndex) { _CurrentLineIndex = lineIndex; } // XNvg ScriptStorage Ɉꊇǂݍ݂܂B // : s؂蕶̃xN^ // O”\̂郁\bhł void LoadScript(const vector<string> scriptLines) { vector<Line> lines; int lineIndex = 1; for (auto scriptLine : scriptLines) { smatch m1, m2; // sł͂Ȃ if (!regex_match(scriptLine, regex("^[ \t]*$"))) { m1 = smatch(); // \Ƀ}b` if (regex_match(scriptLine, m1, regex("^[ \t]*([a-zA-Z0-9._-]+)[ \t]*\\((.+)\\)[ \t]*;[ \t]*$"))) { string commandName = m1[1]; string paramsStr = m1[2]; vector<string> paramsSourceVec = Utility::StrSplit(paramsStr, ','); vector<string> paramsDestVec; int paramIndex = 1; for (auto paramToken : paramsSourceVec) { string content; m1 = smatch(); m2 = smatch(); // NH[gẗł if (regex_match(paramToken, m1, regex("^[ \t]*\"(.*)\"[ \t]*$")) || regex_match(paramToken, m2, regex("^[ \t]*\'(.*)\'[ \t]*$"))) { if (!m1.empty()) content = m1[1]; else if (!m2.empty()) content = m2[1]; else throw exception(("VXeG[܂B}b`ʂĂ܂B(s: " + to_string(lineIndex) + ")").c_str()); } else { m1 = smatch(); if (!regex_match(paramToken, m1, regex("^[ \t]*([^ \t]*)[ \t]*$"))) throw exception(("͎̉ɃG[܂B(s: " + to_string(lineIndex) + ", ԍ: " + to_string(paramIndex) + ")").c_str()); content = m1[1]; } paramsDestVec.push_back(content); paramIndex++; } lines.push_back(Line(commandName, paramsDestVec)); } else throw exception(("\G[܂B(s: " + to_string(lineIndex) + ")").c_str()); } lineIndex++; } _ScriptStorage = vector<Line>(lines); } // XNvg ScriptStorage Ɉꊇǂݍ݂܂B // : XNvg̕ // O”\̂郁\bhł void LoadScript(const string scriptText) { vector<string> scriptLines = Utility::StrSplit(scriptText, '\n'); LoadScript(scriptLines); } // s̑ΏۂƂȂĂXNvgs܂B void ExecuteCurrentLine() { if (_ScriptStorage.empty()) throw("ScriptStorage̒głB"); } }; }<|endoftext|>
<commit_before>/** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <Onsang/config.hpp> #include <Onsang/aux.hpp> #include <Onsang/String.hpp> #include <Onsang/UI/Defs.hpp> #include <Onsang/UI/TabbedView.hpp> #include <duct/debug.hpp> namespace Onsang { namespace UI { // Beard::ui::Widget::Base implementation void TabbedView::cache_geometry_impl() noexcept { m_container->cache_geometry(); if (!get_geometry().is_static()) { auto const& ws = m_container->get_geometry().get_request_size(); auto rs = get_geometry().get_request_size(); rs.width = max_ce(rs.width , ws.width); rs.height = max_ce(rs.height, ws.height); get_geometry().set_request_size(std::move(rs)); } } void TabbedView::reflow_impl( Rect const& area, bool const cache ) noexcept { base::reflow_impl(area, cache); m_container->reflow(area, false); } void TabbedView::render_impl( UI::Widget::RenderData& rd ) noexcept { m_container->render(rd); } signed TabbedView::num_children_impl() const noexcept { return 1; } UI::Widget::SPtr TabbedView::get_child_impl( signed const index ) { DUCT_ASSERTE(0 == index); return m_container; } // UI::View implementation unsigned TabbedView::sub_view_index() noexcept { return m_container->m_position; } UI::View::SPtr TabbedView::sub_view() noexcept { return m_container->empty() ? UI::View::SPtr{} : std::dynamic_pointer_cast<UI::View>( m_container->m_tabs[m_container->m_position].widget ) ; } void TabbedView::set_sub_view_impl( unsigned const index ) noexcept { m_container->set_current_tab(index); } unsigned TabbedView::num_sub_views() noexcept { return m_container->m_tabs.size(); } void TabbedView::close_sub_view( unsigned index ) noexcept { if (index < m_container->m_tabs.size()) { m_container->remove(index); } } void TabbedView::sub_view_title_changed( unsigned index ) noexcept { if (index < m_container->m_tabs.size()) { auto const& tab = m_container->m_tabs[index]; auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget); if (view) { m_container->set_title(index, view->view_title()); } } } void TabbedView::notify_command( UI::View* const /*parent_view*/, Hord::Cmd::UnitBase const& command, Hord::Cmd::type_info const& type_info ) noexcept { auto const& tabs = m_container->m_tabs; for (unsigned index = 0; index < tabs.size(); ++index) { auto& tab = tabs[index]; auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget); if (!view) { continue; } view->notify_command(this, command, type_info); } } } // namespace UI } // namespace Onsang <commit_msg>UI/TabbedView: set CSL description to self when last sub-view is closed.<commit_after>/** @copyright MIT license; see @ref index or the accompanying LICENSE file. */ #include <Onsang/config.hpp> #include <Onsang/aux.hpp> #include <Onsang/String.hpp> #include <Onsang/UI/Defs.hpp> #include <Onsang/UI/TabbedView.hpp> #include <Onsang/App.hpp> #include <duct/debug.hpp> namespace Onsang { namespace UI { // Beard::ui::Widget::Base implementation void TabbedView::cache_geometry_impl() noexcept { m_container->cache_geometry(); if (!get_geometry().is_static()) { auto const& ws = m_container->get_geometry().get_request_size(); auto rs = get_geometry().get_request_size(); rs.width = max_ce(rs.width , ws.width); rs.height = max_ce(rs.height, ws.height); get_geometry().set_request_size(std::move(rs)); } } void TabbedView::reflow_impl( Rect const& area, bool const cache ) noexcept { base::reflow_impl(area, cache); m_container->reflow(area, false); } void TabbedView::render_impl( UI::Widget::RenderData& rd ) noexcept { m_container->render(rd); } signed TabbedView::num_children_impl() const noexcept { return 1; } UI::Widget::SPtr TabbedView::get_child_impl( signed const index ) { DUCT_ASSERTE(0 == index); return m_container; } // UI::View implementation unsigned TabbedView::sub_view_index() noexcept { return m_container->m_position; } UI::View::SPtr TabbedView::sub_view() noexcept { return m_container->empty() ? UI::View::SPtr{} : std::dynamic_pointer_cast<UI::View>( m_container->m_tabs[m_container->m_position].widget ) ; } void TabbedView::set_sub_view_impl( unsigned const index ) noexcept { m_container->set_current_tab(index); } unsigned TabbedView::num_sub_views() noexcept { return m_container->m_tabs.size(); } void TabbedView::close_sub_view( unsigned index ) noexcept { if (index < m_container->m_tabs.size()) { m_container->remove(index); if (m_container->m_tabs.empty()) { App::instance.m_ui.csline->clear_location(); App::instance.m_ui.csline->set_description(view_description()); } } } void TabbedView::sub_view_title_changed( unsigned index ) noexcept { if (index < m_container->m_tabs.size()) { auto const& tab = m_container->m_tabs[index]; auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget); if (view) { m_container->set_title(index, view->view_title()); } } } void TabbedView::notify_command( UI::View* const /*parent_view*/, Hord::Cmd::UnitBase const& command, Hord::Cmd::type_info const& type_info ) noexcept { auto const& tabs = m_container->m_tabs; for (unsigned index = 0; index < tabs.size(); ++index) { auto& tab = tabs[index]; auto const view = std::dynamic_pointer_cast<UI::View>(tab.widget); if (!view) { continue; } view->notify_command(this, command, type_info); } } } // namespace UI } // namespace Onsang <|endoftext|>
<commit_before>// Copyright (C) 2016 DNAnexus, Inc. // // This file is part of dx-toolkit (DNAnexus platform client libraries). // // 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. // This function should be called before opt.setApiserverDxConfig() is called, // since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args #include <string> #include "ua_test.h" #include "dxcpp/dxcpp.h" #include "api_helper.h" #include "options.h" #include "api.h" #include "round_robin_dns.h" #if WINDOWS_BUILD #include <windows.h> #else #include <sys/utsname.h> #endif using namespace std; using namespace dx; using namespace dx::config; void runTests() { version(); printEnvironmentInfo(false); testWhoAmI(); currentProject(); proxySettings(); osInfo(); certificateFile(); resolveAmazonS3(); contactGoogle(); } void version() { cout << "Upload Agent Version: " << UAVERSION; #if OLD_KERNEL_SUPPORT cout << " (old-kernel-support)"; #endif cout << endl << " git version: " << DXTOOLKIT_GITVERSION << endl << " libboost version: " << (BOOST_VERSION / 100000) << "." << ((BOOST_VERSION / 100) % 1000) << "." << (BOOST_VERSION % 100) << endl << " libcurl version: " << LIBCURL_VERSION_MAJOR << "." << LIBCURL_VERSION_MINOR << "." << LIBCURL_VERSION_PATCH << endl; } void osInfo(){ #if WINDOWS_BUILD OSVERSIONINFO vi; vi.dwOSVersionInfoSize = sizeof(vi); try { GetVersionEx(&vi); cout << "Operating System:" << endl << " Windows: " << vi.dwMajorVersion << "." << vi.dwMinorVersion << "." << vi.dwBuildNumber << "." << vi.dwPlatformId << " " << vi.szCSDVersion << endl; } catch(exception &e){ cout << "Unable to get OS information" << e.what() << endl; } #else struct utsname uts; uname(&uts); cout << "Operating System:" << endl << " Name: " << uts.sysname << endl << " Release: " << uts.release << endl << " Version: " << uts.version << endl << " Machine: " << uts.machine << endl; #endif } void printEnvironmentInfo(bool printToken) { cout << "Upload Agent v" << UAVERSION << ", environment info:" << endl << " API server protocol: " << APISERVER_PROTOCOL() << endl << " API server host: " << APISERVER_HOST() << endl << " API server port: " << APISERVER_PORT() << endl; if (printToken) { if (SECURITY_CONTEXT().size() != 0) cout << " Auth token: " << SECURITY_CONTEXT()["auth_token"].get<string>() << endl; else cout << " Auth token: " << endl; } } void currentProject() { string projID = CURRENT_PROJECT(); try { if (projID.empty()) { cout << " Current Project: None" << endl; } else { string projName = getProjectName(projID); cout << " Current Project: " << projName << " (" << projID << ")" << endl; } } catch (DXAPIError &e) { cout << " Current Project: "<< " (" << projID << ")" << e.what() << endl; } } bool getProxyValue(const char * name, string &value) { if (getenv(name) == NULL) return false; value = string(getenv(name)); // Remove credentials from string std::size_t atSimbol = value.find_first_of("@"); if (atSimbol != string::npos ) { if (value.substr(0, 7) == "http://") { value.replace(7, atSimbol-7, "****"); } else if (value.substr(0, 8) == "https://") { value.replace(8, atSimbol-8, "****"); } else { value.replace(0, atSimbol, "****"); } cout << " To see actual username and password run: echo $" << name << endl; cout << " Note that special characters in username / password might prevent credentials from being resolved properly." << endl; } return true; } void proxySettings() { string value; cout << "Proxy Settings:" << endl; bool proxySet = false; if (getProxyValue("http_proxy", value)) { cout << " http_proxy: " << value << endl; proxySet = true;} if (getProxyValue("https_proxy", value)) { cout << " https_proxy: " << value << endl;proxySet = true;} if (getProxyValue("HTTP_PROXY", value)) { cout << " HTTP_PROXY: " << value << endl;proxySet = true;} if (getProxyValue("HTTPS_PROXY", value)) { cout << " HTTP_PROXY: " << value << endl;proxySet = true;} if (!proxySet) { cout << " No proxy set in environment." << endl; } } void certificateFile() { cout << "CA Certificate: " << CA_CERT() << endl; } void testWhoAmI(){ cout << " Current User: "; try { JSON res = systemWhoami(string("{}"), false); cout << res["id"].get<string>() << endl; } catch(DXAPIError &e) { cout << "Error contacting the api: " << e.what() << endl; } catch (DXConnectionError &e) { cout << "Error contacting the api: " << e.what() << endl; } catch (...) { cout << "Error contacting the api." << endl; } } void contactGoogle() { cout << "Testing connection:" << endl; try { string url = "http://www.google.com/"; HttpRequest req = HttpRequest::request(dx::HTTP_GET, url); if (req.responseCode == 200) { cout << " Sucessfully contacted google.com over http: (" << req.responseCode << ")" << endl; } else { cout << " Unable to contact google.com over http: (" << req.responseCode << ")" << endl; } } catch (HttpRequestException &e) { cout << "Error contacting google over http: " << e.what(); } catch (...) { cout << "Error contacting the api." << endl; } try { string url = "https://www.google.com/"; HttpRequest req = HttpRequest::request(dx::HTTP_GET, url); if (req.responseCode == 200) { cout << " Sucessfully contacted google.com over https: (" << req.responseCode << ")" << endl; } else { cout << " Unable to contact google.com over https: (" << req.responseCode << ")" << endl; } } catch (HttpRequestException &e) { cout << "Error contacting google over https: " << e.what() << endl; } catch (...) { cout << "Error contacting google" << endl; } } void resolveAmazonS3(){ cout << "Resolving Amazon S3:" << endl; string awsIP = getRandomIP("s3.amazonaws.com"); if (awsIP.empty()){ cout << " Unable to resolve Amazon S3" << endl; } else { cout << " Resolved to " << awsIP << endl; } } <commit_msg>Fix typo in log output<commit_after>// Copyright (C) 2016 DNAnexus, Inc. // // This file is part of dx-toolkit (DNAnexus platform client libraries). // // 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. // This function should be called before opt.setApiserverDxConfig() is called, // since opt::setApiserverDxConfig() changes the value of dx::config::*, based on command line args #include <string> #include "ua_test.h" #include "dxcpp/dxcpp.h" #include "api_helper.h" #include "options.h" #include "api.h" #include "round_robin_dns.h" #if WINDOWS_BUILD #include <windows.h> #else #include <sys/utsname.h> #endif using namespace std; using namespace dx; using namespace dx::config; void runTests() { version(); printEnvironmentInfo(false); testWhoAmI(); currentProject(); proxySettings(); osInfo(); certificateFile(); resolveAmazonS3(); contactGoogle(); } void version() { cout << "Upload Agent Version: " << UAVERSION; #if OLD_KERNEL_SUPPORT cout << " (old-kernel-support)"; #endif cout << endl << " git version: " << DXTOOLKIT_GITVERSION << endl << " libboost version: " << (BOOST_VERSION / 100000) << "." << ((BOOST_VERSION / 100) % 1000) << "." << (BOOST_VERSION % 100) << endl << " libcurl version: " << LIBCURL_VERSION_MAJOR << "." << LIBCURL_VERSION_MINOR << "." << LIBCURL_VERSION_PATCH << endl; } void osInfo(){ #if WINDOWS_BUILD OSVERSIONINFO vi; vi.dwOSVersionInfoSize = sizeof(vi); try { GetVersionEx(&vi); cout << "Operating System:" << endl << " Windows: " << vi.dwMajorVersion << "." << vi.dwMinorVersion << "." << vi.dwBuildNumber << "." << vi.dwPlatformId << " " << vi.szCSDVersion << endl; } catch(exception &e){ cout << "Unable to get OS information" << e.what() << endl; } #else struct utsname uts; uname(&uts); cout << "Operating System:" << endl << " Name: " << uts.sysname << endl << " Release: " << uts.release << endl << " Version: " << uts.version << endl << " Machine: " << uts.machine << endl; #endif } void printEnvironmentInfo(bool printToken) { cout << "Upload Agent v" << UAVERSION << ", environment info:" << endl << " API server protocol: " << APISERVER_PROTOCOL() << endl << " API server host: " << APISERVER_HOST() << endl << " API server port: " << APISERVER_PORT() << endl; if (printToken) { if (SECURITY_CONTEXT().size() != 0) cout << " Auth token: " << SECURITY_CONTEXT()["auth_token"].get<string>() << endl; else cout << " Auth token: " << endl; } } void currentProject() { string projID = CURRENT_PROJECT(); try { if (projID.empty()) { cout << " Current Project: None" << endl; } else { string projName = getProjectName(projID); cout << " Current Project: " << projName << " (" << projID << ")" << endl; } } catch (DXAPIError &e) { cout << " Current Project: "<< " (" << projID << ")" << e.what() << endl; } } bool getProxyValue(const char * name, string &value) { if (getenv(name) == NULL) return false; value = string(getenv(name)); // Remove credentials from string std::size_t atSimbol = value.find_first_of("@"); if (atSimbol != string::npos ) { if (value.substr(0, 7) == "http://") { value.replace(7, atSimbol-7, "****"); } else if (value.substr(0, 8) == "https://") { value.replace(8, atSimbol-8, "****"); } else { value.replace(0, atSimbol, "****"); } cout << " To see actual username and password run: echo $" << name << endl; cout << " Note that special characters in username / password might prevent credentials from being resolved properly." << endl; } return true; } void proxySettings() { string value; cout << "Proxy Settings:" << endl; bool proxySet = false; if (getProxyValue("http_proxy", value)) { cout << " http_proxy: " << value << endl; proxySet = true;} if (getProxyValue("https_proxy", value)) { cout << " https_proxy: " << value << endl;proxySet = true;} if (getProxyValue("HTTP_PROXY", value)) { cout << " HTTP_PROXY: " << value << endl;proxySet = true;} if (getProxyValue("HTTPS_PROXY", value)) { cout << " HTTP_PROXY: " << value << endl;proxySet = true;} if (!proxySet) { cout << " No proxy set in environment." << endl; } } void certificateFile() { cout << "CA Certificate: " << CA_CERT() << endl; } void testWhoAmI(){ cout << " Current User: "; try { JSON res = systemWhoami(string("{}"), false); cout << res["id"].get<string>() << endl; } catch(DXAPIError &e) { cout << "Error contacting the api: " << e.what() << endl; } catch (DXConnectionError &e) { cout << "Error contacting the api: " << e.what() << endl; } catch (...) { cout << "Error contacting the api." << endl; } } void contactGoogle() { cout << "Testing connection:" << endl; try { string url = "http://www.google.com/"; HttpRequest req = HttpRequest::request(dx::HTTP_GET, url); if (req.responseCode == 200) { cout << " Successfully contacted google.com over http: (" << req.responseCode << ")" << endl; } else { cout << " Unable to contact google.com over http: (" << req.responseCode << ")" << endl; } } catch (HttpRequestException &e) { cout << "Error contacting google over http: " << e.what(); } catch (...) { cout << "Error contacting the api." << endl; } try { string url = "https://www.google.com/"; HttpRequest req = HttpRequest::request(dx::HTTP_GET, url); if (req.responseCode == 200) { cout << " Successfully contacted google.com over https: (" << req.responseCode << ")" << endl; } else { cout << " Unable to contact google.com over https: (" << req.responseCode << ")" << endl; } } catch (HttpRequestException &e) { cout << "Error contacting google over https: " << e.what() << endl; } catch (...) { cout << "Error contacting google" << endl; } } void resolveAmazonS3(){ cout << "Resolving Amazon S3:" << endl; string awsIP = getRandomIP("s3.amazonaws.com"); if (awsIP.empty()){ cout << " Unable to resolve Amazon S3" << endl; } else { cout << " Resolved to " << awsIP << endl; } } <|endoftext|>
<commit_before>#include <JeeLib.h> volatile uint16_t rf69_crc; volatile uint8_t rf69_buf[72]; // void rf69_set_cs (uint8_t pin) { // } // void rf69_spiInit () { // } uint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) { RF69::frf = band == RF12_433MHZ ? 0x6C4000L : // or 0x6C8000 for 434 MHz? band == RF12_868MHZ ? 0xD90000L : 0xE4C000L; RF69::group = group; RF69::node = id; delay(20); // needed to make RFM69 work properly on power-up RF69::configure_compat(); return id; } uint8_t rf69_config (uint8_t show) { rf69_initialize(31, RF12_868MHZ, 5); return 31; // TODO } uint8_t rf69_recvDone () { rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf); return rf69_crc != ~0; } uint8_t rf69_canSend () { return RF69::canSend(); } // void rf69_sendStart (uint8_t hdr) { // } void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) { RF69::sendStart_compat(hdr, ptr, len); } // void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) { // } void rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) { while (!rf69_canSend()) rf69_recvDone(); rf69_sendStart(hdr, ptr, len); } void rf69_sendWait (uint8_t mode) { // TODO } void rf69_onOff (uint8_t value) { // TODO } void rf69_sleep (char n) { // TODO } // char rf69_lowbat () { // } // void rf69_easyInit (uint8_t secs) { // } // char rf69_easyPoll () { // } // char rf69_easySend (const void* data, uint8_t size) { // } // void rf69_encrypt (const uint8_t*) { // } // uint16_t rf69_control (uint16_t cmd) { // } <commit_msg>fix rf69_config<commit_after>#include <JeeLib.h> #include <avr/eeprom.h> #include <util/crc16.h> volatile uint16_t rf69_crc; volatile uint8_t rf69_buf[72]; // void rf69_set_cs (uint8_t pin) { // } // void rf69_spiInit () { // } uint8_t rf69_initialize (uint8_t id, uint8_t band, uint8_t group) { RF69::frf = band == RF12_433MHZ ? 0x6C4000L : // or 0x6C8000 for 434 MHz? band == RF12_868MHZ ? 0xD90000L : 0xE4C000L; RF69::group = group; RF69::node = id; delay(20); // needed to make RFM69 work properly on power-up RF69::configure_compat(); return id; } // same code as rf12_config, just calling rf69_initialize() instead uint8_t rf69_config (uint8_t show) { uint16_t crc = ~0; for (uint8_t i = 0; i < RF12_EEPROM_SIZE; ++i) crc = _crc16_update(crc, eeprom_read_byte(RF12_EEPROM_ADDR + i)); if (crc != 0) return 0; uint8_t nodeId = 0, group = 0; for (uint8_t i = 0; i < RF12_EEPROM_SIZE - 2; ++i) { uint8_t b = eeprom_read_byte(RF12_EEPROM_ADDR + i); if (i == 0) nodeId = b; else if (i == 1) group = b; else if (b == 0) break; else if (show) Serial.print((char) b); } if (show) Serial.println(); rf69_initialize(nodeId, nodeId >> 6, group); return nodeId & RF12_HDR_MASK; } uint8_t rf69_recvDone () { rf69_crc = RF69::recvDone_compat((uint8_t*) rf69_buf); return rf69_crc != ~0; } uint8_t rf69_canSend () { return RF69::canSend(); } // void rf69_sendStart (uint8_t hdr) { // } void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len) { RF69::sendStart_compat(hdr, ptr, len); } // void rf69_sendStart (uint8_t hdr, const void* ptr, uint8_t len, uint8_t sync) { // } void rf69_sendNow (uint8_t hdr, const void* ptr, uint8_t len) { while (!rf69_canSend()) rf69_recvDone(); rf69_sendStart(hdr, ptr, len); } void rf69_sendWait (uint8_t mode) { // TODO } void rf69_onOff (uint8_t value) { // TODO } void rf69_sleep (char n) { // TODO } // char rf69_lowbat () { // } // void rf69_easyInit (uint8_t secs) { // } // char rf69_easyPoll () { // } // char rf69_easySend (const void* data, uint8_t size) { // } // void rf69_encrypt (const uint8_t*) { // } // uint16_t rf69_control (uint16_t cmd) { // } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Generic Win32 window class. *//*--------------------------------------------------------------------*/ #include "tcuWin32Window.hpp" namespace tcu { static LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { Win32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (window) return window->windowProc(uMsg, wParam, lParam); else return DefWindowProc(hWnd, uMsg, wParam, lParam); } Win32Window::Win32Window (HINSTANCE instance, int width, int height) : m_window (DE_NULL) { try { static const char s_className[] = "dEQP Tester Core Class"; static const char s_windowName[] = "dEQP Tester Core"; { WNDCLASS wndClass; memset(&wndClass, 0, sizeof(wndClass)); wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndClass.lpfnWndProc = win32WindowProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = instance; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = CreateSolidBrush(RGB(0, 0, 0)); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = s_className; RegisterClass(&wndClass); } m_window = CreateWindow(s_className, s_windowName, WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, instance, NULL); if (!m_window) throw ResourceError("Failed to create Win32 window", "", __FILE__, __LINE__); // Store this as userdata SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this); setSize(width, height); } catch (...) { if (m_window) DestroyWindow(m_window); throw; } } Win32Window::~Win32Window (void) { if (m_window) { // Clear this pointer from windowproc SetWindowLongPtr(m_window, GWLP_USERDATA, 0); } DestroyWindow(m_window); } void Win32Window::setVisible (bool visible) { ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE); } void Win32Window::setSize (int width, int height) { RECT rc; rc.left = 0; rc.top = 0; rc.right = width; rc.bottom = height; if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL)) throw tcu::TestError("AdjustWindowRect() failed", DE_NULL, __FILE__, __LINE__); if (!SetWindowPos(m_window, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER)) throw tcu::TestError("SetWindowPos() failed", DE_NULL, __FILE__, __LINE__); } IVec2 Win32Window::getSize (void) const { RECT rc; if (!GetClientRect(m_window, &rc)) throw tcu::TestError("GetClientRect() failed", DE_NULL, __FILE__, __LINE__); return IVec2(rc.right - rc.left, rc.bottom - rc.top); } void Win32Window::processEvents (void) { MSG msg; while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE)) DispatchMessage(&msg); } LRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { // \todo [2014-03-12 pyry] Handle WM_SIZE? case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: if (wParam == VK_ESCAPE) { PostQuitMessage(0); return 0; } // fall-through default: return DefWindowProc(m_window, uMsg, wParam, lParam); } } } // tcu <commit_msg>Win32Window cleanup<commit_after>/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Generic Win32 window class. *//*--------------------------------------------------------------------*/ #include "tcuWin32Window.hpp" namespace tcu { static LRESULT CALLBACK win32WindowProc (HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { Win32Window* window = reinterpret_cast<Win32Window*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); if (window) return window->windowProc(uMsg, wParam, lParam); else return DefWindowProc(hWnd, uMsg, wParam, lParam); } Win32Window::Win32Window (HINSTANCE instance, int width, int height) : m_window (DE_NULL) { try { static const char s_className[] = "dEQP Test Process Class"; static const char s_windowName[] = "dEQP Test Process"; { WNDCLASS wndClass; memset(&wndClass, 0, sizeof(wndClass)); wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndClass.lpfnWndProc = win32WindowProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = instance; wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = CreateSolidBrush(RGB(0, 0, 0)); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = s_className; RegisterClass(&wndClass); } m_window = CreateWindow(s_className, s_windowName, WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, width, height, NULL, NULL, instance, NULL); if (!m_window) TCU_THROW(ResourceError, "Failed to create Win32 window"); // Store this as userdata SetWindowLongPtr(m_window, GWLP_USERDATA, (LONG_PTR)this); setSize(width, height); } catch (...) { if (m_window) DestroyWindow(m_window); throw; } } Win32Window::~Win32Window (void) { if (m_window) { // Clear this pointer from windowproc SetWindowLongPtr(m_window, GWLP_USERDATA, 0); } DestroyWindow(m_window); } void Win32Window::setVisible (bool visible) { ShowWindow(m_window, visible ? SW_SHOW : SW_HIDE); } void Win32Window::setSize (int width, int height) { RECT rc; rc.left = 0; rc.top = 0; rc.right = width; rc.bottom = height; if (!AdjustWindowRect(&rc, GetWindowLong(m_window, GWL_STYLE), GetMenu(m_window) != NULL)) TCU_THROW(TestError, "AdjustWindowRect() failed"); if (!SetWindowPos(m_window, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOZORDER)) TCU_THROW(TestError, "SetWindowPos() failed"); } IVec2 Win32Window::getSize (void) const { RECT rc; if (!GetClientRect(m_window, &rc)) TCU_THROW(TestError, "GetClientRect() failed"); return IVec2(rc.right - rc.left, rc.bottom - rc.top); } void Win32Window::processEvents (void) { MSG msg; while (PeekMessage(&msg, m_window, 0, 0, PM_REMOVE)) DispatchMessage(&msg); } LRESULT Win32Window::windowProc (UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { // \todo [2014-03-12 pyry] Handle WM_SIZE? case WM_DESTROY: PostQuitMessage(0); return 0; case WM_KEYDOWN: if (wParam == VK_ESCAPE) { PostQuitMessage(0); return 0; } // fall-through default: return DefWindowProc(m_window, uMsg, wParam, lParam); } } } // tcu <|endoftext|>
<commit_before>#include "Overlay.h" #include "ui_Overlay.h" #include "../Hearthstone.h" #include "../Settings.h" #ifdef Q_OS_MAC #include <objc/objc-runtime.h> #endif #include <cassert> #include <QJsonArray> #include <QJsonObject> #include <QJsonDocument> #include <QFile> #include <QMouseEvent> #define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100 class OverlayHistoryWindow { private: QString mTitle; OverlayHistoryList mHistory; QFont mRowFont; QFont mTitleFont; int mWidth; int mPadding; int mRowSpacing; int TitleHeight() const { QFontMetrics titleMetrics( mTitleFont ); return titleMetrics.ascent() - titleMetrics.descent(); } int Padding() const { return mPadding; } int RowSpacing() const { return mRowSpacing; } int RowHeight() const { QFontMetrics rowMetrics( mRowFont ); return rowMetrics.ascent() - rowMetrics.descent(); } int RowWidth() const { return Width() - Padding() * 2; } void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const { // Draw mana QPen origPen = painter.pen(); QPen pen( QColor( 0, 52, 113 ) ); pen.setCosmetic( true ); pen.setWidth( 1 ); painter.setPen( pen ); QBrush brush( QColor( 40, 119, 238 ) ); painter.setBrush( brush ); QTransform transform; painter.translate( x + width * 0.5, y + height * 0.5 ); painter.scale( width * 0.8, height * 0.8 ); static const QPointF points[5] = { QPointF( 0.0, -1.0 ), QPointF( 1.0, -0.2 ), QPointF( 0.6, 1.0 ), QPointF( -0.6, 1.0 ), QPointF( -1.0, -0.2 ), }; painter.drawConvexPolygon( points, 5 ); painter.resetTransform(); painter.setPen( origPen ); painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) ); } void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const { painter.save(); painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, name ); if( count > 1 ) { int nameWidth = QFontMetrics( painter.font() ).width( name + " " ); QString countString = QString( "x%1" ).arg( count ); QFont font = painter.font(); font.setBold( true ); painter.setFont( font ); painter.drawText( x + nameWidth, y, width - nameWidth, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, countString ); } painter.restore(); } public: OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize ) : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing ) { mRowFont.setPointSize( titleFontSize ); mTitleFont.setPointSize( rowFontSize ); mTitleFont.setUnderline( true ); mTitleFont.setBold( true ); } int Width() const { return mWidth; } int Height() const { return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items mHistory.count() * RowHeight() + // Height per item TitleHeight() + RowSpacing() + // Title Padding() * 2; // Overall padding } void Paint( QPainter& painter, int x, int y ) const { painter.save(); QRect rect( x, y, Width(), Height() ); painter.setClipRect( rect ); // BG QPen pen = QPen( QColor( 160, 160, 160 ) ); pen.setWidth( 3 ); painter.setPen( pen ); painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) ); painter.drawRoundedRect( rect, 10, 10 ); // Title y += Padding(); painter.setPen( QPen( Qt::white) ); painter.setFont( mTitleFont ); painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle ); y += TitleHeight() + RowSpacing(); // Lines painter.setPen( QPen( Qt::white) ); painter.setFont( mRowFont ); for( const QVariantMap& it : mHistory ) { int mx = x + Padding(); DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() ); int cx = mx + RowHeight() + 5; DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() ); y += RowHeight(); y += RowSpacing(); } painter.restore(); } }; Overlay::Overlay( QWidget *parent ) : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN ) { mUI->setupUi( this ); setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput ); #ifdef Q_OS_WIN setWindowFlags( windowFlags() | Qt::Tool ); #else setWindowFlags( windowFlags() | Qt::Window ); #endif setAttribute( Qt::WA_TranslucentBackground ); setAttribute( Qt::WA_ShowWithoutActivating ); connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged ); connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted ); connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped ); connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged ); connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover ); connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged ); hide(); #ifdef Q_OS_MAC WId windowObject = this->winId(); objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject); objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") ); int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0; objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces ); // Ignore mouse events on Mac // Qt::WindowTransparentForInput bug // https://bugreports.qt.io/browse/QTBUG-45498 objc_msgSend( nsWindowObject, sel_registerName("setIgnoresMouseEvents:"), 1 ); #endif } Overlay::~Overlay() { delete mUI; } void Overlay::CheckForHover() { QPoint mouseLoc = mapFromGlobal( QCursor::pos() ); Player showPlayerHistory = PLAYER_UNKNOWN; if( mPlayerDeckRect.contains( mouseLoc ) ) { showPlayerHistory = PLAYER_SELF; } else if( mOpponentDeckRect.contains( mouseLoc ) ) { showPlayerHistory = PLAYER_OPPONENT; } if( mShowPlayerHistory != showPlayerHistory ) { mShowPlayerHistory = showPlayerHistory; update(); } } void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) { int padding = 10; QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() ); rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window wnd.Paint( painter, rect.x(), rect.y() ); } void Overlay::paintEvent( QPaintEvent* ) { QString title; QRect rect; OverlayHistoryList *history = NULL; if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) { title = "Cards drawn"; history = &mPlayerHistory; rect = mPlayerDeckRect; } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) { title = "Cards played by opponent"; history = &mOpponentHistory; rect = mOpponentDeckRect; } QPainter painter( this ); painter.setRenderHint( QPainter::Antialiasing ); #ifdef Q_OS_WIN float rowFontSize = 9; float titleFontSize = 9; #else float rowFontSize = 12; float titleFontSize = 12; #endif int spacing = 8; int overlayWidth = 200; if( history ) { OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize ); QPoint pos = rect.center() + QPoint( rect.width() / 2 + 10, -wnd.Height() / 2 ); PaintHistoryInScreen( painter, wnd, pos ); } } void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) { // Order is important // Otherwise starting fullscreen on windows // will not show the overlay unless the FS mode is toggled setFixedSize( w, h ); move( x, y ); int minWidth = h * 4 / 3; mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 ); mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h ); Update(); } void Overlay::Update() { bool showable = false; if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) { showable = true; if( !mCardDB.Loaded() ) { mCardDB.Load(); } } else { if( mCardDB.Loaded() ) { mCardDB.Unload(); } } if( showable && Hearthstone::Instance()->HasFocus() ) { hide(); // Minimize/Restore on Windows requires a hide() first show(); #ifdef Q_OS_WIN setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466) #endif } else { hide(); } update(); } void Overlay::HandleGameStarted() { mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS ); Update(); } void Overlay::HandleGameStopped() { mCheckForHoverTimer.stop(); Update(); } void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) { QMap< QString, QVariantMap > entries; for( const CardHistoryItem& it : list ) { const QString& cardId = it.cardId; if( cardId.isEmpty() ) { continue; } if( !mCardDB.Contains( cardId ) ) { DBG( "Card %s not found", qt2cstr( cardId ) ); continue; } if( mCardDB.Type( cardId ) == "HERO_POWER" ) { continue; } if( it.player != player ) { continue; } QVariantMap& entry = entries[ cardId ]; entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1; entry[ "mana" ] = mCardDB.Cost( cardId ); entry[ "name" ] = mCardDB.Name( cardId ); } OverlayHistoryList* ref; if( player == PLAYER_SELF ) { ref = &mPlayerHistory; } else { ref = &mOpponentHistory; } *ref = entries.values(); qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) { if( a["mana"].toInt() == b["mana"].toInt() ) { return a["name"].toString() < b["name"].toString(); } else { return a["mana"].toInt() < b["mana"].toInt(); } }); } void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) { UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn ); UpdateHistoryFor( PLAYER_SELF, cardsDrawn ); Update(); } void Overlay::HandleOverlaySettingChanged( bool enabled ) { UNUSED_ARG( enabled ); Update(); } void Overlay::HandleGameFocusChanged( bool focus ) { DBG( "HandleFocusChanged %d", focus ); Update(); } <commit_msg>Adapting overlay text for small displays. 2x is now printed in front of the card text.<commit_after>#include "Overlay.h" #include "ui_Overlay.h" #include "../Hearthstone.h" #include "../Settings.h" #ifdef Q_OS_MAC #include <objc/objc-runtime.h> #endif #include <cassert> #include <QJsonArray> #include <QJsonObject> #include <QJsonDocument> #include <QFile> #include <QMouseEvent> #define CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS 100 class OverlayHistoryWindow { private: QString mTitle; OverlayHistoryList mHistory; QFont mRowFont; QFont mTitleFont; int mWidth; int mPadding; int mRowSpacing; int TitleHeight() const { QFontMetrics titleMetrics( mTitleFont ); return titleMetrics.ascent() - titleMetrics.descent(); } int Padding() const { return mPadding; } int RowSpacing() const { return mRowSpacing; } int RowHeight() const { QFontMetrics rowMetrics( mRowFont ); return rowMetrics.ascent() - rowMetrics.descent(); } int RowWidth() const { return Width() - Padding() * 2; } void DrawMana( QPainter& painter, int x, int y, int width, int height, int mana ) const { // Draw mana QPen origPen = painter.pen(); QPen pen( QColor( 0, 52, 113 ) ); pen.setCosmetic( true ); pen.setWidth( 1 ); painter.setPen( pen ); QBrush brush( QColor( 40, 119, 238 ) ); painter.setBrush( brush ); QTransform transform; painter.translate( x + width * 0.5, y + height * 0.5 ); painter.scale( width * 0.8, height * 0.8 ); static const QPointF points[5] = { QPointF( 0.0, -1.0 ), QPointF( 1.0, -0.2 ), QPointF( 0.6, 1.0 ), QPointF( -0.6, 1.0 ), QPointF( -1.0, -0.2 ), }; painter.drawConvexPolygon( points, 5 ); painter.resetTransform(); painter.setPen( origPen ); painter.drawText( x, y, width, height, Qt::AlignCenter | Qt::AlignVCenter, QString::number( mana ) ); } void DrawCardLine( QPainter& painter, int x, int y, int width, int height, const QString& name, int count ) const { painter.save(); QString text = name; if( count > 1 ) { text.prepend(QString( "%1x " ).arg( count )); QFont font = painter.font(); font.setBold( true ); painter.setFont( font ); } painter.drawText( x, y, width, height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip, text ); painter.restore(); } public: OverlayHistoryWindow( const QString& title, const OverlayHistoryList& history, int width, int padding, int rowSpacing, float titleFontSize, float rowFontSize ) : mTitle( title ), mHistory( history ), mWidth( width ), mPadding( padding ), mRowSpacing( rowSpacing ) { mRowFont.setPointSize( titleFontSize ); mTitleFont.setPointSize( rowFontSize ); mTitleFont.setUnderline( true ); mTitleFont.setBold( true ); } int Width() const { return mWidth; } int Height() const { return ( mHistory.count() - 1 ) * RowSpacing() + // Spacing between items mHistory.count() * RowHeight() + // Height per item TitleHeight() + RowSpacing() + // Title Padding() * 2; // Overall padding } void Paint( QPainter& painter, int x, int y ) const { painter.save(); QRect rect( x, y, Width(), Height() ); painter.setClipRect( rect ); // BG QPen pen = QPen( QColor( 160, 160, 160 ) ); pen.setWidth( 3 ); painter.setPen( pen ); painter.setBrush( QBrush( QColor( 70, 70, 70, 175 ) ) ); painter.drawRoundedRect( rect, 10, 10 ); // Title y += Padding(); painter.setPen( QPen( Qt::white) ); painter.setFont( mTitleFont ); painter.drawText( x, y, Width(), TitleHeight(), Qt::AlignCenter | Qt::AlignVCenter | Qt::TextDontClip, mTitle ); y += TitleHeight() + RowSpacing(); // Lines painter.setPen( QPen( Qt::white) ); painter.setFont( mRowFont ); for( const QVariantMap& it : mHistory ) { int mx = x + Padding(); DrawMana( painter, mx, y, RowHeight(), RowHeight(), it["mana"].toInt() ); int cx = mx + RowHeight() + 5; DrawCardLine( painter, cx, y, RowWidth() - cx, RowHeight(), it["name"].toString(), it["count"].toInt() ); y += RowHeight(); y += RowSpacing(); } painter.restore(); } }; Overlay::Overlay( QWidget *parent ) : QMainWindow( parent ), mUI( new Ui::Overlay ), mShowPlayerHistory( PLAYER_UNKNOWN ) { mUI->setupUi( this ); setWindowFlags( Qt::NoDropShadowWindowHint | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput ); #ifdef Q_OS_WIN setWindowFlags( windowFlags() | Qt::Tool ); #else setWindowFlags( windowFlags() | Qt::Window ); #endif setAttribute( Qt::WA_TranslucentBackground ); setAttribute( Qt::WA_ShowWithoutActivating ); connect( Hearthstone::Instance(), &Hearthstone::GameWindowChanged, this, &Overlay::HandleGameWindowChanged ); connect( Hearthstone::Instance(), &Hearthstone::GameStarted, this, &Overlay::HandleGameStarted ); connect( Hearthstone::Instance(), &Hearthstone::GameStopped, this, &Overlay::HandleGameStopped ); connect( Hearthstone::Instance(), &Hearthstone::FocusChanged, this, &Overlay::HandleGameFocusChanged ); connect( &mCheckForHoverTimer, &QTimer::timeout, this, &Overlay::CheckForHover ); connect( Settings::Instance(), &Settings::OverlayEnabledChanged, this, &Overlay::HandleOverlaySettingChanged ); hide(); #ifdef Q_OS_MAC WId windowObject = this->winId(); objc_object* nsviewObject = reinterpret_cast<objc_object*>(windowObject); objc_object* nsWindowObject = objc_msgSend( nsviewObject, sel_registerName("window") ); int NSWindowCollectionBehaviorCanJoinAllSpaces = 1 << 0; objc_msgSend( nsWindowObject, sel_registerName("setCollectionBehavior:"), NSWindowCollectionBehaviorCanJoinAllSpaces ); // Ignore mouse events on Mac // Qt::WindowTransparentForInput bug // https://bugreports.qt.io/browse/QTBUG-45498 objc_msgSend( nsWindowObject, sel_registerName("setIgnoresMouseEvents:"), 1 ); #endif } Overlay::~Overlay() { delete mUI; } void Overlay::CheckForHover() { QPoint mouseLoc = mapFromGlobal( QCursor::pos() ); Player showPlayerHistory = PLAYER_UNKNOWN; if( mPlayerDeckRect.contains( mouseLoc ) ) { showPlayerHistory = PLAYER_SELF; } else if( mOpponentDeckRect.contains( mouseLoc ) ) { showPlayerHistory = PLAYER_OPPONENT; } if( mShowPlayerHistory != showPlayerHistory ) { mShowPlayerHistory = showPlayerHistory; update(); } } void PaintHistoryInScreen( QPainter& painter, const OverlayHistoryWindow& wnd, const QPoint& pos ) { int padding = 10; QRect rect( pos.x() + 20, pos.y(), wnd.Width(), wnd.Height() ); rect.translate( -qMax( rect.right() - painter.device()->width() + padding, 0 ), -qMax( rect.bottom() - painter.device()->height() + padding, 0 ) ); // fit to window wnd.Paint( painter, rect.x(), rect.y() ); } void Overlay::paintEvent( QPaintEvent* ) { QString title; QRect rect; OverlayHistoryList *history = NULL; if( mShowPlayerHistory == PLAYER_SELF && mPlayerHistory.count() > 0 ) { title = "Cards drawn"; history = &mPlayerHistory; rect = mPlayerDeckRect; } else if( mShowPlayerHistory == PLAYER_OPPONENT && mOpponentHistory.count() > 0 ) { title = "Opponent played"; history = &mOpponentHistory; rect = mOpponentDeckRect; } QPainter painter( this ); painter.setRenderHint( QPainter::Antialiasing ); #ifdef Q_OS_WIN float rowFontSize = 9; float titleFontSize = 9; #else float rowFontSize = 12; float titleFontSize = 12; #endif int spacing = 8; int overlayWidth = 200; if( history ) { OverlayHistoryWindow wnd( title, *history, overlayWidth, spacing, spacing, titleFontSize, rowFontSize ); QPoint pos = rect.center() + QPoint( rect.width() / 2 + 10, -wnd.Height() / 2 ); PaintHistoryInScreen( painter, wnd, pos ); } } void Overlay::HandleGameWindowChanged( int x, int y, int w, int h ) { // Order is important // Otherwise starting fullscreen on windows // will not show the overlay unless the FS mode is toggled setFixedSize( w, h ); move( x, y ); int minWidth = h * 4 / 3; mPlayerDeckRect = QRect( w / 2 + 0.440 * minWidth, h * 0.510, 0.05 * minWidth, h * 0.170 ); mOpponentDeckRect = mPlayerDeckRect.translated( -0.005 * minWidth, -0.275 * h ); Update(); } void Overlay::Update() { bool showable = false; if( Hearthstone::Instance()->GameRunning() && Settings::Instance()->OverlayEnabled() ) { showable = true; if( !mCardDB.Loaded() ) { mCardDB.Load(); } } else { if( mCardDB.Loaded() ) { mCardDB.Unload(); } } if( showable && Hearthstone::Instance()->HasFocus() ) { hide(); // Minimize/Restore on Windows requires a hide() first show(); #ifdef Q_OS_WIN setAttribute( Qt::WA_QuitOnClose ); // otherwise taskkill /IM Track-o-Bot.exe does not work (http://www.qtcentre.org/threads/11713-Qt-Tool?p=62466#post62466) #endif } else { hide(); } update(); } void Overlay::HandleGameStarted() { mCheckForHoverTimer.start( CHECK_FOR_OVERLAY_HOVER_INTERVAL_MS ); Update(); } void Overlay::HandleGameStopped() { mCheckForHoverTimer.stop(); Update(); } void Overlay::UpdateHistoryFor( Player player, const ::CardHistoryList& list ) { QMap< QString, QVariantMap > entries; for( const CardHistoryItem& it : list ) { const QString& cardId = it.cardId; if( cardId.isEmpty() ) { continue; } if( !mCardDB.Contains( cardId ) ) { DBG( "Card %s not found", qt2cstr( cardId ) ); continue; } if( mCardDB.Type( cardId ) == "HERO_POWER" ) { continue; } if( it.player != player ) { continue; } QVariantMap& entry = entries[ cardId ]; entry[ "count" ] = entry.value( "count", 0 ).toInt() + 1; entry[ "mana" ] = mCardDB.Cost( cardId ); entry[ "name" ] = mCardDB.Name( cardId ); } OverlayHistoryList* ref; if( player == PLAYER_SELF ) { ref = &mPlayerHistory; } else { ref = &mOpponentHistory; } *ref = entries.values(); qSort( ref->begin(), ref->end(), []( const QVariantMap& a, const QVariantMap& b ) { if( a["mana"].toInt() == b["mana"].toInt() ) { return a["name"].toString() < b["name"].toString(); } else { return a["mana"].toInt() < b["mana"].toInt(); } }); } void Overlay::HandleCardsDrawnUpdate( const ::CardHistoryList& cardsDrawn ) { UpdateHistoryFor( PLAYER_OPPONENT, cardsDrawn ); UpdateHistoryFor( PLAYER_SELF, cardsDrawn ); Update(); } void Overlay::HandleOverlaySettingChanged( bool enabled ) { UNUSED_ARG( enabled ); Update(); } void Overlay::HandleGameFocusChanged( bool focus ) { DBG( "HandleFocusChanged %d", focus ); Update(); } <|endoftext|>
<commit_before>#pragma once #include <unordered_map> #include <cmath> namespace euler::primes { /** * Return a N+1 size array of booleans such that * mask[a] is true iff a is a composite number. */ template<int N> constexpr std::array<bool, N + 1> composite_mask() { static_assert(N >= 0, "N must be non-negative."); std::array<bool, N + 1> mask = {true, true}; for (int i = 2; i*i <= N; ++i) if (!mask[i]) for (int j = i * i; j <= N; j += i) mask[j] = true; return mask; } template<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; }; template<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; }; /** * Fill a supplied map with (p : a) pairs where a is * the largest power of p which divides n. */ template<typename Integer = int, typename Power = int, typename Maptype = std::unordered_map<Integer, Power>> void prime_map(Integer n, Maptype &map) { Integer d = 2; while (d * d <= n) { while (n % d == 0) { if (map.count(d)) { map[d] += 1; } else { map.emplace(d, 1); } n /= d; } ++d; } if (n > 1) map.emplace(n, 1); }; /** * Return the number of divisors for n^(power). */ template<typename Integer = int, typename Power = int> Integer number_of_divisors(Integer n, Power power = 1) { std::unordered_map<Integer, Integer> primes; prime_map(n, primes); Integer count = 1; for (auto [p, a] : primes) { count *= power * a + 1; } return count; } } <commit_msg>Add missing includes.<commit_after>#pragma once #include <cmath> #include <array> #include <unordered_map> namespace euler::primes { /** * Return a N+1 size array of booleans such that * mask[a] is true iff a is a composite number. */ template<int N> constexpr std::array<bool, N + 1> composite_mask() { static_assert(N >= 0, "N must be non-negative."); std::array<bool, N + 1> mask = {true, true}; for (int i = 2; i*i <= N; ++i) if (!mask[i]) for (int j = i * i; j <= N; j += i) mask[j] = true; return mask; } template<> constexpr std::array<bool, 1> composite_mask<0>() { return {true}; }; template<> constexpr std::array<bool, 2> composite_mask<1>() { return {true, true}; }; /** * Fill a supplied map with (p : a) pairs where a is * the largest power of p which divides n. */ template<typename Integer = int, typename Power = int, typename Maptype = std::unordered_map<Integer, Power>> void prime_map(Integer n, Maptype &map) { Integer d = 2; while (d * d <= n) { while (n % d == 0) { if (map.count(d)) { map[d] += 1; } else { map.emplace(d, 1); } n /= d; } ++d; } if (n > 1) map.emplace(n, 1); }; /** * Return the number of divisors for n^(power). */ template<typename Integer = int, typename Power = int> Integer number_of_divisors(Integer n, Power power = 1) { std::unordered_map<Integer, Integer> primes; prime_map(n, primes); Integer count = 1; for (auto [p, a] : primes) { count *= power * a + 1; } return count; } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: backingwindow.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2008-03-12 10:10:06 $ * * 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 FRAMEWORK_BACKINGWINDOW_HXX #define FRAMEWORK_BACKINGWINDOW_HXX #include "rtl/ustring.hxx" #include "vcl/button.hxx" #include "vcl/fixed.hxx" #include "vcl/bitmapex.hxx" #include "vcl/toolbox.hxx" #include "svtools/moduleoptions.hxx" #include "com/sun/star/frame/XDispatchProvider.hpp" #include "com/sun/star/frame/XDesktop.hpp" #include "com/sun/star/frame/XTerminateListener.hpp" #include "com/sun/star/document/XEventListener.hpp" #include "com/sun/star/document/XEventBroadcaster.hpp" #include "com/sun/star/util/XURLTransformer.hpp" #include "com/sun/star/ui/dialogs/XFilePicker.hpp" #include "com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp" #include "com/sun/star/ui/dialogs/XFilterManager.hpp" #include "com/sun/star/ui/dialogs/XFolderPicker.hpp" #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp" #include <set> namespace framework { // To get the transparent mouse-over look, the closer is actually a toolbox // overload DataChange to handle style changes correctly class DecoToolBox : public ToolBox { Size maMinSize; using Window::ImplInit; public: DecoToolBox( Window* pParent, WinBits nStyle = 0 ); DecoToolBox( Window* pParent, const ResId& rResId ); void DataChanged( const DataChangedEvent& rDCEvt ); void calcMinSize(); Size getMinSize(); }; class BackingWindow : public Window { com::sun::star::uno::Reference<com::sun::star::frame::XDesktop> mxDesktop; com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider > mxDesktopDispatchProvider; com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster> mxBroadcaster; FixedText maWelcome; Size maWelcomeSize; FixedText maProduct; Size maProductSize; FixedText maCreateText; Size maCreateSize; FixedText maWriterText; ImageButton maWriterButton; FixedText maCalcText; ImageButton maCalcButton; FixedText maImpressText; ImageButton maImpressButton; FixedText maDrawText; ImageButton maDrawButton; FixedText maDBText; ImageButton maDBButton; FixedText maOpenText; ImageButton maOpenButton; FixedText maTemplateText; ImageButton maTemplateButton; DecoToolBox maToolbox; BitmapEx maBackgroundLeft; BitmapEx maBackgroundMiddle; BitmapEx maBackgroundRight; String maWelcomeString; String maProductString; String maCreateString; String maOpenString; String maTemplateString; Font maTextFont; Rectangle maControlRect; long mnColumnWidth[2]; Color maLabelTextColor; Color maWelcomeTextColor; Size maButtonImageSize; static const long nBtnPos = 240; static const int nItemId_Extensions = 1; static const int nItemId_Reg = 2; static const int nItemId_Info = 3; static const int nShadowTop = 32; static const int nShadowLeft = 35; static const int nShadowRight = 45; static const int nShadowBottom = 50; void loadImage( const ResId& i_rId, ImageButton& i_rButton ); void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS, SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod, ImageButton& i_rBtn, FixedText& i_rText, const String& i_rStr = String() ); bool executeFileOpen(); void dispatchURL( const rtl::OUString& i_rURL, const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ), const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(), const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >() ); DECL_LINK( ClickHdl, Button* ); DECL_LINK( ToolboxHdl, void* ); public: BackingWindow( Window* pParent ); ~BackingWindow(); virtual void Paint( const Rectangle& rRect ); virtual void Resize(); }; } #endif <commit_msg>INTEGRATION: CWS vcl87 (1.3.2); FILE MERGED 2008/03/18 15:30:35 pl 1.3.2.6: #i87065# initControls only after menubar is set in attachFrame 2008/03/17 16:45:37 pl 1.3.2.5: #i87124# reuse menu file open implementation via dispatch 2008/03/17 15:59:34 pl 1.3.2.4: #i87056# accelerator handling in StartCenter 2008/03/17 13:00:48 pl 1.3.2.3: #i87065# lazy initControls to get menu bar accelerators 2008/03/15 15:34:44 pl 1.3.2.2: #i86671# create mnemonics on the fly 2008/03/15 14:49:15 pl 1.3.2.1: #i86929# change tab order in StartCenter<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: backingwindow.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2008-04-03 17:11:50 $ * * 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 FRAMEWORK_BACKINGWINDOW_HXX #define FRAMEWORK_BACKINGWINDOW_HXX #include "rtl/ustring.hxx" #include "vcl/button.hxx" #include "vcl/fixed.hxx" #include "vcl/bitmapex.hxx" #include "vcl/toolbox.hxx" #include "svtools/moduleoptions.hxx" #include "svtools/acceleratorexecute.hxx" #include "com/sun/star/frame/XDispatchProvider.hpp" #include "com/sun/star/frame/XDesktop.hpp" #include "com/sun/star/frame/XFrame.hpp" #include "com/sun/star/frame/XTerminateListener.hpp" #include "com/sun/star/document/XEventListener.hpp" #include "com/sun/star/document/XEventBroadcaster.hpp" #include "com/sun/star/util/XURLTransformer.hpp" #include "com/sun/star/ui/dialogs/XFilePicker.hpp" #include "com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp" #include "com/sun/star/ui/dialogs/XFilterManager.hpp" #include "com/sun/star/ui/dialogs/XFolderPicker.hpp" #include "com/sun/star/ui/dialogs/TemplateDescription.hpp" #include "com/sun/star/ui/dialogs/ExecutableDialogResults.hpp" #include <set> class MnemonicGenerator; namespace framework { // To get the transparent mouse-over look, the closer is actually a toolbox // overload DataChange to handle style changes correctly class DecoToolBox : public ToolBox { Size maMinSize; using Window::ImplInit; public: DecoToolBox( Window* pParent, WinBits nStyle = 0 ); DecoToolBox( Window* pParent, const ResId& rResId ); void DataChanged( const DataChangedEvent& rDCEvt ); void calcMinSize(); Size getMinSize(); }; class BackingWindow : public Window { com::sun::star::uno::Reference<com::sun::star::frame::XDesktop> mxDesktop; com::sun::star::uno::Reference<com::sun::star::frame::XDispatchProvider > mxDesktopDispatchProvider; com::sun::star::uno::Reference<com::sun::star::frame::XFrame> mxFrame; com::sun::star::uno::Reference<com::sun::star::document::XEventBroadcaster> mxBroadcaster; FixedText maWelcome; Size maWelcomeSize; FixedText maProduct; Size maProductSize; FixedText maCreateText; Size maCreateSize; FixedText maWriterText; ImageButton maWriterButton; FixedText maCalcText; ImageButton maCalcButton; FixedText maImpressText; ImageButton maImpressButton; FixedText maDrawText; ImageButton maDrawButton; FixedText maDBText; ImageButton maDBButton; FixedText maTemplateText; ImageButton maTemplateButton; FixedText maOpenText; ImageButton maOpenButton; DecoToolBox maToolbox; BitmapEx maBackgroundLeft; BitmapEx maBackgroundMiddle; BitmapEx maBackgroundRight; String maWelcomeString; String maProductString; String maCreateString; String maOpenString; String maTemplateString; Font maTextFont; Rectangle maControlRect; long mnColumnWidth[2]; Color maLabelTextColor; Color maWelcomeTextColor; Size maButtonImageSize; bool mbInitControls; svt::AcceleratorExecute* mpAccExec; static const long nBtnPos = 240; static const int nItemId_Extensions = 1; static const int nItemId_Reg = 2; static const int nItemId_Info = 3; static const int nShadowTop = 32; static const int nShadowLeft = 35; static const int nShadowRight = 45; static const int nShadowBottom = 50; void loadImage( const ResId& i_rId, ImageButton& i_rButton ); void layoutButtonAndText( const char* i_pURL, int nColumn, const std::set<rtl::OUString>& i_rURLS, SvtModuleOptions& i_rOpt, SvtModuleOptions::EModule i_eMod, ImageButton& i_rBtn, FixedText& i_rText, MnemonicGenerator& i_rMnemonicGen, const String& i_rStr = String() ); void dispatchURL( const rtl::OUString& i_rURL, const rtl::OUString& i_rTarget = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "_default" ) ), const com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >& i_xProv = com::sun::star::uno::Reference< com::sun::star::frame::XDispatchProvider >(), const com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >& = com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >() ); DECL_LINK( ClickHdl, Button* ); DECL_LINK( ToolboxHdl, void* ); void initControls(); public: BackingWindow( Window* pParent ); ~BackingWindow(); virtual void Paint( const Rectangle& rRect ); virtual void Resize(); virtual long Notify( NotifyEvent& rNEvt ); void setOwningFrame( const com::sun::star::uno::Reference< com::sun::star::frame::XFrame >& xFrame ); }; } #endif <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ // Moose #include "FindContactPoint.h" #include "LineSegment.h" // libMesh #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/plane.h" #include "libmesh/fe_interface.h" #include "libmesh/dense_matrix.h" #include "libmesh/dense_vector.h" #include "libmesh/fe_base.h" namespace Moose { /** * Finds the closest point (called the contact point) on the master_elem on side "side" to the slave_point. * * @param master_elem The element on the master side of the interface * @param side The side number of the side of the master element * @param slave_point The physical space coordinates of the slave node * @param contact_ref The reference coordinate position of the contact point * @param contact_phys The physical space coordinates of the contact point * @param distance The distance between the slave_point and the contact point * @param normal The unit normal at the contact_point * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element. */ void findContactPoint(PenetrationLocator::PenetrationInfo & p_info, FEBase * _fe, FEType & _fe_type, const Point & slave_point, bool start_with_centroid, const Real tangential_tolerance, bool & contact_point_on_side) { const Elem * master_elem = p_info._elem; unsigned int dim = master_elem->dim(); const Elem * side = p_info._side; const std::vector<Point> & phys_point = _fe->get_xyz(); const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi(); const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2(); const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta(); const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta(); const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2(); const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta(); if (dim == 1) { unsigned left(0); unsigned right(left); Real leftCoor((*master_elem->get_node(0))(0)); Real rightCoor(left); for (unsigned i(1); i < master_elem->n_nodes(); ++i) { Real coor = (*master_elem->get_node(i))(0); if (coor < leftCoor) { left = i; leftCoor = coor; } if (coor > rightCoor) { right = i; rightCoor = coor; } } unsigned nearestNode(left); Point nearestPoint(leftCoor, 0, 0); if (side->node(0) == right) { nearestNode = right; nearestPoint(0) = rightCoor; } p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false); p_info._closest_point = nearestPoint; p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0); p_info._distance = (p_info._closest_point - slave_point) * p_info._normal; p_info._dxyzdxi = dxyz_dxi; p_info._dxyzdeta = dxyz_deta; p_info._d2xyzdxideta = d2xyz_dxieta; p_info._side_phi = _fe->get_phi(); contact_point_on_side = true; return; } Point ref_point; if(start_with_centroid) ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false); else ref_point = p_info._closest_point_ref; std::vector<Point> points(1); points[0] = ref_point; _fe->reinit(side, &points); RealGradient d = slave_point - phys_point[0]; Real update_size = 9999999; //Least squares for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it) { DenseMatrix<Real> jac(dim-1, dim-1); jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]); if(dim-1 == 2) { jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]); jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]); jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]); } DenseVector<Real> rhs(dim-1); rhs(0) = dxyz_dxi[0]*d; if(dim-1 == 2) rhs(1) = dxyz_deta[0]*d; DenseVector<Real> update(dim-1); jac.lu_solve(rhs, update); ref_point(0) -= update(0); if(dim-1 == 2) ref_point(1) -= update(1); points[0] = ref_point; _fe->reinit(side, &points); d = slave_point - phys_point[0]; update_size = update.l2_norm(); } update_size = 9999999; unsigned nit=0; // Newton Loop for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++) { d = slave_point - phys_point[0]; DenseMatrix<Real> jac(dim-1, dim-1); jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]); if(dim-1 == 2) { jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]); jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]); jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]); } DenseVector<Real> rhs(dim-1); rhs(0) = -dxyz_dxi[0]*d; if(dim-1 == 2) rhs(1) = -dxyz_deta[0]*d; DenseVector<Real> update(dim-1); jac.lu_solve(rhs, update); ref_point(0) += update(0); if(dim-1 == 2) ref_point(1) += update(1); points[0] = ref_point; _fe->reinit(side, &points); d = slave_point - phys_point[0]; update_size = update.l2_norm(); } /* if(nit == 12 && update_size > TOLERANCE*TOLERANCE) std::cerr<<"Warning! Newton solve for contact point failed to converge!"<<std::endl; */ p_info._closest_point_ref = ref_point; p_info._closest_point = phys_point[0]; p_info._distance = d.size(); if(dim-1 == 2) { p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]); p_info._normal /= p_info._normal.size(); } else { p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0)); p_info._normal /= p_info._normal.size(); } // If the point has not penetrated the face, make the distance negative const Real dot(d * p_info._normal); if (dot > 0.0) p_info._distance = -p_info._distance; contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type()); p_info._tangential_distance = 0.0; if (!contact_point_on_side) { p_info._closest_point_on_face_ref=ref_point; restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes); points[0] = p_info._closest_point_on_face_ref; _fe->reinit(side, &points); Point closest_point_on_face(phys_point[0]); RealGradient off_face = closest_point_on_face - p_info._closest_point; Real tangential_distance = off_face.size(); p_info._tangential_distance = tangential_distance; if (tangential_distance <= tangential_tolerance) { contact_point_on_side = true; } } const std::vector<std::vector<Real> > & phi = _fe->get_phi(); points[0] = p_info._closest_point_ref; _fe->reinit(side, &points); p_info._side_phi = phi; p_info._dxyzdxi = dxyz_dxi; p_info._dxyzdeta = dxyz_deta; p_info._d2xyzdxideta = d2xyz_dxieta; } void restrictPointToFace(Point& p, const Elem* side, std::vector<Node*> &off_edge_nodes) { const ElemType t(side->type()); off_edge_nodes.clear(); Real &xi = p(0); Real &eta = p(1); switch (t) { case EDGE2: case EDGE3: case EDGE4: { // The reference 1D element is [-1,1]. if (xi < -1.0) { xi = -1.0; off_edge_nodes.push_back(side->get_node(0)); } else if (xi > 1.0) { xi = 1.0; off_edge_nodes.push_back(side->get_node(1)); } break; } case TRI3: case TRI6: { // The reference triangle is isosceles // and is bound by xi=0, eta=0, and xi+eta=1. if (xi <= 0.0 && eta <= 0.0) { xi = 0.0; eta = 0.0; off_edge_nodes.push_back(side->get_node(0)); } else if (xi > 0.0 && xi < 1.0 && eta < 0.0) { eta = 0.0; off_edge_nodes.push_back(side->get_node(0)); off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 0.0 && eta < 1.0 && xi < 0.0) { xi = 0.0; off_edge_nodes.push_back(side->get_node(2)); off_edge_nodes.push_back(side->get_node(0)); } else if (xi >= 1.0 && (eta - xi) <= -1.0) { xi = 1.0; eta = 0.0; off_edge_nodes.push_back(side->get_node(1)); } else if (eta >= 1.0 && (eta - xi) >= 1.0) { xi = 0.0; eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); } else if ((xi + eta) > 1.0) { Real delta = (xi+eta-1.0)/2.0; xi -= delta; eta -= delta; off_edge_nodes.push_back(side->get_node(1)); off_edge_nodes.push_back(side->get_node(2)); } break; } case QUAD4: case QUAD8: case QUAD9: { // The reference quadrilateral element is [-1,1]^2. if (xi < -1.0) { xi = -1.0; if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(0)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(3)); } else { off_edge_nodes.push_back(side->get_node(3)); off_edge_nodes.push_back(side->get_node(0)); } } else if (xi > 1.0) { xi = 1.0; if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); } else { off_edge_nodes.push_back(side->get_node(1)); off_edge_nodes.push_back(side->get_node(2)); } } else { if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(0)); off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); off_edge_nodes.push_back(side->get_node(3)); } } break; } default: { mooseError("Unsupported face type: "<<t); break; } } } } //namespace Moose <commit_msg>Fix bug in 1D<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ // Moose #include "FindContactPoint.h" #include "LineSegment.h" // libMesh #include "libmesh/boundary_info.h" #include "libmesh/elem.h" #include "libmesh/plane.h" #include "libmesh/fe_interface.h" #include "libmesh/dense_matrix.h" #include "libmesh/dense_vector.h" #include "libmesh/fe_base.h" namespace Moose { /** * Finds the closest point (called the contact point) on the master_elem on side "side" to the slave_point. * * @param master_elem The element on the master side of the interface * @param side The side number of the side of the master element * @param slave_point The physical space coordinates of the slave node * @param contact_ref The reference coordinate position of the contact point * @param contact_phys The physical space coordinates of the contact point * @param distance The distance between the slave_point and the contact point * @param normal The unit normal at the contact_point * @param contact_point_on_side whether or not the contact_point actually lies on _that_ side of the element. */ void findContactPoint(PenetrationLocator::PenetrationInfo & p_info, FEBase * _fe, FEType & _fe_type, const Point & slave_point, bool start_with_centroid, const Real tangential_tolerance, bool & contact_point_on_side) { const Elem * master_elem = p_info._elem; unsigned int dim = master_elem->dim(); const Elem * side = p_info._side; const std::vector<Point> & phys_point = _fe->get_xyz(); const std::vector<RealGradient> & dxyz_dxi = _fe->get_dxyzdxi(); const std::vector<RealGradient> & d2xyz_dxi2 = _fe->get_d2xyzdxi2(); const std::vector<RealGradient> & d2xyz_dxieta = _fe->get_d2xyzdxideta(); const std::vector<RealGradient> & dxyz_deta = _fe->get_dxyzdeta(); const std::vector<RealGradient> & d2xyz_deta2 = _fe->get_d2xyzdeta2(); const std::vector<RealGradient> & d2xyz_detaxi = _fe->get_d2xyzdxideta(); if (dim == 1) { Node * left(master_elem->get_node(0)); Node * right(left); Real leftCoor((*left)(0)); Real rightCoor(leftCoor); for (unsigned i(1); i < master_elem->n_nodes(); ++i) { Node * curr = master_elem->get_node(i); Real coor = (*curr)(0); if (coor < leftCoor) { left = curr; leftCoor = coor; } if (coor > rightCoor) { right = curr; rightCoor = coor; } } Node * nearestNode(left); Point nearestPoint(leftCoor, 0, 0); if (side->node(0) == right->id()) { nearestNode = right; nearestPoint(0) = rightCoor; } else if (side->node(0) != left->id()) { mooseError("Error findContactPoint. Logic error in 1D"); } p_info._closest_point_ref = FEInterface::inverse_map(dim, _fe_type, master_elem, nearestPoint, TOLERANCE, false); p_info._closest_point = nearestPoint; p_info._normal = Point(left == nearestNode ? -1 : 1, 0, 0); p_info._distance = (p_info._closest_point - slave_point) * p_info._normal; p_info._dxyzdxi = dxyz_dxi; p_info._dxyzdeta = dxyz_deta; p_info._d2xyzdxideta = d2xyz_dxieta; p_info._side_phi = _fe->get_phi(); contact_point_on_side = true; return; } Point ref_point; if(start_with_centroid) ref_point = FEInterface::inverse_map(dim-1, _fe_type, side, side->centroid(), TOLERANCE, false); else ref_point = p_info._closest_point_ref; std::vector<Point> points(1); points[0] = ref_point; _fe->reinit(side, &points); RealGradient d = slave_point - phys_point[0]; Real update_size = 9999999; //Least squares for(unsigned int it=0; it<3 && update_size > TOLERANCE*1e3; ++it) { DenseMatrix<Real> jac(dim-1, dim-1); jac(0,0) = -(dxyz_dxi[0] * dxyz_dxi[0]); if(dim-1 == 2) { jac(1,0) = -(dxyz_dxi[0] * dxyz_deta[0]); jac(0,1) = -(dxyz_deta[0] * dxyz_dxi[0]); jac(1,1) = -(dxyz_deta[0] * dxyz_deta[0]); } DenseVector<Real> rhs(dim-1); rhs(0) = dxyz_dxi[0]*d; if(dim-1 == 2) rhs(1) = dxyz_deta[0]*d; DenseVector<Real> update(dim-1); jac.lu_solve(rhs, update); ref_point(0) -= update(0); if(dim-1 == 2) ref_point(1) -= update(1); points[0] = ref_point; _fe->reinit(side, &points); d = slave_point - phys_point[0]; update_size = update.l2_norm(); } update_size = 9999999; unsigned nit=0; // Newton Loop for(; nit<12 && update_size > TOLERANCE*TOLERANCE; nit++) { d = slave_point - phys_point[0]; DenseMatrix<Real> jac(dim-1, dim-1); jac(0,0) = (d2xyz_dxi2[0]*d)-(dxyz_dxi[0] * dxyz_dxi[0]); if(dim-1 == 2) { jac(1,0) = (d2xyz_dxieta[0]*d)-(dxyz_dxi[0] * dxyz_deta[0]); jac(0,1) = (d2xyz_detaxi[0]*d)-(dxyz_deta[0] * dxyz_dxi[0]); jac(1,1) = (d2xyz_deta2[0]*d)-(dxyz_deta[0] * dxyz_deta[0]); } DenseVector<Real> rhs(dim-1); rhs(0) = -dxyz_dxi[0]*d; if(dim-1 == 2) rhs(1) = -dxyz_deta[0]*d; DenseVector<Real> update(dim-1); jac.lu_solve(rhs, update); ref_point(0) += update(0); if(dim-1 == 2) ref_point(1) += update(1); points[0] = ref_point; _fe->reinit(side, &points); d = slave_point - phys_point[0]; update_size = update.l2_norm(); } /* if(nit == 12 && update_size > TOLERANCE*TOLERANCE) std::cerr<<"Warning! Newton solve for contact point failed to converge!"<<std::endl; */ p_info._closest_point_ref = ref_point; p_info._closest_point = phys_point[0]; p_info._distance = d.size(); if(dim-1 == 2) { p_info._normal = dxyz_dxi[0].cross(dxyz_deta[0]); p_info._normal /= p_info._normal.size(); } else { p_info._normal = RealGradient(dxyz_dxi[0](1),-dxyz_dxi[0](0)); p_info._normal /= p_info._normal.size(); } // If the point has not penetrated the face, make the distance negative const Real dot(d * p_info._normal); if (dot > 0.0) p_info._distance = -p_info._distance; contact_point_on_side = FEInterface::on_reference_element(ref_point, side->type()); p_info._tangential_distance = 0.0; if (!contact_point_on_side) { p_info._closest_point_on_face_ref=ref_point; restrictPointToFace(p_info._closest_point_on_face_ref,side,p_info._off_edge_nodes); points[0] = p_info._closest_point_on_face_ref; _fe->reinit(side, &points); Point closest_point_on_face(phys_point[0]); RealGradient off_face = closest_point_on_face - p_info._closest_point; Real tangential_distance = off_face.size(); p_info._tangential_distance = tangential_distance; if (tangential_distance <= tangential_tolerance) { contact_point_on_side = true; } } const std::vector<std::vector<Real> > & phi = _fe->get_phi(); points[0] = p_info._closest_point_ref; _fe->reinit(side, &points); p_info._side_phi = phi; p_info._dxyzdxi = dxyz_dxi; p_info._dxyzdeta = dxyz_deta; p_info._d2xyzdxideta = d2xyz_dxieta; } void restrictPointToFace(Point& p, const Elem* side, std::vector<Node*> &off_edge_nodes) { const ElemType t(side->type()); off_edge_nodes.clear(); Real &xi = p(0); Real &eta = p(1); switch (t) { case EDGE2: case EDGE3: case EDGE4: { // The reference 1D element is [-1,1]. if (xi < -1.0) { xi = -1.0; off_edge_nodes.push_back(side->get_node(0)); } else if (xi > 1.0) { xi = 1.0; off_edge_nodes.push_back(side->get_node(1)); } break; } case TRI3: case TRI6: { // The reference triangle is isosceles // and is bound by xi=0, eta=0, and xi+eta=1. if (xi <= 0.0 && eta <= 0.0) { xi = 0.0; eta = 0.0; off_edge_nodes.push_back(side->get_node(0)); } else if (xi > 0.0 && xi < 1.0 && eta < 0.0) { eta = 0.0; off_edge_nodes.push_back(side->get_node(0)); off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 0.0 && eta < 1.0 && xi < 0.0) { xi = 0.0; off_edge_nodes.push_back(side->get_node(2)); off_edge_nodes.push_back(side->get_node(0)); } else if (xi >= 1.0 && (eta - xi) <= -1.0) { xi = 1.0; eta = 0.0; off_edge_nodes.push_back(side->get_node(1)); } else if (eta >= 1.0 && (eta - xi) >= 1.0) { xi = 0.0; eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); } else if ((xi + eta) > 1.0) { Real delta = (xi+eta-1.0)/2.0; xi -= delta; eta -= delta; off_edge_nodes.push_back(side->get_node(1)); off_edge_nodes.push_back(side->get_node(2)); } break; } case QUAD4: case QUAD8: case QUAD9: { // The reference quadrilateral element is [-1,1]^2. if (xi < -1.0) { xi = -1.0; if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(0)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(3)); } else { off_edge_nodes.push_back(side->get_node(3)); off_edge_nodes.push_back(side->get_node(0)); } } else if (xi > 1.0) { xi = 1.0; if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); } else { off_edge_nodes.push_back(side->get_node(1)); off_edge_nodes.push_back(side->get_node(2)); } } else { if (eta < -1.0) { eta = -1.0; off_edge_nodes.push_back(side->get_node(0)); off_edge_nodes.push_back(side->get_node(1)); } else if (eta > 1.0) { eta = 1.0; off_edge_nodes.push_back(side->get_node(2)); off_edge_nodes.push_back(side->get_node(3)); } } break; } default: { mooseError("Unsupported face type: "<<t); break; } } } } //namespace Moose <|endoftext|>
<commit_before><commit_msg>error: 'pGen' was not declared in this scope<commit_after><|endoftext|>
<commit_before>#include "./thresholdScan.h" ClassImp(thresholdScan); //standard constructor from AnalysisModule thresholdScan::thresholdScan(const char* name, const char* title, const char* in_file_suffix, const char* out_file_suffix, const std::vector<double>& thresholds, const std::vector<double>& eCut) : JPetCommonAnalysisModule(name, title, in_file_suffix, out_file_suffix) { setVersion(MODULE_VERSION); fThresholds = thresholds; energyCuts = eCut; } //no specific destructor needed thresholdScan::~thresholdScan() { } void thresholdScan::begin() { for( unsigned int i = 0; i < fThresholds.size(); i++ ){ std::vector<double> k; fDeltaTimesForThresholdsTop.push_back( k ); fDeltaTimesForThresholdsBottom.push_back( k ); } } void thresholdScan::exec() { // Take next entry fReader->getEntry(fEvent); // Cast data from the entry into JPetLOR const JPetLOR& lor = (JPetLOR&) fReader->getData(); // Extract signals const JPetRecoSignal& signalFirst = lor.getFirstHit().getSignalA().getRecoSignal(); const JPetRecoSignal& signalSecond = lor.getFirstHit().getSignalB().getRecoSignal(); const JPetRecoSignal& signalThird = lor.getSecondHit().getSignalA().getRecoSignal(); const JPetRecoSignal& signalFourth = lor.getSecondHit().getSignalB().getRecoSignal(); const JPetHit& hitFirst = lor.getFirstHit(); const JPetHit& hitSecond = lor.getSecondHit(); double energyT = hitFirst.getEnergy(); double energyB = hitSecond.getEnergy(); if(energyCuts.size() == 2) { if( energyT > energyCuts[0] && energyT < energyCuts[1] ) { energyTop.push_back(energyT); } if( energyB > energyCuts[0] && energyB < energyCuts[1] ) { energyBottom.push_back(energyB); } } else if(energyCuts.size() == 1) { if( energyT > energyCuts[0] ) { energyTop.push_back(energyT); } if( energyB > energyCuts[0] ) { energyBottom.push_back(energyB); } } // Save times from signals to file for( unsigned int i = 0; i < fThresholds.size(); i++) { if(energyCuts.size() == 2) { if( energyT > energyCuts[0] && energyT < energyCuts[1] ) { fDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); } if(energyB > energyCuts[0] && energyB < energyCuts[1] ) { fDeltaTimesForThresholdsBottom[i].push_back( signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalFourth.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); } } else if(energyCuts.size() == 1) { if(energyT > energyCuts[0] ){ fDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); } if(energyB > energyCuts[0] ) { fDeltaTimesForThresholdsBottom[i].push_back( signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalFourth.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); } } else{ ERROR( Form("Bad energy cuts vector provided") ); } } fEvent++; } void thresholdScan::end() { plotHistosAndGraphs( fDeltaTimesForThresholdsTop, "_TOP_"); plotHistosAndGraphs( fDeltaTimesForThresholdsBottom, "_BOTTOM_"); plotEnergyCuts(energyTop, "_TOP_"); plotEnergyCuts(energyBottom, "_BOTTOM_"); } void thresholdScan::plotEnergyCuts( std::vector<double>& data, std::string name) { TString filePath = fHeader->getBaseFileName(); filePath = filePath(filePath.Last('/')+1, filePath.Length()-1); filePath = filePath(0, filePath.Last('.')); std::stringstream buf; buf << fHeader->getSourcePosition(); buf << "_"; if( energyCuts.size() == 2 ) buf << energyCuts[0] <<"-"<<energyCuts[1]; else if (energyCuts.size() == 1 ) buf << energyCuts[0] << "-inf"; gStyle->SetOptFit(1); TString path = "ThresholdScan" + filePath+buf.str() + "/"; TUnixSystem* system = new TUnixSystem(); system->mkdir( (std::string(path)).c_str(), 1); std::string title = buf.str(); title+=name; TH1F* energy = new TH1F( title.c_str(), title.c_str() , 250, 0, 500); for(unsigned int i = 0; i < data.size(); i++){ energy->Fill( data[i] ); } TCanvas* c1 = new TCanvas(); energy->Draw(); c1->SaveAs( ((std::string)path+title+".png").c_str() ); delete energy; } void thresholdScan::plotHistosAndGraphs( std::vector<std::vector<double> >& data, std::string name) { std::vector<double> resolutions; std::vector<double> chi2; TString filePath = fHeader->getBaseFileName(); filePath = filePath(filePath.Last('/')+1, filePath.Length()-1); filePath = filePath(0, filePath.Last('.')); std::stringstream buf; buf << fHeader->getSourcePosition(); if( energyCuts.size() == 2 ) buf <<"_"<< energyCuts[0] <<"-"<<energyCuts[1]; else if (energyCuts.size() == 1 ) buf << "_" <<energyCuts[0] << "-inf"; gStyle->SetOptFit(1); TString path = "ThresholdScan" + filePath+buf.str() + "/"; TUnixSystem* system = new TUnixSystem(); system->mkdir( (std::string(path)).c_str(), 1); for(unsigned int j = 0; j < fThresholds.size(); j++){ double thr = fThresholds[j]; std::stringstream buf; buf << thr; std::string title = buf.str(); title+="mV"; title+=name; TH1F* deltaT = new TH1F( title.c_str(), title.c_str() , 200, -5000, 5000); for(unsigned int i = 0; i < data[j].size(); i++){ if( 0 == data[j].size()) break; if( data[j][i] != 0 ) deltaT->Fill( data[j][i] ); } TCanvas* c1 = new TCanvas(); deltaT->Sumw2(); double eventsNotInRange = deltaT->GetBinContent(0) + deltaT->GetBinContent(201); if( eventsNotInRange != deltaT->GetEntries() ) { std::cout<< deltaT->GetEntries() << std::endl; deltaT->Fit("gaus","QI"); resolutions.push_back( (double)deltaT->GetFunction("gaus")->GetParameter(2) ); chi2.push_back( ( (double)deltaT->GetFunction("gaus")->GetChisquare() ) / ( (double)deltaT->GetFunction("gaus")->GetNDF() ) ); } else { resolutions.push_back(0); chi2.push_back(0); } deltaT->Draw(); title+=buf.str(); c1->SaveAs( ((std::string)path+title+".png").c_str() ); delete deltaT; } std::ofstream outFile; outFile.open( ((std::string)path+name + "resolutions"+buf.str()+".txt").c_str() ); for(unsigned int i = 0; i < resolutions.size(); i++){ outFile << fThresholds[i] << "\t"<< resolutions[i] << "\t" << chi2[i] << std::endl; } outFile.close(); TCanvas* c1 = new TCanvas(); TGraph* resGraph = new TGraph(resolutions.size(),&fThresholds[0], &resolutions[0]); resGraph->SetTitle( "" ); resGraph->SetMarkerStyle(21); resGraph->SetMarkerSize(1.4); resGraph->GetXaxis()->SetTitle("Threshold [mV]"); resGraph->GetYaxis()->SetTitle("Time difference resolution [ps]"); resGraph->GetXaxis()->SetLabelFont(42); resGraph->GetYaxis()->SetLabelFont(42); resGraph->GetXaxis()->SetLabelSize(0.06); resGraph->GetYaxis()->SetLabelSize(0.06); resGraph->GetYaxis()->SetTitleOffset(1.2); resGraph->GetXaxis()->SetTitleFont(42); resGraph->GetYaxis()->SetTitleFont(42); resGraph->GetXaxis()->SetTitleSize(0.06); resGraph->GetYaxis()->SetTitleSize(0.06); c1->SetLeftMargin(0.1716621); c1->SetRightMargin(0.02815622); c1->SetTopMargin(0.02572016); c1->SetBottomMargin(0.1738683); resGraph->Draw("AP"); c1->SaveAs( ((std::string)path+name+buf.str()+"graph.root").c_str() ); resGraph->Draw("AP"); c1->SaveAs( ((std::string)path+name+"graph.png").c_str() ); delete resGraph; } <commit_msg>Clean commented code<commit_after>#include "./thresholdScan.h" ClassImp(thresholdScan); //standard constructor from AnalysisModule thresholdScan::thresholdScan(const char* name, const char* title, const char* in_file_suffix, const char* out_file_suffix, const std::vector<double>& thresholds, const std::vector<double>& eCut) : JPetCommonAnalysisModule(name, title, in_file_suffix, out_file_suffix) { setVersion(MODULE_VERSION); fThresholds = thresholds; energyCuts = eCut; } //no specific destructor needed thresholdScan::~thresholdScan() { } void thresholdScan::begin() { for( unsigned int i = 0; i < fThresholds.size(); i++ ){ std::vector<double> k; fDeltaTimesForThresholdsTop.push_back( k ); fDeltaTimesForThresholdsBottom.push_back( k ); } } void thresholdScan::exec() { // Take next entry fReader->getEntry(fEvent); // Cast data from the entry into JPetLOR const JPetLOR& lor = (JPetLOR&) fReader->getData(); std::cout << "Doing optimisation for: " << lor.getFirstHit().getSignalA().getPM().getID() << " and " << lor.getFirstHit().getSignalB().getPM().getID() << std::endl; // Extract signals const JPetRecoSignal& signalFirst = lor.getFirstHit().getSignalA().getRecoSignal(); const JPetRecoSignal& signalSecond = lor.getFirstHit().getSignalB().getRecoSignal(); const JPetRecoSignal& signalThird = lor.getSecondHit().getSignalA().getRecoSignal(); const JPetRecoSignal& signalFourth = lor.getSecondHit().getSignalB().getRecoSignal(); const JPetHit& hitFirst = lor.getFirstHit(); const JPetHit& hitSecond = lor.getSecondHit(); double energyT = hitFirst.getEnergy(); double energyB = hitSecond.getEnergy(); double chargeOne = signalFirst.getCharge(); double chargeTwo = signalSecond.getCharge(); double ampOne = signalFirst.getAmplitude(); double ampTwo = signalSecond.getAmplitude(); // Save times from signals to file for( unsigned int i = 0; i < fThresholds.size(); i++) { // if(energyCuts.size() == 2) // { // if( chargeOne > 352 && chargeTwo > 395 ) // if( ampOne > 350 && ampTwo > 350 ) // { fDeltaTimesForThresholdsTop[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalThird.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); // } fDeltaTimesForThresholdsBottom[i].push_back( signalFirst.getRecoTimeAtThreshold( (double)fThresholds[i] ) - signalSecond.getRecoTimeAtThreshold( (double)fThresholds[i] ) ); } fEvent++; } void thresholdScan::end() { plotHistosAndGraphs( fDeltaTimesForThresholdsTop, "_TOP_"); plotHistosAndGraphs( fDeltaTimesForThresholdsBottom, "_BOTTOM_"); plotEnergyCuts(energyTop, "_TOP_"); plotEnergyCuts(energyBottom, "_BOTTOM_"); } void thresholdScan::plotEnergyCuts( std::vector<double>& data, std::string name) { TString filePath = fHeader->getBaseFileName(); filePath = filePath(filePath.Last('/')+1, filePath.Length()-1); filePath = filePath(0, filePath.Last('.')); std::stringstream buf; buf << fHeader->getSourcePosition(); buf << "_"; if( energyCuts.size() == 2 ) buf << energyCuts[0] <<"-"<<energyCuts[1]; else if (energyCuts.size() == 1 ) buf << energyCuts[0] << "-inf"; gStyle->SetOptFit(1); TString path = "ThresholdScan" + filePath+buf.str() + "/"; TUnixSystem* system = new TUnixSystem(); system->mkdir( (std::string(path)).c_str(), 1); std::string title = buf.str(); title+=name; TH1F* energy = new TH1F( title.c_str(), title.c_str() , 250, 0, 500); for(unsigned int i = 0; i < data.size(); i++){ energy->Fill( data[i] ); } TCanvas* c1 = new TCanvas(); energy->Draw(); c1->SaveAs( ((std::string)path+title+".png").c_str() ); delete energy; } void thresholdScan::plotHistosAndGraphs( std::vector<std::vector<double> >& data, std::string name) { std::vector<double> resolutions; std::vector<double> chi2; TString filePath = fHeader->getBaseFileName(); filePath = filePath(filePath.Last('/')+1, filePath.Length()-1); filePath = filePath(0, filePath.Last('.')); std::stringstream buf; buf << fHeader->getSourcePosition(); if( energyCuts.size() == 2 ) buf <<"_"<< energyCuts[0] <<"-"<<energyCuts[1]; else if (energyCuts.size() == 1 ) buf << "_" <<energyCuts[0] << "-inf"; gStyle->SetOptFit(1); TString path = "ThresholdScan" + filePath+buf.str() + "/"; TUnixSystem* system = new TUnixSystem(); system->mkdir( (std::string(path)).c_str(), 1); for(unsigned int j = 0; j < fThresholds.size(); j++){ double thr = fThresholds[j]; std::stringstream buf; buf << thr; std::string title = buf.str(); title+="mV"; title+=name; TH1F* deltaT = new TH1F( title.c_str(), title.c_str() , 400, -10000, 10000); for(unsigned int i = 0; i < data[j].size(); i++){ if( 0 == data[j].size()) break; if( data[j][i] != 0 ) deltaT->Fill( data[j][i] ); } TCanvas* c1 = new TCanvas(); deltaT->Sumw2(); double eventsNotInRange = deltaT->GetBinContent(0) + deltaT->GetBinContent(201); if( eventsNotInRange != deltaT->GetEntries() ) { std::cout<< deltaT->GetEntries() << std::endl; deltaT->Fit("gaus","QI"); resolutions.push_back( (double)deltaT->GetFunction("gaus")->GetParameter(2) ); chi2.push_back( ( (double)deltaT->GetFunction("gaus")->GetChisquare() ) / ( (double)deltaT->GetFunction("gaus")->GetNDF() ) ); } else { resolutions.push_back(0); chi2.push_back(0); } deltaT->Draw(); title+=buf.str(); c1->SaveAs( ((std::string)path+title+".png").c_str() ); delete deltaT; } std::ofstream outFile; outFile.open( ((std::string)path+name + "resolutions"+buf.str()+".txt").c_str() ); for(unsigned int i = 0; i < resolutions.size(); i++){ outFile << fThresholds[i] << "\t"<< resolutions[i] << "\t" << chi2[i] << std::endl; } outFile.close(); TCanvas* c1 = new TCanvas(); TGraph* resGraph = new TGraph(resolutions.size(),&fThresholds[0], &resolutions[0]); resGraph->SetTitle( "" ); resGraph->SetMarkerStyle(21); resGraph->SetMarkerSize(1.4); resGraph->GetXaxis()->SetTitle("Threshold [mV]"); resGraph->GetYaxis()->SetTitle("Time difference resolution [ps]"); resGraph->GetXaxis()->SetLabelFont(42); resGraph->GetYaxis()->SetLabelFont(42); resGraph->GetXaxis()->SetLabelSize(0.06); resGraph->GetYaxis()->SetLabelSize(0.06); resGraph->GetYaxis()->SetTitleOffset(1.2); resGraph->GetXaxis()->SetTitleFont(42); resGraph->GetYaxis()->SetTitleFont(42); resGraph->GetXaxis()->SetTitleSize(0.06); resGraph->GetYaxis()->SetTitleSize(0.06); c1->SetLeftMargin(0.1716621); c1->SetRightMargin(0.02815622); c1->SetTopMargin(0.02572016); c1->SetBottomMargin(0.1738683); resGraph->Draw("AP"); c1->SaveAs( ((std::string)path+name+buf.str()+"graph.root").c_str() ); resGraph->Draw("AP"); c1->SaveAs( ((std::string)path+name+"graph.png").c_str() ); delete resGraph; } <|endoftext|>
<commit_before><commit_msg>All overflow scrolls should clear the scroll anchor, not just the root layer.<commit_after><|endoftext|>
<commit_before>#include "physics/kepler_orbit.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "mathematica/mathematica.hpp" #include "physics/solar_system.hpp" #include "testing_utilities/almost_equals.hpp" namespace principia { using integrators::McLachlanAtela1992Order5Optimal; using quantities::si::Degree; using quantities::si::Kilo; using quantities::si::Metre; using quantities::si::Milli; namespace physics { class ResonanceTest : public ::testing::Test { protected: using KSP = Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>; // Gravitational parameters from the KSP wiki. ResonanceTest() : sun_(AddBody(1.1723328E+18 * Pow<3>(Metre) / Pow<2>(Second))), jool_(AddBody(2.8252800E+14 * Pow<3>(Metre) / Pow<2>(Second))), laythe_(AddBody(1.9620000E+12 * Pow<3>(Metre) / Pow<2>(Second))), vall_(AddBody(2.0748150E+11 * Pow<3>(Metre) / Pow<2>(Second))), tylo_(AddBody(2.8252800E+12 * Pow<3>(Metre) / Pow<2>(Second))), bop_(AddBody(2.4868349E+09 * Pow<3>(Metre) / Pow<2>(Second))), pol_(AddBody(7.2170208E+08 * Pow<3>(Metre) / Pow<2>(Second))) { // Elements from the KSP wiki. jool_elements_.eccentricity = 0.05; jool_elements_.semimajor_axis = 68'773'560'320 * Metre; jool_elements_.inclination = 1.304 * Degree; jool_elements_.longitude_of_ascending_node = 52 * Degree; jool_elements_.argument_of_periapsis = 0 * Degree; jool_elements_.mean_anomaly = 0.1 * Radian; laythe_elements_.eccentricity = 0; laythe_elements_.semimajor_axis = 27'184'000 * Metre; laythe_elements_.inclination = 0 * Degree; laythe_elements_.longitude_of_ascending_node = 0 * Degree; laythe_elements_.argument_of_periapsis = 0 * Degree; laythe_elements_.mean_anomaly = 3.14 * Radian; vall_elements_.eccentricity = 0; vall_elements_.semimajor_axis = 43'152'000 * Metre; vall_elements_.inclination = 0 * Degree; vall_elements_.longitude_of_ascending_node = 0 * Degree; vall_elements_.argument_of_periapsis = 0 * Degree; vall_elements_.mean_anomaly = 0.9 * Radian; tylo_elements_.eccentricity = 0; tylo_elements_.semimajor_axis = 68'500'000 * Metre; tylo_elements_.inclination = 0.025 * Degree; tylo_elements_.longitude_of_ascending_node = 0 * Degree; tylo_elements_.argument_of_periapsis = 0 * Degree; tylo_elements_.mean_anomaly = 3.14 * Radian; bop_elements_.eccentricity = 0.24; bop_elements_.semimajor_axis = 128'500'000 * Metre; bop_elements_.inclination = 15 * Degree; bop_elements_.longitude_of_ascending_node = 10 * Degree; bop_elements_.argument_of_periapsis = 25 * Degree; bop_elements_.mean_anomaly = 0.9 * Radian; pol_elements_.eccentricity = 0.17; pol_elements_.semimajor_axis = 179'890'000 * Metre; pol_elements_.inclination = 4.25 * Degree; pol_elements_.longitude_of_ascending_node = 2 * Degree; pol_elements_.argument_of_periapsis = 15 * Degree; pol_elements_.mean_anomaly = 0.9 * Radian; } std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies_; not_null<MassiveBody const *> const sun_, jool_, laythe_, vall_, tylo_, bop_, pol_; MasslessBody test_particle_; Instant const game_epoch_; DegreesOfFreedom<KSP> const origin_ = {KSP::origin, Velocity<KSP>()}; KeplerianElements<KSP> jool_elements_, laythe_elements_, vall_elements_, tylo_elements_, bop_elements_, pol_elements_; private: not_null<MassiveBody const*> AddBody(GravitationalParameter const& μ) { bodies_.emplace_back(make_not_null_unique<MassiveBody>(μ)); return bodies_.back().get(); } }; TEST_F(ResonanceTest, JoolSystem) { auto const stock_jool_orbit = KeplerOrbit<KSP>(*sun_, test_particle_, game_epoch_, jool_elements_); auto const stock_laythe_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, laythe_elements_); auto const stock_vall_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, vall_elements_); auto const stock_tylo_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, tylo_elements_); auto const stock_bop_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, bop_elements_); auto const stock_pol_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, pol_elements_); auto const stock_jool_initial_state = origin_ + stock_jool_orbit.PrimocentricStateVectors(game_epoch_); Ephemeris<KSP> stock_ephemeris( std::move(bodies_), {origin_, stock_jool_initial_state, stock_jool_initial_state + stock_laythe_orbit.PrimocentricStateVectors(game_epoch_), stock_jool_initial_state + stock_vall_orbit.PrimocentricStateVectors(game_epoch_), stock_jool_initial_state + stock_tylo_orbit.PrimocentricStateVectors(game_epoch_), stock_jool_initial_state + stock_bop_orbit.PrimocentricStateVectors(game_epoch_), stock_jool_initial_state + stock_pol_orbit.PrimocentricStateVectors(game_epoch_)}, game_epoch_, McLachlanAtela1992Order5Optimal<Position<KSP>>(), 45 * Minute, 5 * Milli(Metre)); stock_ephemeris.Prolong(game_epoch_ + 90 * Day); std::vector<Instant> times; std::vector<std::vector<Displacement<KSP>>> displacements; for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) { auto const position = [&stock_ephemeris, t]( not_null<MassiveBody const*> body) { return stock_ephemeris.trajectory(body)->EvaluatePosition(t, nullptr); }; auto const barycentre = Barycentre<Position<KSP>, Mass>( {position(jool_), position(laythe_), position(vall_), position(tylo_), position(bop_), position(pol_)}, {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(), bop_->mass(), pol_->mass()}); times.emplace_back(t); displacements.push_back( {position(jool_) - barycentre, position(laythe_) - barycentre, position(vall_) - barycentre, position(tylo_) - barycentre, position(bop_) - barycentre, position(pol_) - barycentre}); } std::ofstream file; file.open("stock_jool.wl"); file << mathematica::Assign("q", displacements); file << mathematica::Assign("t", times); file.close(); // fails. stock_ephemeris.Prolong(game_epoch_ + 100 * Day); } } // namespace physics } // namespace principia <commit_msg>first correction that's not strictly worse than stock...<commit_after>#include "physics/kepler_orbit.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "mathematica/mathematica.hpp" #include "physics/solar_system.hpp" #include "testing_utilities/almost_equals.hpp" namespace principia { using integrators::McLachlanAtela1992Order5Optimal; using quantities::si::Degree; using quantities::si::Kilo; using quantities::si::Metre; using quantities::si::Milli; namespace physics { class ResonanceTest : public ::testing::Test { protected: using KSP = Frame<serialization::Frame::TestTag, serialization::Frame::TEST, true>; // Gravitational parameters from the KSP wiki. ResonanceTest() : sun_(AddBody(1.1723328E+18 * Pow<3>(Metre) / Pow<2>(Second))), jool_(AddBody(2.8252800E+14 * Pow<3>(Metre) / Pow<2>(Second))), laythe_(AddBody(1.9620000E+12 * Pow<3>(Metre) / Pow<2>(Second))), vall_(AddBody(2.0748150E+11 * Pow<3>(Metre) / Pow<2>(Second))), tylo_(AddBody(2.8252800E+12 * Pow<3>(Metre) / Pow<2>(Second))), bop_(AddBody(2.4868349E+09 * Pow<3>(Metre) / Pow<2>(Second))), pol_(AddBody(7.2170208E+08 * Pow<3>(Metre) / Pow<2>(Second))) { // Elements from the KSP wiki. jool_elements_.eccentricity = 0.05; jool_elements_.semimajor_axis = 68'773'560'320 * Metre; jool_elements_.inclination = 1.304 * Degree; jool_elements_.longitude_of_ascending_node = 52 * Degree; jool_elements_.argument_of_periapsis = 0 * Degree; jool_elements_.mean_anomaly = 0.1 * Radian; laythe_elements_.eccentricity = 0; laythe_elements_.semimajor_axis = 27'184'000 * Metre; laythe_elements_.inclination = 0 * Degree; laythe_elements_.longitude_of_ascending_node = 0 * Degree; laythe_elements_.argument_of_periapsis = 0 * Degree; laythe_elements_.mean_anomaly = 3.14 * Radian; vall_elements_.eccentricity = 0; vall_elements_.semimajor_axis = 43'152'000 * Metre; vall_elements_.inclination = 0 * Degree; vall_elements_.longitude_of_ascending_node = 0 * Degree; vall_elements_.argument_of_periapsis = 0 * Degree; vall_elements_.mean_anomaly = 0.9 * Radian; tylo_elements_.eccentricity = 0; tylo_elements_.semimajor_axis = 68'500'000 * Metre; tylo_elements_.inclination = 0.025 * Degree; tylo_elements_.longitude_of_ascending_node = 0 * Degree; tylo_elements_.argument_of_periapsis = 0 * Degree; tylo_elements_.mean_anomaly = 3.14 * Radian; bop_elements_.eccentricity = 0.24; bop_elements_.semimajor_axis = 128'500'000 * Metre; bop_elements_.inclination = 15 * Degree; bop_elements_.longitude_of_ascending_node = 10 * Degree; bop_elements_.argument_of_periapsis = 25 * Degree; bop_elements_.mean_anomaly = 0.9 * Radian; pol_elements_.eccentricity = 0.17; pol_elements_.semimajor_axis = 179'890'000 * Metre; pol_elements_.inclination = 4.25 * Degree; pol_elements_.longitude_of_ascending_node = 2 * Degree; pol_elements_.argument_of_periapsis = 15 * Degree; pol_elements_.mean_anomaly = 0.9 * Radian; } std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies_; not_null<MassiveBody const *> const sun_, jool_, laythe_, vall_, tylo_, bop_, pol_; MasslessBody test_particle_; Instant const game_epoch_; DegreesOfFreedom<KSP> const origin_ = {KSP::origin, Velocity<KSP>()}; KeplerianElements<KSP> jool_elements_, laythe_elements_, vall_elements_, tylo_elements_, bop_elements_, pol_elements_; private: not_null<MassiveBody const*> AddBody(GravitationalParameter const& μ) { bodies_.emplace_back(make_not_null_unique<MassiveBody>(μ)); return bodies_.back().get(); } }; TEST_F(ResonanceTest, StockJoolSystem) { auto const jool_orbit = KeplerOrbit<KSP>(*sun_, test_particle_, game_epoch_, jool_elements_); auto const laythe_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, laythe_elements_); auto const vall_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, vall_elements_); auto const tylo_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, tylo_elements_); auto const bop_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, bop_elements_); auto const pol_orbit = KeplerOrbit<KSP>(*jool_, test_particle_, game_epoch_, pol_elements_); auto const jool_initial_state = origin_ + jool_orbit.PrimocentricStateVectors(game_epoch_); Ephemeris<KSP> ephemeris( std::move(bodies_), {origin_, jool_initial_state, jool_initial_state + laythe_orbit.PrimocentricStateVectors(game_epoch_), jool_initial_state + vall_orbit.PrimocentricStateVectors(game_epoch_), jool_initial_state + tylo_orbit.PrimocentricStateVectors(game_epoch_), jool_initial_state + bop_orbit.PrimocentricStateVectors(game_epoch_), jool_initial_state + pol_orbit.PrimocentricStateVectors(game_epoch_)}, game_epoch_, McLachlanAtela1992Order5Optimal<Position<KSP>>(), 45 * Minute, 5 * Milli(Metre)); ephemeris.Prolong(game_epoch_ + 90 * Day); std::vector<Instant> times; std::vector<std::vector<Displacement<KSP>>> displacements; for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) { auto const position = [&ephemeris, t]( not_null<MassiveBody const*> body) { return ephemeris.trajectory(body)->EvaluatePosition(t, nullptr); }; auto const barycentre = Barycentre<Position<KSP>, Mass>( {position(jool_), position(laythe_), position(vall_), position(tylo_), position(bop_), position(pol_)}, {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(), bop_->mass(), pol_->mass()}); times.emplace_back(t); displacements.push_back( {position(jool_) - barycentre, position(laythe_) - barycentre, position(vall_) - barycentre, position(tylo_) - barycentre, position(bop_) - barycentre, position(pol_) - barycentre}); } std::ofstream file; file.open("stock_jool.wl"); file << mathematica::Assign("q", displacements); file << mathematica::Assign("t", times); file.close(); // fails. ephemeris.Prolong(game_epoch_ + 100 * Day); } TEST_F(ResonanceTest, BarycentricJoolSystem) { auto const jool_orbit = KeplerOrbit<KSP>(*sun_, *jool_, game_epoch_, jool_elements_); auto const laythe_orbit = KeplerOrbit<KSP>(*jool_, *laythe_, game_epoch_, laythe_elements_); MassiveBody jool_1(jool_->gravitational_parameter() + laythe_->gravitational_parameter()); auto const vall_orbit = KeplerOrbit<KSP>(jool_1, *vall_, game_epoch_, vall_elements_); MassiveBody jool_2(jool_1.gravitational_parameter() + vall_->gravitational_parameter()); auto const tylo_orbit = KeplerOrbit<KSP>(jool_2, *tylo_, game_epoch_, tylo_elements_); MassiveBody jool_3(jool_2.gravitational_parameter() + tylo_->gravitational_parameter()); auto const bop_orbit = KeplerOrbit<KSP>(jool_3, *bop_, game_epoch_, bop_elements_); MassiveBody jool_4(jool_3.gravitational_parameter() + bop_->gravitational_parameter()); auto const pol_orbit = KeplerOrbit<KSP>(jool_4, *pol_, game_epoch_, pol_elements_); auto const jool_barycentre_initial_state = origin_ + jool_orbit.BarycentricStateVectors(game_epoch_); auto const laythe_from_barycentre = laythe_orbit.BarycentricStateVectors(game_epoch_); auto const vall_from_barycentre = vall_orbit.BarycentricStateVectors(game_epoch_); auto const tylo_from_barycentre = tylo_orbit.BarycentricStateVectors(game_epoch_); auto const bop_from_barycentre = bop_orbit.BarycentricStateVectors(game_epoch_); auto const pol_from_barycentre = pol_orbit.BarycentricStateVectors(game_epoch_); auto const jool_initial_state = jool_barycentre_initial_state - (laythe_from_barycentre * laythe_->mass() + vall_from_barycentre * vall_->mass() + tylo_from_barycentre * tylo_->mass() + bop_from_barycentre * bop_->mass() + pol_from_barycentre * pol_->mass()) / jool_->mass(); Ephemeris<KSP> ephemeris( std::move(bodies_), {origin_, // TODO: not actually here jool_initial_state, jool_barycentre_initial_state + laythe_from_barycentre, jool_barycentre_initial_state + vall_from_barycentre, jool_barycentre_initial_state + tylo_from_barycentre, jool_barycentre_initial_state + bop_from_barycentre, jool_barycentre_initial_state + pol_from_barycentre}, game_epoch_, McLachlanAtela1992Order5Optimal<Position<KSP>>(), 45 * Minute, 5 * Milli(Metre)); ephemeris.Prolong(game_epoch_ + 90 * Day); std::vector<Instant> times; std::vector<std::vector<Displacement<KSP>>> displacements; for (Instant t = game_epoch_; t < game_epoch_ + 90 * Day; t += 45 * Minute) { auto const position = [&ephemeris, t]( not_null<MassiveBody const*> body) { return ephemeris.trajectory(body)->EvaluatePosition(t, nullptr); }; auto const barycentre = Barycentre<Position<KSP>, Mass>( {position(jool_), position(laythe_), position(vall_), position(tylo_), position(bop_), position(pol_)}, {jool_->mass(), laythe_->mass(), vall_->mass(), tylo_->mass(), bop_->mass(), pol_->mass()}); times.emplace_back(t); displacements.push_back( {position(jool_) - barycentre, position(laythe_) - barycentre, position(vall_) - barycentre, position(tylo_) - barycentre, position(bop_) - barycentre, position(pol_) - barycentre}); } std::ofstream file; file.open("corrected_jool.wl"); file << mathematica::Assign("q", displacements); file << mathematica::Assign("t", times); file.close(); // fails. ephemeris.Prolong(game_epoch_ + 100 * Day); } } // namespace physics } // namespace principia <|endoftext|>
<commit_before>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h" #include "xterm_mouse.hh" const char *xterm_mouse::XT_TERMCAP = "\033[?1000%?%p1%{1}%=%th%el%;"; const char *xterm_mouse::XT_TERMCAP_TRACKING = "\033[?1002%?%p1%{1}%=%th%el%;"; const char *xterm_mouse::XT_TERMCAP_SGR = "\033[?1006%?%p1%{1}%=%th%el%;"; void xterm_mouse::handle_mouse() { bool release = false; int ch; size_t index = 0; int bstate, x, y; char buffer[64]; bool done = false; while (!done) { if (index >= sizeof(buffer) - 1) { break; } ch = getch(); switch (ch) { case 'm': release = true; done = true; break; case 'M': done = true; break; default: buffer[index++] = (char)ch; break; } } buffer[index] = '\0'; if (sscanf(buffer, "<%d;%d;%d", &bstate, &x, &y) == 3) { if (this->xm_behavior) { this->xm_behavior->mouse_event(bstate, release, x, y); } } else { log_error("bad mouse escape sequence: %s", buffer); } } void xterm_mouse::set_enabled(bool enabled) { if (is_available()) { putp(tparm((char *)XT_TERMCAP, enabled ? 1 : 0)); putp(tparm((char *)XT_TERMCAP_TRACKING, enabled ? 1 : 0)); putp(tparm((char *)XT_TERMCAP_SGR, enabled ? 1 : 0)); fflush(stdout); this->xm_enabled = enabled; } else { log_warning("mouse support is not available"); } } bool xterm_mouse::is_available() { const char *termname = getenv("TERM"); bool retval = false; if (termname and strstr(termname, "xterm") != NULL) { retval = isatty(STDOUT_FILENO); } return retval; } <commit_msg>[mouse] do not require xterm for mouse use<commit_after>/** * Copyright (c) 2007-2012, Timothy Stack * * 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 Timothy Stack 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 REGENTS 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 REGENTS 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 "config.h" #include "xterm_mouse.hh" const char *xterm_mouse::XT_TERMCAP = "\033[?1000%?%p1%{1}%=%th%el%;"; const char *xterm_mouse::XT_TERMCAP_TRACKING = "\033[?1002%?%p1%{1}%=%th%el%;"; const char *xterm_mouse::XT_TERMCAP_SGR = "\033[?1006%?%p1%{1}%=%th%el%;"; void xterm_mouse::handle_mouse() { bool release = false; int ch; size_t index = 0; int bstate, x, y; char buffer[64]; bool done = false; while (!done) { if (index >= sizeof(buffer) - 1) { break; } ch = getch(); switch (ch) { case 'm': release = true; done = true; break; case 'M': done = true; break; default: buffer[index++] = (char)ch; break; } } buffer[index] = '\0'; if (sscanf(buffer, "<%d;%d;%d", &bstate, &x, &y) == 3) { if (this->xm_behavior) { this->xm_behavior->mouse_event(bstate, release, x, y); } } else { log_error("bad mouse escape sequence: %s", buffer); } } void xterm_mouse::set_enabled(bool enabled) { if (is_available()) { putp(tparm((char *)XT_TERMCAP, enabled ? 1 : 0)); putp(tparm((char *)XT_TERMCAP_TRACKING, enabled ? 1 : 0)); putp(tparm((char *)XT_TERMCAP_SGR, enabled ? 1 : 0)); fflush(stdout); this->xm_enabled = enabled; } else { log_warning("mouse support is not available"); } } bool xterm_mouse::is_available() { return isatty(STDOUT_FILENO); } <|endoftext|>
<commit_before>#include "_app/sdl.h" #include "SDL/SDL.h" st::_app::sdl::sdl() { init(); } st::_app::sdl::~sdl() { finish(); } bool st::_app::sdl::init() { SDL_Init ( SDL_INIT_EVERYTHING ); SDL_Surface* hello; m_screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE ); // Let's be honest, right now I don't care. # COPIED!!! hello = SDL_LoadBMP(media()->get_image_media_path("hello.bmp").c_str()); SDL_BlitSurface(hello, NULL, m_screen, NULL); SDL_Flip( m_screen ); SDL_Delay( 2000 ); return true; } bool st::_app::sdl::finish() { SDL_Quit(); // Let's be honest, right now I don't care. return true; } <commit_msg>Free missed screen.<commit_after>#include "_app/sdl.h" #include "SDL/SDL.h" st::_app::sdl::sdl() { init(); } st::_app::sdl::~sdl() { finish(); } bool st::_app::sdl::init() { SDL_Init ( SDL_INIT_EVERYTHING ); SDL_Surface* hello; m_screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE ); // Let's be honest, right now I don't care. # COPIED!!! hello = SDL_LoadBMP(media()->get_image_media_path("hello.bmp").c_str()); SDL_BlitSurface(hello, NULL, m_screen, NULL); // Lazy! SDL_Flip( m_screen ); SDL_Delay( 2000 ); SDL_FreeSurface(hello); return true; } bool st::_app::sdl::finish() { SDL_Quit(); // Let's be honest, right now I don't care. return true; } <|endoftext|>
<commit_before>#include "./MediaDefinitions.h" #include "rtp/SenderBandwidthEstimationHandler.h" namespace erizo { DEFINE_LOGGER(SenderBandwidthEstimationHandler, "rtp.SenderBandwidthEstimationHandler"); constexpr duration SenderBandwidthEstimationHandler::kMinUpdateEstimateInterval; SenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(std::shared_ptr<Clock> the_clock) : connection_{nullptr}, bwe_listener_{nullptr}, clock_{the_clock}, initialized_{false}, enabled_{true}, received_remb_{false}, period_packets_sent_{0}, estimated_bitrate_{0}, estimated_loss_{0}, estimated_rtt_{0}, last_estimate_update_{clock::now()}, sender_bwe_{new SendSideBandwidthEstimation()} { sender_bwe_->SetSendBitrate(kStartSendBitrate); }; SenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(const SenderBandwidthEstimationHandler&& handler) : // NOLINT connection_{handler.connection_}, bwe_listener_{handler.bwe_listener_}, clock_{handler.clock_}, initialized_{handler.initialized_}, enabled_{handler.enabled_}, received_remb_{false}, period_packets_sent_{handler.period_packets_sent_}, estimated_bitrate_{handler.estimated_bitrate_}, estimated_loss_{handler.estimated_loss_}, estimated_rtt_{handler.estimated_rtt_}, sender_bwe_{handler.sender_bwe_}, sr_delay_data_{std::move(handler.sr_delay_data_)} {} void SenderBandwidthEstimationHandler::enable() { enabled_ = true; } void SenderBandwidthEstimationHandler::disable() { enabled_ = false; } void SenderBandwidthEstimationHandler::notifyUpdate() { if (initialized_) { return; } auto pipeline = getContext()->getPipelineShared(); if (pipeline && !connection_) { connection_ = pipeline->getService<WebRtcConnection>().get(); } if (!connection_) { return; } stats_ = pipeline->getService<Stats>(); if (!stats_) { return; } initialized_ = true; } void SenderBandwidthEstimationHandler::read(Context *ctx, std::shared_ptr<DataPacket> packet) { RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data); if (chead->isFeedback()) { char* packet_pointer = packet->data; int rtcp_length = 0; int total_length = 0; int current_block = 0; do { packet_pointer+=rtcp_length; chead = reinterpret_cast<RtcpHeader*>(packet_pointer); rtcp_length = (ntohs(chead->length) + 1) * 4; total_length += rtcp_length; ELOG_DEBUG("%s ssrc %u, sourceSSRC %u, PacketType %u", connection_->toLog(), chead->getSSRC(), chead->getSourceSSRC(), chead->getPacketType()); switch (chead->packettype) { case RTCP_Receiver_PT: { ELOG_DEBUG("%s, Analyzing Video RR: PacketLost %u, Ratio %u, current_block %d, blocks %d" ", sourceSSRC %u, ssrc %u", connection_->toLog(), chead->getLostPackets(), chead->getFractionLost(), current_block, chead->getBlockCount(), chead->getSourceSSRC(), chead->getSSRC()); // calculate RTT + Update receiver block uint32_t delay_since_last_ms = (chead->getDelaySinceLastSr() * 1000) / 65536; int64_t now_ms = ClockUtils::timePointToMs(clock_->now()); uint32_t last_sr = chead->getLastSr(); auto value = std::find_if(sr_delay_data_.begin(), sr_delay_data_.end(), [last_sr](const std::shared_ptr<SrDelayData> sr_info) { return sr_info->sr_ntp == last_sr; }); // TODO(pedro) Implement alternative when there are no REMBs if (received_remb_ && value != sr_delay_data_.end()) { uint32_t delay = now_ms - (*value)->sr_send_time - delay_since_last_ms; ELOG_DEBUG("%s message: Updating Estimate with RR, fraction_lost: %u, " "delay: %u, period_packets_sent_: %u", connection_->toLog(), chead->getFractionLost(), delay, period_packets_sent_); sender_bwe_->UpdateReceiverBlock(chead->getFractionLost(), delay, period_packets_sent_, now_ms); period_packets_sent_ = 0; updateEstimate(); } } break; case RTCP_PS_Feedback_PT: { if (chead->getBlockCount() == RTCP_AFB) { char *uniqueId = reinterpret_cast<char*>(&chead->report.rembPacket.uniqueid); if (!strncmp(uniqueId, "REMB", 4)) { received_remb_ = true; int64_t now_ms = ClockUtils::timePointToMs(clock_->now()); uint64_t remb_bitrate = chead->getBrMantis() << chead->getBrExp(); uint64_t bitrate = estimated_bitrate_ != 0 ? estimated_bitrate_ : remb_bitrate; // We update the REMB with the latest estimation chead->setREMBBitRate(bitrate); ELOG_DEBUG("%s message: Updating estimate REMB, bitrate: %lu, estimated_bitrate %lu, remb_bitrate %lu", connection_->toLog(), bitrate, estimated_bitrate_, remb_bitrate); sender_bwe_->UpdateReceiverEstimate(now_ms, remb_bitrate); updateEstimate(); } else { ELOG_DEBUG("%s message: Unsupported AFB Packet not REMB", connection_->toLog()); } } } break; default: break; } current_block++; } while (total_length < packet->length); } ctx->fireRead(std::move(packet)); } void SenderBandwidthEstimationHandler::write(Context *ctx, std::shared_ptr<DataPacket> packet) { RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data); if (!chead->isRtcp() && packet->type == VIDEO_PACKET) { period_packets_sent_++; time_point now = clock_->now(); if (received_remb_ && now - last_estimate_update_ > kMinUpdateEstimateInterval) { sender_bwe_->UpdateEstimate(ClockUtils::timePointToMs(now)); updateEstimate(); last_estimate_update_ = now; } } else if (chead->getPacketType() == RTCP_Sender_PT) { analyzeSr(chead); } ctx->fireWrite(std::move(packet)); } void SenderBandwidthEstimationHandler::analyzeSr(RtcpHeader* chead) { uint64_t now = ClockUtils::timePointToMs(clock_->now()); uint32_t ntp; ntp = chead->get32MiddleNtp(); ELOG_DEBUG("%s message: adding incoming SR to list, ntp: %u", connection_->toLog(), ntp); sr_delay_data_.push_back(std::shared_ptr<SrDelayData>( new SrDelayData(ntp, now))); if (sr_delay_data_.size() >= kMaxSrListSize) { sr_delay_data_.pop_front(); } } void SenderBandwidthEstimationHandler::updateEstimate() { sender_bwe_->CurrentEstimate(&estimated_bitrate_, &estimated_loss_, &estimated_rtt_); if (stats_) { stats_->getNode()["total"].insertStat("senderBitrateEstimation", CumulativeStat{static_cast<uint64_t>(estimated_bitrate_)}); } ELOG_DEBUG("%s message: estimated bitrate %d, loss %u, rtt %ld", connection_->toLog(), estimated_bitrate_, estimated_loss_, estimated_rtt_); if (bwe_listener_) { bwe_listener_->onBandwidthEstimate(estimated_bitrate_, estimated_loss_, estimated_rtt_); } } } // namespace erizo <commit_msg>Also search REMBs and RRs after SRs (#1473)<commit_after>#include "./MediaDefinitions.h" #include "rtp/SenderBandwidthEstimationHandler.h" #include "rtp/RtpUtils.h" namespace erizo { DEFINE_LOGGER(SenderBandwidthEstimationHandler, "rtp.SenderBandwidthEstimationHandler"); constexpr duration SenderBandwidthEstimationHandler::kMinUpdateEstimateInterval; SenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(std::shared_ptr<Clock> the_clock) : connection_{nullptr}, bwe_listener_{nullptr}, clock_{the_clock}, initialized_{false}, enabled_{true}, received_remb_{false}, period_packets_sent_{0}, estimated_bitrate_{0}, estimated_loss_{0}, estimated_rtt_{0}, last_estimate_update_{clock::now()}, sender_bwe_{new SendSideBandwidthEstimation()} { sender_bwe_->SetSendBitrate(kStartSendBitrate); }; SenderBandwidthEstimationHandler::SenderBandwidthEstimationHandler(const SenderBandwidthEstimationHandler&& handler) : // NOLINT connection_{handler.connection_}, bwe_listener_{handler.bwe_listener_}, clock_{handler.clock_}, initialized_{handler.initialized_}, enabled_{handler.enabled_}, received_remb_{false}, period_packets_sent_{handler.period_packets_sent_}, estimated_bitrate_{handler.estimated_bitrate_}, estimated_loss_{handler.estimated_loss_}, estimated_rtt_{handler.estimated_rtt_}, sender_bwe_{handler.sender_bwe_}, sr_delay_data_{std::move(handler.sr_delay_data_)} {} void SenderBandwidthEstimationHandler::enable() { enabled_ = true; } void SenderBandwidthEstimationHandler::disable() { enabled_ = false; } void SenderBandwidthEstimationHandler::notifyUpdate() { if (initialized_) { return; } auto pipeline = getContext()->getPipelineShared(); if (pipeline && !connection_) { connection_ = pipeline->getService<WebRtcConnection>().get(); } if (!connection_) { return; } stats_ = pipeline->getService<Stats>(); if (!stats_) { return; } initialized_ = true; } void SenderBandwidthEstimationHandler::read(Context *ctx, std::shared_ptr<DataPacket> packet) { RtpUtils::forEachRtcpBlock(packet, [this](RtcpHeader *chead) { ELOG_DEBUG("%s ssrc %u, sourceSSRC %u, PacketType %u", connection_->toLog(), chead->getSSRC(), chead->getSourceSSRC(), chead->getPacketType()); switch (chead->packettype) { case RTCP_Receiver_PT: { // calculate RTT + Update receiver block uint32_t delay_since_last_ms = (chead->getDelaySinceLastSr() * 1000) / 65536; int64_t now_ms = ClockUtils::timePointToMs(clock_->now()); uint32_t last_sr = chead->getLastSr(); auto value = std::find_if(sr_delay_data_.begin(), sr_delay_data_.end(), [last_sr](const std::shared_ptr<SrDelayData> sr_info) { return sr_info->sr_ntp == last_sr; }); ELOG_DEBUG("%s, Analyzing Video RR: PacketLost %u, Ratio %u, blocks %d" ", sourceSSRC %u, ssrc %u, last_sr %u, remb_received %d, found %d", connection_->toLog(), chead->getLostPackets(), chead->getFractionLost(), chead->getBlockCount(), chead->getSourceSSRC(), chead->getSSRC(), chead->getLastSr(), received_remb_, value != sr_delay_data_.end()); // TODO(pedro) Implement alternative when there are no REMBs if (received_remb_ && value != sr_delay_data_.end()) { uint32_t delay = now_ms - (*value)->sr_send_time - delay_since_last_ms; ELOG_DEBUG("%s message: Updating Estimate with RR, fraction_lost: %u, " "delay: %u, period_packets_sent_: %u", connection_->toLog(), chead->getFractionLost(), delay, period_packets_sent_); sender_bwe_->UpdateReceiverBlock(chead->getFractionLost(), delay, period_packets_sent_, now_ms); period_packets_sent_ = 0; updateEstimate(); } } break; case RTCP_PS_Feedback_PT: { if (chead->getBlockCount() == RTCP_AFB) { char *uniqueId = reinterpret_cast<char*>(&chead->report.rembPacket.uniqueid); if (!strncmp(uniqueId, "REMB", 4)) { received_remb_ = true; int64_t now_ms = ClockUtils::timePointToMs(clock_->now()); uint64_t remb_bitrate = chead->getBrMantis() << chead->getBrExp(); uint64_t bitrate = estimated_bitrate_ != 0 ? estimated_bitrate_ : remb_bitrate; // We update the REMB with the latest estimation chead->setREMBBitRate(bitrate); ELOG_DEBUG("%s message: Updating estimate REMB, bitrate: %lu, estimated_bitrate %lu, remb_bitrate %lu", connection_->toLog(), bitrate, estimated_bitrate_, remb_bitrate); sender_bwe_->UpdateReceiverEstimate(now_ms, remb_bitrate); updateEstimate(); } else { ELOG_DEBUG("%s message: Unsupported AFB Packet not REMB", connection_->toLog()); } } } break; default: break; } }); ctx->fireRead(std::move(packet)); } void SenderBandwidthEstimationHandler::write(Context *ctx, std::shared_ptr<DataPacket> packet) { RtcpHeader *chead = reinterpret_cast<RtcpHeader*>(packet->data); if (!chead->isRtcp() && packet->type == VIDEO_PACKET) { period_packets_sent_++; time_point now = clock_->now(); if (received_remb_ && now - last_estimate_update_ > kMinUpdateEstimateInterval) { sender_bwe_->UpdateEstimate(ClockUtils::timePointToMs(now)); updateEstimate(); last_estimate_update_ = now; } } else if (chead->getPacketType() == RTCP_Sender_PT) { analyzeSr(chead); } ctx->fireWrite(std::move(packet)); } void SenderBandwidthEstimationHandler::analyzeSr(RtcpHeader* chead) { uint64_t now = ClockUtils::timePointToMs(clock_->now()); uint32_t ntp; ntp = chead->get32MiddleNtp(); ELOG_DEBUG("%s message: adding incoming SR to list, ntp: %u", connection_->toLog(), ntp); sr_delay_data_.push_back(std::shared_ptr<SrDelayData>( new SrDelayData(ntp, now))); if (sr_delay_data_.size() >= kMaxSrListSize) { sr_delay_data_.pop_front(); } } void SenderBandwidthEstimationHandler::updateEstimate() { sender_bwe_->CurrentEstimate(&estimated_bitrate_, &estimated_loss_, &estimated_rtt_); if (stats_) { stats_->getNode()["total"].insertStat("senderBitrateEstimation", CumulativeStat{static_cast<uint64_t>(estimated_bitrate_)}); } ELOG_DEBUG("%s message: estimated bitrate %d, loss %u, rtt %ld", connection_->toLog(), estimated_bitrate_, estimated_loss_, estimated_rtt_); if (bwe_listener_) { bwe_listener_->onBandwidthEstimate(estimated_bitrate_, estimated_loss_, estimated_rtt_); } } } // namespace erizo <|endoftext|>
<commit_before>/* <x0/plugins/filter_example.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <[email protected]> */ #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpResponse.h> #include <x0/http/HttpRangeDef.h> #include <x0/io/Filter.h> #include <x0/strutils.h> #include <x0/Types.h> #include <x0/sysconfig.h> // {{{ ExampleFilter class ExampleFilter : public x0::Filter { enum Mode { IDENTITY, UPPER, LOWER }; Mode mode_; public: explicit ExampleFilter(Mode mode); virtual x0::Buffer process(const x0::BufferRef& input); }; ExampleFilter::ExampleFilter(Mode mode) : mode_(mode) { } x0::Buffer ExampleFilter::process(const x0::BufferRef& input) { x0::Buffer result; switch (mode_) { case ExampleFilter::LOWER: for (auto i = input.begin(), e = input.end(); i != e; ++i) result.push_back(static_cast<char>(std::tolower(*i))); break; case ExampleFilter::UPPER: for (auto i = input.begin(), e = input.end(); i != e; ++i) result.push_back(static_cast<char>(std::toupper(*i))); break; case ExampleFilter::IDENTITY: default: result.push_back(input); } return result; } // }}} /** * \ingroup plugins * \brief ... */ class filter_plugin : public x0::HttpPlugin { public: filter_plugin(x0::HttpServer& srv, const std::string& name) : x0::HttpPlugin(srv, name) { registerFunction<filter_plugin, &filter_plugin::install_filter>("example_filter", Flow::Value::VOID); } ~filter_plugin() { } void install_filter(Flow::Value& /*result*/, x0::HttpRequest *in, x0::HttpResponse *out, const x0::Params& args) { if (args.count() != 1) { log(x0::Severity::error, "No argument passed."); return; } if (!args[0].isString()) { log(x0::Severity::error, "Invalid argument type passed."); return; } if (strcmp(args[0].toString(), "identity") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::IDENTITY)); else if (strcmp(args[0].toString(), "upper") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::UPPER)); else if (strcmp(args[0].toString(), "lower") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::LOWER)); else { log(x0::Severity::error, "Invalid argument value passed."); return; } out->headers.push_back("Content-Encoding", "filter_example"); // response might change according to Accept-Encoding if (!out->headers.contains("Vary")) out->headers.push_back("Vary", "Accept-Encoding"); else out->headers["Vary"] += ",Accept-Encoding"; // removing content-length implicitely enables chunked encoding out->headers.remove("Content-Length"); } }; X0_EXPORT_PLUGIN(filter) <commit_msg>brain-dead fix<commit_after>/* <x0/plugins/filter_example.cpp> * * This file is part of the x0 web server project and is released under LGPL-3. * http://www.xzero.ws/ * * (c) 2009-2010 Christian Parpart <[email protected]> */ #include <x0/http/HttpPlugin.h> #include <x0/http/HttpServer.h> #include <x0/http/HttpRequest.h> #include <x0/http/HttpResponse.h> #include <x0/http/HttpRangeDef.h> #include <x0/io/Filter.h> #include <x0/strutils.h> #include <x0/Types.h> #include <x0/sysconfig.h> // {{{ ExampleFilter class ExampleFilter : public x0::Filter { public: enum Mode { IDENTITY, UPPER, LOWER }; private: Mode mode_; public: explicit ExampleFilter(Mode mode); virtual x0::Buffer process(const x0::BufferRef& input); }; ExampleFilter::ExampleFilter(Mode mode) : mode_(mode) { } x0::Buffer ExampleFilter::process(const x0::BufferRef& input) { x0::Buffer result; switch (mode_) { case ExampleFilter::LOWER: for (auto i = input.begin(), e = input.end(); i != e; ++i) result.push_back(static_cast<char>(std::tolower(*i))); break; case ExampleFilter::UPPER: for (auto i = input.begin(), e = input.end(); i != e; ++i) result.push_back(static_cast<char>(std::toupper(*i))); break; case ExampleFilter::IDENTITY: default: result.push_back(input); } return result; } // }}} /** * \ingroup plugins * \brief ... */ class filter_plugin : public x0::HttpPlugin { public: filter_plugin(x0::HttpServer& srv, const std::string& name) : x0::HttpPlugin(srv, name) { registerFunction<filter_plugin, &filter_plugin::install_filter>("example_filter", Flow::Value::VOID); } ~filter_plugin() { } void install_filter(Flow::Value& /*result*/, x0::HttpRequest *in, x0::HttpResponse *out, const x0::Params& args) { if (args.count() != 1) { log(x0::Severity::error, "No argument passed."); return; } if (!args[0].isString()) { log(x0::Severity::error, "Invalid argument type passed."); return; } if (strcmp(args[0].toString(), "identity") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::IDENTITY)); else if (strcmp(args[0].toString(), "upper") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::UPPER)); else if (strcmp(args[0].toString(), "lower") == 0) out->filters.push_back(std::make_shared<ExampleFilter>(ExampleFilter::LOWER)); else { log(x0::Severity::error, "Invalid argument value passed."); return; } out->headers.push_back("Content-Encoding", "filter_example"); // response might change according to Accept-Encoding if (!out->headers.contains("Vary")) out->headers.push_back("Vary", "Accept-Encoding"); else out->headers["Vary"] += ",Accept-Encoding"; // removing content-length implicitely enables chunked encoding out->headers.remove("Content-Length"); } }; X0_EXPORT_PLUGIN(filter) <|endoftext|>